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。

feat(starrocks): add StarRocks engine support

bamboo837926cc0b46
diff --git a/apps/desktop/src/components/structure/StarRocksAlterLayoutEditor.vue b/apps/desktop/src/components/structure/StarRocksAlterLayoutEditor.vue
new file mode 100644
index 0000000000..93d4c503e2
--- /dev/null
+++ b/apps/desktop/src/components/structure/StarRocksAlterLayoutEditor.vue
@@ -0,0 +1,120 @@
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import StructureColumnMultiSelect from "./StructureColumnMultiSelect.vue";
+import { getStarRocksCapabilities } from "@/lib/table/starrocksCapabilities";
+import { isStarRocksHashColumn } from "@/lib/table/starrocksPhysicalOptions";
+import type { StarRocksAlterOptions, StarRocksLayoutDraft, StarRocksPartitionChange } from "@/lib/table/starrocksAlterOptions";
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+const props = defineProps<{ modelValue: StarRocksLayoutDraft; context: StarRocksAlterOptions; columns: EditableStructureColumn[]; disabled?: boolean }>();
+const emit = defineEmits<{ "update:modelValue": [value: StarRocksLayoutDraft] }>();
+const { t } = useI18n();
+const caps = computed(() => getStarRocksCapabilities(props.context.serverVersion));
+const locked = computed(() => props.disabled || !caps.value.alterDistribution || props.context.colocated);
+const distributionLocked = computed(() => locked.value || props.context.automaticBucketScaling);
+const hashColumns = computed(() =>
+ props.columns.filter((column) => column.original && !column.markedForDrop && isStarRocksHashColumn(column) && (props.context.model === "duplicate" || props.context.keyColumns.includes(column.original.name))).map((column) => ({ ...column, id: column.original!.name })),
+);
+const canDefault = computed(() => caps.value.defaultBuckets && props.modelValue.method === "hash" && props.context.distribution?.method === "hash" && JSON.stringify(props.modelValue.columns) === JSON.stringify(props.context.distribution.columns));
+const action = ref("replicas");
+const name = ref("");
+const lower = ref<Record<string, string>>({});
+const upper = ref<Record<string, string>>({});
+const listRows = ref<Array<Record<string, string>>>([{}]);
+const replicas = ref("1");
+function update<K extends keyof StarRocksLayoutDraft>(key: K, value: StarRocksLayoutDraft[K]) {
+ emit("update:modelValue", { ...props.modelValue, [key]: value, ...(key === "method" || key === "columns" ? { defaultOnly: false } : {}) });
+}
+function queue() {
+ if (!name.value.trim()) return;
+ const values = (row: Record<string, string>) => props.context.partitionColumns.map((column) => row[column] ?? "");
+ let operation: StarRocksPartitionChange;
+ if (action.value === "addRange") operation = { kind: "addRange", name: name.value.trim(), lower: values(lower.value), upper: values(upper.value) };
+ else if (action.value === "addList") operation = { kind: "addList", name: name.value.trim(), values: listRows.value.map(values) };
+ else if (action.value === "drop") operation = { kind: "drop", name: name.value.trim() };
+ else operation = { kind: "replicas", name: name.value.trim(), replicas: Number.isInteger(Number(replicas.value)) && Number(replicas.value) > 0 && Number(replicas.value) <= 32767 ? Number(replicas.value) : 0 };
+ update("partitions", [...props.modelValue.partitions, operation]);
+ name.value = "";
+}
+</script>
+<template>
+ <details open class="shrink-0 rounded-md border bg-muted/10 px-3 py-2" data-starrocks-alter-layout>
+ <summary class="cursor-pointer font-medium">{{ t("starrocksLayout.alterLayoutTitle") }}</summary>
+ <div class="mt-2 max-h-72 space-y-3 overflow-y-auto pr-1">
+ <p class="text-xs text-muted-foreground">{{ t("starrocksLayout.alterLayoutHint") }}</p>
+ <p v-if="context.colocated || !caps.alterDistribution" class="text-xs text-amber-600">{{ t("starrocksLayout.alterLayoutUnavailable") }}</p>
+ <p v-if="context.automaticBucketScaling" class="text-xs text-muted-foreground">{{ t("starrocksLayout.automaticBucketsReadonly") }}</p>
+ <div class="flex flex-wrap items-end gap-3">
+ <div class="space-y-1">
+ <span class="block text-muted-foreground">{{ t("starrocksLayout.distribution") }}</span>
+ <Select :model-value="modelValue.method" :disabled="distributionLocked" @update:model-value="update('method', $event as 'hash' | 'random')">
+ <SelectTrigger class="h-8 w-36"><SelectValue /></SelectTrigger>
+ <SelectContent
+ ><SelectItem value="hash">{{ t("starrocksLayout.hash") }}</SelectItem
+ ><SelectItem value="random" :disabled="context.model !== 'duplicate'">{{ t("starrocksLayout.random") }}</SelectItem></SelectContent
+ >
+ </Select>
+ </div>
+ <StructureColumnMultiSelect v-if="modelValue.method === 'hash'" :model-value="modelValue.columns" :columns="hashColumns" :label="t('starrocksLayout.hashColumns')" :disabled="distributionLocked" @update:model-value="update('columns', $event)" />
+ <label class="space-y-1"
+ ><span class="block text-muted-foreground">{{ t("starrocksLayout.bucketCount") }}</span
+ ><Input :model-value="modelValue.bucketCount" type="number" min="1" max="2147483647" step="1" class="h-8 w-28" :placeholder="t('starrocksLayout.auto')" :disabled="distributionLocked" @update:model-value="update('bucketCount', String($event ?? ''))"
+ /></label>
+ </div>
+ <label v-if="canDefault" class="flex items-center gap-2 text-xs"><input type="checkbox" :checked="modelValue.defaultOnly" :disabled="distributionLocked" @change="update('defaultOnly', ($event.target as HTMLInputElement).checked)" />{{ t("starrocksLayout.defaultBucketsOnly") }}</label>
+ <p class="text-xs text-muted-foreground">{{ t("starrocksLayout.alterBucketsHint") }}</p>
+ <section class="space-y-2 border-t pt-2">
+ <p class="text-xs text-muted-foreground">{{ t("starrocksLayout.partitionReadonly") }}</p>
+ <pre v-if="context.partitionClause" class="overflow-auto whitespace-pre-wrap text-xs">{{ context.partitionClause }}</pre>
+ <div class="flex flex-wrap items-end gap-2">
+ <Select v-model="action" :disabled="locked"
+ ><SelectTrigger class="h-8 w-44"><SelectValue /></SelectTrigger
+ ><SelectContent>
+ <SelectItem value="replicas">{{ t("starrocksLayout.partitionReplicas") }}</SelectItem>
+ <SelectItem v-if="context.partitionKind" value="drop">{{ t("starrocksLayout.dropPartition") }}</SelectItem>
+ <SelectItem v-if="context.partitionKind === 'range'" value="addRange">{{ t("starrocksLayout.addRangePartition") }}</SelectItem>
+ <SelectItem v-if="context.partitionKind === 'list'" value="addList">{{ t("starrocksLayout.addListPartition") }}</SelectItem>
+ </SelectContent></Select
+ >
+ <Input v-model="name" class="h-8 w-48" :placeholder="t(action === 'replicas' ? 'starrocksLayout.partitionNameAll' : 'starrocksLayout.partitionNameInput')" :disabled="locked" />
+ <Input v-if="action === 'replicas'" v-model="replicas" type="number" min="1" max="32767" step="1" class="h-8 w-24" :disabled="locked" />
+ </div>
+ <div v-if="action === 'addRange'" class="flex flex-wrap gap-2">
+ <div v-for="column in context.partitionColumns" :key="column" class="space-y-1">
+ <span class="text-xs">{{ column }}</span
+ ><Input v-model="lower[column]" :placeholder="t('starrocksLayout.rangeLower')" :disabled="locked" /><Input v-model="upper[column]" :placeholder="t('starrocksLayout.rangeUpper')" :disabled="locked" />
+ </div>
+ </div>
+ <div v-if="action === 'addList'" class="space-y-2">
+ <div v-for="(row, index) in listRows" :key="index" class="flex flex-wrap gap-2">
+ <Input v-for="column in context.partitionColumns" :key="column" v-model="row[column]" :placeholder="column" class="h-8 w-40" :disabled="locked" /><Button variant="ghost" size="sm" :disabled="locked || listRows.length === 1" @click="listRows.splice(index, 1)">{{
+ t("starrocksLayout.removePartitionOperation")
+ }}</Button>
+ </div>
+ <Button variant="outline" size="sm" :disabled="locked" @click="listRows.push({})">{{ t("starrocksLayout.addValueTuple") }}</Button>
+ </div>
+ <p v-if="action === 'drop'" class="text-xs text-amber-600">{{ t("starrocksLayout.dropPartitionHint") }}</p>
+ <p class="text-xs text-muted-foreground">{{ t("starrocksLayout.partitionValuesHint") }}</p>
+ <Button variant="outline" size="sm" :disabled="locked || !name.trim()" @click="queue">{{ t("starrocksLayout.queuePartitionOperation") }}</Button>
+ <div v-for="(operation, index) in modelValue.partitions" :key="index" class="flex items-center justify-between gap-2 rounded border px-2 py-1 text-xs">
+ <span>{{ t(`starrocksLayout.operation_${operation.kind}`) }} · {{ operation.name }}</span
+ ><Button
+ variant="ghost"
+ size="sm"
+ :disabled="disabled"
+ @click="
+ update(
+ 'partitions',
+ modelValue.partitions.filter((_, i) => i !== index),
+ )
+ "
+ >{{ t("starrocksLayout.removePartitionOperation") }}</Button
+ >
+ </div>
+ </section>
+ </div>
+ </details>
+</template>
diff --git a/apps/desktop/src/components/structure/StarRocksAlterStatus.vue b/apps/desktop/src/components/structure/StarRocksAlterStatus.vue
new file mode 100644
index 0000000000..1cae3311f4
--- /dev/null
+++ b/apps/desktop/src/components/structure/StarRocksAlterStatus.vue
@@ -0,0 +1,159 @@
+<script setup lang="ts">
+import { computed, onActivated, onBeforeUnmount, onDeactivated, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import * as api from "@/lib/backend/api";
+import { STARROCKS_ALTER_KINDS, isStarRocksAlterJobActive, parseStarRocksAlterJobs, starRocksAlterStatusSql, type StarRocksAlterJob } from "@/lib/table/starrocksAlterStatus";
+const props = defineProps<{ connectionId: string; database: string; tableName: string; schema?: string; catalog?: string; paused: boolean; revision: number; dirty: boolean; submittedSql?: string }>();
+const emit = defineEmits<{ busy: [value: boolean]; completed: [] }>();
+const { t } = useI18n();
+const jobs = ref<StarRocksAlterJob[]>([]);
+const error = ref("");
+const checking = ref(false);
+const expanded = ref(false);
+const expandedJob = ref<string>();
+const submissionJobIds = ref<string[]>([]);
+let submissionExistingIds = new Set<string>();
+const checkedAt = ref("");
+const knownBusy = ref(false);
+let generation = 0;
+let timer: ReturnType<typeof setTimeout> | undefined;
+let active = true;
+let awaitingUntil = 0;
+let submittedBaseline = new Set<string>();
+const busy = computed(() => knownBusy.value || jobs.value.some(isStarRocksAlterJobActive));
+const unfinished = computed(() => jobs.value.filter(isStarRocksAlterJobActive));
+const current = computed(() => unfinished.value[0]);
+const jobKey = (job: StarRocksAlterJob) => `${job.kind}:${job.id}`;
+const localSqlForJob = (job: StarRocksAlterJob) => (props.submittedSql && submissionJobIds.value.includes(jobKey(job)) ? props.submittedSql : undefined);
+const stateLabel = (state: string) => (["PENDING", "WAITING_TXN", "RUNNING", "FINISHED", "CANCELLED"].includes(state) ? t(`starrocksStatus.${state}`) : t("starrocksStatus.unknownState", { state }));
+const title = computed(() => (error.value ? t("starrocksStatus.queryFailed") : checking.value && !checkedAt.value ? t("starrocksStatus.checking") : current.value ? stateLabel(current.value.state) : t("starrocksStatus.idle")));
+function stop() {
+ generation++;
+ if (timer) clearTimeout(timer);
+ timer = undefined;
+ checking.value = false;
+}
+async function refresh() {
+ if (!active || props.paused || checking.value) return;
+ if (timer) clearTimeout(timer);
+ const request = ++generation;
+ const connectionId = props.connectionId,
+ database = props.database,
+ tableName = props.tableName;
+ checking.value = true;
+ try {
+ const results = await Promise.allSettled(
+ STARROCKS_ALTER_KINDS.map(async (kind) => {
+ const result = await api.executeQuery(connectionId, database, starRocksAlterStatusSql(kind, tableName), props.schema, undefined, { maxRows: 5, timeoutSecs: 10, catalog: props.catalog });
+ if (result.execution_error) throw new Error("SHOW ALTER query failed");
+ return parseStarRocksAlterJobs(kind, result);
+ }),
+ );
+ if (request !== generation) return;
+ const failures = results.filter((result) => result.status === "rejected");
+ const next = results.flatMap((result) => (result.status === "fulfilled" ? result.value : []));
+ const wasBusy = busy.value;
+ if (props.submittedSql && awaitingUntil > 0) {
+ submissionJobIds.value = [...new Set([...submissionJobIds.value, ...next.filter((job) => !submissionExistingIds.has(jobKey(job))).map(jobKey)])];
+ }
+ // Keep previous evidence of an active job on a partial failure.
+ if (!failures.length) jobs.value = next;
+ else {
+ const succeeded = STARROCKS_ALTER_KINDS.filter((_, index) => results[index].status === "fulfilled");
+ jobs.value = [...jobs.value.filter((job) => !succeeded.includes(job.kind)), ...next];
+ }
+ error.value = failures.map((result) => (result.status === "rejected" ? String(result.reason?.message ?? result.reason) : "")).join("\n");
+ knownBusy.value = next.some(isStarRocksAlterJobActive) || (!!failures.length && wasBusy);
+ checkedAt.value = new Date().toLocaleTimeString();
+ emit("busy", busy.value);
+ const newTerminalJob = awaitingUntil > 0 && next.some((job) => !isStarRocksAlterJobActive(job) && !submittedBaseline.has(`${job.kind}:${job.id}:${job.state}`));
+ if (!failures.length && !busy.value && (wasBusy || newTerminalJob)) {
+ awaitingUntil = 0;
+ emit("completed");
+ }
+ } catch (cause) {
+ if (request !== generation) return;
+ error.value = String(cause);
+ } finally {
+ if (request === generation) {
+ checking.value = false;
+ if (active && !props.paused && (busy.value || Date.now() < awaitingUntil)) timer = setTimeout(() => void refresh(), 3000);
+ }
+ }
+}
+watch(
+ () => [props.connectionId, props.database, props.tableName, props.schema, props.catalog],
+ () => {
+ stop();
+ expandedJob.value = undefined;
+ submissionJobIds.value = [];
+ jobs.value = [];
+ knownBusy.value = false;
+ error.value = "";
+ checkedAt.value = "";
+ awaitingUntil = 0;
+ emit("busy", false);
+ void refresh();
+ },
+ { immediate: true },
+);
+watch(
+ () => [props.paused, props.revision],
+ ([paused, revision], previous) => {
+ stop();
+ if (revision !== previous?.[1]) {
+ awaitingUntil = Date.now() + 30000;
+ submissionExistingIds = new Set(jobs.value.map(jobKey));
+ submissionJobIds.value = [];
+ submittedBaseline = new Set(jobs.value.map((job) => `${job.kind}:${job.id}:${job.state}`));
+ }
+ if (!paused) void refresh();
+ },
+);
+onActivated(() => {
+ active = true;
+ void refresh();
+});
+onDeactivated(() => {
+ active = false;
+ stop();
+});
+onBeforeUnmount(() => {
+ active = false;
+ stop();
+});
+</script>
+<template>
+ <div class="shrink-0 rounded-md border bg-muted/20 text-xs" data-starrocks-alter-status>
+ <div class="flex flex-wrap items-center gap-2 px-3 py-2" role="status" aria-live="polite">
+ <span class="h-2 w-2 rounded-full" :class="error ? 'bg-destructive' : busy ? 'bg-primary animate-pulse' : 'bg-emerald-500'" />
+ <span class="font-medium">{{ t("starrocksStatus.label") }} · {{ title }}</span>
+ <span v-if="!error && busy && current?.progress !== undefined">{{ current.progress }}%</span>
+ <span class="text-muted-foreground">{{ busy ? t("starrocksStatus.polling") : checkedAt ? t("starrocksStatus.checkedAt", { time: checkedAt }) : "" }}</span>
+ <div class="ml-auto flex gap-1">
+ <Button variant="ghost" size="sm" :aria-expanded="expanded" @click="expanded = !expanded">{{ t("starrocksStatus.details") }}</Button>
+ <Button variant="ghost" size="sm" :disabled="checking || paused" @click="refresh">{{ t("starrocksStatus.refresh") }}</Button>
+ </div>
+ </div>
+ <div v-if="expanded" class="max-h-48 overflow-auto border-t px-3 py-2">
+ <p v-if="busy" class="mb-2 text-muted-foreground">{{ t("starrocksStatus.busyHint") }}</p>
+ <p v-if="!busy && dirty" class="mb-2 text-muted-foreground">{{ t("starrocksStatus.draftHint") }}</p>
+ <p v-if="error" class="mb-2 whitespace-pre-wrap break-words text-destructive">{{ t("starrocksStatus.failureHint") }}<br />{{ error }}</p>
+ <p v-if="!unfinished.length && !error" class="text-muted-foreground">{{ t("starrocksStatus.noJobs") }}</p>
+ <div v-for="job in unfinished" :key="jobKey(job)" class="mt-1 overflow-hidden rounded-md border">
+ <button type="button" class="flex w-full items-center gap-3 px-3 py-2 text-left hover:bg-muted/50" :aria-expanded="expandedJob === jobKey(job)" @click="expandedJob = expandedJob === jobKey(job) ? undefined : jobKey(job)">
+ <span aria-hidden="true">{{ expandedJob === jobKey(job) ? "▾" : "▸" }}</span>
+ <span>{{ job.kind }} #{{ job.id }}</span>
+ <span>{{ stateLabel(job.state) }}{{ job.progress !== undefined ? ` · ${job.progress}%` : "" }}</span>
+ <span class="ml-auto text-muted-foreground">{{ job.created }}</span>
+ </button>
+ <div v-if="expandedJob === jobKey(job)" class="border-t bg-background/50 px-3 py-2" data-starrocks-job-sql>
+ <p v-if="job.message" class="mb-2 break-words text-muted-foreground">{{ job.message }}</p>
+ <p class="mb-1 text-muted-foreground">{{ job.sql ? t("starrocksStatus.sql") : localSqlForJob(job) ? t("starrocksStatus.localSql") : t("starrocksStatus.sqlUnavailable") }}</p>
+ <pre v-if="job.sql || localSqlForJob(job)" class="select-text whitespace-pre-wrap break-words rounded bg-muted/40 p-2 font-mono leading-5">{{ job.sql || localSqlForJob(job) }}</pre>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/structure/StarRocksLayoutCopyDialog.vue b/apps/desktop/src/components/structure/StarRocksLayoutCopyDialog.vue
new file mode 100644
index 0000000000..a3f5a88b4c
--- /dev/null
+++ b/apps/desktop/src/components/structure/StarRocksLayoutCopyDialog.vue
@@ -0,0 +1,208 @@
+<script setup lang="ts">
+import { computed, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import StarRocksPhysicalOptionsEditor from "./StarRocksPhysicalOptionsEditor.vue";
+import { createColumnDrafts } from "@/lib/table/tableStructureEditorState";
+import { buildStarRocksDialectOptions, emptyStarRocksPhysicalOptions } from "@/lib/table/starrocksPhysicalOptions";
+import { starRocksAlterOptionsFromDdl, type StarRocksAlterOptions } from "@/lib/table/starrocksAlterOptions";
+import { buildStarRocksLayoutCopyDdl, executeStarRocksCopyPlan, starRocksCopyInsertColumns, type StarRocksCopyPlan, type StarRocksCopyStage } from "@/lib/table/starrocksLayoutCopy";
+import { formatDdlForDisplay } from "@/lib/sql/ddlDisplay";
+import { loadObjectDdl } from "@/lib/metadata/objectDdlCache";
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+import * as api from "@/lib/backend/api";
+
+const props = defineProps<{ open: boolean; connectionId: string; database: string; schema?: string; catalog?: string; tableName: string; serverVersion?: string; timeoutSecs?: number; authorize: (sql: string) => Promise<boolean> }>();
+const emit = defineEmits<{ "update:open": [open: boolean]; created: [tableName: string] }>();
+const { t } = useI18n();
+const targetName = ref("");
+const transferData = ref(false);
+const keepPartition = ref(true);
+const physical = ref(emptyStarRocksPhysicalOptions());
+const columns = ref<EditableStructureColumn[]>([]);
+const sourceDdl = ref("");
+const context = ref<StarRocksAlterOptions>();
+const plan = ref<StarRocksCopyPlan>();
+const preview = ref("");
+const warnings = ref<string[]>([]);
+const error = ref("");
+const loading = ref(false);
+const previewLoading = ref(false);
+const running = ref(false);
+const attempted = ref(false);
+const stage = ref<StarRocksCopyStage>();
+let loadRequest = 0;
+let previewRequest = 0;
+const locked = computed(() => loading.value || running.value || attempted.value);
+const canSubmit = computed(() => !!plan.value && !locked.value && !previewLoading.value && !warnings.value.length && !error.value);
+function close(open: boolean) {
+ if (!running.value) emit("update:open", open);
+}
+function preventDismiss(event: Event) {
+ if (running.value) event.preventDefault();
+}
+
+watch(
+ [() => props.open, () => props.connectionId, () => props.database, () => props.schema, () => props.tableName, () => props.catalog],
+ async ([open]) => {
+ if (running.value) return;
+ loadRequest++;
+ previewRequest++;
+ if (!open) return;
+ loading.value = true;
+ attempted.value = false;
+ stage.value = undefined;
+ plan.value = undefined;
+ preview.value = "";
+ error.value = "";
+ warnings.value = [];
+ columns.value = [];
+ sourceDdl.value = "";
+ context.value = undefined;
+ targetName.value = `${props.tableName}_layout`;
+ transferData.value = false;
+ keepPartition.value = true;
+ physical.value = emptyStarRocksPhysicalOptions();
+ const id = loadRequest;
+ try {
+ const [ddl, metadata] = await Promise.all([
+ loadObjectDdl({ connectionId: props.connectionId, database: props.database, schema: props.schema ?? props.database, tableName: props.tableName, catalog: props.catalog }, { force: true }),
+ api.getColumns(props.connectionId, props.database, props.schema ?? props.database, props.tableName, props.catalog),
+ ]);
+ if (id !== loadRequest) return;
+ context.value = starRocksAlterOptionsFromDdl(ddl.ddl, props.serverVersion);
+ if (!context.value.model || !context.value.distribution) throw new Error(t("starrocksLayout.copyMetadataUnavailable"));
+ sourceDdl.value = ddl.ddl;
+ columns.value = createColumnDrafts(metadata, "starrocks").map((column) => ({
+ ...column,
+ // Used only by the layout validator. The copied source DDL keeps its actual key model.
+ isPrimaryKey: context.value!.model !== "duplicate" && context.value!.keyColumns.some((name) => name.toLowerCase() === column.name.toLowerCase()),
+ }));
+ physical.value = {
+ ...emptyStarRocksPhysicalOptions(),
+ distribution: context.value.distribution.method,
+ distributionColumnIds: context.value.distribution.columns.map((name) => columns.value.find((column) => column.name === name)?.id ?? name),
+ bucketCount: context.value.distribution.buckets?.toString() ?? "",
+ };
+ } catch (e) {
+ if (id === loadRequest) error.value = e instanceof Error ? e.message : String(e);
+ } finally {
+ if (id === loadRequest) loading.value = false;
+ }
+ },
+ { immediate: true },
+);
+
+async function refreshPreview() {
+ const id = ++previewRequest;
+ if (!props.open || loading.value || running.value || attempted.value || !sourceDdl.value) return;
+ plan.value = undefined;
+ previewLoading.value = true;
+ warnings.value = [];
+ error.value = "";
+ try {
+ const target = targetName.value.trim();
+ if (!target || target.toLowerCase() === props.tableName.toLowerCase() || target.includes("\0")) throw new Error(t("starrocksLayout.copyNameRequired"));
+ const result = await api.buildCreateTableSql({ databaseType: "starrocks", tableName: target, schema: props.schema, columns: columns.value, indexes: [], foreignKeys: [], triggers: [], tableComment: "", partitioned: false }, props.serverVersion, buildStarRocksDialectOptions(physical.value));
+ if (id !== previewRequest) return;
+ if (result.warnings.length || result.statements.length !== 1) {
+ warnings.value = result.warnings;
+ return;
+ }
+ const createSql = buildStarRocksLayoutCopyDdl(sourceDdl.value, result.statements[0]!, props.database, target, keepPartition.value);
+ const insertColumns = starRocksCopyInsertColumns(sourceDdl.value, columns.value);
+ if (transferData.value && !insertColumns.length) throw new Error(t("starrocksLayout.copyNoInsertColumns"));
+ const copySql = transferData.value ? await api.buildCopyTableDataSql({ databaseType: "starrocks", schema: props.database, sourceName: props.tableName, targetName: target, columns: insertColumns }) : undefined;
+ if (id !== previewRequest) return;
+ // A statement-local setting avoids leaking strict-mode changes into pooled sessions.
+ const insertSql = copySql?.replace(/^INSERT\s+/i, "INSERT /*+ SET_VAR(enable_insert_strict=true) */ ");
+ const formatted = await formatDdlForDisplay(createSql, { dialect: "mysql", databaseType: "starrocks", includeDatabaseName: true, database: props.database, quoteIdentifiers: true });
+ if (id !== previewRequest) return;
+ plan.value = { createSql, insertSql, targetName: target };
+ preview.value = formatted + (insertSql ? "\n\n" + insertSql : "");
+ } catch (e) {
+ if (id === previewRequest) error.value = e instanceof Error ? e.message : String(e);
+ } finally {
+ if (id === previewRequest) previewLoading.value = false;
+ }
+}
+
+watch(
+ [targetName, transferData, keepPartition, physical, sourceDdl, columns],
+ () => {
+ void refreshPreview();
+ },
+ { deep: true },
+);
+watch(loading, (value) => {
+ if (!value) void refreshPreview();
+});
+
+async function submit() {
+ if (!canSubmit.value || !plan.value) return;
+ const snapshot = { ...plan.value };
+ const connectionId = props.connectionId;
+ const database = props.database;
+ const schema = props.schema;
+ const timeout = props.timeoutSecs === 0 ? 0 : Math.max(props.timeoutSecs ?? 0, 3600);
+ let created = false;
+ running.value = true;
+ try {
+ if (!(await props.authorize([snapshot.createSql, snapshot.insertSql].filter(Boolean).join("\n")))) return;
+ attempted.value = true;
+ await executeStarRocksCopyPlan(
+ snapshot,
+ (sql) => api.executeBatch(connectionId, database, [sql], schema, timeout, false),
+ (value) => {
+ stage.value = value;
+ if (value === "created") created = true;
+ },
+ );
+ } catch (e) {
+ const message = e instanceof Error ? e.message : String(e);
+ error.value = t(stage.value === "transferring" || stage.value === "created" ? "starrocksLayout.copyTransferFailed" : "starrocksLayout.copyCreateFailed", { table: snapshot.targetName, message });
+ } finally {
+ running.value = false;
+ if (created) emit("created", snapshot.targetName);
+ }
+}
+</script>
+<template>
+ <Dialog :open="open" @update:open="close">
+ <DialogContent data-starrocks-layout-copy-dialog class="flex max-h-[90vh] flex-col sm:max-w-[900px]" :show-close-button="!running" @escape-key-down="preventDismiss" @interact-outside="preventDismiss">
+ <DialogHeader
+ ><DialogTitle>{{ t("starrocksLayout.copyTitle") }}</DialogTitle></DialogHeader
+ >
+ <div class="min-h-0 space-y-3 overflow-y-auto">
+ <p class="text-sm text-muted-foreground">{{ t("starrocksLayout.copyHint", { table: tableName }) }}</p>
+ <p v-if="loading" class="text-sm">{{ t("starrocksLayout.copyLoading") }}</p>
+ <label class="block space-y-1"
+ ><span>{{ t("starrocksLayout.copyTargetName") }}</span
+ ><Input v-model="targetName" :disabled="locked"
+ /></label>
+ <label class="flex items-center gap-2 text-sm"><input v-model="transferData" type="checkbox" :disabled="locked" />{{ t("starrocksLayout.copyTransferData") }}</label>
+ <p v-if="transferData" class="text-xs text-muted-foreground">{{ t("starrocksLayout.copyTransferHint") }}</p>
+ <label class="flex items-center gap-2 text-sm"><input v-model="keepPartition" type="checkbox" :disabled="locked" />{{ t("starrocksLayout.copyKeepPartition") }}</label>
+ <pre v-if="keepPartition && context?.partitionClause" class="overflow-auto whitespace-pre-wrap rounded border p-2 text-xs">{{ context.partitionClause }}</pre>
+ <StarRocksPhysicalOptionsEditor v-if="sourceDdl" v-model="physical" :columns="columns" :server-version="serverVersion" :disabled="locked" :hide-partition="keepPartition" hide-sorting />
+ <p v-if="context?.colocated" class="text-xs text-muted-foreground">{{ t("starrocksLayout.copyColocationHint") }}</p>
+ <p v-if="!keepPartition" class="text-xs text-muted-foreground">{{ t("starrocksLayout.copyPartitionHint") }}</p>
+ <p v-if="stage && !error" class="text-sm" role="status">{{ t(`starrocksLayout.copyStage_${stage}`, { table: plan?.targetName }) }}</p>
+ <p v-if="error" class="whitespace-pre-wrap text-sm text-destructive" role="alert">{{ error }}</p>
+ <ul v-if="warnings.length" class="space-y-1 text-sm text-amber-600">
+ <li v-for="warning in warnings" :key="warning">{{ warning }}</li>
+ </ul>
+ <details v-if="preview" open>
+ <summary class="cursor-pointer text-sm">{{ t("structureEditor.sqlPreview") }}</summary>
+ <pre class="mt-2 max-h-64 overflow-auto whitespace-pre-wrap rounded border bg-muted/20 p-3 text-xs">{{ preview }}</pre>
+ </details>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" :disabled="running" @click="close(false)">{{ t("common.close") }}</Button>
+ <Button :disabled="!canSubmit" @click="submit">{{ running ? t("starrocksLayout.copyRunning") : t("starrocksLayout.copyExecute") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+</template>
diff --git a/apps/desktop/src/components/structure/StarRocksPartitionOptionsEditor.vue b/apps/desktop/src/components/structure/StarRocksPartitionOptionsEditor.vue
new file mode 100644
index 0000000000..b8b98c1f6b
--- /dev/null
+++ b/apps/desktop/src/components/structure/StarRocksPartitionOptionsEditor.vue
@@ -0,0 +1,189 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { uuid } from "@/lib/common/utils";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import StructureColumnMultiSelect from "./StructureColumnMultiSelect.vue";
+import { getStarRocksCapabilities } from "@/lib/table/starrocksCapabilities";
+import { isStarRocksTimeColumn, isStarRocksPartitionColumn, type StarRocksPhysicalOptionsDraft, type StarRocksPartitionKind } from "@/lib/table/starrocksPhysicalOptions";
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+const props = defineProps<{ modelValue: StarRocksPhysicalOptionsDraft; columns: EditableStructureColumn[]; serverVersion?: string; disabled?: boolean }>();
+const emit = defineEmits<{ "update:modelValue": [value: StarRocksPhysicalOptionsDraft] }>();
+const { t } = useI18n();
+const caps = computed(() => getStarRocksCapabilities(props.serverVersion));
+const timeColumns = computed(() => props.columns.filter(isStarRocksTimeColumn));
+const eligible = computed(() => props.columns.filter((column) => isStarRocksPartitionColumn(column, props.modelValue.partitionKind === "range") && (props.modelValue.partitionKind !== "time" || column.id !== props.modelValue.partitionColumnId)));
+const selected = computed(() => props.modelValue.partitionColumnIds.map((id) => ({ id, name: props.columns.find((column) => column.id === id)?.name ?? t("starrocksLayout.unavailableColumn") })));
+const missingTime = computed(() => !!props.modelValue.partitionColumnId && !timeColumns.value.some((column) => column.id === props.modelValue.partitionColumnId));
+function update<K extends keyof StarRocksPhysicalOptionsDraft>(key: K, value: StarRocksPhysicalOptionsDraft[K]) {
+ emit("update:modelValue", { ...props.modelValue, [key]: value });
+}
+function setKind(kind: StarRocksPartitionKind) {
+ emit("update:modelValue", { ...props.modelValue, partitionKind: kind, timePartitionEnabled: kind === "time" });
+}
+function addRange() {
+ update("rangePartitions", [...props.modelValue.rangePartitions, { id: uuid(), name: `p${props.modelValue.rangePartitions.length + 1}`, lower: {}, upper: {} }]);
+}
+function rangeField(index: number, side: "lower" | "upper", id: string, value: string) {
+ update(
+ "rangePartitions",
+ props.modelValue.rangePartitions.map((row, i) => (i === index ? { ...row, [side]: { ...row[side], [id]: value } } : row)),
+ );
+}
+function addList() {
+ update("listPartitions", [...props.modelValue.listPartitions, { id: uuid(), name: `p${props.modelValue.listPartitions.length + 1}`, values: [{ id: uuid(), fields: {} }] }]);
+}
+function listField(index: number, tupleIndex: number, id: string, value: string) {
+ update(
+ "listPartitions",
+ props.modelValue.listPartitions.map((row, i) => (i === index ? { ...row, values: row.values.map((tuple, j) => (j === tupleIndex ? { ...tuple, fields: { ...tuple.fields, [id]: value } } : tuple)) } : row)),
+ );
+}
+function addTuple(index: number) {
+ update(
+ "listPartitions",
+ props.modelValue.listPartitions.map((row, i) => (i === index ? { ...row, values: [...row.values, { id: uuid(), fields: {} }] } : row)),
+ );
+}
+function removeTuple(index: number, tupleIndex: number) {
+ update(
+ "listPartitions",
+ props.modelValue.listPartitions.map((row, i) => (i === index ? { ...row, values: row.values.filter((_, j) => j !== tupleIndex) } : row)),
+ );
+}
+</script>
+<template>
+ <section class="space-y-2" data-starrocks-partitions>
+ <div class="flex flex-wrap items-end gap-3">
+ <div class="space-y-1">
+ <span class="block text-muted-foreground">{{ t("starrocksLayout.partitionStrategy") }}</span>
+ <Select :model-value="modelValue.partitionKind" :disabled="disabled" @update:model-value="setKind($event as StarRocksPartitionKind)">
+ <SelectTrigger class="h-8 w-52" :aria-label="t('starrocksLayout.partitionStrategy')"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">{{ t("starrocksLayout.none") }}</SelectItem>
+ <SelectItem value="time" :disabled="!caps.timePartitioning">{{ t("starrocksLayout.time") }}</SelectItem>
+ <SelectItem value="values" :disabled="!caps.valuePartitioning">{{ t("starrocksLayout.values") }}</SelectItem>
+ <SelectItem value="range">{{ t("starrocksLayout.range") }}</SelectItem>
+ <SelectItem value="list" :disabled="!caps.valuePartitioning">{{ t("starrocksLayout.list") }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <template v-if="modelValue.partitionKind === 'time'">
+ <div class="space-y-1">
+ <span class="block text-muted-foreground">{{ t("starrocksLayout.partitionColumn") }}</span>
+ <Select :model-value="modelValue.partitionColumnId" :disabled="disabled" @update:model-value="update('partitionColumnId', String($event))">
+ <SelectTrigger class="h-8 w-40" :aria-label="t('starrocksLayout.partitionColumn')"><SelectValue :placeholder="t('starrocksLayout.selectColumn')" /></SelectTrigger>
+ <SelectContent
+ ><SelectItem v-if="missingTime" :value="modelValue.partitionColumnId" disabled>{{ t("starrocksLayout.unavailableColumn") }}</SelectItem
+ ><SelectItem v-for="column in timeColumns" :key="column.id" :value="column.id">{{ column.name }}</SelectItem></SelectContent
+ >
+ </Select>
+ </div>
+ <div class="space-y-1">
+ <span class="block text-muted-foreground">{{ t("starrocksLayout.granularity") }}</span>
+ <Select :model-value="modelValue.granularity" :disabled="disabled" @update:model-value="update('granularity', $event as StarRocksPhysicalOptionsDraft['granularity'])">
+ <SelectTrigger class="h-8 w-24" :aria-label="t('starrocksLayout.granularity')"><SelectValue /></SelectTrigger>
+ <SelectContent
+ ><SelectItem v-for="unit in ['year', 'month', 'day', 'hour'] as const" :key="unit" :value="unit">{{ t(`starrocksLayout.${unit}`) }}</SelectItem></SelectContent
+ >
+ </Select>
+ </div>
+ <label class="space-y-1"
+ ><span class="block text-muted-foreground">{{ t("starrocksLayout.timeInterval") }}</span
+ ><Input :model-value="modelValue.timeInterval" type="number" min="1" step="1" class="h-8 w-32" :placeholder="t('starrocksLayout.calendarUnit')" :disabled="disabled" @update:model-value="update('timeInterval', String($event ?? ''))"
+ /></label>
+ </template>
+ <StructureColumnMultiSelect
+ v-if="modelValue.partitionKind !== 'none' && (modelValue.partitionKind !== 'time' || caps.mixedPartitioning || modelValue.partitionColumnIds.length)"
+ :model-value="modelValue.partitionColumnIds"
+ :columns="eligible"
+ :label="t(modelValue.partitionKind === 'time' ? 'starrocksLayout.additionalColumns' : 'starrocksLayout.partitionColumns')"
+ :disabled="disabled"
+ @update:model-value="update('partitionColumnIds', $event)"
+ />
+ </div>
+ <p class="text-xs text-muted-foreground">{{ t(`starrocksLayout.${modelValue.partitionKind}Hint`) }}</p>
+ <p v-if="modelValue.partitionKind === 'time'" class="text-xs text-muted-foreground">{{ t("starrocksLayout.timeIntervalHint") }}</p>
+ <p v-if="modelValue.partitionKind === 'time' && timeColumns.length === 0" class="text-xs text-destructive">{{ t("starrocksLayout.noTimeColumn") }}</p>
+ <p v-if="(modelValue.partitionKind === 'time' && missingTime) || (modelValue.partitionKind !== 'none' && selected.some((column) => !eligible.some((item) => item.id === column.id)))" class="text-xs text-destructive">{{ t("starrocksLayout.invalidSelection") }}</p>
+ <template v-if="modelValue.partitionKind === 'range'">
+ <div v-for="(row, i) in modelValue.rangePartitions" :key="row.id" class="space-y-2 rounded border p-2">
+ <div class="flex items-center gap-2">
+ <Input
+ :model-value="row.name"
+ class="h-8 w-40"
+ :aria-label="t('starrocksLayout.partitionName')"
+ :placeholder="t('starrocksLayout.partitionName')"
+ :disabled="disabled"
+ @update:model-value="
+ update(
+ 'rangePartitions',
+ modelValue.rangePartitions.map((item, j) => (j === i ? { ...item, name: String($event) } : item)),
+ )
+ "
+ /><Button
+ variant="ghost"
+ size="sm"
+ :disabled="disabled"
+ @click="
+ update(
+ 'rangePartitions',
+ modelValue.rangePartitions.filter((_, j) => j !== i),
+ )
+ "
+ >{{ t("starrocksLayout.removePartition") }}</Button
+ >
+ </div>
+ <div v-for="side in ['lower', 'upper'] as const" :key="side" class="flex flex-wrap items-end gap-2">
+ <span class="w-28 shrink-0 pb-1 text-muted-foreground">{{ t(`starrocksLayout.${side}`) }}</span>
+ <label v-for="column in selected" :key="column.id" class="space-y-1"
+ ><span class="block text-xs">{{ column.name }}</span
+ ><Input :model-value="row[side][column.id] ?? ''" class="h-8 w-44" :disabled="disabled" :placeholder="t('starrocksLayout.valuePlaceholder')" @update:model-value="rangeField(i, side, column.id, String($event))"
+ /></label>
+ </div>
+ </div>
+ <Button variant="outline" size="sm" :disabled="disabled || selected.length === 0" @click="addRange">{{ t("starrocksLayout.addPartition") }}</Button>
+ </template>
+ <template v-if="modelValue.partitionKind === 'list'">
+ <div v-for="(row, i) in modelValue.listPartitions" :key="row.id" class="space-y-2 rounded border p-2">
+ <div class="flex items-center gap-2">
+ <Input
+ :model-value="row.name"
+ class="h-8 w-40"
+ :aria-label="t('starrocksLayout.partitionName')"
+ :placeholder="t('starrocksLayout.partitionName')"
+ :disabled="disabled"
+ @update:model-value="
+ update(
+ 'listPartitions',
+ modelValue.listPartitions.map((item, j) => (j === i ? { ...item, name: String($event) } : item)),
+ )
+ "
+ /><Button
+ variant="ghost"
+ size="sm"
+ :disabled="disabled"
+ @click="
+ update(
+ 'listPartitions',
+ modelValue.listPartitions.filter((_, j) => j !== i),
+ )
+ "
+ >{{ t("starrocksLayout.removePartition") }}</Button
+ >
+ </div>
+ <div v-for="(tuple, j) in row.values" :key="tuple.id" class="flex flex-wrap items-end gap-2">
+ <label v-for="column in selected" :key="column.id" class="space-y-1"
+ ><span class="block text-xs">{{ column.name }}</span
+ ><Input :model-value="tuple.fields[column.id] ?? ''" class="h-8 w-44" :disabled="disabled" :placeholder="t('starrocksLayout.valuePlaceholder')" @update:model-value="listField(i, j, column.id, String($event))"
+ /></label>
+ <Button variant="ghost" size="sm" :disabled="disabled" @click="removeTuple(i, j)">{{ t("starrocksLayout.removeValues") }}</Button>
+ </div>
+ <Button variant="outline" size="sm" :disabled="disabled || selected.length === 0" @click="addTuple(i)">{{ t("starrocksLayout.addValues") }}</Button>
+ </div>
+ <Button variant="outline" size="sm" :disabled="disabled || selected.length === 0" @click="addList">{{ t("starrocksLayout.addPartition") }}</Button>
+ </template>
+ </section>
+</template>
diff --git a/apps/desktop/src/components/structure/StarRocksPhysicalOptionsEditor.vue b/apps/desktop/src/components/structure/StarRocksPhysicalOptionsEditor.vue
new file mode 100644
index 0000000000..26aab512bc
--- /dev/null
+++ b/apps/desktop/src/components/structure/StarRocksPhysicalOptionsEditor.vue
@@ -0,0 +1,96 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import StructureColumnMultiSelect from "./StructureColumnMultiSelect.vue";
+import StarRocksPartitionOptionsEditor from "./StarRocksPartitionOptionsEditor.vue";
+import { getStarRocksCapabilities } from "@/lib/table/starrocksCapabilities";
+import { isStarRocksHashColumn, isStarRocksSortColumn, type StarRocksPhysicalOptionsDraft } from "@/lib/table/starrocksPhysicalOptions";
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+const props = defineProps<{ modelValue: StarRocksPhysicalOptionsDraft; columns: EditableStructureColumn[]; serverVersion?: string; disabled?: boolean; hidePartition?: boolean; hideSorting?: boolean }>();
+const emit = defineEmits<{ "update:modelValue": [value: StarRocksPhysicalOptionsDraft] }>();
+const { t } = useI18n();
+const capabilities = computed(() => getStarRocksCapabilities(props.serverVersion));
+const activeColumns = computed(() => props.columns.filter((column) => !column.markedForDrop && !!column.name.trim()));
+const hasPrimaryKey = computed(() => activeColumns.value.some((column) => column.isPrimaryKey));
+const hashColumns = computed(() => activeColumns.value.filter(isStarRocksHashColumn));
+const sortColumns = computed(() => activeColumns.value.filter((column) => isStarRocksSortColumn(column, hasPrimaryKey.value)));
+const supportsSorting = computed(() => (hasPrimaryKey.value ? capabilities.value.primaryKeySorting : capabilities.value.duplicateKeySorting));
+function moveSortColumn(index: number, offset: number) {
+ const ids = [...props.modelValue.sortColumnIds];
+ const target = index + offset;
+ if (target < 0 || target >= ids.length) return;
+ [ids[index], ids[target]] = [ids[target]!, ids[index]!];
+ update("sortColumnIds", ids);
+}
+const primaryKeyConflict = computed(() => {
+ if (!hasPrimaryKey.value) return false;
+ const draft = props.modelValue;
+ const partitionIds = draft.partitionKind === "none" ? [] : [...draft.partitionColumnIds, ...(draft.partitionKind === "time" ? [draft.partitionColumnId] : [])];
+ const ids = [...partitionIds, ...(draft.distribution === "hash" ? draft.distributionColumnIds : [])];
+ return draft.distribution === "random" || activeColumns.value.some((column) => ids.includes(column.id) && !column.isPrimaryKey);
+});
+function update<K extends keyof StarRocksPhysicalOptionsDraft>(key: K, value: StarRocksPhysicalOptionsDraft[K]) {
+ emit("update:modelValue", { ...props.modelValue, [key]: value });
+}
+</script>
+<template>
+ <details open class="shrink-0 rounded-md border bg-muted/10 px-3 py-2" data-starrocks-physical-options>
+ <summary class="cursor-pointer font-medium">{{ t(hideSorting ? "starrocksLayout.partitionAndBucketTitle" : "starrocksLayout.title") }}</summary>
+ <div class="mt-2 max-h-72 space-y-3 overflow-y-auto pr-1">
+ <StarRocksPartitionOptionsEditor v-if="!hidePartition" :model-value="modelValue" :columns="activeColumns" :server-version="serverVersion" :disabled="disabled" @update:model-value="emit('update:modelValue', $event)" />
+ <section class="space-y-2 border-t pt-2" data-starrocks-buckets>
+ <div class="flex flex-wrap items-end gap-3">
+ <div class="space-y-1">
+ <span class="block text-muted-foreground">{{ t("starrocksLayout.distribution") }}</span>
+ <Select :model-value="modelValue.distribution" :disabled="disabled" @update:model-value="update('distribution', $event as StarRocksPhysicalOptionsDraft['distribution'])">
+ <SelectTrigger class="h-8 w-36" :aria-label="t('starrocksLayout.distribution')"><SelectValue /></SelectTrigger>
+ <SelectContent
+ ><SelectItem value="auto">{{ t("starrocksLayout.auto") }}</SelectItem
+ ><SelectItem value="hash">{{ t("starrocksLayout.hash") }}</SelectItem
+ ><SelectItem value="random" :disabled="hasPrimaryKey || !capabilities.randomDistribution">{{ t("starrocksLayout.random") }}</SelectItem></SelectContent
+ >
+ </Select>
+ </div>
+ <StructureColumnMultiSelect v-if="modelValue.distribution === 'hash'" :model-value="modelValue.distributionColumnIds" :columns="hashColumns" :label="t('starrocksLayout.hashColumns')" :disabled="disabled" @update:model-value="update('distributionColumnIds', $event)" />
+ <label class="space-y-1"
+ ><span class="block text-muted-foreground">{{ t("starrocksLayout.bucketCount") }}</span
+ ><Input :model-value="modelValue.bucketCount" type="number" min="1" max="2147483647" step="1" class="h-8 w-28" :placeholder="t('starrocksLayout.auto')" :disabled="disabled" @update:model-value="update('bucketCount', String($event ?? ''))"
+ /></label>
+ </div>
+ <p class="text-xs text-muted-foreground">{{ t("starrocksLayout.bucketCountHint") }}</p>
+ <p class="text-xs text-muted-foreground">{{ modelValue.distribution === "auto" ? t(hasPrimaryKey ? "starrocksLayout.autoPrimaryHint" : "starrocksLayout.autoDuplicateHint") : t("starrocksLayout.bucketHint") }}</p>
+ </section>
+ <section v-if="!hideSorting" class="space-y-2 border-t pt-2" data-starrocks-sort>
+ <StructureColumnMultiSelect :model-value="modelValue.sortColumnIds" :columns="sortColumns" :label="t('starrocksLayout.sortColumns')" :disabled="disabled || !supportsSorting" @update:model-value="update('sortColumnIds', $event)" />
+ <ol v-if="modelValue.sortColumnIds.length" class="space-y-1">
+ <li v-for="(id, index) in modelValue.sortColumnIds" :key="id" class="flex items-center gap-2">
+ <span class="min-w-0 truncate">{{ index + 1 }}. {{ activeColumns.find((column) => column.id === id)?.name ?? t("starrocksLayout.missingSortColumn") }}</span>
+ <Button type="button" variant="ghost" size="sm" :disabled="disabled || index === 0" :aria-label="t('starrocksLayout.moveSortUp')" @click="moveSortColumn(index, -1)">↑</Button>
+ <Button type="button" variant="ghost" size="sm" :disabled="disabled || index === modelValue.sortColumnIds.length - 1" :aria-label="t('starrocksLayout.moveSortDown')" @click="moveSortColumn(index, 1)">↓</Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ :disabled="disabled"
+ :aria-label="t('starrocksLayout.removeSortColumn')"
+ @click="
+ update(
+ 'sortColumnIds',
+ modelValue.sortColumnIds.filter((value) => value !== id),
+ )
+ "
+ >×</Button
+ >
+ </li>
+ </ol>
+ <p class="text-xs text-muted-foreground">{{ t("starrocksLayout.sortHint") }}</p>
+ <p v-if="!supportsSorting" class="text-xs text-amber-600">{{ t("starrocksLayout.sortVersionHint") }}</p>
+ </section>
+ <p v-if="hasPrimaryKey" class="text-xs" :class="primaryKeyConflict ? 'text-destructive' : 'text-muted-foreground'">{{ t("starrocksLayout.primaryKeyHint") }}</p>
+ <p v-if="!capabilities.timePartitioning" class="text-xs text-amber-600">{{ t("starrocksLayout.versionHint") }}</p>
+ </div>
+ </details>
+</template>
diff --git a/apps/desktop/src/components/structure/StarRocksSortKeyEditor.vue b/apps/desktop/src/components/structure/StarRocksSortKeyEditor.vue
new file mode 100644
index 0000000000..58e2f707ee
--- /dev/null
+++ b/apps/desktop/src/components/structure/StarRocksSortKeyEditor.vue
@@ -0,0 +1,67 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import StructureColumnMultiSelect from "./StructureColumnMultiSelect.vue";
+import { getStarRocksCapabilities } from "@/lib/table/starrocksCapabilities";
+import { isStarRocksSortColumn } from "@/lib/table/starrocksPhysicalOptions";
+import type { StarRocksAlterOptions } from "@/lib/table/starrocksAlterOptions";
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+const props = defineProps<{ modelValue: string[]; context?: StarRocksAlterOptions; columns: EditableStructureColumn[]; disabled?: boolean }>();
+const emit = defineEmits<{ "update:modelValue": [names: string[]] }>();
+const { t } = useI18n();
+const available = computed(() =>
+ props.columns
+ .filter(
+ (column) =>
+ column.original &&
+ !column.markedForDrop &&
+ isStarRocksSortColumn(column, props.context?.model === "primary") &&
+ !/^(json|array|map|struct|bitmap|hll|percentile|binary|varbinary)/i.test(column.dataType) &&
+ (!["aggregate", "unique"].includes(props.context?.model ?? "") || props.context?.keyColumns.includes(column.original.name)),
+ )
+ .map((column) => ({ ...column, id: column.original!.name })),
+);
+const supported = computed(() => {
+ if (!props.context?.model) return false;
+ const capabilities = getStarRocksCapabilities(props.context.serverVersion);
+ return props.context.model === "primary" ? capabilities.primaryKeySorting : capabilities.duplicateKeySorting;
+});
+function move(index: number, offset: number) {
+ const names = [...props.modelValue];
+ const target = index + offset;
+ if (target < 0 || target >= names.length) return;
+ [names[index], names[target]] = [names[target]!, names[index]!];
+ emit("update:modelValue", names);
+}
+</script>
+<template>
+ <details class="shrink-0 rounded-md border bg-muted/10 px-3 py-2" data-starrocks-edit-sort>
+ <summary class="cursor-pointer font-medium">{{ t("starrocksLayout.sortColumns") }}</summary>
+ <div class="mt-2 max-h-48 space-y-2 overflow-y-auto">
+ <StructureColumnMultiSelect :model-value="modelValue" :columns="available" :label="t('starrocksLayout.sortColumns')" :disabled="disabled || !supported" @update:model-value="emit('update:modelValue', $event)" />
+ <ol class="space-y-1">
+ <li v-for="(name, index) in modelValue" :key="name" class="flex items-center gap-2 text-xs">
+ <span class="min-w-0 flex-1 truncate">{{ index + 1 }}. {{ available.find((column) => column.id === name)?.name ?? name }}</span>
+ <Button variant="ghost" size="sm" :disabled="disabled || !supported || index === 0" :aria-label="t('starrocksLayout.moveSortUp')" @click="move(index, -1)">↑</Button>
+ <Button variant="ghost" size="sm" :disabled="disabled || !supported || index === modelValue.length - 1" :aria-label="t('starrocksLayout.moveSortDown')" @click="move(index, 1)">↓</Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ :disabled="disabled || !supported"
+ :aria-label="t('starrocksLayout.removeSortColumn')"
+ @click="
+ emit(
+ 'update:modelValue',
+ modelValue.filter((value) => value !== name),
+ )
+ "
+ >×</Button
+ >
+ </li>
+ </ol>
+ <p class="text-xs text-muted-foreground">{{ t("starrocksLayout.editSortHint") }}</p>
+ <p v-if="!supported" class="text-xs text-amber-600">{{ t("starrocksLayout.editSortVersionHint") }}</p>
+ </div>
+ </details>
+</template>
diff --git a/apps/desktop/src/components/structure/StructureColumnMultiSelect.vue b/apps/desktop/src/components/structure/StructureColumnMultiSelect.vue
new file mode 100644
index 0000000000..db01060fc1
--- /dev/null
+++ b/apps/desktop/src/components/structure/StructureColumnMultiSelect.vue
@@ -0,0 +1,32 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { ChevronDown } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+const props = defineProps<{ modelValue: string[]; columns: Array<{ id: string; name: string }>; label: string; disabled?: boolean }>();
+const emit = defineEmits<{ "update:modelValue": [value: string[]] }>();
+const { t } = useI18n();
+const missing = computed(() => props.modelValue.filter((id) => !props.columns.some((column) => column.id === id)));
+const names = computed(() => props.modelValue.map((id) => props.columns.find((column) => column.id === id)?.name ?? t("starrocksLayout.unavailableColumn")).join(", "));
+function setChecked(id: string, checked: boolean) {
+ emit("update:modelValue", checked ? [...props.modelValue.filter((value) => value !== id), id] : props.modelValue.filter((value) => value !== id));
+}
+</script>
+<template>
+ <div class="space-y-1">
+ <span class="block text-muted-foreground">{{ label }}</span>
+ <DropdownMenu>
+ <DropdownMenuTrigger as-child
+ ><Button variant="outline" size="sm" class="h-8 w-52 justify-between font-normal" :disabled="disabled" :aria-label="label"
+ ><span class="truncate">{{ names || t("starrocksLayout.selectColumn") }}</span
+ ><ChevronDown class="size-3.5 shrink-0" /></Button
+ ></DropdownMenuTrigger>
+ <DropdownMenuContent class="max-h-56 min-w-52 overflow-y-auto">
+ <DropdownMenuCheckboxItem v-for="column in columns" :key="column.id" :model-value="modelValue.includes(column.id)" @select.prevent @update:model-value="setChecked(column.id, $event)">{{ column.name }}</DropdownMenuCheckboxItem>
+ <DropdownMenuCheckboxItem v-for="id in missing" :key="id" :model-value="true" @select.prevent @update:model-value="setChecked(id, $event)">{{ t("starrocksLayout.unavailableColumn") }}</DropdownMenuCheckboxItem>
+ <div v-if="columns.length === 0 && missing.length === 0" class="px-2 py-1 text-xs text-muted-foreground">{{ t("starrocksLayout.noEligibleColumns") }}</div>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
index 7ad4d30b74..c1cd0ff3ef 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
+++ b/apps/desktop/src/components/structure/TableStructureEditor.charsetCollation.spec.ts
@@ -336,6 +336,16 @@ afterEach(() => {
});
describe("TableStructureEditor charset/collation column width", () => {
+ it.each(["starrocks", "mysql"])("hides MySQL charset and collation for StarRocks via %s", async (dbType) => {
+ mocks.connection.db_type = dbType;
+ mocks.connection.driver_profile = "starrocks";
+ const root = await mountEditor();
+ const headers = Array.from(root.querySelectorAll("thead th")).map((cell) => cell.textContent?.trim());
+ expect(headers).not.toContain("structureEditor.characterSet");
+ expect(headers).not.toContain("structureEditor.collation");
+ expect(mocks.executeQuery.mock.calls.some((call) => /SHOW (CHARACTER SET|COLLATION)/.test(String(call[2])))).toBe(false);
+ });
+
it("lets the charset trigger fill its resizable column instead of a fixed width cap", async () => {
const root = await mountEditor();
const charsetSelect = searchableSelectInColumn(root, "structureEditor.characterSet");
@@ -522,16 +532,16 @@ describe("TableStructureEditor MySQL creation counter", () => {
expect(input.placeholder).toBe("1");
expect(root.textContent).toContain("structureEditor.mysqlAutoIncrementStartHint");
expect(root.textContent).not.toContain("contextMenu.mysqlAutoIncrementNonemptyHint");
- await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: undefined })));
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: undefined }), undefined, undefined));
input.value = "66";
input.dispatchEvent(new Event("input", { bubbles: true }));
- await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: "66" })));
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: "66" }), undefined, undefined));
const label = Array.from(root.querySelectorAll("label")).find((label) => label.textContent?.includes("structureEditor.autoIncrement"))!;
const checkbox = label.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
checkbox.checked = false;
checkbox.dispatchEvent(new Event("change", { bubbles: true }));
await vi.waitFor(() => expect(root.querySelector("[data-mysql-auto-increment-editor-trigger]")).toBeNull());
- await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: undefined })));
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: undefined }), undefined, undefined));
checkbox.checked = true;
checkbox.dispatchEvent(new Event("change", { bubbles: true }));
await nextTick();
@@ -539,7 +549,7 @@ describe("TableStructureEditor MySQL creation counter", () => {
expect(restored.value).toBe("66");
restored.value = "";
restored.dispatchEvent(new Event("input", { bubbles: true }));
- await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: undefined })));
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: undefined }), undefined, undefined));
expect(mocks.getMysqlTableAutoIncrement).not.toHaveBeenCalled();
expect(mocks.buildMysqlAutoIncrementSql).not.toHaveBeenCalled();
});
@@ -547,7 +557,7 @@ describe("TableStructureEditor MySQL creation counter", () => {
it("restores a creation draft without losing integer precision", async () => {
const value = "18446744073709551615";
const root = await mountEditor(true, undefined, createDraft(value), true);
- await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: value })));
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenCalledWith(expect.objectContaining({ mysqlAutoIncrementValue: value }), undefined, undefined));
expect(root.querySelector<HTMLInputElement>("[data-mysql-auto-increment-counter]")?.value).toBe(value);
expect(mocks.getMysqlTableAutoIncrement).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vue
index c94ae499a5..895610dc56 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.vue
+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue
@@ -1,6 +1,9 @@
<script setup lang="ts">
import { Compartment } from "@codemirror/state";
import { keymap as codeMirrorKeymap } from "@codemirror/view";
+import { getStarRocksCapabilities } from "@/lib/table/starrocksCapabilities";
+import { starRocksAlterOptionsFromDdl, starRocksColumnDefinitionLocked, type StarRocksAlterOptions } from "@/lib/table/starrocksAlterOptions";
+import { getColumnDefaultValuePresets } from "@/lib/table/columnDefaultPresets";
import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
import DdlStorageToggle from "@/components/objects/DdlStorageToggle.vue";
import StructureIndexColumnPicker from "./StructureIndexColumnPicker.vue";
@@ -47,6 +50,11 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigge
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { SearchableSelect } from "@/components/ui/searchable-select";
+import StarRocksAlterStatus from "@/components/structure/StarRocksAlterStatus.vue";
+import StarRocksSortKeyEditor from "@/components/structure/StarRocksSortKeyEditor.vue";
+import StarRocksLayoutCopyDialog from "@/components/structure/StarRocksLayoutCopyDialog.vue";
+import StarRocksPhysicalOptionsEditor from "@/components/structure/StarRocksPhysicalOptionsEditor.vue";
+import { buildStarRocksDialectOptions, emptyStarRocksPhysicalOptions, hasStarRocksPhysicalOptions, restoreStarRocksPhysicalOptions } from "@/lib/table/starrocksPhysicalOptions";
import TablePhysicalOptionsEditor from "@/components/structure/TablePhysicalOptionsEditor.vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import EditorSearchPanel from "@/components/editor/EditorSearchPanel.vue";
@@ -527,6 +535,20 @@ async function fetchDdl(force = false) {
const errorMessage = ref("");
const secondaryMetadataErrors = ref<Partial<Record<ObjectMetadataFacet, string>>>({});
const columns = ref<EditableStructureColumn[]>([]);
+const starrocksStatusBusy = ref(false);
+const starrocksStatusRevision = ref(0);
+const starrocksSubmittedSql = ref<{ target: string; sql: string }>();
+const starrocksStatusTarget = computed(() => JSON.stringify([props.connectionId, props.database, props.tableName, props.schema, props.catalog]));
+const starrocksDraftDirty = computed(() => hasPendingStructureChanges() || ddlDirty.value);
+const starrocksAlterContext = ref<StarRocksAlterOptions>();
+const starrocksLayoutCopyOpen = ref(false);
+const starrocksSortColumns = ref<string[]>();
+const pendingStarRocksSort = computed(() => (starrocksSortColumns.value && starrocksAlterContext.value?.sortColumns && JSON.stringify(starrocksSortColumns.value) !== JSON.stringify(starrocksAlterContext.value.sortColumns) ? starrocksSortColumns.value : undefined));
+async function authorizeStarRocksLayoutCopy(sql: string): Promise<boolean> {
+ const config = store.getConfig(props.connectionId);
+ const productionContext = productionContextForDatabase(config, props.database);
+ return !productionContext.active || (await productionSafetyStore.requestConfirmation({ sql, connectionName: config?.name, database: props.database, productionDatabases: productionContext.databases, source: t("starrocksLayout.copyTitle") }));
+}
const copyColumnsDialogOpen = ref(false);
const copySourceTables = ref<TableInfo[]>([]);
const copySourceTableName = ref("");
@@ -932,7 +954,7 @@ function columnChanged(column: EditableStructureColumn, index: number): boolean
if (!column.original || column.markedForDrop) return true;
const original = column.original;
return (
- isPhysicalTableColumnOrderChange(databaseType.value, connection.value?.db_type, column.originalPosition, index) ||
+ isPhysicalTableColumnOrderChange(databaseType.value, connection.value?.db_type, column.originalPosition, index, structureCapabilities.value.reorderColumn ? starrocksAlterContext.value?.model : undefined) ||
column.name !== original.name ||
column.dataType !== original.data_type ||
column.isNullable !== original.is_nullable ||
@@ -982,7 +1004,7 @@ function triggerChanged(trigger: EditableStructureTrigger): boolean {
function captureStructureRefreshScope(): TableStructureRefreshScope {
return {
- columns: columns.value.some(columnChanged),
+ columns: columns.value.some(columnChanged) || !!pendingStarRocksSort.value,
indexes: indexes.value.some(indexChanged),
foreignKeys: foreignKeys.value.some(foreignKeyChanged),
// Constraints have no editable draft of their own, but column/index/FK
@@ -1373,13 +1395,13 @@ const usesNativeMysqlIndexNames = computed(() => {
});
const supportsCharacterLengthUnits = computed(() => databaseType.value === "dameng" || databaseType.value === "oracle" || databaseType.value === "oceanbase-oracle");
const usesMysql8SafeDefaults = computed(() => databaseType.value === "mysql" && connection.value?.db_type === "mysql" && connection.value.driver_profile === "mysql");
-const structureCapabilities = computed(() => getTableStructureCapabilities(databaseType.value, connection.value?.db_type, connection.value?.database_info?.productVersion));
+const structureCapabilities = computed(() => getTableStructureCapabilities(databaseType.value, connection.value?.db_type, connection.value?.database_info?.productVersion, starrocksAlterContext.value?.model));
const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(databaseType.value));
const structureDialect = computed(() => structureCapabilities.value.dialect);
-const isTableCommentDisabled = computed(() => !structureCapabilities.value.comment);
+const isTableCommentDisabled = computed(() => !structureCapabilities.value.comment || (!isCreateMode.value && databaseType.value === "starrocks" && !getStarRocksCapabilities(connection.value?.database_info?.productVersion).tableComment));
const dynamicDataTypeOptions = ref<string[]>([]);
const dataTypeOptions = computed(() => {
- const options = mergeDataTypeOptions(dynamicDataTypeOptions.value, getDataTypeOptions(databaseType.value));
+ const options = getDataTypeOptions(databaseType.value, dynamicDataTypeOptions.value, connection.value?.database_info?.productVersion);
if (databaseType.value !== "oceanbase-oracle") return options;
// JDBC may advertise Oracle types that OceanBase rejects.
return options.filter((type) => !/^(?:nclob|long(?:\s+raw)?|bfile|boolean|vector)\s*(?:\(|$)/i.test(type.trim()));
@@ -1464,9 +1486,19 @@ const defaultValuePresets = computed((): DefaultValuePreset[] => {
return [...universal, ...(dialectPresets[structureDialect.value] ?? [])];
});
+function columnDefaultValuePresets(column: EditableStructureColumn): DefaultValuePreset[] {
+ if (databaseType.value !== "starrocks") return defaultValuePresets.value;
+ return getColumnDefaultValuePresets(column, {
+ databaseType: databaseType.value,
+ dialect: structureDialect.value,
+ serverVersion: connection.value?.database_info?.productVersion,
+ unsetLabel: t("structureEditor.unsetDefault"),
+ isCreateMode: isCreateMode.value,
+ }).map((preset) => ({ ...preset, dataType: column.dataType }));
+}
const showExtendedProperties = computed(() => supportsTableStructureExtendedProperties(databaseType.value));
-const showCharacterSet = computed(() => structureDialect.value === "mysql");
+const showCharacterSet = computed(() => structureDialect.value === "mysql" && databaseType.value !== "starrocks");
const serverCharsetMetadata = ref<CreateDatabaseCharsetMetadata>();
const charsetMetadataLoading = ref(false);
@@ -1921,7 +1953,7 @@ const tableStoresCaseSensitiveIdentifiers = computed(() => {
});
const usesSqliteRebuildStrategy = computed(() => !isCreateMode.value && structureCapabilities.value.alterStrategy === "sqlite-rebuild");
const hasSqliteTypeChange = computed(() => usesSqliteRebuildStrategy.value && hasExistingColumnTypeChange(columns.value));
-const canAddColumn = computed(() => canAddTableStructureColumn(databaseType.value, isCreateMode.value));
+const canAddColumn = computed(() => canAddTableStructureColumn(databaseType.value, isCreateMode.value) && (isCreateMode.value || databaseType.value !== "starrocks" || ["primary", "duplicate"].includes(starrocksAlterContext.value?.model ?? "")));
const newTableName = ref("");
const tableComment = ref("");
const originalTableComment = ref("");
@@ -1932,6 +1964,7 @@ const mysqlAutoIncrementLoadError = ref("");
const mysqlTableEngine = ref("");
const originalMysqlTableEngine = ref("");
const physicalOptions = ref(emptyTablePhysicalOptions());
+const starrocksPhysicalOptions = ref(emptyStarRocksPhysicalOptions());
watch(
() => columns.value.filter((column) => !column.markedForDrop).map((column) => column.id),
(ids) => {
@@ -2334,6 +2367,8 @@ function createCurrentDraft(initialized = true): TableStructureEditorDraft {
mysqlTableEngine: mysqlTableEngine.value,
originalMysqlTableEngine: originalMysqlTableEngine.value,
physicalOptions: cloneDraftValue(physicalOptions.value),
+ starrocksPhysicalOptions: cloneDraftValue(starrocksPhysicalOptions.value),
+ starrocksSortColumns: starrocksSortColumns.value ? [...starrocksSortColumns.value] : undefined,
tableOwner: tableOwner.value,
originalTableOwner: originalTableOwner.value,
columns: cloneDraftValue(columns.value),
@@ -2412,6 +2447,8 @@ function restoreDraft(draft: TableStructureEditorDraft) {
originalTableOwner.value = draft.originalTableOwner || "";
columns.value = cloneDraftValue(draft.columns || []);
physicalOptions.value = restoreTablePhysicalOptions(draft);
+ starrocksPhysicalOptions.value = restoreStarRocksPhysicalOptions(draft.starrocksPhysicalOptions);
+ starrocksSortColumns.value = draft.starrocksSortColumns ? [...draft.starrocksSortColumns] : undefined;
// Existing-index edits never support Concurrent (the checkbox is disabled and
// the core builder rejects the request), so a stale `concurrently: true`
// saved in a restored draft must not be submitted or deadlock the save.
@@ -2513,6 +2550,7 @@ function hasPendingStructureChanges(): boolean {
!!tableComment.value.trim() ||
mysqlTableEngine.value !== originalMysqlTableEngine.value ||
hasTablePhysicalOptions(physicalOptions.value) ||
+ (databaseType.value === "starrocks" && hasStarRocksPhysicalOptions(starrocksPhysicalOptions.value)) ||
columns.value.length > 0 ||
indexes.value.length > 0 ||
foreignKeys.value.length > 0 ||
@@ -2643,7 +2681,10 @@ function scheduleSqlPreviewRefresh() {
}
sqlPreviewRequestId++;
deferredSqlPreviewRefresh = false;
- if (!hasPendingStructureChanges() && !ddlDirty.value) {
+ // Existing StarRocks tables need their model metadata before definition
+ // controls can be enabled, even when no column has been edited yet.
+ const needsStarRocksAlterContext = !isCreateMode.value && databaseType.value === "starrocks" && !starrocksAlterContext.value;
+ if (!hasPendingStructureChanges() && !ddlDirty.value && !needsStarRocksAlterContext) {
pendingStatements.value = [];
warnings.value = [];
sqliteSchemaRevision.value = undefined;
@@ -2751,6 +2792,16 @@ async function refreshSqlPreview() {
sqlPreviewPending.value = false;
return;
}
+ if (!isCreateMode.value && databaseType.value === "starrocks") {
+ try {
+ const { ddl } = await loadObjectDdl(ddlRequest());
+ starrocksAlterContext.value = starRocksAlterOptionsFromDdl(ddl, connection.value?.database_info?.productVersion);
+ if (!starrocksSortColumns.value) starrocksSortColumns.value = [...(starrocksAlterContext.value.sortColumns ?? [])];
+ } catch {
+ starrocksAlterContext.value = starRocksAlterOptionsFromDdl("", connection.value?.database_info?.productVersion);
+ }
+ }
+ if (requestId !== sqlPreviewRequestId) return;
if (!hasPendingStructureChanges()) {
pendingStatements.value = [];
warnings.value = [];
@@ -2773,6 +2824,13 @@ async function refreshSqlPreview() {
sqlPreviewPending.value = false;
return;
}
+ if (pendingStarRocksSort.value && (columns.value.some(columnChanged) || tableComment.value !== originalTableComment.value || indexes.value.some(indexChanged) || foreignKeys.value.some(foreignKeyChanged) || triggers.value.some(triggerChanged))) {
+ pendingStatements.value = [];
+ warnings.value = [t("starrocksLayout.sortSaveSeparately")];
+ sqlPreviewLoading.value = false;
+ sqlPreviewPending.value = false;
+ return;
+ }
// Layer B: a stale `concurrently: true` whose availability is no longer
// enabled must never reach the SQL builder, even if normalization was
// skipped (race, restored draft, non-UI caller).
@@ -2793,10 +2851,12 @@ async function refreshSqlPreview() {
isCreateMode.value
? createPartitioningEnabled.value
? api.buildCreatePartitionedTableSql({ options, partitioning: { kind: createPartitioningKind.value, columns: createPartitioningColumns.value, expression: createPartitioningExpression.value } })
- : api.buildCreateTableSql(options)
+ : api.buildCreateTableSql(options, connection.value?.database_info?.productVersion, databaseType.value === "starrocks" ? buildStarRocksDialectOptions(starrocksPhysicalOptions.value) : undefined)
: hasSqliteTypeChange.value
? api.previewSqliteTableStructureChange(props.connectionId, props.database, options)
- : api.buildTableStructureChangeSql(options),
+ : databaseType.value === "starrocks"
+ ? api.buildTableStructureChangeSql(options, { ...starrocksAlterContext.value!, reorderColumns: false, positionColumnOrder: structureCapabilities.value.reorderColumn, sortColumnNames: pendingStarRocksSort.value })
+ : api.buildTableStructureChangeSql(options),
supportsTableOwner.value
? api.buildTableOwnerChangeSql({
databaseType: databaseType.value,
@@ -2841,6 +2901,7 @@ const canApply = computed(
() =>
!loading.value &&
!saving.value &&
+ (databaseType.value !== "starrocks" || !starrocksStatusBusy.value) &&
!postSaveRefreshing.value &&
!secondaryMetadataLoading.value &&
!mysqlTableEngineLoading.value &&
@@ -2911,6 +2972,9 @@ function resetState() {
mysqlTableEngine.value = "";
originalMysqlTableEngine.value = "";
physicalOptions.value = emptyTablePhysicalOptions();
+ starrocksPhysicalOptions.value = emptyStarRocksPhysicalOptions();
+ starrocksAlterContext.value = undefined;
+ starrocksSortColumns.value = undefined;
mysqlTableEngineOptions.value = [];
mysqlTableEngineLoadRequestId += 1;
mysqlTableEngineLoading.value = false;
@@ -2951,6 +3015,8 @@ async function reloadStructureFromDatabase() {
// Refreshing from the database discards every other draft; pending partition
// operations must not survive it and still be applied on save.
partitionOperations.value = [];
+ starrocksAlterContext.value = undefined;
+ starrocksSortColumns.value = undefined;
const refreshDdl = activeTab.value === "ddl";
const metadataMatch = { connectionId: props.connectionId, database: props.database, schema: metadataSchema.value, tableName: props.tableName };
invalidateTableMetadataCache(metadataMatch);
@@ -3795,12 +3861,27 @@ function canDropColumnAt(sourceIndex: number, insertionIndex: number): boolean {
if (!sourceColumn) return false;
const crossedColumns = insertionIndex < sourceIndex ? columns.value.slice(insertionIndex, sourceIndex) : columns.value.slice(sourceIndex + 1, insertionIndex);
if (crossedColumns.some((column) => column.markedForDrop)) return false;
+ if (!isCreateMode.value && databaseType.value === "starrocks" && structureCapabilities.value.reorderColumn) {
+ const reordered = [...columns.value];
+ reordered.splice(sourceIndex, 1);
+ reordered.splice(insertionIndex > sourceIndex ? insertionIndex - 1 : insertionIndex, 0, sourceColumn);
+ const keys = new Set(starrocksAlterContext.value?.keyColumns.map((name) => name.toLowerCase()) ?? []);
+ let sawValue = false;
+ for (const column of reordered) {
+ if (column.markedForDrop) continue;
+ if (keys.has(column.original?.name.toLowerCase() ?? "")) {
+ if (sawValue) return false;
+ } else {
+ sawValue = true;
+ }
+ }
+ }
if (canShowColumnDragControls.value) return true;
if (sourceColumn.original) return false;
return crossedColumns.every((column) => !column.original);
}
-const usesLocalTableColumnOrder = computed(() => !isCreateMode.value && supportsLocalTableColumnReorder(databaseType.value, connection.value?.db_type));
+const usesLocalTableColumnOrder = computed(() => !isCreateMode.value && (databaseType.value === "starrocks" ? !!starrocksAlterContext.value?.model && starrocksAlterContext.value.model !== "duplicate" : supportsLocalTableColumnReorder(databaseType.value, connection.value?.db_type)));
const canShowColumnDragControls = computed(() => isCreateMode.value || structureCapabilities.value.reorderColumn || usesLocalTableColumnOrder.value);
function localTableColumnOrderScopeKey(): string {
@@ -4569,6 +4650,7 @@ function commitColumnNameInput(column: EditableStructureColumn) {
}
function isColumnTypeDisabled(column: EditableStructureColumn): boolean {
+ if (databaseType.value === "starrocks" && starRocksColumnDefinitionLocked(column, starrocksAlterContext.value)) return true;
return column.markedForDrop || (!!column.original && !structureCapabilities.value.alterType);
}
@@ -4589,10 +4671,12 @@ function isColumnLengthUnitDisabled(column: EditableStructureColumn): boolean {
}
function isColumnNullableDisabled(column: EditableStructureColumn): boolean {
+ if (databaseType.value === "starrocks" && (starRocksColumnDefinitionLocked(column, starrocksAlterContext.value) || column.original?.is_nullable)) return true;
return column.markedForDrop || column.isPrimaryKey || (!!column.original && !structureCapabilities.value.alterNullability);
}
function isColumnDefaultDisabled(column: EditableStructureColumn): boolean {
+ if (databaseType.value === "starrocks" && starRocksColumnDefinitionLocked(column, starrocksAlterContext.value)) return true;
return column.markedForDrop || (!!column.original && !structureCapabilities.value.alterDefault) || isMysqlGeneratedActive(column);
}
@@ -4614,6 +4698,7 @@ function isPrimaryKeyDisabled(column: EditableStructureColumn): boolean {
}
function canDropColumn(column: EditableStructureColumn): boolean {
+ if (databaseType.value === "starrocks" && (starRocksColumnDefinitionLocked(column, starrocksAlterContext.value) || starrocksAlterContext.value?.keyColumns.some((name) => name.toLowerCase() === column.original?.name.toLowerCase()))) return false;
return !!column.original && !column.isPrimaryKey && !isProtectedManticoreIdColumn(databaseType.value, column.original.name) && structureCapabilities.value.dropColumn;
}
@@ -5051,6 +5136,7 @@ async function applyChanges() {
return false;
}
const sql = previewSqlText.value;
+ const submittedStarRocksTarget = starrocksStatusTarget.value;
const connection = store.getConfig(props.connectionId);
const productionContext = productionContextForDatabase(connection, props.database);
if (productionContext.active) {
@@ -5064,11 +5150,13 @@ async function applyChanges() {
if (!confirmed) return false;
}
saving.value = true;
+ if (databaseType.value === "starrocks") starrocksSubmittedSql.value = undefined;
errorMessage.value = "";
// A hand-written DDL script can change anything about the table, and the
// structure draft it was applied from is clean, so the change-derived scope
// would be empty: reload every facet instead of leaving the tabs stale.
const refreshScope = ddlDirty.value ? { columns: true, indexes: true, foreignKeys: true, constraints: true, triggers: true, partitions: true, tableComment: true } : captureStructureRefreshScope();
+ const starrocksPhysicalOrderChanged = !ddlDirty.value && databaseType.value === "starrocks" && structureCapabilities.value.reorderColumn && columns.value.some((column, index) => column.original && column.originalPosition !== index);
// Plan A guard: concurrent builds only run with a long-enough query timeout
// (a cancelled build leaves an INVALID index behind), and are blocked
// up-front when a same-name INVALID index already exists.
@@ -5118,6 +5206,7 @@ async function applyChanges() {
hasSqliteTypeChange.value && !ddlDirty.value
? await api.applySqliteTableStructureChange(props.connectionId, props.database, structureChangeOptions(), sqliteSchemaRevision.value!)
: await api.executeBatch(props.connectionId, props.database, pendingStatements.value, props.schema, executionTimeoutSecs, useTransaction);
+ if (databaseType.value === "starrocks") starrocksSubmittedSql.value = { target: submittedStarRocksTarget, sql };
await recordStructureHistory(sql, startedAt, true, result);
if (!isCreateMode.value && props.tableName) {
const metadataMatch = { connectionId: props.connectionId, database: props.database, schema: metadataSchema.value, tableName: props.tableName };
@@ -5126,7 +5215,7 @@ async function applyChanges() {
await invalidateObjectDdl(ddlRequest());
loadedMetadataFacets.clear();
}
- toast(t(isCreateMode.value ? "structureEditor.created" : "structureEditor.saved"), 2500);
+ toast(t(isCreateMode.value ? "structureEditor.created" : databaseType.value === "starrocks" && refreshScope.columns ? "starrocksLayout.alterSubmitted" : "structureEditor.saved"), 4000);
sqlPreviewPending.value = false;
sqlPreviewLoading.value = false;
pendingStatements.value = [];
@@ -5135,6 +5224,10 @@ async function applyChanges() {
// Partition operations are applied in place; drop them now so the reload
// below reflects the new catalog state instead of replaying them.
partitionOperations.value = [];
+ if (databaseType.value === "starrocks") {
+ starrocksAlterContext.value = undefined;
+ starrocksSortColumns.value = undefined;
+ }
ddlFetched.value = false;
rawDdlContent.value = "";
ddlDraft.value = null;
@@ -5146,6 +5239,12 @@ async function applyChanges() {
// exact spelling — mirror the DDL generator's quoting rule here.
emit("saved", tableComment.value !== originalTableComment.value, foldCreatedTableName(newTableName.value, databaseType.value));
} else {
+ // An old local-only preference must not mask the newly submitted schema order.
+ if (starrocksPhysicalOrderChanged) {
+ const scopeKey = localTableColumnOrderScopeKey();
+ removeTableDataGridColumnOrder(scopeKey);
+ notifyTableDataGridColumnOrderChanged(scopeKey);
+ }
// Refresh persisted keys after successful renames/additions before metadata reloads.
persistLocalColumnOrder(false);
saving.value = false;
@@ -5160,11 +5259,39 @@ async function applyChanges() {
// A cancelled/errored concurrent build leaves a same-name INVALID index
// behind; surface that so retries are not silently doomed.
const invalidIndexHint = hasConcurrentIndexBuild && /already exists/i.test(rawMessage) ? `\n\n${t("structureEditor.invalidIndexRetryHint")}` : "";
- errorMessage.value = `${rawMessage}${invalidIndexHint}`;
- await recordStructureHistory(sql, startedAt, false, undefined, errorMessage.value);
+ const starrocksSchemaChangeBusy = databaseType.value === "starrocks" && /a schema change operation is in progress on the table\b/i.test(rawMessage);
+ errorMessage.value = starrocksSchemaChangeBusy ? t("starrocksLayout.schemaChangeBusy", { table: props.tableName }) : `${rawMessage}${invalidIndexHint}`;
+ await recordStructureHistory(sql, startedAt, false, undefined, starrocksSchemaChangeBusy ? rawMessage : errorMessage.value);
return false;
} finally {
saving.value = false;
+ if (databaseType.value === "starrocks") starrocksStatusRevision.value++;
+ }
+}
+
+async function onStarRocksAlterCompleted() {
+ if (saving.value || loading.value || starrocksDraftDirty.value) return;
+ const requestId = structureLoadRequestId;
+ const target = JSON.stringify([props.connectionId, props.database, props.tableName, props.schema, props.catalog]);
+ const metadataRequest = { connectionId: props.connectionId, database: props.database, schema: metadataSchema.value, tableName: props.tableName!, catalog: props.catalog };
+ try {
+ invalidateTableMetadataCache(metadataRequest);
+ await Promise.all([invalidateObjectMetadataCache(metadataRequest), invalidateObjectDdl(ddlRequest())]);
+ const [nextColumns, ddlResult] = await Promise.all([api.getColumns(props.connectionId, props.database, metadataSchema.value, props.tableName!, props.catalog), loadObjectDdl(ddlRequest(), { force: true })]);
+ const formatted = await formatStructureDdl(ddlResult.ddl);
+ // Editing while the fetch is in flight must preserve the new draft.
+ if (requestId !== structureLoadRequestId || target !== JSON.stringify([props.connectionId, props.database, props.tableName, props.schema, props.catalog]) || saving.value || loading.value || starrocksDraftDirty.value) return;
+ columns.value = applyStoredLocalColumnOrder(createColumnDrafts(nextColumns, databaseType.value));
+ starrocksAlterContext.value = starRocksAlterOptionsFromDdl(ddlResult.ddl, connection.value?.database_info?.productVersion);
+ starrocksSortColumns.value = [...(starrocksAlterContext.value.sortColumns ?? [])];
+ rawDdlContent.value = formatted;
+ ddlFetched.value = true;
+ scheduleSqlPreviewRefresh();
+ syncDraftToParent();
+ skipNextRefreshVersion = true;
+ emit("saved", false);
+ } catch {
+ toast(t("starrocksStatus.structureRefreshFailed"), 5000);
}
}
@@ -5379,6 +5506,7 @@ onDeactivated(() => {
destroyDdlEditor();
});
onBeforeUnmount(() => {
+ structureLoadRequestId++;
flushStructureScrollDraftSync();
if (structureColumnScrollingTimer) clearTimeout(structureColumnScrollingTimer);
structureColumnScrollingTimer = undefined;
@@ -5498,6 +5626,8 @@ watch([() => props.connectionId, () => props.database, databaseType], () => {
void loadDynamicDataTypeOptions();
});
+watch(() => connection.value?.database_info?.productVersion, scheduleSqlPreviewRefresh);
+
watch(
[
isCreateMode,
@@ -5516,6 +5646,8 @@ watch(
mysqlTableEngine,
originalMysqlTableEngine,
physicalOptions,
+ starrocksPhysicalOptions,
+ starrocksSortColumns,
mysqlTableEngineLoading,
mysqlTableEngineLoadError,
mysqlTableDefaultCollation,
@@ -5646,6 +5778,19 @@ watch(
<template>
<div ref="rootRef" class="flex h-full min-h-0 flex-col gap-2 overflow-hidden p-[var(--structure-shell-padding)] text-[length:var(--structure-font-size)]" :data-structure-density="localStructureDensity" :style="structureDensityStyle">
+ <StarRocksLayoutCopyDialog
+ v-if="!isCreateMode && databaseType === 'starrocks' && props.tableName"
+ v-model:open="starrocksLayoutCopyOpen"
+ :connection-id="props.connectionId"
+ :database="props.database"
+ :schema="props.schema"
+ :catalog="props.catalog"
+ :table-name="props.tableName"
+ :server-version="connection?.database_info?.productVersion"
+ :timeout-secs="queryTimeoutSecsForConnection(connection, settingsStore.editorSettings.globalQueryTimeoutSecs)"
+ :authorize="authorizeStarRocksLayoutCopy"
+ @created="emit('saved', false)"
+ />
<div class="flex shrink-0 items-center gap-2 rounded-md border bg-muted/20 px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)]">
<Database :class="[structureIconClass, 'text-muted-foreground']" />
<span class="min-w-0 flex-1 truncate font-medium">{{ targetLabel || t("editor.noDatabase") }}</span>
@@ -5656,6 +5801,21 @@ watch(
</Button>
</div>
+ <StarRocksAlterStatus
+ v-if="!isCreateMode && databaseType === 'starrocks' && props.tableName"
+ :connection-id="props.connectionId"
+ :database="props.database"
+ :table-name="props.tableName"
+ :schema="metadataSchema"
+ :catalog="props.catalog"
+ :paused="saving || loading || postSaveRefreshing"
+ :revision="starrocksStatusRevision"
+ :dirty="starrocksDraftDirty"
+ :submitted-sql="starrocksSubmittedSql?.target === starrocksStatusTarget ? starrocksSubmittedSql.sql : undefined"
+ @busy="starrocksStatusBusy = $event"
+ @completed="onStarRocksAlterCompleted"
+ />
+
<div v-if="isCreateMode" class="flex shrink-0 items-center gap-2">
<label class="shrink-0 font-medium text-muted-foreground">{{ t("structureEditor.tableName") }}</label>
<Input v-model="newTableName" :placeholder="t('contextMenu.duplicateNamePlaceholder')" :class="[structureControlClass, 'max-w-[220px]']" />
@@ -5823,6 +5983,18 @@ watch(
</TooltipTrigger>
<TooltipContent side="bottom" class="font-mono font-medium" data-add-column-shortcut-content>Shift+Enter</TooltipContent>
</Tooltip>
+ <Button
+ v-if="activeTab === 'columns' && !isCreateMode && databaseType === 'starrocks'"
+ variant="outline"
+ size="sm"
+ :class="structureToolbarButtonClass"
+ :disabled="loading || saving || hasPendingStructureChanges() || ddlDirty"
+ :title="hasPendingStructureChanges() || ddlDirty ? t('starrocksLayout.copySaveFirst') : undefined"
+ @click="starrocksLayoutCopyOpen = true"
+ data-starrocks-layout-copy-button
+ >
+ <SlidersHorizontal :class="structureIconClass" />{{ t("starrocksLayout.copyButton") }}
+ </Button>
<Button v-if="activeTab === 'columns'" size="sm" variant="outline" :class="structureToolbarButtonClass" :disabled="!canAddColumn" @click="openCopyColumnsDialog">
<Copy :class="structureIconClass" />
{{ t("structureEditor.copyColumns") }}
@@ -6141,7 +6313,7 @@ watch(
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="max-h-56 w-max min-w-36 max-w-[calc(100vw-1rem)] overflow-y-auto">
- <DropdownMenuItem v-for="preset in defaultValuePresets" :key="preset.value" @click="column.defaultValue = preset.value">
+ <DropdownMenuItem v-for="preset in columnDefaultValuePresets(column)" :key="preset.value" @click="column.defaultValue = preset.value">
<code :class="['structure-data-type-option block truncate font-mono text-[length:var(--structure-font-size)]', structureDefaultValueToneClass(preset.value, preset.dataType)]">{{ preset.label }}</code>
</DropdownMenuItem>
</DropdownMenuContent>
@@ -6928,6 +7100,12 @@ watch(
</Tabs>
</div>
+ <p v-if="!isCreateMode && databaseType === 'starrocks'" class="shrink-0 px-3 py-2 text-xs text-muted-foreground">
+ {{ t("starrocksLayout.alterHint") }} {{ t(structureCapabilities.reorderColumn ? "starrocksLayout.reorderHint" : starrocksAlterContext?.model === "primary" ? "starrocksLayout.localReorderHint" : "starrocksLayout.reorderMetadataHint") }}
+ </p>
+ <StarRocksSortKeyEditor v-if="!isCreateMode && databaseType === 'starrocks' && activeTab === 'columns' && starrocksSortColumns" v-model="starrocksSortColumns" :context="starrocksAlterContext" :columns="columns" :disabled="saving || loading" />
+ <StarRocksPhysicalOptionsEditor v-if="isCreateMode && databaseType === 'starrocks'" v-model="starrocksPhysicalOptions" :columns="columns" :server-version="connection?.database_info?.productVersion" :disabled="saving" />
+
<div :class="['flex min-w-0 shrink-0 flex-col overflow-hidden rounded-md border', sqlPreviewCollapsed ? '' : 'h-[28%] min-h-40 max-h-64']">
<div class="flex shrink-0 items-center justify-between border-b px-[var(--structure-cell-px)] py-[var(--structure-header-py)] text-[length:var(--structure-font-size)] font-medium">
<div class="flex items-center gap-1.5">
diff --git a/apps/desktop/src/components/structure/__tests__/StarRocksAlterStatus.spec.ts b/apps/desktop/src/components/structure/__tests__/StarRocksAlterStatus.spec.ts
new file mode 100644
index 0000000000..1e7f322225
--- /dev/null
+++ b/apps/desktop/src/components/structure/__tests__/StarRocksAlterStatus.spec.ts
@@ -0,0 +1,150 @@
+// @vitest-environment happy-dom
+import { createApp, nextTick, reactive, type App } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({ query: vi.fn() }));
+vi.mock("@/lib/backend/api", () => ({ executeQuery: mocks.query }));
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+vi.mock("@/components/ui/button", () => ({ Button: { template: "<button><slot /></button>" } }));
+import Status from "../StarRocksAlterStatus.vue";
+let app: App | undefined;
+const empty = { columns: ["JobId", "State", "CreateTime"], rows: [] };
+const result = (state: string) => ({ ...empty, rows: [["1", state, "2026-01-01"]] });
+const flush = async () => {
+ for (let i = 0; i < 10; i++) await Promise.resolve();
+ await nextTick();
+};
+function mount() {
+ const props = reactive({ connectionId: "c", database: "d", tableName: "t", paused: false, revision: 0, dirty: false });
+ const busy = vi.fn(),
+ completed = vi.fn();
+ const host = document.createElement("div");
+ document.body.append(host);
+ // Reactive props passed through a small wrapper so target changes update the child.
+ app = createApp({ components: { Status }, setup: () => ({ props, busy, completed }), template: '<Status v-bind="props" @busy="busy" @completed="completed" />' });
+ app.mount(host);
+ return { props, busy, completed, host };
+}
+beforeEach(() => {
+ vi.useFakeTimers();
+ mocks.query.mockReset();
+});
+afterEach(() => {
+ app?.unmount();
+ app = undefined;
+ document.body.innerHTML = "";
+ vi.useRealTimers();
+});
+describe("ALTER status polling", () => {
+ it("polls active tasks, emits completion once, then stops", async () => {
+ let state = "RUNNING";
+ mocks.query.mockImplementation((_c, _d, sql) => Promise.resolve(sql.includes(" COLUMN ") ? result(state) : empty));
+ const { busy, completed } = mount();
+ await flush();
+ expect(busy).toHaveBeenLastCalledWith(true);
+ state = "FINISHED";
+ await vi.advanceTimersByTimeAsync(3000);
+ await flush();
+ expect(completed).toHaveBeenCalledTimes(1);
+ expect(busy).toHaveBeenLastCalledWith(false);
+ await vi.advanceTimersByTimeAsync(9000);
+ expect(mocks.query).toHaveBeenCalledTimes(6);
+ });
+ it("keeps busy evidence on failed polling instead of emitting completion", async () => {
+ mocks.query.mockImplementation((_c, _d, sql) => Promise.resolve(sql.includes(" COLUMN ") ? result("RUNNING") : empty));
+ const { busy, completed, host } = mount();
+ await flush();
+ mocks.query.mockRejectedValue(new Error("permission denied"));
+ await vi.advanceTimersByTimeAsync(3000);
+ await flush();
+ expect(busy).toHaveBeenLastCalledWith(true);
+ expect(completed).not.toHaveBeenCalled();
+ expect(host.textContent).toContain("starrocksStatus.queryFailed");
+ });
+ it("discards responses from the previous table and stops on unmount", async () => {
+ const oldResolvers: ((value: unknown) => void)[] = [];
+ mocks.query.mockImplementation((_c, _d, sql) =>
+ sql.includes("TableName = 't'")
+ ? new Promise((resolve) => {
+ oldResolvers.push(resolve);
+ })
+ : Promise.resolve(empty),
+ );
+ const { props, busy, host } = mount();
+ props.tableName = "new";
+ await nextTick();
+ await flush();
+ oldResolvers.forEach((resolve) => resolve(result("RUNNING")));
+ await flush();
+ expect(busy).toHaveBeenLastCalledWith(false);
+ expect(host.textContent).toContain("starrocksStatus.idle");
+ app?.unmount();
+ app = undefined;
+ const calls = mocks.query.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(10000);
+ expect(mocks.query).toHaveBeenCalledTimes(calls);
+ });
+ it("pauses while saving and probes after submission even without visible jobs", async () => {
+ mocks.query.mockResolvedValue(empty);
+ const { props } = mount();
+ await flush();
+ props.paused = true;
+ await nextTick();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(mocks.query).toHaveBeenCalledTimes(3);
+ props.revision++;
+ props.paused = false;
+ await nextTick();
+ await flush();
+ await vi.advanceTimersByTimeAsync(3000);
+ await flush();
+ expect(mocks.query).toHaveBeenCalledTimes(9);
+ });
+ it("refreshes a newly finished job after submission even when never observed running", async () => {
+ mocks.query.mockResolvedValue(empty);
+ const { props, completed } = mount();
+ await flush();
+ mocks.query.mockImplementation((_c, _d, sql) => Promise.resolve(sql.includes(" COLUMN ") ? result("FINISHED") : empty));
+ props.revision++;
+ await nextTick();
+ await flush();
+ expect(completed).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(mocks.query).toHaveBeenCalledTimes(6);
+ });
+
+ it("shows only unfinished jobs and expands the server SQL below the task", async () => {
+ mocks.query.mockImplementation((_c, _d, sql) =>
+ Promise.resolve(
+ sql.includes(" COLUMN ")
+ ? {
+ columns: ["JobId", "State", "Sql"],
+ rows: [
+ [1, "RUNNING", "ALTER TABLE t MODIFY COLUMN name varchar(500);"],
+ [2, "FINISHED", "old SQL"],
+ ],
+ }
+ : empty,
+ ),
+ );
+ const { host } = mount();
+ await flush();
+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent === "starrocksStatus.details")!.click();
+ await nextTick();
+ expect(host.textContent).not.toContain("#2");
+ expect(host.querySelector("[data-starrocks-job-sql]")).toBeNull();
+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("#1"))!.click();
+ await nextTick();
+ expect(host.querySelector("[data-starrocks-job-sql] pre")?.textContent).toBe("ALTER TABLE t MODIFY COLUMN name varchar(500);");
+ expect(host.textContent).not.toContain("old SQL");
+ });
+ it("explains when the database did not return the original SQL", async () => {
+ mocks.query.mockImplementation((_c, _d, sql) => Promise.resolve(sql.includes(" COLUMN ") ? result("RUNNING") : empty));
+ const { host } = mount();
+ await flush();
+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent === "starrocksStatus.details")!.click();
+ await nextTick();
+ [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("#1"))!.click();
+ await nextTick();
+ expect(host.querySelector("[data-starrocks-job-sql]")?.textContent).toContain("starrocksStatus.sqlUnavailable");
+ });
+});
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts
index ca146a4f25..ab1a26b05e 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.createModeSavedName.spec.ts
@@ -12,16 +12,20 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// converted edit tab querying a case that matches nothing.
const mocks = vi.hoisted(() => ({
+ renderColumnRows: false,
connection: {
id: "structure-create-mode",
name: "Oracle",
db_type: "oracle",
driver_label: "Oracle",
+ database_info: { productVersion: "3.5.0" },
},
ensureConnected: vi.fn(),
executeQuery: vi.fn(),
executeBatch: vi.fn(),
listDataTypes: vi.fn(),
+ getColumns: vi.fn(),
+ buildCopyTableDataSql: vi.fn(),
buildTableStructureChangeSql: vi.fn(),
buildCreateTableSql: vi.fn(),
buildMysqlAutoIncrementSql: vi.fn(),
@@ -39,6 +43,20 @@ const mocks = vi.hoisted(() => ({
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+// Render rows without browser layout measurements so drag controls can be exercised.
+vi.mock("vue-virtual-scroller", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ RecycleScroller: defineComponent({
+ props: { items: { type: Array, default: () => [] } },
+ setup:
+ (props, { slots }) =>
+ () =>
+ h("div", [slots.before?.(), ...props.items.map((item, index) => slots.default?.({ item, index, active: true })), slots.after?.()]),
+ }),
+ };
+});
+
vi.mock("@lucide/vue", async () => {
const { defineComponent, h } = await import("vue");
const Icon = defineComponent({ name: "Icon", setup: () => () => h("span") });
@@ -73,6 +91,24 @@ vi.mock("@lucide/vue", async () => {
};
});
+vi.mock("@/components/ui/dialog", async () => {
+ const { defineComponent, h } = await import("vue");
+ const Div = defineComponent({
+ setup:
+ (_props, { attrs, slots }) =>
+ () =>
+ h("div", attrs, slots.default?.()),
+ });
+ const Dialog = defineComponent({
+ props: { open: Boolean },
+ setup:
+ (props, { slots }) =>
+ () =>
+ props.open ? h("div", slots.default?.()) : null,
+ });
+ return { Dialog, DialogContent: Div, DialogHeader: Div, DialogTitle: Div, DialogFooter: Div };
+});
+
vi.mock("@/components/ui/button", async () => {
const { defineComponent, h } = await import("vue");
return {
@@ -123,17 +159,17 @@ vi.mock("@/components/ui/tabs", async () => {
const Div = defineComponent({
inheritAttrs: false,
setup:
- (_props, { attrs }) =>
+ (_props, { attrs, slots }) =>
() =>
- h("div", attrs),
+ h("div", attrs, slots.default?.()),
});
const TabsContent = defineComponent({
name: "MockTabsContent",
inheritAttrs: false,
setup:
- (_props, { attrs }) =>
+ (_props, { attrs, slots }) =>
() =>
- h("div", attrs),
+ h("div", attrs, mocks.renderColumnRows && attrs.value === "columns" ? slots.default?.() : undefined),
});
const TabsTrigger = defineComponent({
name: "MockTabsTrigger",
@@ -151,9 +187,9 @@ vi.mock("@/components/ui/dropdown-menu", async () => {
const Div = defineComponent({
inheritAttrs: false,
setup:
- (_props, { attrs }) =>
+ (_props, { attrs, slots }) =>
() =>
- h("div", attrs),
+ h("div", attrs, mocks.renderColumnRows ? slots.default?.() : undefined),
});
return { DropdownMenu: Div, DropdownMenuCheckboxItem: Div, DropdownMenuContent: Div, DropdownMenuItem: Div, DropdownMenuTrigger: Div };
});
@@ -249,6 +285,8 @@ vi.mock("@/lib/backend/api", () => ({
executeQuery: mocks.executeQuery,
executeBatch: mocks.executeBatch,
listDataTypes: mocks.listDataTypes,
+ getColumns: mocks.getColumns,
+ buildCopyTableDataSql: mocks.buildCopyTableDataSql,
buildTableStructureChangeSql: mocks.buildTableStructureChangeSql,
buildCreateTableSql: mocks.buildCreateTableSql,
buildMysqlAutoIncrementSql: mocks.buildMysqlAutoIncrementSql,
@@ -257,7 +295,11 @@ vi.mock("@/lib/backend/api", () => ({
getTableOwner: mocks.getTableOwner,
}));
+import StarRocksLayoutCopyDialog from "@/components/structure/StarRocksLayoutCopyDialog.vue";
+import StarRocksAlterLayoutEditor from "@/components/structure/StarRocksAlterLayoutEditor.vue";
import TableStructureEditor from "@/components/structure/TableStructureEditor.vue";
+import { emptyStarRocksPhysicalOptions } from "@/lib/table/starrocksPhysicalOptions";
+import type { TableStructureEditorDraft } from "@/types/database";
const mountedApps: App[] = [];
@@ -327,6 +369,7 @@ async function createTableAndCaptureSaved(dbType: string, newTableName: string):
beforeEach(() => {
vi.clearAllMocks();
+ mocks.renderColumnRows = false;
mocks.ensureConnected.mockResolvedValue(undefined);
mocks.executeQuery.mockResolvedValue({ columns: [], rows: [] });
mocks.executeBatch.mockResolvedValue({ rowsAffected: 0 });
@@ -372,3 +415,400 @@ describe("TableStructureEditor created-table name write-back", () => {
expect(saved.createdTableName).toBe("my table");
});
});
+
+describe("StarRocks create layout integration", () => {
+ it("restores layout drafts, sends dialect options, and persists bucket and sort priority edits", async () => {
+ const previousType = mocks.connection.db_type;
+ mocks.connection.db_type = "starrocks";
+ try {
+ const root = document.createElement("div");
+ document.body.append(root);
+ let latestDraft: TableStructureEditorDraft | undefined;
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "test",
+ tableName: "",
+ draft: {
+ dirty: true,
+ activeTab: "columns",
+ newTableName: "events",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [
+ { id: "id", name: "id", dataType: "bigint", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, markedForDrop: false },
+ { id: "ts", name: "event_time", dataType: "datetime", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, markedForDrop: false },
+ ],
+ indexes: [],
+ foreignKeys: [],
+ triggers: [],
+ initialized: true,
+ starrocksPhysicalOptions: { ...emptyStarRocksPhysicalOptions(), partitionKind: "time", partitionColumnId: "ts", bucketCount: "8", sortColumnIds: ["ts", "id"] },
+ },
+ "onUpdate:draft": (draft) => {
+ latestDraft = draft;
+ },
+ });
+ mountedApps.push(app);
+ app.mount(root);
+ await vi.waitFor(() =>
+ expect(mocks.buildCreateTableSql).toHaveBeenCalledWith(
+ expect.objectContaining({ tableName: "events", databaseType: "starrocks" }),
+ "3.5.0",
+ expect.objectContaining({ starrocks: expect.objectContaining({ timePartition: expect.objectContaining({ columnId: "ts", granularity: "month" }), bucketCount: 8, sortColumnIds: ["ts", "id"] }) }),
+ ),
+ );
+ const panel = root.querySelector("[data-starrocks-physical-options]");
+ expect(panel).not.toBeNull();
+ const sortPanel = panel!.querySelector("[data-starrocks-sort]")!;
+ const moveDown = sortPanel.querySelector<HTMLButtonElement>('button[aria-label="starrocksLayout.moveSortDown"]')!;
+ moveDown.click();
+ await vi.waitFor(() => expect(latestDraft?.starrocksPhysicalOptions?.sortColumnIds).toEqual(["id", "ts"]));
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.anything(), "3.5.0", expect.objectContaining({ starrocks: expect.objectContaining({ sortColumnIds: ["id", "ts"] }) })));
+ const bucketInput = panel!.querySelector<HTMLInputElement>("[data-starrocks-buckets] input[type=number]")!;
+ bucketInput.value = "12";
+ bucketInput.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.waitFor(() => expect(latestDraft?.starrocksPhysicalOptions?.bucketCount).toBe("12"));
+ await vi.waitFor(() => expect(mocks.buildCreateTableSql).toHaveBeenLastCalledWith(expect.anything(), "3.5.0", expect.objectContaining({ starrocks: expect.objectContaining({ bucketCount: 12 }) })));
+ } finally {
+ mocks.connection.db_type = previousType;
+ }
+ });
+});
+
+describe("StarRocks existing-table layout", () => {
+ it("replaces inline ALTER controls with an independent create-and-transfer dialog", async () => {
+ const previousType = mocks.connection.db_type;
+ mocks.connection.db_type = "starrocks";
+ mocks.loadObjectDdl.mockResolvedValue({ ddl: 'CREATE TABLE `events` (`id` bigint NOT NULL) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM PROPERTIES("bucket_size"="1073741824")', cacheStatus: "remote" });
+ mocks.getColumns.mockResolvedValue([{ name: "id", data_type: "bigint", is_nullable: false, is_primary_key: false }]);
+ mocks.buildCreateTableSql.mockResolvedValue({ statements: ["CREATE TABLE `events_layout` (`id` bigint NOT NULL) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM"], warnings: [] });
+ mocks.buildCopyTableDataSql.mockResolvedValue("INSERT INTO `test`.`events_layout` (`id`) SELECT `id` FROM `test`.`events`;");
+ try {
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "test",
+ tableName: "events",
+ initialTab: "columns",
+ draft: {
+ dirty: false,
+ activeTab: "columns",
+ newTableName: "events",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [{ id: "id", name: "id", dataType: "bigint", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, markedForDrop: false, original: { name: "id", data_type: "bigint", is_nullable: false, is_primary_key: false } }],
+ indexes: [],
+ foreignKeys: [],
+ triggers: [],
+ initialized: true,
+ },
+ });
+ mountedApps.push(app);
+ app.mount(root);
+ await settle();
+ expect(root.querySelector("[data-starrocks-alter-layout]")).toBeNull();
+ await vi.waitFor(() => expect(root.querySelector("[data-starrocks-layout-copy-button]")).not.toBeNull());
+ const button = root.querySelector<HTMLButtonElement>("[data-starrocks-layout-copy-button]")!;
+ button.click();
+ await vi.waitFor(() => expect(root.querySelector("[data-starrocks-layout-copy-dialog] pre")?.textContent).toContain("CREATE TABLE"));
+ const dialog = root.querySelector("[data-starrocks-layout-copy-dialog]")!;
+ const checkboxes = dialog.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
+ expect(checkboxes[0]!.checked).toBe(false);
+ expect(mocks.executeBatch).not.toHaveBeenCalled();
+ checkboxes[0]!.click();
+ await vi.waitFor(() => expect(dialog.querySelector("details:last-child pre")?.textContent).toContain("SET_VAR(enable_insert_strict=true)"));
+ const create = [...dialog.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent === "starrocksLayout.copyExecute")!;
+ expect(create.disabled).toBe(false);
+ create.click();
+ await vi.waitFor(() => expect(mocks.executeBatch).toHaveBeenCalledTimes(2));
+ expect(mocks.executeBatch.mock.calls[0]![2][0]).toContain("CREATE TABLE `test`.`events_layout`");
+ expect(mocks.executeBatch.mock.calls[1]![2][0]).toContain("INSERT /*+ SET_VAR(enable_insert_strict=true) */");
+ await vi.waitFor(() => expect(create.disabled).toBe(true));
+ create.click();
+ await settle();
+ expect(mocks.executeBatch).toHaveBeenCalledTimes(2);
+ } finally {
+ mocks.connection.db_type = previousType;
+ }
+ });
+});
+
+it("locks automatic-scaling distribution while retaining partition controls", async () => {
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(StarRocksAlterLayoutEditor, {
+ modelValue: { method: "random", columns: [], bucketCount: "", defaultOnly: false, partitions: [] },
+ context: { serverVersion: "3.5.0", model: "duplicate", keyColumns: [], partitionColumns: [], distributionColumns: [], automaticBucketScaling: true },
+ columns: [],
+ });
+ mountedApps.push(app);
+ app.mount(root);
+ await settle();
+ const numbers = root.querySelectorAll<HTMLInputElement>('input[type="number"]');
+ expect(numbers[0]!.disabled).toBe(true);
+ expect(numbers[1]!.disabled).toBe(false);
+ expect(root.textContent).toContain("starrocksLayout.automaticBucketsReadonly");
+});
+
+describe("StarRocks layout copy execution", () => {
+ it.each(["empty", "createFailure", "transferFailure"])("handles %s without replaying creation or data", async (scenario) => {
+ mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE `source` (`id` INT) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM", cacheStatus: "remote" });
+ mocks.getColumns.mockResolvedValue([{ name: "id", data_type: "int", is_nullable: true, is_primary_key: false }]);
+ mocks.buildCreateTableSql.mockResolvedValue({ statements: ["CREATE TABLE `new` (`id` INT) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM"], warnings: [] });
+ mocks.buildCopyTableDataSql.mockResolvedValue("INSERT INTO `test`.`source_layout` (`id`) SELECT `id` FROM `test`.`source`;");
+ if (scenario === "createFailure") mocks.executeBatch.mockRejectedValueOnce(new Error("already exists"));
+ if (scenario === "transferFailure") mocks.executeBatch.mockResolvedValueOnce({ rowsAffected: 0 }).mockRejectedValueOnce(new Error("load failed"));
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(StarRocksLayoutCopyDialog, { open: true, connectionId: "c", database: "test", tableName: "source", serverVersion: "3.5.0", authorize: async () => true });
+ mountedApps.push(app);
+ app.mount(root);
+ const execute = () => [...root.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent === "starrocksLayout.copyExecute");
+ await vi.waitFor(() => expect(execute()?.disabled).toBe(false));
+ if (scenario !== "empty") {
+ root.querySelector<HTMLInputElement>('input[type="checkbox"]')!.click();
+ await vi.waitFor(() => expect(root.textContent).toContain("SET_VAR(enable_insert_strict=true)"));
+ }
+ execute()!.click();
+ if (scenario === "empty") {
+ await vi.waitFor(() => expect(root.textContent).toContain("starrocksLayout.copyStage_complete"));
+ expect(mocks.executeBatch).toHaveBeenCalledTimes(1);
+ } else {
+ await vi.waitFor(() => expect(root.querySelector('[role="alert"]')?.textContent).toBe(`starrocksLayout.copy${scenario === "createFailure" ? "Create" : "Transfer"}Failed`));
+ expect(mocks.executeBatch).toHaveBeenCalledTimes(scenario === "createFailure" ? 1 : 2);
+ }
+ expect(execute()?.disabled).toBe(true);
+ execute()!.click();
+ await settle();
+ expect(mocks.executeBatch).toHaveBeenCalledTimes(scenario === "transferFailure" ? 2 : 1);
+ });
+});
+
+it("routes a restored StarRocks column order through the physical ALTER interface", async () => {
+ const previousType = mocks.connection.db_type;
+ mocks.connection.db_type = "starrocks";
+ mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE `t` (`id` INT, `first` INT, `last` INT) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM", cacheStatus: "remote" });
+ const makeColumn = (name: string, index: number) => ({
+ id: `existing:${name}`,
+ name,
+ dataType: "int",
+ isNullable: false,
+ defaultValue: "",
+ comment: "",
+ isPrimaryKey: false,
+ extra: {},
+ markedForDrop: false,
+ originalPosition: index,
+ original: { name, data_type: "int", is_nullable: false, is_primary_key: false },
+ });
+ try {
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "test",
+ tableName: "t",
+ draft: { dirty: true, activeTab: "columns", newTableName: "t", tableComment: "", originalTableComment: "", columns: [makeColumn("id", 0), makeColumn("last", 2), makeColumn("first", 1)], indexes: [], foreignKeys: [], triggers: [], initialized: true },
+ });
+ mountedApps.push(app);
+ app.mount(root);
+ await vi.waitFor(() =>
+ expect(mocks.buildTableStructureChangeSql).toHaveBeenCalledWith(
+ expect.objectContaining({ columns: [expect.objectContaining({ name: "id" }), expect.objectContaining({ name: "last" }), expect.objectContaining({ name: "first" })] }),
+ expect.objectContaining({ model: "duplicate", columnNames: ["id", "first", "last"], reorderColumns: false, positionColumnOrder: true }),
+ ),
+ );
+ expect(root.textContent).toContain("starrocksLayout.reorderHint");
+ } finally {
+ mocks.connection.db_type = previousType;
+ }
+});
+
+it.each(["beforeDay", "afterName", "valueFirst", "valueBetweenKeys"])("allows key swaps but rejects crossing the StarRocks key/value boundary: %s", async (placement) => {
+ mocks.renderColumnRows = true;
+ const previousType = mocks.connection.db_type;
+ mocks.connection.db_type = "starrocks";
+ const metadata = ["day", "id", "name"].map((name) => ({ name, data_type: "int", is_nullable: false, is_primary_key: false }));
+ mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE `t` (`day` INT, `id` INT, `name` INT) ENGINE=OLAP DUPLICATE KEY(`day`, `id`) PARTITION BY (time_slice(`day`, INTERVAL 7 year, floor), `id`) DISTRIBUTED BY RANDOM ORDER BY (`id`, `day`)", cacheStatus: "remote" });
+ mocks.loadObjectMetadataFacet.mockImplementation(async (_request: unknown, facet: string) => ({ value: facet === "columns" ? metadata : facet === "comment" ? "" : [], cacheStatus: "remote" }));
+ let latestDraft: TableStructureEditorDraft | undefined;
+ try {
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "test",
+ tableName: "t",
+ initialTab: "columns",
+ "onUpdate:draft": (draft) => {
+ latestDraft = draft;
+ },
+ });
+ mountedApps.push(app);
+ app.mount(root);
+ await vi.waitFor(() => expect(root.querySelectorAll('[aria-label="structureEditor.dragColumn"]')).toHaveLength(3));
+ await settle();
+ const handles = root.querySelectorAll<HTMLButtonElement>('[aria-label="structureEditor.dragColumn"]');
+ expect(handles[0]!.disabled).toBe(false);
+ expect(handles[1]!.disabled).toBe(false);
+ const sourceIndex = placement.startsWith("value") ? 2 : 1;
+ handles[sourceIndex]!.dispatchEvent(new Event("dragstart", { bubbles: true, cancelable: true }));
+ const targetIndex = placement === "afterName" ? 2 : 0;
+ root.querySelector(`[data-column-row-index="${targetIndex}"]`)!.dispatchEvent(new MouseEvent("drop", { bubbles: true, cancelable: true, clientY: placement === "beforeDay" || placement === "valueFirst" ? -1 : 1 }));
+ const expected = placement === "beforeDay" ? ["id", "day", "name"] : ["day", "id", "name"];
+ await vi.waitFor(() => expect(latestDraft?.columns?.map((column) => column.name)).toEqual(expected));
+ if (placement !== "beforeDay") {
+ expect(mocks.buildTableStructureChangeSql).not.toHaveBeenCalled();
+ return;
+ }
+ await vi.waitFor(() =>
+ expect(mocks.buildTableStructureChangeSql).toHaveBeenCalledWith(
+ expect.objectContaining({ columns: expected.map((name) => expect.objectContaining({ name })) }),
+ expect.objectContaining({ model: "duplicate", keyColumns: ["day", "id"], partitionColumns: ["day", "id"], partitionExpressionColumns: ["day"], positionColumnOrder: true }),
+ ),
+ );
+ expect(latestDraft?.starrocksSortColumns).toEqual(["id", "day"]);
+ } finally {
+ mocks.connection.db_type = previousType;
+ }
+});
+
+it("hydrates and persists edited sort-key priority independently of column order", async () => {
+ const previousType = mocks.connection.db_type;
+ mocks.connection.db_type = "starrocks";
+ const metadata = ["id", "first", "last"].map((name) => ({ name, data_type: "int", is_nullable: false, is_primary_key: false }));
+ mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE `t` (`id` INT, `first` INT, `last` INT) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM ORDER BY(`id`, `last`)", cacheStatus: "remote" });
+ mocks.loadObjectMetadataFacet.mockImplementation(async (_request: unknown, facet: string) => ({ value: facet === "columns" ? metadata : facet === "comment" ? "" : [], cacheStatus: "remote" }));
+ let latestDraft: TableStructureEditorDraft | undefined;
+ try {
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "test",
+ tableName: "t",
+ initialTab: "columns",
+ "onUpdate:draft": (draft) => {
+ latestDraft = draft;
+ },
+ });
+ mountedApps.push(app);
+ app.mount(root);
+ await vi.waitFor(() => expect(root.querySelector("[data-starrocks-edit-sort] li")?.textContent).toContain("id"));
+ expect(mocks.buildTableStructureChangeSql).not.toHaveBeenCalled();
+ const panel = root.querySelector("[data-starrocks-edit-sort]")!;
+ panel.querySelector<HTMLButtonElement>('[aria-label="starrocksLayout.moveSortDown"]')!.click();
+ await vi.waitFor(() => expect(latestDraft?.starrocksSortColumns).toEqual(["last", "id"]));
+ await vi.waitFor(() =>
+ expect(mocks.buildTableStructureChangeSql).toHaveBeenCalledWith(
+ expect.objectContaining({ columns: [expect.objectContaining({ name: "id" }), expect.objectContaining({ name: "first" }), expect.objectContaining({ name: "last" })] }),
+ expect.objectContaining({ sortColumns: ["id", "last"], sortColumnNames: ["last", "id"], reorderColumns: false }),
+ ),
+ );
+ } finally {
+ mocks.connection.db_type = previousType;
+ }
+});
+
+it.each([false, true])("refreshes finished StarRocks jobs only without a draft (dirty=%s)", async (dirty) => {
+ const previousType = mocks.connection.db_type;
+ mocks.connection.db_type = "starrocks";
+ const metadata = ["id", "name"].map((name) => ({ name, data_type: "int", is_nullable: false, is_primary_key: false }));
+ const ddl = "CREATE TABLE `t` (`id` INT, `name` INT) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM";
+ mocks.loadObjectDdl.mockResolvedValue({ ddl, cacheStatus: "remote" });
+ mocks.loadObjectMetadataFacet.mockImplementation(async (_request: unknown, facet: string) => ({ value: facet === "columns" ? metadata : facet === "comment" ? "" : [], cacheStatus: "remote" }));
+ mocks.getColumns.mockResolvedValue(metadata);
+ let state = "RUNNING";
+ mocks.executeQuery.mockImplementation(async (_c, _d, sql) => ({ columns: ["JobId", "State", "CreateTime"], rows: sql.includes(" COLUMN ") ? [[1, state, "2026-01-01"]] : [] }));
+ const makeColumn = (name: string, index: number) => ({ id: `existing:${name}`, name, dataType: "int", isNullable: false, defaultValue: "", comment: "", isPrimaryKey: false, extra: {}, markedForDrop: false, originalPosition: index, original: metadata[index] });
+ let latestDraft: TableStructureEditorDraft | undefined;
+ try {
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "test",
+ tableName: "t",
+ initialTab: "columns",
+ ...(dirty ? { draft: { dirty: true, activeTab: "columns" as const, newTableName: "t", tableComment: "", originalTableComment: "", columns: [makeColumn("id", 0), { ...makeColumn("name", 1), name: "draft_name" }], indexes: [], foreignKeys: [], triggers: [], initialized: true } } : {}),
+ "onUpdate:draft": (draft) => {
+ latestDraft = draft;
+ },
+ });
+ mountedApps.push(app);
+ app.mount(root);
+ await vi.waitFor(() => expect(root.querySelector("[data-starrocks-alter-status]")?.textContent).toContain("starrocksStatus.RUNNING"));
+ await settle();
+ mocks.getColumns.mockClear();
+ state = "FINISHED";
+ const refresh = [...root.querySelectorAll<HTMLButtonElement>("[data-starrocks-alter-status] button")].find((button) => button.textContent === "starrocksStatus.refresh")!;
+ await vi.waitFor(() => expect(refresh.disabled).toBe(false));
+ refresh.click();
+ await vi.waitFor(() => expect(root.querySelector("[data-starrocks-alter-status]")?.textContent).toContain("starrocksStatus.idle"));
+ await settle();
+ if (dirty) {
+ expect(mocks.getColumns).not.toHaveBeenCalled();
+ expect(latestDraft?.columns?.[1]?.name).toBe("draft_name");
+ } else {
+ await vi.waitFor(() => expect(mocks.getColumns).toHaveBeenCalled());
+ expect(latestDraft?.columns?.[1]?.name).toBe("name");
+ }
+ } finally {
+ mocks.connection.db_type = previousType;
+ }
+});
+
+it.each(["existing", "added", "create"].flatMap((mode) => ["decimal(7,0)", "varchar(255)"].map((dataType) => ({ mode, dataType }))))("keeps StarRocks defaults valid for $mode $dataType", async ({ mode, dataType }) => {
+ mocks.renderColumnRows = true;
+ const previousType = mocks.connection.db_type;
+ mocks.connection.db_type = "starrocks";
+ mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE `t` (`id` INT, `price` DECIMAL(7,0)) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM", cacheStatus: "remote" });
+ try {
+ const root = document.createElement("div");
+ document.body.append(root);
+ const app = createApp(TableStructureEditor, {
+ connectionId: mocks.connection.id,
+ database: "test",
+ tableName: mode === "create" ? "" : "t",
+ draft: {
+ dirty: true,
+ activeTab: "columns",
+ newTableName: "t",
+ tableComment: "",
+ originalTableComment: "",
+ columns: [
+ {
+ id: "price",
+ name: "price",
+ dataType,
+ isNullable: true,
+ defaultValue: "'0'",
+ comment: "",
+ isPrimaryKey: false,
+ extra: {},
+ markedForDrop: false,
+ original: mode === "existing" ? { name: "price", data_type: dataType, is_nullable: true, is_primary_key: false, column_default: "'0'" } : undefined,
+ },
+ ],
+ indexes: [],
+ foreignKeys: [],
+ triggers: [],
+ initialized: true,
+ },
+ });
+ mountedApps.push(app);
+ app.mount(root);
+ await vi.waitFor(() => expect(root.querySelector(".structure-column-default-value input")).not.toBeNull());
+ await settle();
+ const input = root.querySelector<HTMLInputElement>(".structure-column-default-value input")!;
+ const presets = root.querySelector<HTMLButtonElement>('button[aria-label="structureEditor.defaultValuePresets"]')!;
+ expect(input.value).toBe("'0'");
+ expect(input.disabled).toBe(mode === "existing");
+ expect(presets.disabled).toBe(mode === "existing");
+ const expected = dataType.startsWith("decimal") ? ["'0'", "'1'"] : mode === "create" ? ["''", "(uuid())"] : ["''"];
+ expect(Array.from(root.querySelectorAll(".structure-column-default-value code"), (node) => node.textContent)).toEqual(["structureEditor.unsetDefault", "NULL", ...expected]);
+ } finally {
+ mocks.connection.db_type = previousType;
+ }
+});
diff --git a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts
index dae618a564..c37f6697be 100644
--- a/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts
+++ b/apps/desktop/src/components/structure/__tests__/TableStructureEditor.metadataRevalidation.spec.ts
@@ -610,8 +610,6 @@ describe("TableStructureEditor column index actions", () => {
it.each([
["Doris", "doris", "doris"],
["Doris MySQL profile", "mysql", "doris"],
- ["StarRocks", "starrocks", "starrocks"],
- ["StarRocks MySQL profile", "mysql", "starrocks"],
["GoldenDB", "goldendb", "goldendb"],
["SunDB", "sundb", "sundb"],
["Databend", "databend", "databend"],
@@ -626,6 +624,23 @@ describe("TableStructureEditor column index actions", () => {
expect(mocks.executeBatch).not.toHaveBeenCalled();
});
+ it.each([
+ ["StarRocks", "starrocks", "starrocks"],
+ ["StarRocks MySQL profile", "mysql", "starrocks"],
+ ] as const)("disables unsupported ordinary index creation on %s", async (_label, databaseType, driverProfile) => {
+ mocks.connection.db_type = databaseType;
+ mocks.connection.driver_profile = driverProfile;
+ loadMetadata();
+ const root = await mountStructureEditor();
+ await openSubmenu(fieldRow(root, "email"), "structureEditor.createColumnIndex");
+ const button = menuButton("structureEditor.createNormalIndex");
+ expect(button.disabled).toBe(true);
+ button.click();
+ await settle();
+ expect(indexRow(root)).toBeNull();
+ expect(mocks.executeBatch).not.toHaveBeenCalled();
+ });
+
it("preserves lowercase table-qualified naming for GaussDB M-mode", async () => {
mocks.connection.db_type = "gaussdb";
mocks.connection.driver_profile = "gaussdb-m";
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 77c8f93955..01dae4b685 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -88,6 +88,151 @@ export default {
templateHelp:
"Variables: table.name, table.schema, table.comment, class.name; inside a columns section: column.name, column.type, column.originalType, column.comment, column.defaultValue, column.nullable, column.primaryKey. Use double braces for variables, #columns and /columns for loops, #column.nullable and /column.nullable for conditional sections.",
},
+ starrocksStatus: {
+ sql: "Job SQL",
+ localSql: "Last SQL submitted here; matching job unconfirmed.",
+ sqlUnavailable: "SQL is unavailable for this job.",
+ label: "Schema change",
+ checking: "Checking",
+ idle: "No active jobs",
+ PENDING: "Pending",
+ WAITING_TXN: "Waiting for transactions",
+ RUNNING: "Running",
+ FINISHED: "Finished",
+ CANCELLED: "Cancelled",
+ unknownState: "Unknown state: {state}",
+ queryFailed: "Status unavailable",
+ polling: "Checking every 3 seconds",
+ checkedAt: "Last checked {time}",
+ details: "Job details",
+ refresh: "Check status",
+ busyHint: "Keep editing while the job runs; save when it finishes.",
+ draftHint: "Job finished. Review your saved draft before refreshing.",
+ failureHint: "Job status is unconfirmed. Try again.",
+ noJobs: "No unfinished schema change jobs.",
+ job: "Job",
+ state: "State",
+ created: "Created",
+ finished: "Finished",
+ structureRefreshFailed: "The job ended but the structure could not be refreshed. Refresh manually.",
+ },
+ starrocksLayout: {
+ schemaChangeBusy: "Table {table} is being changed. Wait, refresh, then save.",
+ sortSaveSeparately: "Save sort-key changes separately from other table-structure changes.",
+ editSortHint: "Select sort columns in priority order and save separately. Select at least one, but not every column. Aggregate and Unique tables require all key columns.",
+ editSortVersionHint: "This connection does not support editing sort columns.",
+ reorderMetadataHint: "Refresh the table structure before reordering columns.",
+ reorderHint: "Drag and save to reorder columns. Keep key columns first and save separately from other column edits.",
+ localReorderHint: "Dragging changes display order only.",
+ copySaveFirst: "Save or discard current structure edits before creating a new table.",
+ partitionAndBucketTitle: "Partitions and buckets",
+ copyButton: "Change partitions and buckets",
+ copyTitle: "Change partitions and buckets · Create a new table",
+ copyHint: "Create a new table from {table} with the settings below. Keep the original table.",
+ copyLoading: "Reading the source table structure…",
+ copyTargetName: "New table name",
+ copyTransferData: "Transfer source data",
+ copyTransferHint: "One-time copy; later changes are not synced. Pause writes for a full migration and ensure partitions cover all data.",
+ copyKeepPartition: "Keep the source partition configuration",
+ copyColocationHint: "The new table does not inherit the source colocation group.",
+ copyPartitionHint: "New partition settings replace the source partition creation and retention rules.",
+ copyMetadataUnavailable: "Could not read the full table structure. Refresh the connection and retry.",
+ copyNameRequired: "Enter a new table name different from the source.",
+ copyNoInsertColumns: "There are no writable columns to transfer.",
+ copyTransferFailed: "Table {table} created; data transfer is unconfirmed. Check before retrying to avoid duplicates.\n{message}",
+ copyCreateFailed: "Table creation is unconfirmed. Check whether {table} exists before retrying.\n{message}",
+ copyStage_creating: "Creating {table}…",
+ copyStage_created: "Table {table} was created.",
+ copyStage_transferring: "Table created; transferring data…",
+ copyStage_complete: "Completed. New table: {table}.",
+ copyRunning: "Running…",
+ copyExecute: "Create new table",
+
+ automaticBucketsReadonly: "Automatic bucket scaling is enabled. Create a new table and migrate data to change bucketing.",
+ operation_replicas: "Change replicas",
+ operation_drop: "Drop partition",
+ operation_addList: "Add list partition",
+ operation_addRange: "Add range partition",
+ addValueTuple: "Add value tuple",
+ removePartitionOperation: "Remove",
+ queuePartitionOperation: "Queue operation",
+ partitionValuesHint: "Enter raw values without quotes; include all fields in each combination. Automatic partitions are created on write.",
+ dropPartitionHint: "Dropping a partition deletes its data. Check before saving.",
+ rangeUpper: "Upper bound (exclusive)",
+ rangeLower: "Lower bound (inclusive)",
+ partitionNameInput: "Partition name",
+ partitionNameAll: "Partition name, or * for all",
+ addListPartition: "Add list partition",
+ addRangePartition: "Add range partition",
+ dropPartition: "Drop partition",
+ partitionReplicas: "Change partition replicas",
+ partitionReadonly: "Create a new table and migrate data to change partitioning.",
+ alterBucketsHint: "Leave blank for automatic sizing. Saving redistributes existing data. Random bucketing is for Duplicate Key tables only.",
+ defaultBucketsOnly: "Apply only to new partitions",
+ alterLayoutUnavailable: "Bucketing cannot be edited for this table.",
+ alterLayoutHint: "Save partition, bucket and column changes separately. Refresh when the job finishes.",
+ alterLayoutTitle: "Partitions and buckets (existing table)",
+ alterSubmitted: "Changes submitted. Refresh when complete.",
+ alterHint: "Some column properties are read-only. Set defaults when creating tables or adding columns. Nullable columns cannot become required. Wait for changes to finish, then refresh.",
+ sortColumns: "Sort columns",
+ missingSortColumn: "Removed column",
+ moveSortUp: "Increase sort priority",
+ moveSortDown: "Decrease sort priority",
+ removeSortColumn: "Remove sort column",
+ sortHint: "Set storage sorting in priority order, or leave blank for defaults. Query results follow the query’s sort order.",
+ sortVersionHint: "This connection does not support custom sort columns.",
+
+ title: "Partitioning, bucketing and sorting",
+ timePartition: "Partition by time",
+ partitionColumn: "Time column",
+ selectColumn: "Select a column",
+ granularity: "Granularity",
+ year: "Year",
+ month: "Month",
+ day: "Day",
+ distribution: "Bucketing strategy",
+ auto: "Automatic",
+ hash: "Hash",
+ random: "Random",
+ hashColumns: "Hash columns",
+ bucketCount: "Buckets per partition",
+ partitionHint: "Choose a date or time column to create partitions by the selected period on write.",
+ autoPrimaryHint: "Automatically hash by primary key columns.",
+ autoDuplicateHint: "Automatically choose an available strategy, preferring random bucketing.",
+ bucketHint: "Hash by frequently filtered, evenly distributed columns. Random bucketing requires a table without a primary key.",
+ primaryKeyHint: "Partition and hash columns must belong to the primary key. Key columns are placed first.",
+ versionHint: "Time partitioning or random bucketing is unavailable for this connection.",
+ noTimeColumn: "Add a date or datetime column first.",
+ unavailableColumn: "Removed or unsupported column",
+ invalidSelection: "A selected column is no longer available. Select again.",
+ partitionStrategy: "Partition strategy",
+ none: "No partitioning",
+ time: "Automatic · time expression",
+ values: "Automatic · column values",
+ range: "Range · explicit bounds",
+ list: "List · explicit values",
+ partitionColumns: "Partition columns (in selection order)",
+ additionalColumns: "Additional dimensions (optional)",
+ noneHint: "Use one partition for the table; bucketing still applies.",
+ timeHint: "Partition automatically by period; add columns to subdivide further.",
+ valuesHint: "Partition by distinct values or combinations. Avoid columns with many unique values, such as IDs.",
+ rangeHint: "Ranges include the start, not the end. Compare multi-column values in order; values outside all ranges cannot be inserted.",
+ listHint: "Enter a complete value combination per row, without quotes. Unlisted values cannot be inserted.",
+ timeInterval: "Custom interval (optional)",
+ calendarUnit: "Calendar unit",
+ timeIntervalHint: "Leave blank for calendar periods. Enter 7 with Day for seven-day partitions. Custom intervals and hourly partitions need a datetime column.",
+ hour: "Hour",
+ partitionName: "Partition name",
+ lower: "From (inclusive)",
+ upper: "To (exclusive)",
+ valuePlaceholder: "Value, without SQL quotes",
+ addPartition: "Add partition",
+ removePartition: "Remove partition",
+ addValues: "Add value tuple",
+ removeValues: "Remove tuple",
+ noEligibleColumns: "No eligible columns",
+ bucketCountHint: "Automatic bucket counts depend on cluster resources and data volume. Enter a number to use that many buckets per partition.",
+ },
graph: {
title: "Graph",
search: "Search graph",
@@ -5435,6 +5580,8 @@ export default {
sortBy: "Sort by",
},
structureEditor: {
+ unsetDefault: "No default value",
+ title: "Edit Table Structure",
createTitle: "Create Table",
editTabTitle: "Edit: {tableName}",
tableName: "Table Name",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 9075b6800e..8022585aa7 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -5218,6 +5218,8 @@ export default withEnglishFallback({
partitionSqlPreview: "SQL que se ejecutará",
partitionNameRequired: "Introduce el nombre de la partición.",
notNull: "No nulo",
+ unsetDefault: "Sin valor predeterminado",
+ title: "Editar estructura de la tabla",
},
diagram: {
title: "Diagrama de relaciones",
@@ -11761,4 +11763,147 @@ export default withEnglishFallback({
noDetails: "Este core no tiene detalles de replicación.",
},
},
+ starrocksStatus: {
+ sql: "SQL de la tarea",
+ localSql: "SQL enviado recientemente desde esta página; aún no se ha confirmado la tarea correspondiente.",
+ sqlUnavailable: "No hay SQL disponible para esta tarea.",
+ label: "Cambio de estructura",
+ checking: "Comprobando",
+ idle: "No hay tareas en ejecución",
+ PENDING: "En cola",
+ WAITING_TXN: "Esperando una transacción",
+ RUNNING: "En ejecución",
+ FINISHED: "Completada",
+ CANCELLED: "Cancelada",
+ unknownState: "Estado desconocido: {state}",
+ queryFailed: "No se pudo obtener el estado",
+ polling: "Comprobar cada 3 segundos",
+ checkedAt: "Última comprobación: {time}",
+ details: "Detalles de la tarea",
+ refresh: "Comprobar estado",
+ busyHint: "Podrá guardar cuando termine la tarea. Puede seguir editando mientras tanto.",
+ draftHint: "La tarea ha terminado y se ha conservado el borrador. Confirme antes de actualizar la estructura.",
+ failureHint: "No se ha confirmado el estado de la tarea. Vuelva a intentarlo.",
+ noJobs: "No hay tareas de cambio de estructura pendientes.",
+ job: "Tarea",
+ state: "Estado",
+ created: "Fecha de creación",
+ finished: "Fecha de finalización",
+ structureRefreshFailed: "La tarea ha terminado, pero no se pudo actualizar la estructura. Actualícela manualmente.",
+ },
+ starrocksLayout: {
+ schemaChangeBusy: "La tabla {table} se está modificando. Espere a que termine y actualícela antes de guardar.",
+ sortSaveSeparately: "Guarde los cambios de ordenación por separado de los demás cambios de estructura.",
+ editSortHint: "Seleccione las columnas de ordenación por prioridad y guárdelas por separado. Seleccione al menos una, pero no todas; las tablas de agregación y de clave única requieren todas las columnas de clave.",
+ editSortVersionHint: "Esta conexión aún no permite modificar las columnas de ordenación.",
+ reorderMetadataHint: "No se puede cambiar el orden de las columnas. Actualice la estructura y vuelva a intentarlo.",
+ reorderHint: "Arrastre y guarde para cambiar el orden de las columnas. Las columnas de clave deben ir primero. Guarde este cambio por separado.",
+ localReorderHint: "Arrastrar solo cambia el orden de visualización, no la base de datos.",
+ copySaveFirst: "Guarde o descarte los cambios de estructura antes de crear otra tabla.",
+ partitionAndBucketTitle: "Particiones y buckets",
+ copyButton: "Modificar particiones y buckets",
+ copyTitle: "Modificar particiones y buckets · Crear tabla",
+ copyHint: "Cree otra tabla con la estructura de {table} y la configuración siguiente. Se conservará la tabla original.",
+ copyLoading: "Leyendo la estructura original…",
+ copyTargetName: "Nombre de la nueva tabla",
+ copyTransferData: "Transferir los datos originales",
+ copyTransferHint: "Los datos se copian una sola vez y no se sincronizan después. Detenga las escrituras antes de una migración completa y asegúrese de que las particiones cubran todos los datos.",
+ copyKeepPartition: "Conservar la configuración de particiones original",
+ copyColocationHint: "La nueva tabla no hereda el grupo Colocate de la original.",
+ copyPartitionHint: "Al reconfigurar las particiones, dejan de aplicarse las reglas originales de creación y retención.",
+ copyMetadataUnavailable: "No se pudo leer la estructura completa. Actualice la conexión y vuelva a intentarlo.",
+ copyNameRequired: "Introduzca un nombre distinto al de la tabla original.",
+ copyNoInsertColumns: "No hay columnas normales que se puedan transferir.",
+ copyTransferFailed: "Se ha creado {table}, pero no se ha confirmado que la transferencia haya terminado. Compruébelo antes de reintentar para evitar duplicados.\n{message}",
+ copyCreateFailed: "No se ha confirmado la creación. Compruebe primero si {table} ya existe.\n{message}",
+ copyStage_creating: "Creando {table}…",
+ copyStage_created: "Se ha creado la tabla {table}.",
+ copyStage_transferring: "Tabla creada. Transfiriendo datos…",
+ copyStage_complete: "Completado. Nueva tabla: {table}.",
+ copyRunning: "Ejecutando…",
+ copyExecute: "Crear tabla",
+ automaticBucketsReadonly: "La ampliación automática de buckets está activada. Para cambiar los buckets, cree otra tabla y migre los datos.",
+ operation_replicas: "Cambiar el número de réplicas",
+ operation_drop: "Eliminar partición",
+ operation_addList: "Añadir partición de lista",
+ operation_addRange: "Añadir partición de rango",
+ addValueTuple: "Añadir un conjunto de valores",
+ removePartitionOperation: "Quitar",
+ queuePartitionOperation: "Añadir a las operaciones pendientes",
+ partitionValuesHint: "Introduzca valores sin comillas; para varias columnas, introduzca combinaciones completas. Las particiones automáticas se crean al escribir datos.",
+ dropPartitionHint: "Eliminar una partición borra sus datos. Confirme antes de guardar.",
+ rangeUpper: "Valor final (exclusivo)",
+ rangeLower: "Valor inicial (inclusivo)",
+ partitionNameInput: "Nombre de la partición",
+ partitionNameAll: "Nombre de partición, o * para todas",
+ addListPartition: "Añadir partición de lista",
+ addRangePartition: "Añadir partición de rango",
+ dropPartition: "Eliminar partición",
+ partitionReplicas: "Cambiar las réplicas de la partición",
+ partitionReadonly: "Para cambiar el método de particionado, cree otra tabla y migre los datos.",
+ alterBucketsHint: "Déjelo vacío para determinar automáticamente el número de buckets. Guardar redistribuye los datos existentes. La distribución aleatoria solo se admite en tablas de clave duplicada.",
+ defaultBucketsOnly: "Aplicar solo a particiones nuevas",
+ alterLayoutUnavailable: "Esta tabla aún no permite modificar los buckets.",
+ alterLayoutHint: "Guarde los cambios de particiones, buckets y columnas por separado. Actualice cuando termine la tarea.",
+ alterLayoutTitle: "Particiones y buckets (tabla existente)",
+ alterSubmitted: "Cambio enviado. Actualice cuando termine.",
+ alterHint: "Algunos atributos no se pueden modificar. Los valores predeterminados solo se establecen al crear la tabla o añadir columnas; las columnas que admiten NULL no pueden pasar a NOT NULL. Tras guardar, espere a que termine antes de actualizar.",
+ sortColumns: "Columnas de ordenación",
+ missingSortColumn: "Columna eliminada",
+ moveSortUp: "Subir prioridad de ordenación",
+ moveSortDown: "Bajar prioridad de ordenación",
+ removeSortColumn: "Quitar columna de ordenación",
+ sortHint: "Defina la ordenación de almacenamiento por prioridad, o déjelo vacío para usar la predeterminada. El orden de los resultados depende de la consulta.",
+ sortVersionHint: "Esta conexión aún no admite columnas de ordenación personalizadas.",
+ title: "Particiones, buckets y ordenación",
+ timePartition: "Particionado temporal",
+ partitionColumn: "Columna temporal",
+ selectColumn: "Seleccionar columna",
+ granularity: "Granularidad de partición",
+ year: "Por año",
+ month: "Por mes",
+ day: "Por día",
+ distribution: "Método de distribución",
+ auto: "Automático",
+ hash: "Distribución hash",
+ random: "Distribución aleatoria",
+ hashColumns: "Columnas de distribución",
+ bucketCount: "Buckets por partición",
+ partitionHint: "Seleccione una columna de fecha o fecha y hora. Al escribir, los datos se particionan automáticamente por el periodo seleccionado.",
+ autoPrimaryHint: "Distribución hash automática por las columnas de clave primaria.",
+ autoDuplicateHint: "Selecciona automáticamente un método disponible, con preferencia por la distribución aleatoria.",
+ bucketHint: "Para hash, elija columnas usadas habitualmente como filtro y con distribución uniforme. La distribución aleatoria solo se admite en tablas sin clave primaria.",
+ primaryKeyHint: "Las columnas de partición y hash deben pertenecer a la clave primaria. Las columnas de clave primaria se colocan primero automáticamente.",
+ versionHint: "Esta conexión aún no admite particionado temporal o distribución aleatoria.",
+ noTimeColumn: "Añada primero una columna de tipo date o datetime.",
+ unavailableColumn: "Columna eliminada o tipo no compatible",
+ invalidSelection: "La selección ya no es válida. Vuelva a seleccionar las columnas.",
+ partitionStrategy: "Método de particionado",
+ none: "Sin particiones",
+ time: "Automático · Expresión temporal",
+ values: "Automático · Valores de columnas",
+ range: "Manual · Rango",
+ list: "Manual · Lista",
+ partitionColumns: "Columnas de partición (en orden de selección)",
+ additionalColumns: "Columnas de dimensión adicionales (opcional)",
+ noneHint: "Toda la tabla forma una partición; puede seguir usando buckets.",
+ timeHint: "Particionado automático por el periodo seleccionado. Añada columnas para subdividirlo.",
+ valuesHint: "Particionado automático por valores o combinaciones. Evite columnas con demasiados valores distintos, como los ID únicos.",
+ rangeHint: "El rango incluye el inicio y excluye el final. Las combinaciones se comparan por orden de columna; no se pueden escribir datos fuera de los rangos.",
+ listHint: "Introduzca un conjunto completo de valores sin comillas por fila. No se pueden escribir valores que no estén en la lista.",
+ timeInterval: "Intervalo personalizado (opcional)",
+ calendarUnit: "Periodo natural",
+ timeIntervalHint: "Déjelo vacío para usar periodos naturales. Por ejemplo, 7 con «Por día» crea particiones de 7 días. Los intervalos personalizados y las particiones por hora requieren una columna datetime.",
+ hour: "Por hora",
+ partitionName: "Nombre de la partición",
+ lower: "Valor inicial (inclusivo)",
+ upper: "Valor final (exclusivo)",
+ valuePlaceholder: "Valor sin comillas",
+ addPartition: "Añadir partición",
+ removePartition: "Quitar partición",
+ addValues: "Añadir conjunto de valores",
+ removeValues: "Quitar conjunto",
+ noEligibleColumns: "No hay columnas compatibles",
+ bucketCountHint: "La base de datos determina automáticamente el número de buckets según los recursos del clúster y el volumen de datos; no es fijo. Introduzca un número para fijarlo por partición.",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index b242acf9d0..bb1d629c3b 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -5033,6 +5033,8 @@ export default withEnglishFallback({
partitionSqlPreview: "SQL da eseguire",
partitionNameRequired: "Inserisci il nome della partizione.",
notNull: "Non NULL",
+ unsetDefault: "Nessun valore predefinito",
+ title: "Modifica struttura della tabella",
},
diagram: {
title: "Diagramma delle Relazioni",
@@ -11323,4 +11325,147 @@ export default withEnglishFallback({
noDetails: "Questo core non ha dettagli di replicazione.",
},
},
+ starrocksStatus: {
+ sql: "SQL dell'attività",
+ localSql: "SQL inviato di recente da questa pagina; l'attività corrispondente non è ancora confermata.",
+ sqlUnavailable: "SQL non disponibile per questa attività.",
+ label: "Modifica della struttura",
+ checking: "Verifica in corso",
+ idle: "Nessuna attività in esecuzione",
+ PENDING: "In coda",
+ WAITING_TXN: "In attesa di una transazione",
+ RUNNING: "In esecuzione",
+ FINISHED: "Completata",
+ CANCELLED: "Annullata",
+ unknownState: "Stato sconosciuto: {state}",
+ queryFailed: "Impossibile ottenere lo stato",
+ polling: "Verifica ogni 3 secondi",
+ checkedAt: "Ultima verifica: {time}",
+ details: "Dettagli dell'attività",
+ refresh: "Verifica stato",
+ busyHint: "Sarà possibile salvare al termine dell'attività. Nel frattempo è possibile continuare a modificare.",
+ draftHint: "L'attività è terminata e la bozza è stata conservata. Confermare prima di aggiornare la struttura.",
+ failureHint: "Stato dell'attività non confermato. Riprovare.",
+ noJobs: "Nessuna modifica della struttura in sospeso.",
+ job: "Attività",
+ state: "Stato",
+ created: "Data di creazione",
+ finished: "Data di completamento",
+ structureRefreshFailed: "L'attività è terminata, ma l'aggiornamento della struttura è fallito. Aggiornare manualmente.",
+ },
+ starrocksLayout: {
+ schemaChangeBusy: "La tabella {table} è in modifica. Attendere il completamento e aggiornare prima di salvare.",
+ sortSaveSeparately: "Salvare le modifiche all'ordinamento separatamente dalle altre modifiche della struttura.",
+ editSortHint: "Selezionare le colonne di ordinamento per priorità e salvarle separatamente. Sceglierne almeno una, ma non tutte; le tabelle di aggregazione e con chiave univoca richiedono tutte le colonne chiave.",
+ editSortVersionHint: "Questa connessione non supporta ancora la modifica delle colonne di ordinamento.",
+ reorderMetadataHint: "Impossibile riordinare le colonne. Aggiornare la struttura e riprovare.",
+ reorderHint: "Trascinare e salvare per riordinare le colonne. Le colonne chiave devono precedere le altre. Salvare questa modifica separatamente.",
+ localReorderHint: "Il trascinamento cambia solo l'ordine visualizzato, non il database.",
+ copySaveFirst: "Salvare o annullare le modifiche alla struttura prima di creare un'altra tabella.",
+ partitionAndBucketTitle: "Partizioni e bucket",
+ copyButton: "Modifica partizioni e bucket",
+ copyTitle: "Modifica partizioni e bucket · Crea tabella",
+ copyHint: "Creare una nuova tabella con la struttura di {table} e la configurazione seguente. La tabella originale verrà conservata.",
+ copyLoading: "Lettura della struttura originale…",
+ copyTargetName: "Nome della nuova tabella",
+ copyTransferData: "Trasferisci i dati originali",
+ copyTransferHint: "I dati vengono copiati una sola volta e non vengono sincronizzati in seguito. Sospendere le scritture prima di una migrazione completa e assicurarsi che le partizioni coprano tutti i dati.",
+ copyKeepPartition: "Mantieni la configurazione delle partizioni originale",
+ copyColocationHint: "La nuova tabella non eredita il gruppo Colocate dell'originale.",
+ copyPartitionHint: "Riconfigurando le partizioni, le regole originali di creazione e conservazione non vengono mantenute.",
+ copyMetadataUnavailable: "Impossibile leggere la struttura completa. Aggiornare la connessione e riprovare.",
+ copyNameRequired: "Inserire un nome diverso da quello della tabella originale.",
+ copyNoInsertColumns: "Nessuna colonna ordinaria trasferibile.",
+ copyTransferFailed: "La tabella {table} è stata creata, ma il completamento del trasferimento non è confermato. Verificare prima di riprovare per evitare importazioni duplicate.\n{message}",
+ copyCreateFailed: "Creazione non confermata. Verificare prima se {table} esiste già.\n{message}",
+ copyStage_creating: "Creazione di {table}…",
+ copyStage_created: "La tabella {table} è stata creata.",
+ copyStage_transferring: "Tabella creata. Trasferimento dei dati…",
+ copyStage_complete: "Completato. Nuova tabella: {table}.",
+ copyRunning: "Esecuzione…",
+ copyExecute: "Crea tabella",
+ automaticBucketsReadonly: "L'espansione automatica dei bucket è attiva. Per modificarli, creare un'altra tabella e migrare i dati.",
+ operation_replicas: "Modifica numero di repliche",
+ operation_drop: "Elimina partizione",
+ operation_addList: "Aggiungi partizione a elenco",
+ operation_addRange: "Aggiungi partizione a intervallo",
+ addValueTuple: "Aggiungi un insieme di valori",
+ removePartitionOperation: "Rimuovi",
+ queuePartitionOperation: "Aggiungi alle operazioni in sospeso",
+ partitionValuesHint: "Inserire valori senza virgolette e combinazioni complete per più colonne. Le partizioni automatiche vengono create durante la scrittura.",
+ dropPartitionHint: "Eliminando una partizione si eliminano i suoi dati. Confermare prima di salvare.",
+ rangeUpper: "Valore finale (escluso)",
+ rangeLower: "Valore iniziale (incluso)",
+ partitionNameInput: "Nome della partizione",
+ partitionNameAll: "Nome della partizione, oppure * per tutte",
+ addListPartition: "Aggiungi partizione a elenco",
+ addRangePartition: "Aggiungi partizione a intervallo",
+ dropPartition: "Elimina partizione",
+ partitionReplicas: "Modifica repliche della partizione",
+ partitionReadonly: "Per cambiare il metodo di partizionamento, creare un'altra tabella e migrare i dati.",
+ alterBucketsHint: "Lasciare vuoto per determinare automaticamente il numero di bucket. Il salvataggio ridistribuisce i dati esistenti. La distribuzione casuale è disponibile solo per le tabelle con chiave duplicata.",
+ defaultBucketsOnly: "Applica solo alle nuove partizioni",
+ alterLayoutUnavailable: "Questa tabella non supporta ancora la modifica dei bucket.",
+ alterLayoutHint: "Salvare separatamente le modifiche a partizioni, bucket e colonne. Aggiornare al termine dell'attività.",
+ alterLayoutTitle: "Partizioni e bucket (tabella esistente)",
+ alterSubmitted: "Modifica inviata. Aggiornare al completamento.",
+ alterHint: "Alcuni attributi non sono modificabili. I valori predefiniti si impostano solo alla creazione della tabella o all'aggiunta di colonne; le colonne che ammettono NULL non possono diventare NOT NULL. Dopo il salvataggio, attendere il completamento prima di aggiornare.",
+ sortColumns: "Colonne di ordinamento",
+ missingSortColumn: "Colonna eliminata",
+ moveSortUp: "Aumenta priorità di ordinamento",
+ moveSortDown: "Riduci priorità di ordinamento",
+ removeSortColumn: "Rimuovi colonna di ordinamento",
+ sortHint: "Impostare l'ordinamento dei dati per priorità o lasciare vuoto per quello predefinito. L'ordine dei risultati dipende dalla query.",
+ sortVersionHint: "Questa connessione non supporta ancora colonne di ordinamento personalizzate.",
+ title: "Partizioni, bucket e ordinamento",
+ timePartition: "Partizionamento temporale",
+ partitionColumn: "Colonna temporale",
+ selectColumn: "Seleziona colonna",
+ granularity: "Granularità delle partizioni",
+ year: "Per anno",
+ month: "Per mese",
+ day: "Per giorno",
+ distribution: "Metodo di distribuzione",
+ auto: "Automatico",
+ hash: "Distribuzione hash",
+ random: "Distribuzione casuale",
+ hashColumns: "Colonne di distribuzione",
+ bucketCount: "Bucket per partizione",
+ partitionHint: "Selezionare una colonna data o data e ora. Durante la scrittura, i dati vengono partizionati automaticamente per il periodo selezionato.",
+ autoPrimaryHint: "Distribuzione hash automatica sulle colonne della chiave primaria.",
+ autoDuplicateHint: "Seleziona automaticamente un metodo disponibile, preferendo la distribuzione casuale.",
+ bucketHint: "Per l'hash, scegliere colonne usate spesso nei filtri e distribuite uniformemente. La distribuzione casuale è disponibile solo per tabelle senza chiave primaria.",
+ primaryKeyHint: "Le colonne di partizione e hash devono appartenere alla chiave primaria. Le colonne della chiave primaria vengono posizionate automaticamente per prime.",
+ versionHint: "Questa connessione non supporta ancora il partizionamento temporale o la distribuzione casuale.",
+ noTimeColumn: "Aggiungere prima una colonna di tipo date o datetime.",
+ unavailableColumn: "Colonna rimossa o tipo non supportato",
+ invalidSelection: "Selezione non più valida. Selezionare nuovamente le colonne.",
+ partitionStrategy: "Metodo di partizionamento",
+ none: "Nessuna partizione",
+ time: "Automatico · Espressione temporale",
+ values: "Automatico · Valori delle colonne",
+ range: "Manuale · Intervallo",
+ list: "Manuale · Elenco",
+ partitionColumns: "Colonne di partizione (in ordine di selezione)",
+ additionalColumns: "Colonne dimensionali aggiuntive (facoltative)",
+ noneHint: "L'intera tabella costituisce una partizione; è comunque possibile usare i bucket.",
+ timeHint: "Partizionamento automatico per il periodo selezionato. Aggiungere colonne per ulteriori suddivisioni.",
+ valuesHint: "Partizionamento automatico per valori o combinazioni. Evitare colonne con troppi valori distinti, come ID univoci.",
+ rangeHint: "L'intervallo include l'inizio ed esclude la fine. Le combinazioni vengono confrontate nell'ordine delle colonne; i dati esterni agli intervalli non possono essere scritti.",
+ listHint: "Inserire un insieme completo di valori senza virgolette per riga. I valori non elencati non possono essere scritti.",
+ timeInterval: "Intervallo personalizzato (facoltativo)",
+ calendarUnit: "Periodo naturale",
+ timeIntervalHint: "Lasciare vuoto per i periodi naturali. Ad esempio, 7 con «Per giorno» crea partizioni di 7 giorni. Gli intervalli personalizzati e il partizionamento orario richiedono una colonna datetime.",
+ hour: "Per ora",
+ partitionName: "Nome della partizione",
+ lower: "Valore iniziale (incluso)",
+ upper: "Valore finale (escluso)",
+ valuePlaceholder: "Valore senza virgolette",
+ addPartition: "Aggiungi partizione",
+ removePartition: "Rimuovi partizione",
+ addValues: "Aggiungi insieme di valori",
+ removeValues: "Rimuovi insieme",
+ noEligibleColumns: "Nessuna colonna supportata",
+ bucketCountHint: "Il database determina automaticamente il numero di bucket in base alle risorse del cluster e al volume dei dati; non è fisso. Inserire un numero per fissarlo per ogni partizione.",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index fc0e78cabd..85f7c9d5ab 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -5100,6 +5100,8 @@ export default withEnglishFallback({
partitionSqlPreview: "実行される SQL",
partitionNameRequired: "パーティション名を入力してください。",
notNull: "NOT NULL",
+ unsetDefault: "デフォルト値を設定しない",
+ title: "テーブル構造を編集",
},
diagram: {
title: "リレーション図",
@@ -11361,4 +11363,147 @@ export default withEnglishFallback({
noDetails: "このコアにはレプリケーションの詳細がありません。",
},
},
+ starrocksStatus: {
+ sql: "タスクの SQL",
+ localSql: "このページで直近に送信した SQL です。対応するタスクはまだ確認されていません。",
+ sqlUnavailable: "このタスクの SQL はありません。",
+ label: "構造変更",
+ checking: "確認中",
+ idle: "実行中のタスクはありません",
+ PENDING: "待機中",
+ WAITING_TXN: "トランザクション待ち",
+ RUNNING: "実行中",
+ FINISHED: "完了",
+ CANCELLED: "キャンセル済み",
+ unknownState: "不明な状態:{state}",
+ queryFailed: "状態の取得に失敗しました",
+ polling: "3 秒ごとに確認",
+ checkedAt: "最終確認:{time}",
+ details: "タスクの詳細",
+ refresh: "状態を確認",
+ busyHint: "タスク完了後に保存できます。その間も編集を続けられます。",
+ draftHint: "タスクが完了しました。下書きは保持されています。確認後にテーブル構造を更新してください。",
+ failureHint: "タスクの状態を確認できませんでした。再試行してください。",
+ noJobs: "未完了の構造変更タスクはありません。",
+ job: "タスク",
+ state: "状態",
+ created: "作成日時",
+ finished: "終了日時",
+ structureRefreshFailed: "タスクは終了しましたが、テーブル構造の更新に失敗しました。手動で更新してください。",
+ },
+ starrocksLayout: {
+ schemaChangeBusy: "テーブル {table} は変更中です。完了後に更新してから保存してください。",
+ sortSaveSeparately: "ソート列の変更は、他の構造変更と分けて保存してください。",
+ editSortHint: "優先順位順にソート列を選択し、変更を個別に保存してください。1 列以上選び、全列は選択できません。集約テーブルとユニークキーテーブルでは、すべてのキー列を選択する必要があります。",
+ editSortVersionHint: "現在の接続ではソート列の変更に対応していません。",
+ reorderMetadataHint: "列の順序を変更できません。テーブル構造を更新して再試行してください。",
+ reorderHint: "ドラッグして保存すると列の順序を変更できます。キー列は通常列より前に置いてください。他の列変更と分けて保存してください。",
+ localReorderHint: "ドラッグで変わるのは表示順だけです。データベースは変更されません。",
+ copySaveFirst: "新しいテーブルを作成する前に、現在の構造変更を保存または破棄してください。",
+ partitionAndBucketTitle: "パーティションとバケット",
+ copyButton: "パーティションとバケットを変更",
+ copyTitle: "パーティションとバケットを変更 · 新規テーブル作成",
+ copyHint: "{table} の構造と以下の設定で新しいテーブルを作成します。元のテーブルは保持されます。",
+ copyLoading: "元のテーブル構造を読み込み中…",
+ copyTargetName: "新しいテーブル名",
+ copyTransferData: "元のテーブルのデータを転送",
+ copyTransferHint: "データのコピーは 1 回のみで、その後は同期されません。完全移行の前に書き込みを停止し、パーティションがすべてのデータをカバーしていることを確認してください。",
+ copyKeepPartition: "元のパーティション設定を使用",
+ copyColocationHint: "新しいテーブルは元の Colocate グループを継承しません。",
+ copyPartitionHint: "パーティションを再設定すると、元の作成ルールと保持ルールは引き継がれません。",
+ copyMetadataUnavailable: "完全なテーブル構造を取得できません。接続を更新して再試行してください。",
+ copyNameRequired: "元のテーブルとは異なる名前を入力してください。",
+ copyNoInsertColumns: "転送できる通常列がありません。",
+ copyTransferFailed: "テーブル {table} は作成されましたが、データ転送の完了を確認できません。重複インポートを防ぐため、確認してから再試行してください。\n{message}",
+ copyCreateFailed: "テーブルの作成を確認できません。まず {table} がすでに存在するか確認してください。\n{message}",
+ copyStage_creating: "{table} を作成中…",
+ copyStage_created: "テーブル {table} を作成しました。",
+ copyStage_transferring: "テーブルを作成しました。データを転送中…",
+ copyStage_complete: "完了しました。新しいテーブル:{table}。",
+ copyRunning: "実行中…",
+ copyExecute: "新しいテーブルを作成",
+ automaticBucketsReadonly: "バケットの自動拡張が有効です。バケットを変更するには、新しいテーブルを作成してデータを移行してください。",
+ operation_replicas: "レプリカ数を変更",
+ operation_drop: "パーティションを削除",
+ operation_addList: "リストパーティションを追加",
+ operation_addRange: "範囲パーティションを追加",
+ addValueTuple: "値の組を追加",
+ removePartitionOperation: "削除",
+ queuePartitionOperation: "実行待ちの操作に追加",
+ partitionValuesHint: "引用符なしで元の値を入力してください。複数列の場合は完全な組を入力します。自動パーティションは書き込み時に作成されます。",
+ dropPartitionHint: "パーティションを削除すると、そのデータも削除されます。確認してから保存してください。",
+ rangeUpper: "終了値(含まない)",
+ rangeLower: "開始値(含む)",
+ partitionNameInput: "パーティション名",
+ partitionNameAll: "パーティション名、または全件を示す *",
+ addListPartition: "リストパーティションを追加",
+ addRangePartition: "範囲パーティションを追加",
+ dropPartition: "パーティションを削除",
+ partitionReplicas: "パーティションのレプリカ数を変更",
+ partitionReadonly: "パーティション方式を変更するには、新しいテーブルを作成してデータを移行してください。",
+ alterBucketsHint: "空欄にするとバケット数を自動決定します。保存後に既存データが再分配されます。ランダム分配は Duplicate Key テーブルのみで使用できます。",
+ defaultBucketsOnly: "新規パーティションのみに適用",
+ alterLayoutUnavailable: "現在のテーブルではバケット設定の変更に対応していません。",
+ alterLayoutHint: "パーティション、バケット、列の変更は分けて保存し、タスク完了後に更新してください。",
+ alterLayoutTitle: "パーティションとバケット(既存テーブル)",
+ alterSubmitted: "変更を送信しました。完了後に更新してください。",
+ alterHint: "一部の列属性は変更できません。デフォルト値はテーブル作成時または列追加時のみ設定できます。NULL 許可列は NOT NULL に変更できません。保存後は完了を待ってから更新してください。",
+ sortColumns: "ソート列",
+ missingSortColumn: "列は削除されました",
+ moveSortUp: "ソートの優先順位を上げる",
+ moveSortDown: "ソートの優先順位を下げる",
+ removeSortColumn: "ソート列を削除",
+ sortHint: "格納時のソート順を優先順位順に設定します。空欄はデフォルトです。クエリ結果の順序はクエリで決まります。",
+ sortVersionHint: "現在の接続ではソート列のカスタマイズに対応していません。",
+ title: "パーティション、バケット、ソート",
+ timePartition: "時間でパーティション分割",
+ partitionColumn: "時間列",
+ selectColumn: "列を選択",
+ granularity: "パーティションの粒度",
+ year: "年単位",
+ month: "月単位",
+ day: "日単位",
+ distribution: "バケット分配方式",
+ auto: "自動",
+ hash: "ハッシュ分配",
+ random: "ランダム分配",
+ hashColumns: "バケット列",
+ bucketCount: "パーティションごとのバケット数",
+ partitionHint: "日付または日時列を選択してください。書き込み時に、選択した周期で自動的に分割されます。",
+ autoPrimaryHint: "主キー列で自動的にハッシュ分配します。",
+ autoDuplicateHint: "使用可能な分配方式を自動選択します。ランダム分配が優先されます。",
+ bucketHint: "ハッシュ分配には、フィルターでよく使う均等に分布した列を推奨します。ランダム分配は主キーのないテーブルのみで使用できます。",
+ primaryKeyHint: "パーティション列とハッシュ列は主キーに含まれる必要があります。主キー列は自動的に先頭へ配置されます。",
+ versionHint: "現在の接続では時間分割またはランダム分配に対応していません。",
+ noTimeColumn: "先に date または datetime 型の列を追加してください。",
+ unavailableColumn: "列が削除されたか、型が非対応です",
+ invalidSelection: "選択した列は無効です。選択し直してください。",
+ partitionStrategy: "パーティション方式",
+ none: "分割しない",
+ time: "自動分割 · 時間式",
+ values: "自動分割 · 列の値",
+ range: "手動分割 · 範囲",
+ list: "手動分割 · リスト",
+ partitionColumns: "パーティション列(選択順)",
+ additionalColumns: "追加のディメンション列(任意)",
+ noneHint: "テーブル全体を 1 つのパーティションにします。バケット分配は引き続き使用できます。",
+ timeHint: "選択した周期で自動分割します。列を追加すると、さらに細分化できます。",
+ valuesHint: "異なる値または値の組で自動分割します。一意の ID など、値の種類が多すぎる列は避けてください。",
+ rangeHint: "範囲は開始値を含み、終了値を含みません。複数列の組は列順に比較されます。範囲外のデータは書き込めません。",
+ listHint: "各行に引用符なしで完全な値の組を入力してください。未登録の値は書き込めません。",
+ timeInterval: "カスタム間隔(任意)",
+ calendarUnit: "暦の周期",
+ timeIntervalHint: "空欄は暦の周期で分割します。例えば 7 と「日単位」を指定すると 7 日ごとに分割します。カスタム間隔と時間単位の分割には日時列が必要です。",
+ hour: "時間単位",
+ partitionName: "パーティション名",
+ lower: "開始値(含む)",
+ upper: "終了値(含まない)",
+ valuePlaceholder: "引用符なしの元の値",
+ addPartition: "パーティションを追加",
+ removePartition: "パーティションを削除",
+ addValues: "値の組を追加",
+ removeValues: "この組を削除",
+ noEligibleColumns: "対応する列がありません",
+ bucketCountHint: "自動バケット数は、クラスターのリソースとデータ量に応じてデータベースが決定し、固定ではありません。数値を入力すると各パーティションに指定の数を使用します。",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 700cbad9f0..4dc5a00ab1 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -5076,6 +5076,8 @@ export default withEnglishFallback({
partitionSqlPreview: "실행될 SQL",
partitionNameRequired: "파티션 이름을 입력하세요.",
notNull: "NOT NULL",
+ unsetDefault: "기본값 설정 안 함",
+ title: "테이블 구조 편집",
},
diagram: {
title: "관계 다이어그램",
@@ -10801,4 +10803,147 @@ export default withEnglishFallback({
noDetails: "이 코어에는 복제 세부 정보가 없습니다.",
},
},
+ starrocksStatus: {
+ sql: "작업 SQL",
+ localSql: "이 페이지에서 최근 제출한 SQL입니다. 해당 작업은 아직 확인되지 않았습니다.",
+ sqlUnavailable: "이 작업의 SQL이 없습니다.",
+ label: "구조 변경",
+ checking: "확인 중",
+ idle: "실행 중인 작업 없음",
+ PENDING: "대기 중",
+ WAITING_TXN: "트랜잭션 대기 중",
+ RUNNING: "실행 중",
+ FINISHED: "완료됨",
+ CANCELLED: "취소됨",
+ unknownState: "알 수 없는 상태: {state}",
+ queryFailed: "상태 조회 실패",
+ polling: "3초마다 확인",
+ checkedAt: "마지막 확인: {time}",
+ details: "작업 상세 정보",
+ refresh: "상태 확인",
+ busyHint: "작업 완료 후 저장할 수 있습니다. 그동안 계속 편집할 수 있습니다.",
+ draftHint: "작업이 완료되었으며 초안이 유지됩니다. 확인 후 테이블 구조를 새로 고치세요.",
+ failureHint: "작업 상태가 확인되지 않았습니다. 다시 시도하세요.",
+ noJobs: "완료되지 않은 구조 변경 작업이 없습니다.",
+ job: "작업",
+ state: "상태",
+ created: "생성 시간",
+ finished: "종료 시간",
+ structureRefreshFailed: "작업이 종료되었지만 테이블 구조를 새로 고치지 못했습니다. 수동으로 새로 고치세요.",
+ },
+ starrocksLayout: {
+ schemaChangeBusy: "테이블 {table}을 변경 중입니다. 완료 후 새로 고친 다음 저장하세요.",
+ sortSaveSeparately: "정렬 열 변경은 다른 테이블 구조 변경과 별도로 저장하세요.",
+ editSortHint: "정렬 열을 우선순위대로 선택하고 별도로 저장하세요. 최소 하나를 선택해야 하며 모든 열을 선택할 수는 없습니다. 집계 테이블과 고유 키 테이블은 모든 키 열을 선택해야 합니다.",
+ editSortVersionHint: "현재 연결에서는 정렬 열 변경을 지원하지 않습니다.",
+ reorderMetadataHint: "열 순서를 변경할 수 없습니다. 테이블 구조를 새로 고친 후 다시 시도하세요.",
+ reorderHint: "드래그 후 저장하여 열 순서를 변경할 수 있습니다. 키 열은 일반 열보다 앞에 있어야 합니다. 다른 열 변경과 별도로 저장하세요.",
+ localReorderHint: "드래그는 표시 순서만 변경하며 데이터베이스는 변경하지 않습니다.",
+ copySaveFirst: "새 테이블을 만들기 전에 현재 구조 변경을 저장하거나 취소하세요.",
+ partitionAndBucketTitle: "파티션 및 버킷",
+ copyButton: "파티션 및 버킷 변경",
+ copyTitle: "파티션 및 버킷 변경 · 새 테이블 만들기",
+ copyHint: "{table}의 구조와 아래 설정으로 새 테이블을 만듭니다. 원본 테이블은 유지됩니다.",
+ copyLoading: "원본 테이블 구조를 읽는 중…",
+ copyTargetName: "새 테이블 이름",
+ copyTransferData: "원본 데이터 전송",
+ copyTransferHint: "데이터는 한 번만 복사되며 이후 동기화되지 않습니다. 전체 마이그레이션 전에 쓰기를 중단하고 파티션이 모든 데이터를 포함하는지 확인하세요.",
+ copyKeepPartition: "원본 파티션 설정 유지",
+ copyColocationHint: "새 테이블은 원본의 Colocate 그룹을 상속하지 않습니다.",
+ copyPartitionHint: "파티션을 다시 구성하면 원본의 파티션 생성 및 보존 규칙이 유지되지 않습니다.",
+ copyMetadataUnavailable: "전체 테이블 구조를 읽을 수 없습니다. 연결을 새로 고친 후 다시 시도하세요.",
+ copyNameRequired: "원본 테이블과 다른 이름을 입력하세요.",
+ copyNoInsertColumns: "전송할 수 있는 일반 열이 없습니다.",
+ copyTransferFailed: "테이블 {table}이 생성되었지만 데이터 전송 완료가 확인되지 않았습니다. 중복 가져오기를 방지하려면 확인 후 다시 시도하세요.\n{message}",
+ copyCreateFailed: "테이블 생성 성공이 확인되지 않았습니다. 먼저 {table}이 이미 존재하는지 확인하세요.\n{message}",
+ copyStage_creating: "{table} 생성 중…",
+ copyStage_created: "새 테이블 {table}이 생성되었습니다.",
+ copyStage_transferring: "테이블이 생성되었습니다. 데이터 전송 중…",
+ copyStage_complete: "완료되었습니다. 새 테이블: {table}.",
+ copyRunning: "실행 중…",
+ copyExecute: "새 테이블 만들기",
+ automaticBucketsReadonly: "자동 버킷 확장이 활성화되어 있습니다. 버킷을 변경하려면 새 테이블을 만들고 데이터를 마이그레이션하세요.",
+ operation_replicas: "복제본 수 변경",
+ operation_drop: "파티션 삭제",
+ operation_addList: "목록 파티션 추가",
+ operation_addRange: "범위 파티션 추가",
+ addValueTuple: "값 조합 추가",
+ removePartitionOperation: "제거",
+ queuePartitionOperation: "대기 중인 작업에 추가",
+ partitionValuesHint: "따옴표 없이 원래 값을 입력하세요. 여러 열은 완전한 값 조합을 입력하세요. 자동 파티션은 쓰기 시 생성됩니다.",
+ dropPartitionHint: "파티션을 삭제하면 그 안의 데이터도 삭제됩니다. 확인 후 저장하세요.",
+ rangeUpper: "종료값 (제외)",
+ rangeLower: "시작값 (포함)",
+ partitionNameInput: "파티션 이름",
+ partitionNameAll: "파티션 이름 또는 전체를 나타내는 *",
+ addListPartition: "목록 파티션 추가",
+ addRangePartition: "범위 파티션 추가",
+ dropPartition: "파티션 삭제",
+ partitionReplicas: "파티션 복제본 수 변경",
+ partitionReadonly: "파티션 방식을 변경하려면 새 테이블을 만들고 데이터를 마이그레이션하세요.",
+ alterBucketsHint: "비워 두면 버킷 수를 자동 결정합니다. 저장 후 기존 데이터가 재분배됩니다. 무작위 분배는 Duplicate Key 테이블에서만 사용할 수 있습니다.",
+ defaultBucketsOnly: "새 파티션에만 적용",
+ alterLayoutUnavailable: "현재 테이블에서는 버킷 설정 변경을 지원하지 않습니다.",
+ alterLayoutHint: "파티션, 버킷 및 열 변경을 별도로 저장하고 작업 완료 후 새로 고치세요.",
+ alterLayoutTitle: "파티션 및 버킷 (기존 테이블)",
+ alterSubmitted: "변경이 제출되었습니다. 완료 후 새로 고치세요.",
+ alterHint: "일부 열 속성은 변경할 수 없습니다. 기본값은 테이블 생성 또는 열 추가 시에만 설정할 수 있으며 NULL 허용 열을 NOT NULL로 변경할 수 없습니다. 저장 후 완료를 기다린 다음 새로 고치세요.",
+ sortColumns: "정렬 열",
+ missingSortColumn: "열이 삭제됨",
+ moveSortUp: "정렬 우선순위 높이기",
+ moveSortDown: "정렬 우선순위 낮추기",
+ removeSortColumn: "정렬 열 제거",
+ sortHint: "저장 시 정렬 순서를 우선순위대로 설정합니다. 비워 두면 기본값을 사용합니다. 조회 결과 순서는 쿼리로 결정됩니다.",
+ sortVersionHint: "현재 연결에서는 사용자 지정 정렬 열을 지원하지 않습니다.",
+ title: "파티션, 버킷 및 정렬",
+ timePartition: "시간 기준 파티션",
+ partitionColumn: "시간 열",
+ selectColumn: "열 선택",
+ granularity: "파티션 단위",
+ year: "연 단위",
+ month: "월 단위",
+ day: "일 단위",
+ distribution: "버킷 분배 방식",
+ auto: "자동",
+ hash: "해시 분배",
+ random: "무작위 분배",
+ hashColumns: "버킷 열",
+ bucketCount: "파티션별 버킷 수",
+ partitionHint: "날짜 또는 날짜/시간 열을 선택하세요. 데이터를 쓸 때 선택한 주기에 따라 자동으로 분할됩니다.",
+ autoPrimaryHint: "기본 키 열을 기준으로 자동 해시 분배합니다.",
+ autoDuplicateHint: "사용 가능한 분배 방식을 자동 선택하며 무작위 분배를 우선합니다.",
+ bucketHint: "해시 분배에는 필터에 자주 사용하고 고르게 분포된 열을 권장합니다. 무작위 분배는 기본 키가 없는 테이블에서만 사용할 수 있습니다.",
+ primaryKeyHint: "파티션 및 해시 열은 기본 키에 포함되어야 합니다. 기본 키 열은 자동으로 맨 앞에 배치됩니다.",
+ versionHint: "현재 연결에서는 시간 파티션 또는 무작위 분배를 지원하지 않습니다.",
+ noTimeColumn: "먼저 date 또는 datetime 유형의 열을 추가하세요.",
+ unavailableColumn: "열이 제거되었거나 지원되지 않는 유형임",
+ invalidSelection: "선택한 열이 더 이상 유효하지 않습니다. 다시 선택하세요.",
+ partitionStrategy: "파티션 방식",
+ none: "파티션 없음",
+ time: "자동 파티션 · 시간 표현식",
+ values: "자동 파티션 · 열 값",
+ range: "수동 파티션 · 범위",
+ list: "수동 파티션 · 목록",
+ partitionColumns: "파티션 열 (선택 순서)",
+ additionalColumns: "추가 차원 열 (선택 사항)",
+ noneHint: "테이블 전체를 하나의 파티션으로 사용하며 버킷 분배도 가능합니다.",
+ timeHint: "선택한 주기에 따라 자동 분할합니다. 열을 추가하여 더 세분화할 수 있습니다.",
+ valuesHint: "서로 다른 값 또는 값 조합으로 자동 분할합니다. 고유 ID처럼 값의 종류가 지나치게 많은 열은 피하세요.",
+ rangeHint: "범위는 시작값을 포함하고 종료값을 제외합니다. 여러 열의 조합은 열 순서대로 비교하며 범위 밖의 데이터는 쓸 수 없습니다.",
+ listHint: "각 행에 따옴표 없이 완전한 값 조합을 입력하세요. 목록에 없는 값은 쓸 수 없습니다.",
+ timeInterval: "사용자 지정 간격 (선택 사항)",
+ calendarUnit: "달력 주기",
+ timeIntervalHint: "비워 두면 달력 주기로 분할합니다. 예를 들어 7과 '일 단위'를 선택하면 7일마다 분할합니다. 사용자 지정 간격 및 시간 단위 분할에는 datetime 열이 필요합니다.",
+ hour: "시간 단위",
+ partitionName: "파티션 이름",
+ lower: "시작값 (포함)",
+ upper: "종료값 (제외)",
+ valuePlaceholder: "따옴표 없는 원래 값",
+ addPartition: "파티션 추가",
+ removePartition: "파티션 제거",
+ addValues: "값 조합 추가",
+ removeValues: "이 조합 제거",
+ noEligibleColumns: "지원되는 열 없음",
+ bucketCountHint: "자동 버킷 수는 클러스터 리소스와 데이터 양에 따라 데이터베이스가 결정하며 고정되지 않습니다. 숫자를 입력하면 각 파티션에 지정된 버킷 수를 사용합니다.",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 60ac138770..a85bcae8fa 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -5033,6 +5033,8 @@ export default withEnglishFallback({
partitionSqlPreview: "SQL a ser executado",
partitionNameRequired: "Digite o nome da partição.",
notNull: "Não nulo",
+ unsetDefault: "Sem valor padrão",
+ title: "Editar estrutura da tabela",
},
diagram: {
title: "Diagrama de relacionamentos",
@@ -11320,4 +11322,147 @@ export default withEnglishFallback({
noDetails: "Este core não possui detalhes de replicação.",
},
},
+ starrocksStatus: {
+ sql: "SQL da tarefa",
+ localSql: "SQL enviado recentemente nesta página; a tarefa correspondente ainda não foi confirmada.",
+ sqlUnavailable: "SQL indisponível para esta tarefa.",
+ label: "Alteração de estrutura",
+ checking: "Verificando",
+ idle: "Nenhuma tarefa em execução",
+ PENDING: "Na fila",
+ WAITING_TXN: "Aguardando transação",
+ RUNNING: "Em execução",
+ FINISHED: "Concluída",
+ CANCELLED: "Cancelada",
+ unknownState: "Estado desconhecido: {state}",
+ queryFailed: "Falha ao obter o estado",
+ polling: "Verificar a cada 3 segundos",
+ checkedAt: "Última verificação: {time}",
+ details: "Detalhes da tarefa",
+ refresh: "Verificar estado",
+ busyHint: "Você poderá salvar quando a tarefa terminar. Pode continuar editando enquanto isso.",
+ draftHint: "A tarefa terminou e o rascunho foi preservado. Confirme antes de atualizar a estrutura.",
+ failureHint: "O estado da tarefa não foi confirmado. Tente novamente.",
+ noJobs: "Nenhuma tarefa de alteração de estrutura pendente.",
+ job: "Tarefa",
+ state: "Estado",
+ created: "Data de criação",
+ finished: "Data de conclusão",
+ structureRefreshFailed: "A tarefa terminou, mas a atualização da estrutura falhou. Atualize manualmente.",
+ },
+ starrocksLayout: {
+ schemaChangeBusy: "A tabela {table} está sendo alterada. Aguarde o término e atualize antes de salvar.",
+ sortSaveSeparately: "Salve as alterações de ordenação separadamente das demais alterações de estrutura.",
+ editSortHint: "Selecione as colunas de ordenação por prioridade e salve separadamente. Selecione pelo menos uma, mas não todas; tabelas de agregação e de chave única exigem todas as colunas de chave.",
+ editSortVersionHint: "Esta conexão ainda não permite alterar as colunas de ordenação.",
+ reorderMetadataHint: "Não é possível reordenar as colunas. Atualize a estrutura e tente novamente.",
+ reorderHint: "Arraste e salve para reordenar as colunas. As colunas de chave devem vir antes das demais. Salve essa alteração separadamente.",
+ localReorderHint: "Arrastar altera apenas a ordem de exibição, sem modificar o banco de dados.",
+ copySaveFirst: "Salve ou descarte as alterações de estrutura antes de criar outra tabela.",
+ partitionAndBucketTitle: "Partições e buckets",
+ copyButton: "Alterar partições e buckets",
+ copyTitle: "Alterar partições e buckets · Criar tabela",
+ copyHint: "Crie outra tabela com a estrutura de {table} e a configuração abaixo. A tabela original será preservada.",
+ copyLoading: "Lendo a estrutura original…",
+ copyTargetName: "Nome da nova tabela",
+ copyTransferData: "Transferir os dados originais",
+ copyTransferHint: "Os dados são copiados uma única vez e não são sincronizados depois. Suspenda as gravações antes de uma migração completa e certifique-se de que as partições cubram todos os dados.",
+ copyKeepPartition: "Manter a configuração original de partições",
+ copyColocationHint: "A nova tabela não herda o grupo Colocate da original.",
+ copyPartitionHint: "Ao reconfigurar as partições, as regras originais de criação e retenção deixam de ser usadas.",
+ copyMetadataUnavailable: "Não foi possível ler a estrutura completa. Atualize a conexão e tente novamente.",
+ copyNameRequired: "Informe um nome diferente do da tabela original.",
+ copyNoInsertColumns: "Não há colunas comuns que possam ser transferidas.",
+ copyTransferFailed: "A tabela {table} foi criada, mas a conclusão da transferência não foi confirmada. Verifique antes de tentar novamente para evitar importações duplicadas.\n{message}",
+ copyCreateFailed: "A criação não foi confirmada. Verifique primeiro se {table} já existe.\n{message}",
+ copyStage_creating: "Criando {table}…",
+ copyStage_created: "A nova tabela {table} foi criada.",
+ copyStage_transferring: "Tabela criada. Transferindo dados…",
+ copyStage_complete: "Concluído. Nova tabela: {table}.",
+ copyRunning: "Executando…",
+ copyExecute: "Criar tabela",
+ automaticBucketsReadonly: "A expansão automática de buckets está ativada. Para alterá-los, crie outra tabela e migre os dados.",
+ operation_replicas: "Alterar número de réplicas",
+ operation_drop: "Excluir partição",
+ operation_addList: "Adicionar partição de lista",
+ operation_addRange: "Adicionar partição de intervalo",
+ addValueTuple: "Adicionar um conjunto de valores",
+ removePartitionOperation: "Remover",
+ queuePartitionOperation: "Adicionar às operações pendentes",
+ partitionValuesHint: "Informe valores sem aspas e combinações completas para várias colunas. As partições automáticas são criadas durante a gravação.",
+ dropPartitionHint: "Excluir uma partição remove os dados nela contidos. Confirme antes de salvar.",
+ rangeUpper: "Valor final (exclusivo)",
+ rangeLower: "Valor inicial (inclusivo)",
+ partitionNameInput: "Nome da partição",
+ partitionNameAll: "Nome da partição, ou * para todas",
+ addListPartition: "Adicionar partição de lista",
+ addRangePartition: "Adicionar partição de intervalo",
+ dropPartition: "Excluir partição",
+ partitionReplicas: "Alterar réplicas da partição",
+ partitionReadonly: "Para alterar o método de particionamento, crie outra tabela e migre os dados.",
+ alterBucketsHint: "Deixe em branco para determinar automaticamente o número de buckets. Salvar redistribui os dados existentes. A distribuição aleatória só é permitida em tabelas de chave duplicada.",
+ defaultBucketsOnly: "Aplicar apenas às novas partições",
+ alterLayoutUnavailable: "Esta tabela ainda não permite alterar os buckets.",
+ alterLayoutHint: "Salve as alterações de partições, buckets e colunas separadamente. Atualize após o término da tarefa.",
+ alterLayoutTitle: "Partições e buckets (tabela existente)",
+ alterSubmitted: "Alteração enviada. Atualize após a conclusão.",
+ alterHint: "Alguns atributos não podem ser alterados. Valores padrão só são definidos na criação da tabela ou ao adicionar colunas; colunas que aceitam NULL não podem passar a NOT NULL. Após salvar, aguarde a conclusão antes de atualizar.",
+ sortColumns: "Colunas de ordenação",
+ missingSortColumn: "Coluna excluída",
+ moveSortUp: "Aumentar prioridade de ordenação",
+ moveSortDown: "Diminuir prioridade de ordenação",
+ removeSortColumn: "Remover coluna de ordenação",
+ sortHint: "Defina a ordenação no armazenamento por prioridade ou deixe em branco para usar o padrão. A ordem dos resultados depende da consulta.",
+ sortVersionHint: "Esta conexão ainda não permite personalizar as colunas de ordenação.",
+ title: "Partições, buckets e ordenação",
+ timePartition: "Particionar por tempo",
+ partitionColumn: "Coluna temporal",
+ selectColumn: "Selecionar coluna",
+ granularity: "Granularidade da partição",
+ year: "Por ano",
+ month: "Por mês",
+ day: "Por dia",
+ distribution: "Método de distribuição",
+ auto: "Automático",
+ hash: "Distribuição hash",
+ random: "Distribuição aleatória",
+ hashColumns: "Colunas de distribuição",
+ bucketCount: "Buckets por partição",
+ partitionHint: "Selecione uma coluna de data ou data e hora. Os dados são particionados automaticamente pelo período selecionado durante a gravação.",
+ autoPrimaryHint: "Distribuição hash automática pelas colunas de chave primária.",
+ autoDuplicateHint: "Seleciona automaticamente um método disponível, dando preferência à distribuição aleatória.",
+ bucketHint: "Para hash, escolha colunas usadas frequentemente em filtros e com distribuição uniforme. A distribuição aleatória só é permitida em tabelas sem chave primária.",
+ primaryKeyHint: "As colunas de partição e hash devem pertencer à chave primária. As colunas da chave primária são colocadas primeiro automaticamente.",
+ versionHint: "Esta conexão ainda não permite particionamento temporal ou distribuição aleatória.",
+ noTimeColumn: "Adicione primeiro uma coluna do tipo date ou datetime.",
+ unavailableColumn: "Coluna removida ou tipo incompatível",
+ invalidSelection: "A seleção não é mais válida. Selecione novamente as colunas.",
+ partitionStrategy: "Método de particionamento",
+ none: "Sem particionamento",
+ time: "Automático · Expressão temporal",
+ values: "Automático · Valores das colunas",
+ range: "Manual · Intervalo",
+ list: "Manual · Lista",
+ partitionColumns: "Colunas de partição (na ordem de seleção)",
+ additionalColumns: "Colunas de dimensão adicionais (opcional)",
+ noneHint: "A tabela inteira forma uma partição; ainda é possível usar buckets.",
+ timeHint: "Particionamento automático pelo período selecionado. Adicione colunas para subdividir ainda mais.",
+ valuesHint: "Particionamento automático por valores ou combinações. Evite colunas com muitos valores distintos, como IDs únicos.",
+ rangeHint: "O intervalo inclui o início e exclui o fim. As combinações são comparadas na ordem das colunas; dados fora dos intervalos não podem ser gravados.",
+ listHint: "Informe um conjunto completo de valores sem aspas por linha. Valores não listados não podem ser gravados.",
+ timeInterval: "Intervalo personalizado (opcional)",
+ calendarUnit: "Período natural",
+ timeIntervalHint: "Deixe em branco para usar períodos naturais. Por exemplo, 7 com “Por dia” cria partições de 7 dias. Intervalos personalizados e partições por hora exigem uma coluna datetime.",
+ hour: "Por hora",
+ partitionName: "Nome da partição",
+ lower: "Valor inicial (inclusivo)",
+ upper: "Valor final (exclusivo)",
+ valuePlaceholder: "Valor sem aspas",
+ addPartition: "Adicionar partição",
+ removePartition: "Remover partição",
+ addValues: "Adicionar conjunto de valores",
+ removeValues: "Remover conjunto",
+ noEligibleColumns: "Nenhuma coluna compatível",
+ bucketCountHint: "O banco de dados determina automaticamente o número de buckets conforme os recursos do cluster e o volume de dados; ele não é fixo. Informe um número para fixá-lo em cada partição.",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 44c499e00a..e1c6e36851 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -5559,6 +5559,8 @@ export default withEnglishFallback({
identitySeed: "Начальное значение",
identityIncrement: "Шаг",
sqlServerIdentityTypeHint: "Identity в SQL Server поддерживает только tinyint, smallint, int, bigint и decimal/numeric с масштабом 0",
+ unsetDefault: "Без значения по умолчанию",
+ title: "Редактировать структуру таблицы",
},
diagram: {
title: "Диаграмма связей",
@@ -12332,4 +12334,147 @@ export default withEnglishFallback({
authFailed: "Не удалось проверить аутентификацию DBX.",
retry: "Повторить",
},
+ starrocksStatus: {
+ sql: "SQL задачи",
+ localSql: "SQL, недавно отправленный с этой страницы; соответствующая задача ещё не подтверждена.",
+ sqlUnavailable: "SQL для этой задачи недоступен.",
+ label: "Изменение структуры",
+ checking: "Проверка",
+ idle: "Нет выполняющихся задач",
+ PENDING: "В очереди",
+ WAITING_TXN: "Ожидание транзакции",
+ RUNNING: "Выполняется",
+ FINISHED: "Завершена",
+ CANCELLED: "Отменена",
+ unknownState: "Неизвестное состояние: {state}",
+ queryFailed: "Не удалось получить состояние",
+ polling: "Проверять каждые 3 секунды",
+ checkedAt: "Последняя проверка: {time}",
+ details: "Сведения о задаче",
+ refresh: "Проверить состояние",
+ busyHint: "Сохранение доступно после завершения задачи. Пока можно продолжать редактирование.",
+ draftHint: "Задача завершена, черновик сохранён. Проверьте изменения перед обновлением структуры.",
+ failureHint: "Состояние задачи не подтверждено. Повторите попытку.",
+ noJobs: "Нет незавершённых задач изменения структуры.",
+ job: "Задача",
+ state: "Состояние",
+ created: "Время создания",
+ finished: "Время завершения",
+ structureRefreshFailed: "Задача завершена, но обновить структуру не удалось. Обновите её вручную.",
+ },
+ starrocksLayout: {
+ schemaChangeBusy: "Таблица {table} изменяется. Дождитесь завершения и обновите структуру перед сохранением.",
+ sortSaveSeparately: "Сохраняйте изменения сортировки отдельно от остальных изменений структуры.",
+ editSortHint: "Выберите столбцы сортировки по приоритету и сохраните отдельно. Нужен хотя бы один, но нельзя выбрать все; для таблиц агрегации и с уникальным ключом нужны все ключевые столбцы.",
+ editSortVersionHint: "Это подключение пока не поддерживает изменение столбцов сортировки.",
+ reorderMetadataHint: "Невозможно изменить порядок столбцов. Обновите структуру и повторите попытку.",
+ reorderHint: "Перетащите столбцы и сохраните порядок. Ключевые столбцы должны быть перед обычными. Сохраняйте это изменение отдельно.",
+ localReorderHint: "Перетаскивание меняет только порядок отображения, не базу данных.",
+ copySaveFirst: "Перед созданием новой таблицы сохраните или отмените текущие изменения структуры.",
+ partitionAndBucketTitle: "Партиции и бакеты",
+ copyButton: "Изменить партиции и бакеты",
+ copyTitle: "Изменить партиции и бакеты · Создать таблицу",
+ copyHint: "Создайте новую таблицу со структурой {table} и настройками ниже. Исходная таблица сохранится.",
+ copyLoading: "Чтение исходной структуры…",
+ copyTargetName: "Имя новой таблицы",
+ copyTransferData: "Перенести исходные данные",
+ copyTransferHint: "Данные копируются один раз и затем не синхронизируются. Перед полной миграцией остановите запись и убедитесь, что партиции охватывают все данные.",
+ copyKeepPartition: "Сохранить исходные настройки партиций",
+ copyColocationHint: "Новая таблица не наследует группу Colocate исходной таблицы.",
+ copyPartitionHint: "При перенастройке партиций исходные правила создания и хранения не сохраняются.",
+ copyMetadataUnavailable: "Не удалось прочитать полную структуру. Обновите подключение и повторите попытку.",
+ copyNameRequired: "Введите имя, отличающееся от имени исходной таблицы.",
+ copyNoInsertColumns: "Нет обычных столбцов для переноса.",
+ copyTransferFailed: "Таблица {table} создана, но завершение переноса данных не подтверждено. Проверьте результат перед повторной попыткой, чтобы избежать повторного импорта.\n{message}",
+ copyCreateFailed: "Создание таблицы не подтверждено. Сначала проверьте, существует ли уже {table}.\n{message}",
+ copyStage_creating: "Создание {table}…",
+ copyStage_created: "Новая таблица {table} создана.",
+ copyStage_transferring: "Таблица создана. Перенос данных…",
+ copyStage_complete: "Готово. Новая таблица: {table}.",
+ copyRunning: "Выполнение…",
+ copyExecute: "Создать таблицу",
+ automaticBucketsReadonly: "Включено автоматическое расширение бакетов. Для изменения бакетов создайте новую таблицу и перенесите данные.",
+ operation_replicas: "Изменить число реплик",
+ operation_drop: "Удалить партицию",
+ operation_addList: "Добавить списочную партицию",
+ operation_addRange: "Добавить диапазонную партицию",
+ addValueTuple: "Добавить набор значений",
+ removePartitionOperation: "Убрать",
+ queuePartitionOperation: "Добавить в ожидающие операции",
+ partitionValuesHint: "Введите исходные значения без кавычек; для нескольких столбцов — полные комбинации. Автоматические партиции создаются при записи.",
+ dropPartitionHint: "Удаление партиции удаляет её данные. Подтвердите перед сохранением.",
+ rangeUpper: "Конечное значение (не включается)",
+ rangeLower: "Начальное значение (включается)",
+ partitionNameInput: "Имя партиции",
+ partitionNameAll: "Имя партиции или * для всех",
+ addListPartition: "Добавить списочную партицию",
+ addRangePartition: "Добавить диапазонную партицию",
+ dropPartition: "Удалить партицию",
+ partitionReplicas: "Изменить число реплик партиции",
+ partitionReadonly: "Для изменения способа партиционирования создайте новую таблицу и перенесите данные.",
+ alterBucketsHint: "Оставьте пустым для автоматического выбора числа бакетов. После сохранения имеющиеся данные перераспределяются. Случайное распределение доступно только для таблиц Duplicate Key.",
+ defaultBucketsOnly: "Применять только к новым партициям",
+ alterLayoutUnavailable: "Эта таблица пока не поддерживает изменение бакетов.",
+ alterLayoutHint: "Сохраняйте изменения партиций, бакетов и столбцов отдельно. Обновите структуру после завершения задачи.",
+ alterLayoutTitle: "Партиции и бакеты (существующая таблица)",
+ alterSubmitted: "Изменение отправлено. Обновите после завершения.",
+ alterHint: "Некоторые свойства столбцов нельзя менять. Значения по умолчанию задаются только при создании таблицы или добавлении столбцов; столбцы, допускающие NULL, нельзя изменить на NOT NULL. После сохранения дождитесь завершения перед обновлением.",
+ sortColumns: "Столбцы сортировки",
+ missingSortColumn: "Столбец удалён",
+ moveSortUp: "Повысить приоритет сортировки",
+ moveSortDown: "Понизить приоритет сортировки",
+ removeSortColumn: "Убрать столбец сортировки",
+ sortHint: "Задайте порядок хранения по приоритету или оставьте пустым для значения по умолчанию. Порядок результатов определяется запросом.",
+ sortVersionHint: "Это подключение пока не поддерживает пользовательские столбцы сортировки.",
+ title: "Партиции, бакеты и сортировка",
+ timePartition: "Партиционирование по времени",
+ partitionColumn: "Столбец времени",
+ selectColumn: "Выбрать столбец",
+ granularity: "Шаг партиционирования",
+ year: "По годам",
+ month: "По месяцам",
+ day: "По дням",
+ distribution: "Способ распределения",
+ auto: "Автоматически",
+ hash: "Хеш-распределение",
+ random: "Случайное распределение",
+ hashColumns: "Столбцы распределения",
+ bucketCount: "Бакетов на партицию",
+ partitionHint: "Выберите столбец даты или даты и времени. При записи данные автоматически делятся по выбранному периоду.",
+ autoPrimaryHint: "Автоматическое хеш-распределение по столбцам первичного ключа.",
+ autoDuplicateHint: "Автоматический выбор доступного способа, предпочтительно случайного распределения.",
+ bucketHint: "Для хеш-распределения выбирайте часто используемые в фильтрах столбцы с равномерными значениями. Случайное распределение доступно только для таблиц без первичного ключа.",
+ primaryKeyHint: "Столбцы партиционирования и хеширования должны входить в первичный ключ. Столбцы первичного ключа автоматически ставятся первыми.",
+ versionHint: "Это подключение пока не поддерживает партиционирование по времени или случайное распределение.",
+ noTimeColumn: "Сначала добавьте столбец типа date или datetime.",
+ unavailableColumn: "Столбец удалён или тип не поддерживается",
+ invalidSelection: "Выбранные столбцы больше недоступны. Выберите их заново.",
+ partitionStrategy: "Способ партиционирования",
+ none: "Без партиций",
+ time: "Автоматически · Выражение времени",
+ values: "Автоматически · Значения столбцов",
+ range: "Вручную · Диапазон",
+ list: "Вручную · Список",
+ partitionColumns: "Столбцы партиционирования (в порядке выбора)",
+ additionalColumns: "Дополнительные столбцы измерений (необязательно)",
+ noneHint: "Вся таблица образует одну партицию; распределение по бакетам остаётся доступным.",
+ timeHint: "Автоматическое деление по выбранному периоду. Добавьте столбцы для дальнейшего разделения.",
+ valuesHint: "Автоматическое деление по значениям или комбинациям. Избегайте столбцов с большим числом разных значений, например уникальных ID.",
+ rangeHint: "Диапазон включает начало и исключает конец. Комбинации сравниваются в порядке столбцов; данные вне диапазонов записать нельзя.",
+ listHint: "Введите полный набор значений без кавычек в каждой строке. Значения вне списка записать нельзя.",
+ timeInterval: "Свой интервал (необязательно)",
+ calendarUnit: "Календарный период",
+ timeIntervalHint: "Оставьте пустым для календарных периодов. Например, 7 и «По дням» создают партиции по 7 дней. Свой интервал и деление по часам требуют столбца datetime.",
+ hour: "По часам",
+ partitionName: "Имя партиции",
+ lower: "Начальное значение (включается)",
+ upper: "Конечное значение (не включается)",
+ valuePlaceholder: "Исходное значение без кавычек",
+ addPartition: "Добавить партицию",
+ removePartition: "Убрать партицию",
+ addValues: "Добавить набор значений",
+ removeValues: "Убрать набор",
+ noEligibleColumns: "Нет поддерживаемых столбцов",
+ bucketCountHint: "Автоматическое число бакетов определяется базой данных по ресурсам кластера и объёму данных и не является фиксированным. Введите число, чтобы задать его для каждой партиции.",
+ },
});
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 8b1bf612cd..9e12a22e25 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -34,6 +34,151 @@ export default withEnglishFallback({
templateHelp:
"变量:table.name、table.schema、table.comment、class.name;字段循环内可用 column.name、column.type、column.originalType、column.comment、column.defaultValue、column.nullable、column.primaryKey。变量用双花括号包围,#columns 与 /columns 表示循环,#column.nullable 与 /column.nullable 表示条件块。",
},
+ starrocksStatus: {
+ sql: "任务 SQL",
+ localSql: "本页最近提交的 SQL,尚未确认对应任务。",
+ sqlUnavailable: "暂无此任务的 SQL。",
+ label: "结构变更",
+ checking: "检查中",
+ idle: "无运行中的任务",
+ PENDING: "排队中",
+ WAITING_TXN: "等待事务",
+ RUNNING: "执行中",
+ FINISHED: "已完成",
+ CANCELLED: "已取消",
+ unknownState: "未知状态:{state}",
+ queryFailed: "状态获取失败",
+ polling: "每 3 秒检查",
+ checkedAt: "上次检查 {time}",
+ details: "任务详情",
+ refresh: "检查状态",
+ busyHint: "任务完成后可保存,期间可继续编辑。",
+ draftHint: "任务已完成,草稿已保留。请确认后刷新表结构。",
+ failureHint: "任务状态未确认,请重试。",
+ noJobs: "暂无未完成的结构变更任务。",
+ job: "任务",
+ state: "状态",
+ created: "创建时间",
+ finished: "结束时间",
+ structureRefreshFailed: "任务已结束,但表结构刷新失败,请手动刷新。",
+ },
+ starrocksLayout: {
+ schemaChangeBusy: "表 {table} 正在变更,请等待完成后刷新再保存。",
+ sortSaveSeparately: "排序字段修改与其他表结构修改请分别保存。",
+ editSortHint: "按优先级选择排序字段,修改后单独保存。至少选一项,不能选满全部字段;聚合表和唯一键表须选择全部键列。",
+ editSortVersionHint: "当前连接暂不支持修改排序字段。",
+ reorderMetadataHint: "暂无法调整字段顺序,请刷新表结构后重试。",
+ reorderHint: "拖动后保存可调整字段顺序,键列须在普通列之前。请与其他字段修改分开保存。",
+ localReorderHint: "拖动仅调整显示顺序,不修改数据库。",
+ copySaveFirst: "请先保存或放弃当前表结构修改,再创建新表。",
+ partitionAndBucketTitle: "分区与分桶",
+ copyButton: "修改分区与分桶",
+ copyTitle: "修改分区与分桶 · 创建新表",
+ copyHint: "按 {table} 的结构和以下配置创建新表,原表保留。",
+ copyLoading: "正在读取原表结构…",
+ copyTargetName: "新表名称",
+ copyTransferData: "传输原表数据",
+ copyTransferHint: "仅复制一次,后续数据不同步。完整迁移前请暂停写入,并确保分区覆盖全部数据。",
+ copyKeepPartition: "沿用原表分区配置",
+ copyColocationHint: "新表不继承原表的 Colocate 分组。",
+ copyPartitionHint: "重新配置分区后,原表的分区创建和保留规则不再沿用。",
+ copyMetadataUnavailable: "无法读取完整表结构,请刷新连接后重试。",
+ copyNameRequired: "请填写与原表不同的新表名称。",
+ copyNoInsertColumns: "没有可传输的普通字段。",
+ copyTransferFailed: "新表 {table} 已创建,数据传输未确认完成。请检查后再重试,避免重复导入。\n{message}",
+ copyCreateFailed: "建表未确认成功,请先检查 {table} 是否已存在。\n{message}",
+ copyStage_creating: "正在创建 {table}…",
+ copyStage_created: "新表 {table} 已创建。",
+ copyStage_transferring: "新表已创建,正在传输数据…",
+ copyStage_complete: "已完成,新表:{table}。",
+ copyRunning: "正在执行…",
+ copyExecute: "创建新表",
+
+ automaticBucketsReadonly: "已启用自动扩桶。如需修改分桶,请新建表并迁移数据。",
+ operation_replicas: "修改副本数",
+ operation_drop: "删除分区",
+ operation_addList: "新增枚举分区",
+ operation_addRange: "新增范围分区",
+ addValueTuple: "添加一组枚举值",
+ removePartitionOperation: "移除",
+ queuePartitionOperation: "加入待执行操作",
+ partitionValuesHint: "填写原始值,不加引号;多字段填写完整组合。自动分区在写入时创建。",
+ dropPartitionHint: "删除分区会删除其中的数据,请确认后保存。",
+ rangeUpper: "结束值(不包含)",
+ rangeLower: "起始值(包含)",
+ partitionNameInput: "分区名称",
+ partitionNameAll: "分区名,或 * 表示全部",
+ addListPartition: "新增枚举分区",
+ addRangePartition: "新增范围分区",
+ dropPartition: "删除分区",
+ partitionReplicas: "修改分区副本数",
+ partitionReadonly: "修改分区方式需新建表并迁移数据。",
+ alterBucketsHint: "留空自动决定桶数,保存后会重新分配已有数据。随机分桶仅用于明细表。",
+ defaultBucketsOnly: "仅应用于新增分区",
+ alterLayoutUnavailable: "当前表暂不支持修改分桶配置。",
+ alterLayoutHint: "分区、分桶和字段修改请分别保存,任务完成后刷新。",
+ alterLayoutTitle: "分区与分桶(已有表)",
+ alterSubmitted: "变更已提交,完成后请刷新。",
+ alterHint: "部分字段属性不可修改。默认值仅在建表或新增列时设置,允许空值的列不能改为非空。保存后请等待完成再刷新。",
+ sortColumns: "排序字段",
+ missingSortColumn: "字段已删除",
+ moveSortUp: "提高排序优先级",
+ moveSortDown: "降低排序优先级",
+ removeSortColumn: "移除排序字段",
+ sortHint: "按优先级设置存储排序,留空使用默认值。查询结果顺序由查询语句决定。",
+ sortVersionHint: "当前连接暂不支持自定义排序字段。",
+
+ title: "分区、分桶与排序",
+ timePartition: "按时间分区",
+ partitionColumn: "时间字段",
+ selectColumn: "选择字段",
+ granularity: "分区粒度",
+ year: "按年",
+ month: "按月",
+ day: "按日",
+ distribution: "分桶方式",
+ auto: "自动",
+ hash: "哈希分桶",
+ random: "随机分桶",
+ hashColumns: "分桶字段",
+ bucketCount: "每分区桶数",
+ partitionHint: "选择日期或时间字段,写入数据时自动按所选周期分区。",
+ autoPrimaryHint: "自动按主键字段哈希分桶。",
+ autoDuplicateHint: "自动选择可用的分桶方式,优先使用随机分桶。",
+ bucketHint: "哈希分桶建议选择常用筛选且分布均匀的字段。随机分桶仅用于无主键的表。",
+ primaryKeyHint: "分区和哈希分桶字段须属于主键,主键字段会自动排在最前。",
+ versionHint: "当前连接暂不支持时间分区或随机分桶。",
+ noTimeColumn: "请先添加 date 或 datetime 类型的字段。",
+ unavailableColumn: "字段已移除或类型不支持",
+ invalidSelection: "所选字段已失效,请重新选择。",
+ partitionStrategy: "分区方式",
+ none: "不分区",
+ time: "自动分区 · 时间表达式",
+ values: "自动分区 · 字段值",
+ range: "手动分区 · 范围",
+ list: "手动分区 · 枚举",
+ partitionColumns: "分区字段(按勾选顺序)",
+ additionalColumns: "附加维度字段(可选)",
+ noneHint: "整表作为一个分区,仍可分桶。",
+ timeHint: "按所选周期自动分区,可添加字段进一步细分。",
+ valuesHint: "按不同值或值组合自动分区,避免选择唯一 ID 等取值过多的字段。",
+ rangeHint: "范围包含起始值,不含结束值。多字段按顺序比较组合;范围外的数据无法写入。",
+ listHint: "每行填写一组完整值,不加引号。未列出的值无法写入。",
+ timeInterval: "自定义间隔(可选)",
+ calendarUnit: "自然周期",
+ timeIntervalHint: "留空按自然周期分区,如填 7 并选“按日”则每 7 天分区。自定义间隔和按小时需使用日期时间字段。",
+ hour: "按小时",
+ partitionName: "分区名称",
+ lower: "起始值(包含)",
+ upper: "结束值(不包含)",
+ valuePlaceholder: "原始值,不加引号",
+ addPartition: "添加分区",
+ removePartition: "移除分区",
+ addValues: "添加一组值",
+ removeValues: "移除此组",
+ noEligibleColumns: "暂无支持的字段",
+ bucketCountHint: "自动桶数由数据库根据集群资源和数据量决定,并不固定;填写数字则每个分区使用指定桶数。",
+ },
graph: {
title: "图谱",
search: "搜索图谱",
@@ -5425,6 +5570,8 @@ export default withEnglishFallback({
sortBy: "排序方式",
},
structureEditor: {
+ unsetDefault: "不设置默认值",
+ title: "编辑表结构",
createTitle: "新建表",
editTabTitle: "编辑: {tableName}",
tableName: "表名",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 4733ed9042..f283114e18 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -4780,6 +4780,8 @@ export default withEnglishFallback({
partitionSqlPreview: "將執行的 SQL",
partitionNameRequired: "請輸入分割區名稱。",
notNull: "非空",
+ unsetDefault: "不設定預設值",
+ title: "編輯資料表結構",
},
diagram: {
title: "關係圖",
@@ -11333,4 +11335,147 @@ export default withEnglishFallback({
noDetails: "此 Core 沒有複製詳細資料。",
},
},
+ starrocksStatus: {
+ sql: "任務 SQL",
+ localSql: "本頁最近提交的 SQL,尚未確認對應任務。",
+ sqlUnavailable: "暫無此任務的 SQL。",
+ label: "結構變更",
+ checking: "檢查中",
+ idle: "無執行中的任務",
+ PENDING: "排隊中",
+ WAITING_TXN: "等待交易",
+ RUNNING: "執行中",
+ FINISHED: "已完成",
+ CANCELLED: "已取消",
+ unknownState: "未知狀態:{state}",
+ queryFailed: "狀態取得失敗",
+ polling: "每 3 秒檢查",
+ checkedAt: "上次檢查 {time}",
+ details: "任務詳情",
+ refresh: "檢查狀態",
+ busyHint: "任務完成後可儲存,期間可繼續編輯。",
+ draftHint: "任務已完成,草稿已保留。請確認後重新整理資料表結構。",
+ failureHint: "任務狀態未確認,請重試。",
+ noJobs: "暫無未完成的結構變更任務。",
+ job: "任務",
+ state: "狀態",
+ created: "建立時間",
+ finished: "結束時間",
+ structureRefreshFailed: "任務已結束,但資料表結構重新整理失敗,請手動重新整理。",
+ },
+ starrocksLayout: {
+ schemaChangeBusy: "資料表 {table} 正在變更,請等待完成後重新整理再儲存。",
+ sortSaveSeparately: "排序欄位修改與其他資料表結構修改請分別儲存。",
+ editSortHint: "按優先順序選擇排序欄位,修改後單獨儲存。至少選一項,不能選滿全部欄位;彙總資料表和唯一鍵資料表須選擇全部鍵欄位。",
+ editSortVersionHint: "目前連線暫不支援修改排序欄位。",
+ reorderMetadataHint: "暫無法調整欄位順序,請重新整理資料表結構後重試。",
+ reorderHint: "拖曳後儲存可調整欄位順序,鍵欄位須在一般欄位之前。請與其他欄位修改分開儲存。",
+ localReorderHint: "拖曳僅調整顯示順序,不修改資料庫。",
+ copySaveFirst: "請先儲存或放棄目前的資料表結構修改,再建立新資料表。",
+ partitionAndBucketTitle: "分割區與分桶",
+ copyButton: "修改分割區與分桶",
+ copyTitle: "修改分割區與分桶 · 建立新資料表",
+ copyHint: "按 {table} 的結構和以下設定建立新資料表,原資料表保留。",
+ copyLoading: "正在讀取原資料表結構…",
+ copyTargetName: "新資料表名稱",
+ copyTransferData: "傳輸原資料表資料",
+ copyTransferHint: "僅複製一次,後續資料不同步。完整移轉前請暫停寫入,並確保分割區涵蓋全部資料。",
+ copyKeepPartition: "沿用原資料表分割區設定",
+ copyColocationHint: "新資料表不繼承原資料表的 Colocate 群組。",
+ copyPartitionHint: "重新設定分割區後,原資料表的分割區建立和保留規則不再沿用。",
+ copyMetadataUnavailable: "無法讀取完整資料表結構,請重新整理連線後重試。",
+ copyNameRequired: "請填寫與原資料表不同的新資料表名稱。",
+ copyNoInsertColumns: "沒有可傳輸的一般欄位。",
+ copyTransferFailed: "新資料表 {table} 已建立,資料傳輸未確認完成。請檢查後再重試,避免重複匯入。\n{message}",
+ copyCreateFailed: "資料表建立未確認成功,請先檢查 {table} 是否已存在。\n{message}",
+ copyStage_creating: "正在建立 {table}…",
+ copyStage_created: "新資料表 {table} 已建立。",
+ copyStage_transferring: "新資料表已建立,正在傳輸資料…",
+ copyStage_complete: "已完成,新資料表:{table}。",
+ copyRunning: "正在執行…",
+ copyExecute: "建立新資料表",
+ automaticBucketsReadonly: "已啟用自動擴桶。如需修改分桶,請建立新資料表並移轉資料。",
+ operation_replicas: "修改複本數",
+ operation_drop: "刪除分割區",
+ operation_addList: "新增清單分割區",
+ operation_addRange: "新增範圍分割區",
+ addValueTuple: "新增一組清單值",
+ removePartitionOperation: "移除",
+ queuePartitionOperation: "加入待執行操作",
+ partitionValuesHint: "填寫原始值,不加引號;多欄位填寫完整組合。自動分割區在寫入時建立。",
+ dropPartitionHint: "刪除分割區會刪除其中的資料,請確認後儲存。",
+ rangeUpper: "結束值(不包含)",
+ rangeLower: "起始值(包含)",
+ partitionNameInput: "分割區名稱",
+ partitionNameAll: "分割區名稱,或 * 表示全部",
+ addListPartition: "新增清單分割區",
+ addRangePartition: "新增範圍分割區",
+ dropPartition: "刪除分割區",
+ partitionReplicas: "修改分割區複本數",
+ partitionReadonly: "修改分割區方式需建立新資料表並移轉資料。",
+ alterBucketsHint: "留空自動決定桶數,儲存後會重新分配既有資料。隨機分桶僅用於明細資料表。",
+ defaultBucketsOnly: "僅套用於新增分割區",
+ alterLayoutUnavailable: "目前資料表暫不支援修改分桶設定。",
+ alterLayoutHint: "分割區、分桶和欄位修改請分別儲存,任務完成後重新整理。",
+ alterLayoutTitle: "分割區與分桶(既有資料表)",
+ alterSubmitted: "變更已提交,完成後請重新整理。",
+ alterHint: "部分欄位屬性不可修改。預設值僅在建立資料表或新增欄位時設定,允許空值的欄位不能改為非空。儲存後請等待完成再重新整理。",
+ sortColumns: "排序欄位",
+ missingSortColumn: "欄位已刪除",
+ moveSortUp: "提高排序優先順序",
+ moveSortDown: "降低排序優先順序",
+ removeSortColumn: "移除排序欄位",
+ sortHint: "按優先順序設定儲存排序,留空使用預設值。查詢結果順序由查詢語句決定。",
+ sortVersionHint: "目前連線暫不支援自訂排序欄位。",
+ title: "分割區、分桶與排序",
+ timePartition: "按時間分割",
+ partitionColumn: "時間欄位",
+ selectColumn: "選擇欄位",
+ granularity: "分割區粒度",
+ year: "按年",
+ month: "按月",
+ day: "按日",
+ distribution: "分桶方式",
+ auto: "自動",
+ hash: "雜湊分桶",
+ random: "隨機分桶",
+ hashColumns: "分桶欄位",
+ bucketCount: "每個分割區的桶數",
+ partitionHint: "選擇日期或日期時間欄位,寫入資料時自動按所選週期分割。",
+ autoPrimaryHint: "自動按主鍵欄位雜湊分桶。",
+ autoDuplicateHint: "自動選擇可用的分桶方式,優先使用隨機分桶。",
+ bucketHint: "雜湊分桶建議選擇常用於篩選且分布均勻的欄位。隨機分桶僅用於無主鍵的資料表。",
+ primaryKeyHint: "分割區和雜湊分桶欄位須屬於主鍵,主鍵欄位會自動排在最前。",
+ versionHint: "目前連線暫不支援時間分割或隨機分桶。",
+ noTimeColumn: "請先新增 date 或 datetime 類型的欄位。",
+ unavailableColumn: "欄位已移除或類型不支援",
+ invalidSelection: "所選欄位已失效,請重新選擇。",
+ partitionStrategy: "分割區方式",
+ none: "不分割",
+ time: "自動分割 · 時間運算式",
+ values: "自動分割 · 欄位值",
+ range: "手動分割 · 範圍",
+ list: "手動分割 · 清單",
+ partitionColumns: "分割區欄位(按勾選順序)",
+ additionalColumns: "附加維度欄位(選填)",
+ noneHint: "整個資料表作為一個分割區,仍可分桶。",
+ timeHint: "按所選週期自動分割,可新增欄位進一步細分。",
+ valuesHint: "按不同值或值組合自動分割,避免選擇唯一 ID 等值過多的欄位。",
+ rangeHint: "範圍包含起始值,不含結束值。多欄位按順序比較組合;範圍外的資料無法寫入。",
+ listHint: "每行填寫一組完整值,不加引號。未列出的值無法寫入。",
+ timeInterval: "自訂間隔(選填)",
+ calendarUnit: "自然週期",
+ timeIntervalHint: "留空按自然週期分割,如填 7 並選「按日」則每 7 天分割。自訂間隔和按小時需使用日期時間欄位。",
+ hour: "按小時",
+ partitionName: "分割區名稱",
+ lower: "起始值(包含)",
+ upper: "結束值(不包含)",
+ valuePlaceholder: "原始值,不加引號",
+ addPartition: "新增分割區",
+ removePartition: "移除分割區",
+ addValues: "新增一組值",
+ removeValues: "移除此組",
+ noEligibleColumns: "暫無支援的欄位",
+ bucketCountHint: "自動桶數由資料庫根據叢集資源和資料量決定,並不固定;填寫數字則每個分割區使用指定桶數。",
+ },
});
diff --git a/apps/desktop/src/lib/__tests__/table/columnDefaultPresets.spec.ts b/apps/desktop/src/lib/__tests__/table/columnDefaultPresets.spec.ts
new file mode 100644
index 0000000000..4a22bdb50a
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/table/columnDefaultPresets.spec.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+import { getColumnDefaultValuePresets } from "@/lib/table/columnDefaultPresets";
+
+const context = { databaseType: "starrocks", dialect: "mysql", serverVersion: "3.5.0", unsetLabel: "No default", isCreateMode: true };
+const column = (dataType: string) => ({ dataType, isNullable: true, isPrimaryKey: false, extra: {} });
+const values = (dataType: string) => getColumnDefaultValuePresets(column(dataType), context).map((p) => p.value);
+
+describe("StarRocks default preset provider", () => {
+ it.each([
+ ["int", ["", "NULL", "'0'", "'1'"]],
+ ["decimal(10,2)", ["", "NULL", "'0'", "'1'"]],
+ ["boolean", ["", "NULL", "'false'", "'true'"]],
+ ["date", ["", "NULL", "1970-01-01"]],
+ ["DATETIME", ["", "NULL", "CURRENT_TIMESTAMP"]],
+ ["varchar(36)", ["", "NULL", "''", "(uuid())"]],
+ ["varchar(35)", ["", "NULL", "''"]],
+ ["varchar", ["", "NULL", "''"]],
+ ["char(100)", ["", "NULL", "''"]],
+ ["string", ["", "NULL", "''", "(uuid())"]],
+ ["largeint", ["", "NULL", "'0'", "'1'", "(uuid_numeric())"]],
+ ["bigint", ["", "NULL", "'0'", "'1'"]],
+ ["array<int>", ["", "NULL"]],
+ ["map<int, int>", ["", "NULL"]],
+ ["struct<id int>", ["", "NULL"]],
+ ["json", ["", "NULL"]],
+ ["binary", ["", "NULL"]],
+ ["hll", [""]],
+ ["bitmap", [""]],
+ ])("offers type-specific defaults for %s", (type, expected) => {
+ expect(values(type)).toEqual(expected);
+ });
+
+ it("updates suggestions when a column's type or length changes", () => {
+ const draft = column("varchar(36)");
+ expect(getColumnDefaultValuePresets(draft, context).map((p) => p.value)).toContain("(uuid())");
+ draft.dataType = "varchar(20)";
+ expect(getColumnDefaultValuePresets(draft, context).map((p) => p.value)).not.toContain("(uuid())");
+ draft.dataType = "datetime";
+ expect(getColumnDefaultValuePresets(draft, context).map((p) => p.value)).toEqual(["", "NULL", "CURRENT_TIMESTAMP"]);
+ });
+
+ it("excludes NULL for nonnullable and primary key columns, and defaults for auto increment", () => {
+ for (const draft of [
+ { ...column("int"), isNullable: false },
+ { ...column("int"), isPrimaryKey: true },
+ ]) {
+ expect(getColumnDefaultValuePresets(draft, context).map((p) => p.value)).not.toContain("NULL");
+ }
+ expect(getColumnDefaultValuePresets({ ...column("bigint"), extra: { autoIncrement: true } }, context)).toEqual([{ label: "No default", value: "" }]);
+ });
+
+ it.each([undefined, "5.1.0", "2.0.0"])("does not offer unverified UUID defaults on %s", (serverVersion) => {
+ expect(getColumnDefaultValuePresets(column("varchar(100)"), { ...context, serverVersion }).map((p) => p.value)).not.toContain("(uuid())");
+ });
+
+ it.each([false, undefined])("omits UUID expressions outside create mode (%s), preserving ADD literals and timestamp", (isCreateMode) => {
+ const addContext = { ...context, isCreateMode };
+ for (const type of ["varchar(255)", "string", "largeint"]) {
+ expect(getColumnDefaultValuePresets(column(type), addContext).map((p) => p.value)).not.toEqual(expect.arrayContaining([expect.stringMatching(/uuid/)]));
+ }
+ expect(getColumnDefaultValuePresets(column("varchar(255)"), addContext).map((p) => p.value)).toEqual(["", "NULL", "''"]);
+ expect(getColumnDefaultValuePresets(column("largeint"), addContext).map((p) => p.value)).toEqual(["", "NULL", "'0'", "'1'"]);
+ expect(getColumnDefaultValuePresets(column("datetime"), addContext).map((p) => p.value)).toEqual(["", "NULL", "CURRENT_TIMESTAMP"]);
+ });
+
+ it("preserves MySQL and PostgreSQL presets", () => {
+ expect(getColumnDefaultValuePresets(column("int"), { ...context, databaseType: "mysql" }).map((p) => p.value)).toEqual(["''", "NULL", "0", "1", "CURRENT_TIMESTAMP", "CURRENT_DATE", "CURRENT_TIME"]);
+ expect(getColumnDefaultValuePresets(column("varchar"), { ...context, databaseType: "postgres", dialect: "postgres" }).map((p) => p.value)).toContain("gen_random_uuid()");
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/table/starrocksAlterOptions.spec.ts b/apps/desktop/src/lib/__tests__/table/starrocksAlterOptions.spec.ts
new file mode 100644
index 0000000000..9a58e12e60
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/table/starrocksAlterOptions.spec.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import { starRocksAlterOptionsFromDdl, starRocksColumnDefinitionLocked, starRocksLayoutDraft, starRocksLayoutChanges } from "@/lib/table/starrocksAlterOptions";
+import { getTableStructureCapabilities } from "@/lib/table/tableStructureCapabilities";
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+
+describe("StarRocks ALTER metadata", () => {
+ const ddl = "CREATE TABLE `events` (\n`id` bigint, `ts` datetime, `value` varchar(100) COMMENT 'PRIMARY KEY(fake)'\n) ENGINE=OLAP\nPRIMARY KEY(`id`, `ts`)\nCOMMENT 'DISTRIBUTED BY HASH(value)'\nPARTITION BY date_trunc('day', `ts`)\nDISTRIBUTED BY HASH(`id`) BUCKETS 8\nPROPERTIES ('x'='y')";
+ it("reads table clauses while ignoring parentheses and fake clauses in strings", () => {
+ const context = starRocksAlterOptionsFromDdl(ddl, "3.5.0");
+ expect(context.model).toBe("primary");
+ expect(context.keyColumns).toEqual(["id", "ts"]);
+ expect(context.partitionColumns).toContain("ts");
+ expect(context.distributionColumns).toContain("id");
+ expect(context.distributionColumns).not.toContain("value");
+ });
+ it("rejects unconfirmed or external table metadata", () => {
+ expect(starRocksAlterOptionsFromDdl("").model).toBeUndefined();
+ expect(starRocksAlterOptionsFromDdl(ddl.replace("ENGINE=OLAP", "ENGINE=MYSQL")).model).toBeUndefined();
+ });
+ it("locks protected columns and aggregate/unknown definitions but not ordinary values", () => {
+ const context = starRocksAlterOptionsFromDdl(ddl);
+ const draft = (name: string) => ({ original: { name } }) as EditableStructureColumn;
+ expect(starRocksColumnDefinitionLocked(draft("ts"), context)).toBe(true);
+ expect(starRocksColumnDefinitionLocked(draft("id"), context)).toBe(true);
+ expect(starRocksColumnDefinitionLocked(draft("value"), context)).toBe(false);
+ expect(starRocksColumnDefinitionLocked(draft("value"), { ...context, model: "aggregate" })).toBe(true);
+ expect(starRocksColumnDefinitionLocked(draft("value"))).toBe(true);
+ expect(starRocksColumnDefinitionLocked({} as EditableStructureColumn)).toBe(false);
+ });
+ it("separates StarRocks editing capabilities from MySQL and gates rename versions", () => {
+ const caps = getTableStructureCapabilities("starrocks", "mysql", "3.5.0");
+ expect(caps).toMatchObject({ renameColumn: true, alterDefault: false, alterType: true, alterPrimaryKey: false, addPrimaryKey: false, createIndex: false, foreignKey: false, reorderColumn: false });
+ expect(getTableStructureCapabilities("starrocks", "starrocks", "3.3.1").renameColumn).toBe(false);
+ expect(getTableStructureCapabilities("starrocks", "starrocks", "3.3.2").renameColumn).toBe(true);
+ expect(getTableStructureCapabilities("starrocks").renameColumn).toBe(false);
+ expect(getTableStructureCapabilities("mysql").alterPrimaryKey).toBe(true);
+ });
+});
+
+describe("StarRocks layout draft", () => {
+ it("hydrates distribution and preserves a clean draft", () => {
+ const context = starRocksAlterOptionsFromDdl('CREATE TABLE `t` (`id` INT) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY HASH(`id`) BUCKETS 8 PROPERTIES("x"="y")', "3.5.8");
+ expect(context.distribution).toEqual({ method: "hash", columns: ["id"], buckets: 8 });
+ const draft = starRocksLayoutDraft(context)!;
+ expect(starRocksLayoutChanges(draft, context)).toBeUndefined();
+ draft.bucketCount = "12";
+ draft.defaultOnly = true;
+ expect(starRocksLayoutChanges(draft, context)?.distribution).toEqual({ method: "hash", columns: ["id"], buckets: 12, defaultOnly: true });
+ draft.bucketCount = "1.5";
+ expect(starRocksLayoutChanges(draft, context)?.distribution?.buckets).toBe(0);
+ });
+ it("extracts manual partition keys without mistaking properties or comments for clauses", () => {
+ const context = starRocksAlterOptionsFromDdl(
+ 'CREATE TABLE `t` (`dt` DATE COMMENT "PARTITION BY fake", `city` VARCHAR(20)) ENGINE=OLAP DUPLICATE KEY(`dt`) PARTITION BY LIST(`dt`, `city`) (PARTITION p1 VALUES IN (("2026-01-01", "a"))) DISTRIBUTED BY RANDOM PROPERTIES("colocate_with"="")',
+ "3.5.0",
+ );
+ expect(context.partitionKind).toBe("list");
+ expect(context.partitionColumns).toEqual(["dt", "city"]);
+ expect(context.partitionClause).toMatch(/^PARTITION BY LIST/);
+ expect(context.distribution).toEqual({ method: "random", columns: [], buckets: undefined });
+ expect(context.colocated).toBe(false);
+ });
+});
+
+describe("automatic bucket scaling", () => {
+ it("reads positive bucket_size only from actual table properties", () => {
+ const base = 'CREATE TABLE `t` (`id` INT COMMENT \'"bucket_size"="99"\') ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM';
+ expect(starRocksAlterOptionsFromDdl(base).automaticBucketScaling).toBe(false);
+ expect(starRocksAlterOptionsFromDdl(base + ' PROPERTIES("bucket_size"="1073741824")').automaticBucketScaling).toBe(true);
+ expect(starRocksAlterOptionsFromDdl(base + ' PROPERTIES("bucket_size"="0")').automaticBucketScaling).toBe(false);
+ });
+});
+
+describe("StarRocks physical column reordering", () => {
+ it.each([
+ ["(time_slice(`day`, INTERVAL 7 year, floor), `id`)", ["day"]],
+ ["(date_trunc('day', from_unixtime(`ts`)), `id`)", ["ts"]],
+ ["(`day`, `id`)", []],
+ ["LIST(`day`, `id`) (PARTITION p1 VALUES IN (('2026-01-01', 'id')))", []],
+ ])("distinguishes partition-expression sources from plain keys: %s", (partition, expected) => {
+ const ddl = "CREATE TABLE `test4` (`day` datetime, `id` varchar(255), `ts` bigint) ENGINE=OLAP DUPLICATE KEY(`day`, `id`) PARTITION BY " + partition + " DISTRIBUTED BY RANDOM";
+ const context = starRocksAlterOptionsFromDdl(ddl, "3.5.0");
+ expect(context.partitionExpressionColumns).toEqual(expected);
+ expect(context.partitionExpressionColumns).not.toContain("id");
+ });
+
+ it("uses table-model capabilities and keeps complete schema names including complex types", () => {
+ const ddl = "CREATE TABLE `t` (`id` bigint, `attrs` STRUCT<x INT, y VARCHAR(20)>, `value` varchar(20), INDEX idx (`value`) USING BITMAP) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM";
+ const context = starRocksAlterOptionsFromDdl(ddl, "3.5.0");
+ expect(context.columnNames).toEqual(["id", "attrs", "value"]);
+ expect(getTableStructureCapabilities("starrocks", "mysql", "3.5.0", "duplicate").reorderColumn).toBe(true);
+ for (const model of ["aggregate", "unique"]) expect(getTableStructureCapabilities("starrocks", "mysql", "3.5.0", model).reorderColumn).toBe(false);
+ expect(getTableStructureCapabilities("starrocks", "mysql", "3.5.0", "primary").reorderColumn).toBe(false);
+ expect(getTableStructureCapabilities("starrocks", "mysql", "3.5.0").reorderColumn).toBe(false);
+ });
+});
+
+describe("existing StarRocks sort keys", () => {
+ it("reads explicit sort priority independently of field order and falls back to key columns", () => {
+ const ddl = 'CREATE TABLE `t` (`id` INT, `dt` DATETIME, `value` INT COMMENT "ORDER BY(fake)") ENGINE=OLAP DUPLICATE KEY(`id`, `dt`) DISTRIBUTED BY RANDOM';
+ expect(starRocksAlterOptionsFromDdl(ddl).sortColumns).toEqual(["id", "dt"]);
+ expect(starRocksAlterOptionsFromDdl(ddl + " ORDER BY(`dt`, `value`)").sortColumns).toEqual(["dt", "value"]);
+ expect(starRocksAlterOptionsFromDdl(ddl + " ORDER BY(`dt`, `value`)").columnNames).toEqual(["id", "dt", "value"]);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/table/starrocksAlterStatus.spec.ts b/apps/desktop/src/lib/__tests__/table/starrocksAlterStatus.spec.ts
new file mode 100644
index 0000000000..125a953be3
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/table/starrocksAlterStatus.spec.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { isStarRocksAlterJobActive, parseStarRocksAlterJobs, recentStarRocksAlterJobs, starRocksAlterStatusSql } from "@/lib/table/starrocksAlterStatus";
+describe("StarRocks ALTER status", () => {
+ it("quotes table literals and rejects SQL-mode-sensitive names", () => {
+ expect(starRocksAlterStatusSql("COLUMN", "a'b")).toContain("TableName = 'a''b'");
+ expect(() => starRocksAlterStatusSql("COLUMN", "a\\b")).toThrow();
+ expect(() => starRocksAlterStatusSql("COLUMN", "a\0b")).toThrow();
+ });
+ it("maps by column name, supports rollup finish spelling and real progress", () => {
+ const jobs = parseStarRocksAlterJobs("ROLLUP", {
+ columns: ["State", "JobId", "Progress", "FinishedTime", "Msg"],
+ rows: [
+ ["RUNNING", 12, "2/8", null, ""],
+ ["CANCELLED", 13, "N/A", "2026-01-01", "reason"],
+ ],
+ });
+ expect(jobs[0].progress).toBe(25);
+ expect(jobs[1].progress).toBeUndefined();
+ expect(jobs[1].finished).toBe("2026-01-01");
+ expect(jobs[1].message).toBe("reason");
+ expect(isStarRocksAlterJobActive(jobs[0])).toBe(true);
+ expect(isStarRocksAlterJobActive(jobs[1])).toBe(false);
+ });
+ it("does not treat unknown states or malformed result shapes as completed", () => {
+ const [job] = parseStarRocksAlterJobs("COLUMN", { columns: ["JobId", "State", "Progress"], rows: [[1, "FUTURE_STATE", "150%"]] });
+ expect(isStarRocksAlterJobActive(job)).toBe(true);
+ expect(job.progress).toBeUndefined();
+ expect(() => parseStarRocksAlterJobs("COLUMN", { columns: ["error"], rows: [] })).toThrow();
+ });
+ it("combines the latest five across kinds", () => {
+ const jobs = parseStarRocksAlterJobs("COLUMN", { columns: ["JobId", "State", "CreateTime"], rows: Array.from({ length: 8 }, (_, i) => [i, "FINISHED", `2026-01-0${i + 1}`]) });
+ expect(recentStarRocksAlterJobs(jobs).map((job) => job.id)).toEqual(["7", "6", "5", "4", "3"]);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/table/starrocksLayoutCopy.spec.ts b/apps/desktop/src/lib/__tests__/table/starrocksLayoutCopy.spec.ts
new file mode 100644
index 0000000000..e4842beabd
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/table/starrocksLayoutCopy.spec.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it, vi } from "vitest";
+import { buildStarRocksLayoutCopyDdl, executeStarRocksCopyPlan, starRocksCopyInsertColumns } from "@/lib/table/starrocksLayoutCopy";
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+
+const source = `CREATE TABLE \`old\` (
+ \`id\` bigint NOT NULL COMMENT 'PROPERTIES fake',
+ \`dt\` datetime NULL,
+ \`amount\` decimal(18, 2) SUM DEFAULT '0'
+) ENGINE=OLAP
+AGGREGATE KEY(\`id\`, \`dt\`)
+COMMENT 'original table'
+PARTITION BY RANGE(\`dt\`) (PARTITION p1 VALUES [("2026-01-01"), ("2027-01-01")))
+DISTRIBUTED BY RANDOM
+ORDER BY(\`dt\`, \`id\`)
+PROPERTIES ("bucket_size"="1073741824", "compression"="LZ4", "dynamic_partition.enable"="true", "colocate_with"="g", "unknown"="keep; DISTRIBUTED BY RANDOM");`;
+const generated = `CREATE TABLE \`new\` (\`id\` bigint, \`dt\` datetime) PRIMARY KEY(\`id\`) PARTITION BY date_trunc('month', \`dt\`) DISTRIBUTED BY HASH(\`id\`) BUCKETS 16;`;
+
+describe("StarRocks layout copy", () => {
+ it("keeps raw columns, actual key model, comments, sorting and unknown properties", () => {
+ const ddl = buildStarRocksLayoutCopyDdl(source, generated, "db", "new`table", false);
+ expect(ddl).toContain("CREATE TABLE `db`.`new``table` (");
+ expect(ddl).toContain("`amount` decimal(18, 2) SUM DEFAULT '0'");
+ expect(ddl).toContain("AGGREGATE KEY(`id`, `dt`)");
+ expect(ddl).not.toContain("PRIMARY KEY");
+ expect(ddl).toContain("COMMENT 'original table'");
+ expect(ddl).toContain("PARTITION BY date_trunc('month', `dt`)");
+ expect(ddl).toContain("DISTRIBUTED BY HASH(`id`) BUCKETS 16");
+ expect(ddl).toContain("ORDER BY(`dt`, `id`)");
+ expect(ddl).toContain('"unknown"="keep; DISTRIBUTED BY RANDOM"');
+ expect(ddl).toContain('"compression"="LZ4"');
+ expect(ddl).not.toContain('"bucket_size"');
+ expect(ddl).not.toContain('"colocate_with"');
+ expect(ddl).not.toContain('"dynamic_partition.enable"');
+ });
+ it("preserves manual ranges and retention when requested", () => {
+ const ddl = buildStarRocksLayoutCopyDdl(source, generated, "db", "new", true);
+ expect(ddl).toContain('PARTITION BY RANGE(`dt`) (PARTITION p1 VALUES [("2026-01-01"), ("2027-01-01")))');
+ expect(ddl).toContain('"dynamic_partition.enable"="true"');
+ });
+ it("inserts or removes partition clauses without corrupting adjacent distribution", () => {
+ const unpartitioned = "CREATE TABLE `t` (`id` INT) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY HASH(`id`);";
+ const withPartition = buildStarRocksLayoutCopyDdl(unpartitioned, generated, "db", "new", false);
+ expect(withPartition.indexOf("PARTITION BY")).toBeLessThan(withPartition.indexOf("DISTRIBUTED BY"));
+ const withoutPartition = buildStarRocksLayoutCopyDdl(source, unpartitioned, "db", "new", false);
+ expect(withoutPartition).not.toContain("PARTITION BY RANGE");
+ expect(withoutPartition).toContain("DISTRIBUTED BY HASH(`id`)");
+ });
+ it("rejects external tables and multi-statement inputs", () => {
+ expect(() => buildStarRocksLayoutCopyDdl(source.replace("ENGINE=OLAP", "ENGINE=MYSQL"), generated, "db", "new", false)).toThrow();
+ expect(() => buildStarRocksLayoutCopyDdl(source + "DROP TABLE x;", generated, "db", "new", false)).toThrow();
+ });
+ it("omits generated columns from explicit data transfer", () => {
+ const ddl = "CREATE TABLE `t` (`id` INT, `derived` INT AS (`id` + 1)) ENGINE=OLAP DUPLICATE KEY(`id`) DISTRIBUTED BY RANDOM;";
+ expect(starRocksCopyInsertColumns(ddl, [{ name: "id" }, { name: "derived" }] as EditableStructureColumn[])).toEqual(["id"]);
+ });
+ it("creates first, copies only when selected, and never replays a failed step", async () => {
+ const execute = vi.fn().mockResolvedValue(undefined);
+ const stages: string[] = [];
+ await executeStarRocksCopyPlan({ createSql: "CREATE", insertSql: "INSERT", targetName: "new" }, execute, (stage) => stages.push(stage));
+ expect(execute.mock.calls.map((call) => call[0])).toEqual(["CREATE", "INSERT"]);
+ expect(stages).toEqual(["creating", "created", "transferring", "complete"]);
+ execute.mockClear();
+ await executeStarRocksCopyPlan({ createSql: "CREATE", targetName: "empty" }, execute, () => {});
+ expect(execute).toHaveBeenCalledTimes(1);
+ execute.mockReset().mockRejectedValueOnce(new Error("already exists"));
+ await expect(executeStarRocksCopyPlan({ createSql: "CREATE", insertSql: "INSERT", targetName: "new" }, execute, () => {})).rejects.toThrow("already exists");
+ expect(execute).toHaveBeenCalledTimes(1);
+ execute.mockReset().mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("load failed"));
+ const failedStages: string[] = [];
+ await expect(executeStarRocksCopyPlan({ createSql: "CREATE", insertSql: "INSERT", targetName: "new" }, execute, (stage) => failedStages.push(stage))).rejects.toThrow("load failed");
+ expect(execute).toHaveBeenCalledTimes(2);
+ expect(failedStages).toEqual(["creating", "created", "transferring"]);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/table/starrocksPhysicalOptions.spec.ts b/apps/desktop/src/lib/__tests__/table/starrocksPhysicalOptions.spec.ts
new file mode 100644
index 0000000000..3313e5bfa9
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/table/starrocksPhysicalOptions.spec.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+import { buildStarRocksDialectOptions, emptyStarRocksPhysicalOptions, hasStarRocksPhysicalOptions, isStarRocksHashColumn, isStarRocksTimeColumn, restoreStarRocksPhysicalOptions } from "@/lib/table/starrocksPhysicalOptions";
+import { getStarRocksCapabilities } from "@/lib/table/starrocksCapabilities";
+
+describe("StarRocks physical options", () => {
+ it("leaves partitioning off and bucket sizing automatic by default", () => {
+ const draft = emptyStarRocksPhysicalOptions();
+ expect(hasStarRocksPhysicalOptions(draft)).toBe(false);
+ expect(buildStarRocksDialectOptions(draft)).toEqual({ starrocks: { partition: undefined, timePartition: undefined, distribution: "auto", distributionColumnIds: [], sortColumnIds: [], bucketCount: undefined } });
+ });
+ it("round trips drafts without sharing selected arrays and sends stable IDs", () => {
+ const saved = { ...emptyStarRocksPhysicalOptions(), timePartitionEnabled: true, partitionColumnId: "time-id", distribution: "hash" as const, distributionColumnIds: ["user-id"], bucketCount: "8" };
+ const restored = restoreStarRocksPhysicalOptions(saved);
+ restored.distributionColumnIds.push("another-id");
+ expect(saved.distributionColumnIds).toEqual(["user-id"]);
+ expect(hasStarRocksPhysicalOptions(restored)).toBe(true);
+ expect(buildStarRocksDialectOptions(restored).starrocks).toEqual({
+ partition: undefined,
+ timePartition: { columnId: "time-id", granularity: "month", additionalColumnIds: [], interval: undefined },
+ distribution: "hash",
+ distributionColumnIds: ["user-id", "another-id"],
+ sortColumnIds: [],
+ bucketCount: 8,
+ });
+ });
+ it("does not send inactive choices after switching modes", () => {
+ const draft = { ...emptyStarRocksPhysicalOptions(), partitionColumnId: "time-id", distributionColumnIds: ["user-id"], distribution: "random" as const };
+ expect(buildStarRocksDialectOptions(draft).starrocks).toMatchObject({ timePartition: undefined, distributionColumnIds: [] });
+ });
+ it.each(["0", "-1", "1.5", "bad", "2147483648", "Infinity"])("sends invalid bucket count %s for backend rejection", (bucketCount) => {
+ expect(buildStarRocksDialectOptions({ ...emptyStarRocksPhysicalOptions(), bucketCount }).starrocks?.bucketCount).toBe(0);
+ });
+ it.each(["date", "DATETIME"])("allows %s time partitions", (dataType) => expect(isStarRocksTimeColumn({ dataType })).toBe(true));
+ it.each(["timestamp", "datetime(6)", "varchar(255)", "int"])("rejects %s time partitions", (dataType) => expect(isStarRocksTimeColumn({ dataType })).toBe(false));
+ it.each(["json", "array<int>", "float", "decimal(18,2)", "varbinary(10)"])("does not offer %s as a hash key", (dataType) => expect(isStarRocksHashColumn({ dataType })).toBe(false));
+ it.each(["bigint(20)", "varchar(255)", "date", "datetime"])("offers %s as a hash key", (dataType) => expect(isStarRocksHashColumn({ dataType })).toBe(true));
+ it("gates modern layouts using the actual product version", () => {
+ for (const version of [undefined, "5.1.0", "3.0.0"]) {
+ expect(getStarRocksCapabilities(version).timePartitioning).toBe(false);
+ expect(getStarRocksCapabilities(version).randomDistribution).toBe(false);
+ }
+ expect(getStarRocksCapabilities("3.5.0")).toMatchObject({ timePartitioning: true, randomDistribution: true });
+ });
+});
+
+describe("StarRocks partition strategies", () => {
+ it("keeps named bounds associated with column IDs after selection reordering", () => {
+ const draft = { ...emptyStarRocksPhysicalOptions(), partitionKind: "range" as const, partitionColumnIds: ["b", "a"], rangePartitions: [{ id: "p", name: "p1", lower: { a: "1", b: "2" }, upper: { a: "10", b: "20" } }] };
+ expect(buildStarRocksDialectOptions(draft).starrocks?.partition).toEqual({ kind: "range", columnIds: ["b", "a"], partitions: [{ name: "p1", lower: ["2", "1"], upper: ["20", "10"] }] });
+ expect(buildStarRocksDialectOptions(draft).starrocks?.timePartition).toBeUndefined();
+ });
+ it("preserves commas and quotes as list values rather than parsing SQL", () => {
+ const draft = { ...emptyStarRocksPhysicalOptions(), partitionKind: "list" as const, partitionColumnIds: ["city"], listPartitions: [{ id: "p", name: "p1", values: [{ id: "v", fields: { city: "Xi'an, city" } }] }] };
+ expect(buildStarRocksDialectOptions(draft).starrocks?.partition).toEqual({ kind: "list", columnIds: ["city"], partitions: [{ name: "p1", values: [["Xi'an, city"]] }] });
+ const restored = restoreStarRocksPhysicalOptions(draft);
+ restored.listPartitions[0]!.values[0]!.fields.city = "changed";
+ expect(draft.listPartitions[0]!.values[0]!.fields.city).toBe("Xi'an, city");
+ });
+ it("generates mixed time dimensions and interval settings", () => {
+ const draft = { ...emptyStarRocksPhysicalOptions(), partitionKind: "time" as const, partitionColumnId: "dt", partitionColumnIds: ["city"], timeInterval: "7", granularity: "day" as const };
+ expect(buildStarRocksDialectOptions(draft).starrocks?.timePartition).toEqual({ columnId: "dt", additionalColumnIds: ["city"], interval: 7, granularity: "day" });
+ });
+});
+
+it("preserves independent sort priority across draft restoration and serialization", () => {
+ const draft = { ...emptyStarRocksPhysicalOptions(), sortColumnIds: ["time", "id"] };
+ expect(hasStarRocksPhysicalOptions(draft)).toBe(true);
+ const restored = restoreStarRocksPhysicalOptions(draft);
+ restored.sortColumnIds.reverse();
+ expect(draft.sortColumnIds).toEqual(["time", "id"]);
+ expect(buildStarRocksDialectOptions(restored).starrocks?.sortColumnIds).toEqual(["id", "time"]);
+});
diff --git a/apps/desktop/src/lib/__tests__/table/tableStructureEditorState.starrocks.spec.ts b/apps/desktop/src/lib/__tests__/table/tableStructureEditorState.starrocks.spec.ts
new file mode 100644
index 0000000000..3c77b03aca
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/table/tableStructureEditorState.starrocks.spec.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from "vitest";
+import { tableStructureDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
+import { combineDataTypeForDatabase, dataTypeBaseInputValue, dataTypeLengthInputValue, defaultNewColumnDataType, getDataTypeOptions, getDefaultLengthForType, isDataTypeLengthDisabled } from "@/lib/table/tableStructureEditorState";
+
+describe("StarRocks structure editor types", () => {
+ it("uses native choices even when MySQL metadata supplies incompatible types", () => {
+ const dbType = tableStructureDatabaseTypeForConnection({ db_type: "mysql", driver_profile: "starrocks" });
+ expect(dbType).toBe("starrocks");
+ const options = getDataTypeOptions(dbType, ["bigint unsigned", "timestamp", "enum", "text"], "3.5.0");
+ expect(options).toEqual(getDataTypeOptions("starrocks", [], "3.5.0"));
+ expect(options).toEqual(expect.arrayContaining(["bigint", "largeint", "datetime", "json", "array<int>", "map<int, int>", "struct<field int>", "bitmap", "hll", "percentile", "varbinary"]));
+ expect(options.some((type) => /unsigned|timestamp|mediumint|text|blob|enum|^set$|geometry|^time$|^year$/i.test(type))).toBe(false);
+ expect(defaultNewColumnDataType(dbType, options)).toBe("varchar(255)");
+ });
+
+ it.each(["BOOLEAN", "FLOAT", "DOUBLE", "DATE", "DATETIME", "STRING", "JSON", "BITMAP", "HLL", "PERCENTILE"])("does not add MySQL parameters to %s", (type) => {
+ expect(isDataTypeLengthDisabled("starrocks", type)).toBe(true);
+ expect(getDefaultLengthForType("starrocks", type)).toBe("");
+ expect(combineDataTypeForDatabase("starrocks", type, "20")).toBe(type);
+ });
+
+ it.each([
+ ["TINYINT", "4"],
+ ["SMALLINT", "6"],
+ ["INT", "11"],
+ ["BIGINT", "20"],
+ ["VARCHAR", "255"],
+ ["CHAR", "1"],
+ ["DECIMAL", "10,0"],
+ ])("fills and displays the default parameter for %s", (type, length) => {
+ expect(isDataTypeLengthDisabled("starrocks", type)).toBe(false);
+ const defaultLength = getDefaultLengthForType("starrocks", type);
+ expect(defaultLength).toBe(length);
+ const dataType = combineDataTypeForDatabase("starrocks", type, defaultLength);
+ expect(dataType).toBe(`${type}(${length})`);
+ expect(dataTypeLengthInputValue("starrocks", dataType)).toBe(length);
+ });
+
+ it.each([
+ ["VARCHAR", "255"],
+ ["CHAR", "10"],
+ ["BINARY", "16"],
+ ["VARBINARY", "1024"],
+ ["DECIMAL", "18,4"],
+ ])("retains supported parameters for %s", (type, params) => {
+ expect(isDataTypeLengthDisabled("starrocks", type)).toBe(false);
+ expect(combineDataTypeForDatabase("starrocks", type, params)).toBe(`${type}(${params})`);
+ });
+
+ it.each(["ARRAY<DECIMAL(18,4)>", "MAP<VARCHAR(32), ARRAY<INT>>", "STRUCT<name VARCHAR(64), amount DECIMAL(18,2)>"])("preserves nested parameters in %s", (type) => {
+ expect(dataTypeBaseInputValue("starrocks", type)).toBe(type);
+ expect(dataTypeLengthInputValue("starrocks", type)).toBe("");
+ expect(combineDataTypeForDatabase("starrocks", type, "255")).toBe(type);
+ });
+
+ it("keeps MySQL unsigned types, display widths and dynamic choices", () => {
+ expect(getDataTypeOptions("mysql")).toContain("bigint unsigned");
+ expect(getDataTypeOptions("mysql", [" custom_type ", "CUSTOM_TYPE"])[0]).toBe("custom_type");
+ expect(getDataTypeOptions("mysql", [" custom_type ", "CUSTOM_TYPE"]).filter((type) => type.toLowerCase() === "custom_type")).toHaveLength(1);
+ expect(combineDataTypeForDatabase("mysql", "bigint unsigned", "20")).toBe("bigint(20) unsigned");
+ expect(getDefaultLengthForType("mysql", "bigint unsigned")).toBe("20");
+ });
+});
+
+describe("StarRocks version capabilities", () => {
+ it.each([
+ [undefined, false, false, false, false],
+ ["5.1.0", false, false, false, false],
+ ["2.1.0", false, false, false, false],
+ ["2.2.0", true, false, false, false],
+ ["3.0.0", true, true, false, false],
+ ["3.1.0", true, true, true, false],
+ ["StarRocks version 3.5.0 abc123", true, true, true, false],
+ ["4.0.0", true, true, true, true],
+ ])("filters type choices for %s", (version, json, binary, complex, decimal256) => {
+ const types = getDataTypeOptions("starrocks", [], version as string | undefined);
+ expect(types.includes("json")).toBe(json);
+ expect(types.includes("varbinary")).toBe(binary);
+ expect(types.includes("map<int, int>")).toBe(complex);
+ expect(types.includes("struct<field int>")).toBe(complex);
+ expect(types.includes("decimal256")).toBe(decimal256);
+ });
+});
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index 48e285398d..003bade88a 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -1,3 +1,5 @@
+import type { StarRocksAlterOptions } from "@/lib/table/starrocksAlterOptions";
+import type { CreateTableDialectOptions } from "@/lib/table/starrocksPhysicalOptions";
import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRestoreSourcePreview, MongoDatabaseDumpRequest, MongoDatabaseRestoreRequest, MongoDatabaseDumpProgress } from "./mongodbDumpTypes";
import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTypes";
import type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./damengDumpTypes";
@@ -1967,8 +1969,8 @@ export async function buildViewDdlSql(input: BuildViewDdlInput): Promise<string>
return post("/api/query/build-view-ddl-sql", { input });
}
-export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
- return post("/api/query/build-table-structure-change-sql", { options });
+export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions, starrocks?: StarRocksAlterOptions): Promise<TableStructureChangeSql> {
+ return post("/api/query/build-table-structure-change-sql", { options, starrocks });
}
export async function buildTableOwnerChangeSql(options: BuildTableOwnerChangeSqlOptions): Promise<TableStructureChangeSql> {
@@ -2000,8 +2002,8 @@ export async function applySqliteTableStructureChange(connectionId: string, data
});
}
-export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
- return post("/api/query/build-create-table-sql", { options });
+export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions, serverVersion?: string, dialectOptions?: CreateTableDialectOptions): Promise<TableStructureChangeSql> {
+ return post("/api/query/build-create-table-sql", { options, serverVersion, dialectOptions });
}
export async function buildSingleColumnAlterSql(options: BuildSingleColumnAlterSqlOptions): Promise<TableStructureChangeSql> {
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index f2d6894caa..f5af507749 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -1,3 +1,5 @@
+import type { StarRocksAlterOptions } from "@/lib/table/starrocksAlterOptions";
+import type { CreateTableDialectOptions } from "@/lib/table/starrocksPhysicalOptions";
import { invoke as tauriInvoke } from "@tauri-apps/api/core";
import { Channel } from "@tauri-apps/api/core";
import type { MongoDumpFormat, MongoDumpSourceInput, MongoDumpCatalog, MongoRestoreSourcePreview, MongoDatabaseDumpRequest, MongoDatabaseRestoreRequest, MongoDatabaseDumpProgress } from "./mongodbDumpTypes";
@@ -2386,8 +2388,8 @@ export async function buildViewDdlSql(input: BuildViewDdlInput): Promise<string>
return invoke("build_view_ddl_sql", { input });
}
-export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
- return invoke("build_table_structure_change_sql", { options });
+export async function buildTableStructureChangeSql(options: BuildTableStructureChangeSqlOptions, starrocks?: StarRocksAlterOptions): Promise<TableStructureChangeSql> {
+ return invoke("build_table_structure_change_sql", { options, starrocks });
}
export async function buildTableOwnerChangeSql(options: BuildTableOwnerChangeSqlOptions): Promise<TableStructureChangeSql> {
@@ -2419,8 +2421,8 @@ export async function applySqliteTableStructureChange(connectionId: string, data
});
}
-export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions): Promise<TableStructureChangeSql> {
- return invoke("build_create_table_sql", { options });
+export async function buildCreateTableSql(options: BuildTableStructureChangeSqlOptions, serverVersion?: string, dialectOptions?: CreateTableDialectOptions): Promise<TableStructureChangeSql> {
+ return invoke("build_create_table_sql", { options, serverVersion, dialectOptions });
}
export async function buildSingleColumnAlterSql(options: BuildSingleColumnAlterSqlOptions): Promise<TableStructureChangeSql> {
diff --git a/apps/desktop/src/lib/sql/__tests__/starrocksDdlDisplay.spec.ts b/apps/desktop/src/lib/sql/__tests__/starrocksDdlDisplay.spec.ts
new file mode 100644
index 0000000000..50573b1d45
--- /dev/null
+++ b/apps/desktop/src/lib/sql/__tests__/starrocksDdlDisplay.spec.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+import { formatStarRocksDdlForDisplay } from "../starrocksDdlDisplay";
+import { formatDdlForDisplay } from "../ddlDisplay";
+import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
+
+const source =
+ 'CREATE TABLE `test4` (`day` datetime NULL COMMENT "", `id` VARCHAR(255) NOT NULL COMMENT "", `price1` DECIMAL(7, 0) NULL COMMENT "工资, PROPERTIES (x)") ENGINE = OLAP DUPLICATE KEY(`day`, `id`) PARTITION BY (time_slice (`day`, INTERVAL 7 YEAR, floor), `id`) DISTRIBUTED BY RANDOM PROPERTIES("bucket_size" = "1073741824", "compression" = "LZ4");';
+const expected = `CREATE TABLE \`test4\` (
+ \`day\` datetime NULL COMMENT "",
+ \`id\` varchar(255) NOT NULL COMMENT "",
+ \`price1\` decimal(7, 0) NULL COMMENT "工资, PROPERTIES (x)"
+) ENGINE=OLAP
+DUPLICATE KEY(\`day\`, \`id\`)
+PARTITION BY (time_slice(\`day\`, INTERVAL 7 year, floor), \`id\`)
+DISTRIBUTED BY RANDOM
+PROPERTIES (
+"bucket_size" = "1073741824",
+"compression" = "LZ4"
+);`;
+
+describe("StarRocks DDL display", () => {
+ it("keeps nested expressions and string contents while separating table clauses", () => {
+ expect(formatStarRocksDdlForDisplay(source)).toBe(expected);
+ expect(formatStarRocksDdlForDisplay(expected)).toBe(expected);
+ });
+ it("uses the StarRocks branch through the shared display interface", async () => {
+ expect(await formatDdlForDisplay(source, { dialect: "mysql", databaseType: "starrocks", includeDatabaseName: false, quoteIdentifiers: true })).toBe(expected);
+ });
+ it.each([
+ { db_type: "starrocks", driver_profile: "starrocks" },
+ { db_type: "mysql", driver_profile: "starrocks" },
+ { db_type: "mysql", driver_profile: "StarRocks" },
+ ] as const)("formats the effective StarRocks type for $db_type / $driver_profile", async (connection) => {
+ const databaseType = effectiveDatabaseTypeForConnection(connection);
+ expect(databaseType).toBe("starrocks");
+ expect(await formatDdlForDisplay(source, { dialect: "mysql", databaseType, includeDatabaseName: false, quoteIdentifiers: true })).toBe(expected);
+ });
+ it("does not treat ordinary MySQL as StarRocks", () => {
+ expect(effectiveDatabaseTypeForConnection({ db_type: "mysql", driver_profile: "mysql" })).toBe("mysql");
+ });
+ it("preserves unfamiliar statements and comments", () => {
+ for (const sql of ["ALTER TABLE `t` RENAME COLUMN `x` TO `y`;", "CREATE TABLE `t` (`id` INT /* retain comment */);", "CREATE TABLE `t` (`id` INT); DROP TABLE `t`;"]) {
+ expect(formatStarRocksDdlForDisplay(sql)).toBe(sql);
+ }
+ });
+});
diff --git a/apps/desktop/src/lib/sql/ddlDisplay.ts b/apps/desktop/src/lib/sql/ddlDisplay.ts
index 37971dfb16..094daed1ec 100644
--- a/apps/desktop/src/lib/sql/ddlDisplay.ts
+++ b/apps/desktop/src/lib/sql/ddlDisplay.ts
@@ -4,6 +4,7 @@ import type { SqlSemanticToken } from "@/lib/sql/semantic/types";
import { formatSqlForDisplay, sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import { DEFAULT_SQL_FORMATTER_SETTINGS, type SqlFormatterSettings } from "@/lib/sql/sqlFormatterConfig";
import { applyDdlStoragePreference } from "@/lib/sql/ddlStorage";
+import { formatStarRocksDdlForDisplay } from "@/lib/sql/starrocksDdlDisplay";
import { dropsSchemaQualifier, quoteTableIdentifier } from "@/lib/table/tableSelectSql";
import type { DatabaseType } from "@/types/database";
@@ -547,6 +548,7 @@ export function alignDdlColumnDefinitions(sql: string, dialect: SqlFormatDialect
export interface DdlDisplayFormatOptions {
dialect: SqlFormatDialect;
+ /** Effective type from effectiveDatabaseTypeForConnection, including MySQL driver profiles. */
databaseType?: DatabaseType;
database?: string;
catalog?: string;
@@ -570,7 +572,7 @@ export interface DdlDisplayFormatOptions {
export function applyDdlDisplayPreferences(sql: string, options: DdlDisplayFormatOptions): string {
const qualified = applyDdlDatabaseQualifier(sql, options.dialect, options.databaseType, options.includeDatabaseName, options.database, options.catalog);
const quoted = options.quoteIdentifiers ? qualified : omitDdlIdentifierQuotes(qualified, options.dialect);
- const aligned = alignDdlColumnDefinitions(uppercaseDdlColumnTypes(quoted, options.dialect), options.dialect);
+ const aligned = options.databaseType === "starrocks" ? formatStarRocksDdlForDisplay(quoted) : alignDdlColumnDefinitions(uppercaseDdlColumnTypes(quoted, options.dialect), options.dialect);
return options.excludeDdlStorage ? applyDdlStoragePreference(aligned, options.databaseType) : aligned;
}
@@ -581,5 +583,5 @@ export function applyDdlDisplayPreferences(sql: string, options: DdlDisplayForma
* result of the object DDL fetch straight through it.
*/
export async function formatDdlForDisplay(ddl: string, options: DdlDisplayFormatOptions, formatter: Partial<SqlFormatterSettings> = DEFAULT_SQL_FORMATTER_SETTINGS): Promise<string> {
- return applyDdlDisplayPreferences(await formatSqlForDisplay(ddl, options.dialect, formatter), options);
+ return applyDdlDisplayPreferences(options.databaseType === "starrocks" ? ddl : await formatSqlForDisplay(ddl, options.dialect, formatter), options);
}
diff --git a/apps/desktop/src/lib/sql/semantic/tokens.ts b/apps/desktop/src/lib/sql/semantic/tokens.ts
index 624ee552e2..7b45c76ed6 100644
--- a/apps/desktop/src/lib/sql/semantic/tokens.ts
+++ b/apps/desktop/src/lib/sql/semantic/tokens.ts
@@ -103,7 +103,7 @@ export function matchDollarQuoteTag(input: string, index: number): string | unde
* decides string-vs-identifier per token position instead of per dialect (see that function's doc
* comment) -- but the option stays available as a general tokenizer capability.
*/
-export function tokenizeSqlSemantic(input: string, dialectId = "mysql", options?: { mysqlDashCommentRequiresWhitespace?: boolean; mysqlBackslashEscape?: boolean; mysqlDoubleQuoteIsString?: boolean }): SqlSemanticToken[] {
+export function tokenizeSqlSemantic(input: string, dialectId = "mysql", options?: { mysqlDashCommentRequiresWhitespace?: boolean; mysqlBackslashEscape?: boolean; mysqlDoubleQuoteIsString?: boolean; squareBracketsAsDelimiters?: boolean }): SqlSemanticToken[] {
const tokens: SqlSemanticToken[] = [];
const mysqlDashCommentRequiresWhitespace = !!options?.mysqlDashCommentRequiresWhitespace;
const mysqlBackslashEscape = !!options?.mysqlBackslashEscape;
@@ -197,7 +197,7 @@ export function tokenizeSqlSemantic(input: string, dialectId = "mysql", options?
continue;
}
- if (ch === "[") {
+ if (ch === "[" && !options?.squareBracketsAsDelimiters) {
const quoted = readQuoted(input, start, "[", "]");
index = quoted.end;
tokens.push(token("quoted_identifier", input.slice(start, index), start, index, depth, "[", quoted.closed));
@@ -236,10 +236,10 @@ export function tokenizeSqlSemantic(input: string, dialectId = "mysql", options?
// Fullwidth () (U+FF08/U+FF09) are common IME typos in Chinese locales; treat them like
// ASCII () for nesting depth so commas inside to_date(…, …) stay nested and do not split
// INSERT ... SELECT projections (insert value column hints).
- if ("(),.;*".includes(ch) || ch === "\uFF08" || ch === "\uFF09") {
- if (ch === ")" || ch === "\uFF09") depth = Math.max(0, depth - 1);
+ if ("(),.;*".includes(ch) || ch === "\uFF08" || ch === "\uFF09" || (options?.squareBracketsAsDelimiters && (ch === "[" || ch === "]"))) {
+ if (ch === ")" || ch === "\uFF09" || ch === "]") depth = Math.max(0, depth - 1);
tokens.push(token("punctuation", ch, start, start + ch.length, depth));
- if (ch === "(" || ch === "\uFF08") depth += 1;
+ if (ch === "(" || ch === "\uFF08" || ch === "[") depth += 1;
index += ch.length;
continue;
}
diff --git a/apps/desktop/src/lib/sql/starrocksDdlDisplay.ts b/apps/desktop/src/lib/sql/starrocksDdlDisplay.ts
new file mode 100644
index 0000000000..64103ab6b3
--- /dev/null
+++ b/apps/desktop/src/lib/sql/starrocksDdlDisplay.ts
@@ -0,0 +1,100 @@
+import { tokenizeSqlSemantic } from "./semantic/tokens";
+import type { SqlSemanticToken } from "./semantic/types";
+
+const TYPES = new Set([
+ "boolean",
+ "tinyint",
+ "smallint",
+ "int",
+ "integer",
+ "bigint",
+ "largeint",
+ "float",
+ "double",
+ "decimal",
+ "decimalv2",
+ "decimal32",
+ "decimal64",
+ "decimal128",
+ "date",
+ "datetime",
+ "char",
+ "varchar",
+ "string",
+ "binary",
+ "varbinary",
+ "json",
+ "array",
+ "map",
+ "struct",
+ "bitmap",
+ "hll",
+ "percentile",
+]);
+const ATTRIBUTES = new Set(["null", "not", "default", "comment", "key", "auto_increment", "as", "generated", "sum", "min", "max", "replace", "replace_if_not_null", "hll_union", "bitmap_union", "percentile_union"]);
+
+function inline(tokens: SqlSemanticToken[]): string {
+ let text = "";
+ let previous: SqlSemanticToken | undefined;
+ for (const token of tokens) {
+ const tight = !previous || [")", ",", ";", "."].includes(token.text) || ["(", "."].includes(previous.text) || (token.text === "(" && previous.kind === "word" && !["by", "properties"].includes(previous.normalized));
+ text += (tight ? "" : " ") + token.text;
+ previous = token;
+ }
+ return text;
+}
+
+function split(tokens: SqlSemanticToken[], depth: number): SqlSemanticToken[][] {
+ const groups: SqlSemanticToken[][] = [[]];
+ for (const token of tokens) {
+ if (token.text === "," && token.depth === depth) groups.push([]);
+ else groups[groups.length - 1]!.push(token);
+ }
+ return groups;
+}
+
+/** Format only a single CREATE TABLE; unfamiliar/commented SQL stays intact. */
+export function formatStarRocksDdlForDisplay(sql: string): string {
+ const tokens = tokenizeSqlSemantic(sql, "mysql");
+ if (tokens.some((token) => token.kind === "comment" || token.closed === false)) return sql;
+ if (tokens[0]?.normalized !== "create" || tokens[1]?.normalized !== "table") return sql;
+ if (tokens.filter((token) => token.text === ";" && token.depth === 0).length > 1 || tokens.some((token, index) => token.text === ";" && index < tokens.length - 1)) return sql;
+ const opening = tokens.findIndex((token) => token.text === "(" && token.depth === 0);
+ if (opening < 0) return sql;
+ const closing = tokens.findIndex((token, index) => index > opening && token.text === ")" && token.depth === 0);
+ if (closing < 0) return sql;
+ const columns = split(tokens.slice(opening + 1, closing), 1).map((column) => {
+ let inType = true;
+ return (
+ " " +
+ inline(
+ column.map((token, index) => {
+ if (index > 0 && token.depth === 1 && token.kind === "word" && ATTRIBUTES.has(token.normalized)) inType = false;
+ return index > 0 && inType && token.kind === "word" && TYPES.has(token.normalized) ? { ...token, text: token.normalized } : token;
+ }),
+ )
+ );
+ });
+ const tail = tokens.slice(closing + 1).filter((token) => token.text !== ";");
+ const clauses: SqlSemanticToken[][] = [];
+ for (let index = 0; index < tail.length; index++) {
+ const token = tail[index]!;
+ const next = tail[index + 1]?.normalized;
+ const boundary =
+ token.depth === 0 &&
+ token.kind === "word" &&
+ (["engine", "comment", "properties"].includes(token.normalized) || (["primary", "duplicate", "unique", "aggregate"].includes(token.normalized) && next === "key") || (["partition", "distributed", "order"].includes(token.normalized) && next === "by"));
+ if (boundary || !clauses.length) clauses.push([]);
+ clauses[clauses.length - 1]!.push(token);
+ }
+ let result = inline(tokens.slice(0, opening)) + " (\n" + columns.join(",\n") + "\n)";
+ for (const clause of clauses) {
+ if (clause[0]?.normalized === "properties" && clause[1]?.text === "(" && clause[clause.length - 1]?.text === ")") {
+ result += "\nPROPERTIES (\n" + split(clause.slice(2, -1), 1).map(inline).join(",\n") + "\n)";
+ } else {
+ const text = inline(clause.map((token, index) => (token.kind === "word" && clause[index - 1]?.kind === "number" && clause[index - 2]?.normalized === "interval" && ["year", "month", "day", "hour", "minute", "second"].includes(token.normalized) ? { ...token, text: token.normalized } : token)));
+ result += (clause[0]?.normalized === "engine" ? " " : "\n") + (clause[0]?.normalized === "engine" ? text.replace(/\s*=\s*/, "=") : text);
+ }
+ }
+ return result + (tokens[tokens.length - 1]?.text === ";" ? ";" : "");
+}
diff --git a/apps/desktop/src/lib/table/columnDefaultPresets.ts b/apps/desktop/src/lib/table/columnDefaultPresets.ts
new file mode 100644
index 0000000000..7e8a3c3250
--- /dev/null
+++ b/apps/desktop/src/lib/table/columnDefaultPresets.ts
@@ -0,0 +1,110 @@
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+import { getStarRocksCapabilities } from "./starrocksCapabilities";
+
+export interface DefaultValuePreset {
+ label: string;
+ value: string;
+}
+export interface ColumnDefaultPresetContext {
+ databaseType?: string;
+ dialect: string;
+ serverVersion?: string;
+ unsetLabel: string;
+ isCreateMode?: boolean;
+}
+type DefaultColumn = Pick<EditableStructureColumn, "dataType" | "isNullable" | "isPrimaryKey" | "extra">;
+type DefaultPresetProvider = (column: DefaultColumn, context: ColumnDefaultPresetContext) => DefaultValuePreset[];
+const presets = (...values: string[]): DefaultValuePreset[] => values.map((value) => ({ label: value, value }));
+
+// Keep product-specific defaults separate from the compatible wire/SQL dialect.
+const providers: Record<string, DefaultPresetProvider> = {
+ starrocks: starRocksDefaultPresets,
+};
+
+export function getColumnDefaultValuePresets(column: DefaultColumn, context: ColumnDefaultPresetContext): DefaultValuePreset[] {
+ const provider = providers[context.databaseType ?? ""];
+ return provider ? provider(column, context) : legacyDefaultPresets(context);
+}
+
+function starRocksDefaultPresets(column: DefaultColumn, context: ColumnDefaultPresetContext): DefaultValuePreset[] {
+ const result = [{ label: context.unsetLabel, value: "" }];
+ const base = column.dataType.split(/[<(]/)[0]!.trim().toLowerCase();
+ if (column.extra?.autoIncrement || base === "hll" || base === "bitmap") return result;
+ if (column.isNullable && !column.isPrimaryKey) result.push(...presets("NULL"));
+ // ADD COLUMN cannot backfill per-row UUID expressions.
+ const functions = context.isCreateMode === true && getStarRocksCapabilities(context.serverVersion).defaultFunctions;
+ if (/^(tinyint|smallint|int|integer|bigint|largeint|float|double|decimal|decimalv2|decimal32|decimal64|decimal128|decimal256)$/.test(base)) {
+ result.push(...presets("'0'", "'1'"));
+ if (base === "largeint" && functions) result.push(...presets("(uuid_numeric())"));
+ } else if (base === "boolean") {
+ result.push(...presets("'false'", "'true'"));
+ } else if (base === "date") {
+ result.push(...presets("1970-01-01"));
+ } else if (base === "datetime") {
+ result.push(...presets("CURRENT_TIMESTAMP"));
+ } else if (base === "char" || base === "varchar" || base === "string") {
+ result.push(...presets("''"));
+ const length = Number(column.dataType.match(/\(\s*(\d+)\s*\)/)?.[1] ?? 1);
+ if (functions && (base === "string" || (base === "varchar" && length >= 36))) result.push(...presets("(uuid())"));
+ }
+ // 3.5 complex/JSON/binary columns do not use scalar or newer-version expression presets.
+ // Other literals remain manually editable; changing type never discards user input.
+ return result;
+}
+
+function legacyDefaultPresets(context: ColumnDefaultPresetContext): DefaultValuePreset[] {
+ const universal: DefaultValuePreset[] = [
+ { label: "''", value: "''" },
+ { label: "NULL", value: "NULL" },
+ { label: "0", value: "0" },
+ { label: "1", value: "1" },
+ ];
+
+ const dialectPresets: Record<string, DefaultValuePreset[]> = {
+ mysql: [
+ { label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
+ { label: "CURRENT_DATE", value: "CURRENT_DATE" },
+ { label: "CURRENT_TIME", value: "CURRENT_TIME" },
+ ],
+ postgres: [
+ { label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
+ { label: "CURRENT_DATE", value: "CURRENT_DATE" },
+ { label: "now()", value: "now()" },
+ { label: "gen_random_uuid()", value: "gen_random_uuid()" },
+ ],
+ sqlite: [
+ { label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
+ { label: "CURRENT_DATE", value: "CURRENT_DATE" },
+ { label: "CURRENT_TIME", value: "CURRENT_TIME" },
+ ],
+ duckdb: [
+ { label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
+ { label: "CURRENT_DATE", value: "CURRENT_DATE" },
+ ],
+ sqlserver: [
+ { label: "GETDATE()", value: "GETDATE()" },
+ { label: "GETUTCDATE()", value: "GETUTCDATE()" },
+ { label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
+ { label: "NEWID()", value: "NEWID()" },
+ ],
+ oracle: [
+ { label: "SYSDATE", value: "SYSDATE" },
+ { label: "SYSTIMESTAMP", value: "SYSTIMESTAMP" },
+ { label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
+ ],
+ h2: [
+ { label: "CURRENT_TIMESTAMP", value: "CURRENT_TIMESTAMP" },
+ { label: "CURRENT_DATE", value: "CURRENT_DATE" },
+ ],
+ clickhouse: [
+ { label: "now()", value: "now()" },
+ { label: "today()", value: "today()" },
+ ],
+ informix: [
+ { label: "CURRENT", value: "CURRENT" },
+ { label: "TODAY", value: "TODAY" },
+ ],
+ };
+
+ return [...universal, ...(dialectPresets[context.dialect] ?? [])];
+}
diff --git a/apps/desktop/src/lib/table/starrocksAlterOptions.ts b/apps/desktop/src/lib/table/starrocksAlterOptions.ts
new file mode 100644
index 0000000000..7292297e5e
--- /dev/null
+++ b/apps/desktop/src/lib/table/starrocksAlterOptions.ts
@@ -0,0 +1,184 @@
+import { tokenizeSqlSemantic, unquoteSqlSemanticIdentifier } from "@/lib/sql/semantic/tokens";
+import type { EditableStructureColumn } from "./tableStructureEditorSql";
+
+export interface StarRocksDistributionChange {
+ method: "hash" | "random";
+ columns: string[];
+ buckets?: number;
+ defaultOnly?: boolean;
+}
+export type StarRocksPartitionChange = { kind: "addRange"; name: string; lower: string[]; upper: string[] } | { kind: "addList"; name: string; values: string[][] } | { kind: "drop"; name: string } | { kind: "replicas"; name: string; replicas: number };
+export interface StarRocksLayoutChanges {
+ distribution?: StarRocksDistributionChange;
+ partitions: StarRocksPartitionChange[];
+}
+export interface StarRocksLayoutDraft {
+ method: "hash" | "random";
+ columns: string[];
+ bucketCount: string;
+ defaultOnly: boolean;
+ partitions: StarRocksPartitionChange[];
+}
+export interface StarRocksAlterOptions {
+ serverVersion?: string;
+ columnNames?: string[];
+ reorderColumns?: boolean;
+ positionColumnOrder?: boolean;
+ sortColumns?: string[];
+ sortColumnNames?: string[];
+ model?: "primary" | "duplicate" | "unique" | "aggregate";
+ keyColumns: string[];
+ partitionColumns: string[];
+ /** Source columns of partition expressions; these can back hidden generated columns. */
+ partitionExpressionColumns?: string[];
+ distributionColumns: string[];
+ distribution?: StarRocksDistributionChange;
+ partitionKind?: "range" | "list" | "expression";
+ partitionClause?: string;
+ colocated?: boolean;
+ automaticBucketScaling?: boolean;
+ layout?: StarRocksLayoutChanges;
+}
+
+// Read only the table-level clauses of SHOW CREATE TABLE. Quoted strings and
+// comments are discarded, so comments cannot masquerade as schema metadata.
+export function starRocksAlterOptionsFromDdl(ddl: string, serverVersion?: string): StarRocksAlterOptions {
+ const result: StarRocksAlterOptions = { serverVersion, keyColumns: [], partitionColumns: [], distributionColumns: [] };
+ const tokens = [...ddl.matchAll(/--[^\n]*|\/\*[\s\S]*?\*\/|'(?:\\.|''|[^'\\])*'|"(?:\\.|""|[^"\\])*"|`(?:``|[^`])*`|[a-zA-Z_][\w$]*|\d+|[(),=]/g)].map((match) => match[0]).filter((token) => !/^('|"|--|\/\*)/.test(token));
+ let start = tokens.indexOf("(");
+ if (start < 0) return result;
+ let depth = 0;
+ for (; start < tokens.length; start++) {
+ if (tokens[start] === "(") depth++;
+ if (tokens[start] === ")" && --depth === 0) {
+ start++;
+ break;
+ }
+ }
+ const schemaTokens = tokenizeSqlSemantic(ddl, "mysql", { squareBracketsAsDelimiters: true, mysqlDoubleQuoteIsString: true, mysqlBackslashEscape: true });
+ const closing = schemaTokens.findIndex((token) => token.text === ")" && token.depth === 0);
+ result.columnNames = [];
+ let angleDepth = 0;
+ let nextColumn = false;
+ for (const token of schemaTokens.slice(0, closing)) {
+ if (token.text === "(" && token.depth === 0) {
+ nextColumn = true;
+ continue;
+ }
+ if (token.depth !== 1 || token.kind === "comment") continue;
+ if (token.text === "<") angleDepth++;
+ if (token.text === ">") angleDepth = Math.max(0, angleDepth - 1);
+ if (token.text === "," && angleDepth === 0) {
+ nextColumn = true;
+ continue;
+ }
+ if (nextColumn) {
+ if (["word", "quoted_identifier"].includes(token.kind) && !["index", "key", "primary", "unique", "constraint", "foreign", "check"].includes(token.normalized)) result.columnNames.push(unquoteSqlSemanticIdentifier(token));
+ nextColumn = false;
+ }
+ }
+ const tail = tokens.slice(start);
+ const upper = tail.map((token) => token.toUpperCase());
+ const engine = upper.indexOf("ENGINE");
+ if (engine < 0 || upper[engine + 1] !== "=" || upper[engine + 2] !== "OLAP") return result;
+ const key = upper.findIndex((token, i) => ["PRIMARY", "DUPLICATE", "UNIQUE", "AGGREGATE"].includes(token) && upper[i + 1] === "KEY");
+ if (key < 0) return result;
+ result.model = upper[key]!.toLowerCase() as StarRocksAlterOptions["model"];
+ const identifier = (token: string) => (token.startsWith("`") ? token.slice(1, -1).replaceAll("``", "`") : token);
+ const names = (values: string[]) => values.filter((token) => token.startsWith("`") || /^[a-zA-Z_]/.test(token)).map(identifier);
+ const endKey = tail.indexOf(")", key + 2);
+ if (tail[key + 2] !== "(" || endKey < 0) {
+ result.model = undefined;
+ return result;
+ }
+ result.keyColumns = names(tail.slice(key + 3, endKey));
+ const sort = upper.findIndex((token, index) => token === "ORDER" && upper[index + 1] === "BY");
+ const sortClose = sort >= 0 ? tail.indexOf(")", sort + 2) : -1;
+ result.sortColumns = sort >= 0 && tail[sort + 2] === "(" && sortClose >= 0 ? names(tail.slice(sort + 3, sortClose)) : [...result.keyColumns];
+ const partition = upper.indexOf("PARTITION", endKey);
+ const distribution = upper.indexOf("DISTRIBUTED", endKey);
+ const end = (from: number) => {
+ const boundaries = ["DISTRIBUTED", "ORDER", "PROPERTIES"].map((word) => upper.indexOf(word, from + 1)).filter((i) => i >= 0);
+ return boundaries.length ? Math.min(...boundaries) : tail.length;
+ };
+ if (partition >= 0) result.partitionColumns = names(tail.slice(partition + 2, end(partition)));
+ if (distribution >= 0) result.distributionColumns = names(tail.slice(distribution + 2, end(distribution)));
+ if (distribution >= 0) {
+ const method = upper[distribution + 2]?.toLowerCase();
+ if (method === "hash" || method === "random") {
+ const close = tail.indexOf(")", distribution + 3);
+ const columns = method === "hash" && tail[distribution + 3] === "(" && close >= 0 ? names(tail.slice(distribution + 4, close)) : [];
+ result.distributionColumns = columns;
+ const bucket = upper.indexOf("BUCKETS", distribution);
+ const count = bucket >= 0 ? Number(tail[bucket + 1]) : undefined;
+ result.distribution = { method, columns, buckets: count && Number.isSafeInteger(count) ? count : undefined };
+ }
+ }
+ if (partition >= 0) {
+ result.partitionKind = upper[partition + 2] === "RANGE" ? "range" : upper[partition + 2] === "LIST" ? "list" : "expression";
+ const semantic = tokenizeSqlSemantic(ddl, "mysql", { squareBracketsAsDelimiters: true, mysqlDoubleQuoteIsString: true, mysqlBackslashEscape: true });
+ const begin = semantic.findIndex((token) => token.kind === "word" && token.depth === 0 && token.normalized === "partition");
+ const stop = semantic.find((token, index) => index > begin && token.kind === "word" && token.depth === 0 && ["distributed", "order", "properties"].includes(token.normalized));
+ result.partitionClause = begin >= 0 ? ddl.slice(semantic[begin]!.span.start, stop?.span.start).trim() : undefined;
+ const bodyEnd = semantic.findIndex((token) => token.text === ")" && token.depth === 0);
+ const columnNames = new Set(
+ semantic
+ .slice(0, bodyEnd)
+ .filter((token, index) => token.depth === 1 && ["word", "quoted_identifier"].includes(token.kind) && ((semantic[index - 1]?.text === "(" && semantic[index - 1]?.depth === 0) || (semantic[index - 1]?.text === "," && semantic[index - 1]?.depth === 1)))
+ .map((token) => unquoteSqlSemanticIdentifier(token).toLowerCase()),
+ );
+ const clauseTokens = semantic.filter((token) => begin >= 0 && token.span.start >= semantic[begin]!.span.start && (!stop || token.span.start < stop.span.start));
+ // A plain partition key can move, but MODIFY on a function's source column
+ // may be rejected because StarRocks uses a hidden generated partition column.
+ const expressionColumns = new Set<string>();
+ for (let index = 2; index < clauseTokens.length; index++) {
+ const token = clauseTokens[index]!;
+ const open = clauseTokens[index + 1];
+ if (token.kind !== "word" || open?.text !== "(" || ["range", "list", "values"].includes(token.normalized)) continue;
+ for (let argument = index + 2; argument < clauseTokens.length; argument++) {
+ const reference = clauseTokens[argument]!;
+ if (reference.text === ")" && reference.depth === open.depth) break;
+ if (!["word", "quoted_identifier"].includes(reference.kind) || clauseTokens[argument + 1]?.text === "(") continue;
+ const name = unquoteSqlSemanticIdentifier(reference);
+ if (columnNames.has(name.toLowerCase())) expressionColumns.add(name);
+ }
+ }
+ result.partitionExpressionColumns = [...expressionColumns];
+ result.partitionColumns = [...new Set(clauseTokens.filter((token) => ["word", "quoted_identifier"].includes(token.kind) && columnNames.has(unquoteSqlSemanticIdentifier(token).toLowerCase())).map((token) => unquoteSqlSemanticIdentifier(token)))];
+ if (clauseTokens.some((token) => token.kind === "word" && ["date_trunc", "time_slice", "str2date", "from_unixtime"].includes(token.normalized))) result.partitionKind = "expression";
+ if (result.partitionKind !== "expression") {
+ const close = tail.indexOf(")", partition + 3);
+ result.partitionColumns = names(tail.slice(partition + 4, close));
+ }
+ }
+ const semantic = tokenizeSqlSemantic(ddl, "mysql", { squareBracketsAsDelimiters: true, mysqlDoubleQuoteIsString: true, mysqlBackslashEscape: true });
+ const property = semantic.findIndex((token) => ["string", "quoted_identifier"].includes(token.kind) && token.depth === 1 && token.text.slice(1, -1).toLowerCase() === "colocate_with");
+ result.colocated = property >= 0 && semantic[property + 1]?.text === "=" && (semantic[property + 2]?.text.length ?? 0) > 2;
+ const properties = semantic.findIndex((token) => token.kind === "word" && token.depth === 0 && token.normalized === "properties");
+ const bucketSize = semantic.findIndex((token, index) => index > properties && properties >= 0 && ["string", "quoted_identifier"].includes(token.kind) && token.depth === 1 && token.text.slice(1, -1).toLowerCase() === "bucket_size");
+ const bucketValue = semantic[bucketSize + 2];
+ result.automaticBucketScaling = bucketSize >= 0 && semantic[bucketSize + 1]?.text === "=" && Number(bucketValue?.kind === "number" ? bucketValue.text : bucketValue?.text.slice(1, -1)) > 0;
+ return result;
+}
+
+export function starRocksLayoutDraft(context: StarRocksAlterOptions): StarRocksLayoutDraft | undefined {
+ if (!context.distribution) return undefined;
+ return { method: context.distribution.method, columns: [...context.distribution.columns], bucketCount: context.distribution.buckets?.toString() ?? "", defaultOnly: false, partitions: [] };
+}
+
+export function starRocksLayoutChanges(draft: StarRocksLayoutDraft | undefined, context?: StarRocksAlterOptions): StarRocksLayoutChanges | undefined {
+ if (!draft || !context?.distribution) return undefined;
+ const count = draft.bucketCount.trim();
+ const distribution: StarRocksDistributionChange = { method: draft.method, columns: draft.method === "hash" ? [...draft.columns] : [], buckets: count ? (Number.isSafeInteger(Number(count)) && Number(count) > 0 && Number(count) <= 2147483647 ? Number(count) : 0) : undefined };
+ const original = context.distribution;
+ const changed = distribution.method !== original.method || JSON.stringify(distribution.columns) !== JSON.stringify(original.columns) || distribution.buckets !== original.buckets;
+ if (!changed && !draft.partitions.length) return undefined;
+ return { distribution: changed ? { ...distribution, defaultOnly: draft.defaultOnly } : undefined, partitions: draft.partitions };
+}
+
+export function starRocksColumnDefinitionLocked(column: EditableStructureColumn, context?: StarRocksAlterOptions): boolean {
+ if (!column.original) return false;
+ if (!context || !["primary", "duplicate"].includes(context.model ?? "")) return true;
+ const name = column.original.name.toLowerCase();
+ return [...context.partitionColumns, ...context.distributionColumns, ...(context.model === "primary" ? context.keyColumns : [])].some((key) => key.toLowerCase() === name) || /auto_increment|generated/i.test(column.original.extra ?? "");
+}
diff --git a/apps/desktop/src/lib/table/starrocksAlterStatus.ts b/apps/desktop/src/lib/table/starrocksAlterStatus.ts
new file mode 100644
index 0000000000..0cc734f8f0
--- /dev/null
+++ b/apps/desktop/src/lib/table/starrocksAlterStatus.ts
@@ -0,0 +1,46 @@
+import type { QueryResult } from "@/types/database";
+export const STARROCKS_ALTER_KINDS = ["COLUMN", "OPTIMIZE", "ROLLUP"] as const;
+export type StarRocksAlterKind = (typeof STARROCKS_ALTER_KINDS)[number];
+export interface StarRocksAlterJob {
+ kind: StarRocksAlterKind;
+ id: string;
+ state: string;
+ created: string;
+ finished: string;
+ message: string;
+ progress?: number;
+ sql?: string;
+}
+const terminalStates = new Set(["FINISHED", "CANCELLED"]);
+export function isStarRocksAlterJobActive(job: StarRocksAlterJob): boolean {
+ // Future/unknown states must not silently be treated as completion.
+ return !terminalStates.has(job.state);
+}
+export function starRocksAlterStatusSql(kind: StarRocksAlterKind, table: string): string {
+ if (!STARROCKS_ALTER_KINDS.includes(kind) || !table || /[\\\x00-\x1f]/.test(table)) throw new Error("Unsupported table name for ALTER status query");
+ return `SHOW ALTER TABLE ${kind} WHERE TableName = '${table.replaceAll("'", "''")}' ORDER BY CreateTime DESC LIMIT 5;`;
+}
+export function parseStarRocksAlterJobs(kind: StarRocksAlterKind, result: Pick<QueryResult, "columns" | "rows">): StarRocksAlterJob[] {
+ const names = result.columns.map((name) => name.toLowerCase());
+ if (!names.includes("state") || !names.includes("jobid")) throw new Error("Unexpected SHOW ALTER result columns");
+ return result.rows.map((row) => {
+ const get = (name: string) => String(row[names.indexOf(name.toLowerCase())] ?? "");
+ const progressText = get("Progress").trim();
+ const numeric = /^(\d+(?:\.\d+)?)%$/.exec(progressText);
+ const fraction = /^(\d+)\s*\/\s*(\d+)$/.exec(progressText);
+ const progress = numeric ? Number(numeric[1]) : fraction && Number(fraction[2]) > 0 ? (Number(fraction[1]) / Number(fraction[2])) * 100 : undefined;
+ return {
+ kind,
+ id: get("JobId"),
+ state: get("State").toUpperCase(),
+ created: get("CreateTime"),
+ finished: get("FinishTime") || get("FinishedTime"),
+ message: get("Msg"),
+ sql: get("Sql") || get("Statement") || get("OriginalStmt") || undefined,
+ progress: progress !== undefined && progress >= 0 && progress <= 100 ? Math.round(progress) : undefined,
+ };
+ });
+}
+export function recentStarRocksAlterJobs(jobs: StarRocksAlterJob[]): StarRocksAlterJob[] {
+ return [...jobs].sort((a, b) => b.created.localeCompare(a.created) || b.id.localeCompare(a.id, undefined, { numeric: true })).slice(0, 5);
+}
diff --git a/apps/desktop/src/lib/table/starrocksCapabilities.ts b/apps/desktop/src/lib/table/starrocksCapabilities.ts
new file mode 100644
index 0000000000..e614b914dd
--- /dev/null
+++ b/apps/desktop/src/lib/table/starrocksCapabilities.ts
@@ -0,0 +1,49 @@
+/** StarRocks product capabilities, based on current_version(), never MySQL VERSION(). */
+export interface StarRocksCapabilities {
+ alterDistribution: boolean;
+ defaultBuckets: boolean;
+ primaryKeySorting: boolean;
+ duplicateKeySorting: boolean;
+ defaultFunctions: boolean;
+ renameColumn: boolean;
+ tableComment: boolean;
+ versionKnown: boolean;
+ timePartitioning: boolean;
+ randomDistribution: boolean;
+ valuePartitioning: boolean;
+ mixedPartitioning: boolean;
+ dataTypes: string[];
+}
+
+export const STARROCKS_DATA_TYPES = ["boolean", "tinyint", "smallint", "int", "bigint", "largeint", "float", "double", "decimal", "date", "datetime", "char", "varchar", "string", "binary", "varbinary", "json", "array<int>", "map<int, int>", "struct<field int>", "bitmap", "hll", "percentile"];
+
+export function getStarRocksCapabilities(productVersion?: string): StarRocksCapabilities {
+ const match = productVersion?.trim().match(/^(?:StarRocks(?: version)?\s+)?v?(\d+)\.(\d+)(?:\.(\d+))?/i);
+ const version = match ? [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)] : undefined;
+ const versionKnown = !!version && version.join(".") !== "5.1.0";
+ const atLeast = (major: number, minor: number) => versionKnown && (version![0]! > major || (version![0] === major && version![1]! >= minor));
+ // Product introduction versions: JSON 2.2, BINARY 3.0, MAP/STRUCT 3.1, DECIMAL256 4.0.
+ const dataTypes = STARROCKS_DATA_TYPES.filter((type) => {
+ if (type === "binary" || type === "varbinary") return atLeast(3, 0);
+ if (type.startsWith("map<") || type.startsWith("struct<")) return atLeast(3, 1);
+ if (type === "json") return atLeast(2, 2);
+ return true;
+ });
+ if (atLeast(4, 0)) dataTypes.push("decimal256");
+ // 3.1 covers time partitions in both shared-data and shared-nothing deployments.
+ return {
+ alterDistribution: atLeast(3, 2),
+ defaultBuckets: atLeast(4, 1) || (atLeast(4, 0) && version![2]! >= 1) || (atLeast(3, 5) && version![2]! >= 8),
+ renameColumn: atLeast(3, 4) || (atLeast(3, 3) && version![2]! >= 2),
+ tableComment: atLeast(3, 1),
+ defaultFunctions: atLeast(3, 0),
+ primaryKeySorting: atLeast(3, 0),
+ duplicateKeySorting: atLeast(3, 3),
+ versionKnown,
+ dataTypes,
+ timePartitioning: atLeast(3, 1),
+ randomDistribution: atLeast(3, 1),
+ valuePartitioning: atLeast(3, 2) || (atLeast(3, 1) && version![2]! >= 1),
+ mixedPartitioning: atLeast(3, 4),
+ };
+}
diff --git a/apps/desktop/src/lib/table/starrocksLayoutCopy.ts b/apps/desktop/src/lib/table/starrocksLayoutCopy.ts
new file mode 100644
index 0000000000..c77bd885d8
--- /dev/null
+++ b/apps/desktop/src/lib/table/starrocksLayoutCopy.ts
@@ -0,0 +1,122 @@
+import { tokenizeSqlSemantic, unquoteSqlSemanticIdentifier } from "@/lib/sql/semantic/tokens";
+import type { SqlSemanticToken } from "@/lib/sql/semantic/types";
+import type { EditableStructureColumn } from "./tableStructureEditorSql";
+
+function tokens(sql: string) {
+ return tokenizeSqlSemantic(sql, "mysql", { mysqlBackslashEscape: true, mysqlDoubleQuoteIsString: true, squareBracketsAsDelimiters: true });
+}
+function body(sql: string) {
+ const all = tokens(sql);
+ if (all.some((token) => token.closed === false)) throw new Error("Unclosed source DDL token.");
+ if (all[0]?.normalized !== "create" || all[1]?.normalized !== "table") throw new Error("An internal CREATE TABLE statement is required.");
+ const open = all.find((token) => token.text === "(" && token.depth === 0);
+ const close = all.find((token) => open && token.span.start > open.span.start && token.text === ")" && token.depth === 0);
+ if (!open || !close) throw new Error("Could not read the table column definitions.");
+ const semicolon = all.find((token) => token.text === ";" && token.depth === 0);
+ if (semicolon && all.some((token) => token.kind !== "comment" && token.span.start > semicolon.span.start)) throw new Error("Only one CREATE TABLE is allowed.");
+ return { all, open, close, end: semicolon?.span.start ?? sql.length };
+}
+interface Clause {
+ name: string;
+ start: number;
+ end: number;
+ tokens: SqlSemanticToken[];
+}
+function clauses(sql: string): Clause[] {
+ const info = body(sql);
+ const starts = info.all.filter(
+ (token, index, all) =>
+ token.span.start > info.close.span.start &&
+ token.depth === 0 &&
+ token.kind === "word" &&
+ (["engine", "comment", "properties"].includes(token.normalized) || (["primary", "duplicate", "unique", "aggregate"].includes(token.normalized) && all[index + 1]?.normalized === "key") || (["partition", "distributed", "order"].includes(token.normalized) && all[index + 1]?.normalized === "by")),
+ );
+ return starts.map((token, index) => ({ name: token.normalized, start: token.span.start, end: starts[index + 1]?.span.start ?? info.end, tokens: info.all.filter((part) => part.span.start >= token.span.start && part.span.start < (starts[index + 1]?.span.start ?? info.end)) }));
+}
+const quote = (name: string) => "`" + name.replaceAll("`", "``") + "`";
+export function starRocksCopyTarget(database: string, name: string): string {
+ if (!name.trim() || name.includes("\0")) throw new Error("Enter a valid new table name.");
+ return `${quote(database)}.${quote(name.trim())}`;
+}
+
+/** Replace only layout clauses; retain column definitions, model, indexes, order and unknown properties verbatim. */
+export function buildStarRocksLayoutCopyDdl(source: string, generated: string, database: string, targetName: string, keepPartition: boolean): string {
+ const info = body(source);
+ const original = clauses(source);
+ const proposed = clauses(generated);
+ const engine = original.find((clause) => clause.name === "engine");
+ if (!engine || engine.tokens[2]?.normalized !== "olap") throw new Error("Only internal OLAP tables can be copied with this workflow.");
+ const distribution = proposed.find((clause) => clause.name === "distributed");
+ if (!distribution) throw new Error("No distribution clause was generated.");
+ const partition = proposed.find((clause) => clause.name === "partition");
+ const replacements: Array<{ start: number; end: number; text: string }> = [{ start: 0, end: info.open.span.start, text: `CREATE TABLE ${starRocksCopyTarget(database, targetName)} ` }];
+ const originalDistribution = original.find((clause) => clause.name === "distributed");
+ if (!originalDistribution) throw new Error("The original distribution metadata is unavailable.");
+ replacements.push({ start: originalDistribution.start, end: originalDistribution.end, text: generated.slice(distribution.start, distribution.end).trim() + "\n" });
+ if (!keepPartition) {
+ const existing = original.find((clause) => clause.name === "partition");
+ const text = partition ? generated.slice(partition.start, partition.end).trim() + "\n" : "";
+ replacements.push({ start: existing?.start ?? originalDistribution.start, end: existing?.end ?? originalDistribution.start, text });
+ }
+ const properties = original.find((clause) => clause.name === "properties");
+ if (properties) {
+ const open = properties.tokens.findIndex((token) => token.text === "(");
+ const close = properties.tokens.findIndex((token, index) => index > open && token.text === ")" && token.depth === 0);
+ if (open < 0 || close < 0) throw new Error("Could not preserve table properties safely.");
+ const parts: SqlSemanticToken[][] = [[]];
+ for (const token of properties.tokens.slice(open + 1, close)) {
+ if (token.text === "," && token.depth === 1) parts.push([]);
+ else parts[parts.length - 1]!.push(token);
+ }
+ const desired = distribution.tokens;
+ const isHash = desired.some((token) => token.kind === "word" && token.normalized === "hash");
+ const fixedBuckets = desired.some((token) => token.kind === "word" && token.normalized === "buckets");
+ const retained = parts
+ .filter((part) => {
+ const key = part[0]?.text.slice(1, -1).toLowerCase() ?? "";
+ // An old colocation contract or automatic scaling property conflicts with the new layout.
+ if (key === "colocate_with") return false;
+ if (key === "bucket_size" && (isHash || fixedBuckets)) return false;
+ if (!keepPartition && (key.startsWith("dynamic_partition.") || ["partition_live_number", "partition_ttl", "partition_retention_condition"].includes(key))) return false;
+ return true;
+ })
+ .map((part) => (part.length ? source.slice(part[0]!.span.start, part[part.length - 1]!.span.end) : ""));
+ replacements.push({ start: properties.start, end: properties.end, text: retained.filter(Boolean).length ? `PROPERTIES (\n${retained.filter(Boolean).join(",\n")}\n)` : "" });
+ }
+ let result = source;
+ // For an inserted partition and replaced distribution at the same offset,
+ // replace distribution first, then insert the partition in front of it.
+ for (const change of replacements.sort((a, b) => b.start - a.start || b.end - a.end)) {
+ result = result.slice(0, change.start) + change.text + result.slice(change.end);
+ }
+ return result.trim().replace(/;\s*$/, "") + ";";
+}
+
+export function starRocksCopyInsertColumns(sourceDdl: string, columns: EditableStructureColumn[]): string[] {
+ const info = body(sourceDdl);
+ const groups: SqlSemanticToken[][] = [[]];
+ for (const token of info.all.filter((token) => token.span.start >= info.open.span.end && token.span.start < info.close.span.start)) {
+ if (token.text === "," && token.depth === 1) groups.push([]);
+ else groups[groups.length - 1]!.push(token);
+ }
+ const generated = new Set(groups.filter((group) => group.some((token) => token.kind === "word" && token.depth === 1 && ["generated", "as"].includes(token.normalized))).map((group) => (group[0] ? unquoteSqlSemanticIdentifier(group[0]).toLowerCase() : "")));
+ return columns.filter((column) => !generated.has(column.name.toLowerCase()) && !/generated/i.test(column.original?.extra ?? "")).map((column) => column.name);
+}
+
+export interface StarRocksCopyPlan {
+ createSql: string;
+ insertSql?: string;
+ targetName: string;
+}
+export type StarRocksCopyStage = "creating" | "created" | "transferring" | "complete";
+/** Sequential execution never replays an INSERT or creates into an existing table. */
+export async function executeStarRocksCopyPlan(plan: StarRocksCopyPlan, execute: (sql: string) => Promise<unknown>, stage: (value: StarRocksCopyStage) => void): Promise<void> {
+ stage("creating");
+ await execute(plan.createSql);
+ stage("created");
+ if (plan.insertSql) {
+ stage("transferring");
+ await execute(plan.insertSql);
+ }
+ stage("complete");
+}
diff --git a/apps/desktop/src/lib/table/starrocksPhysicalOptions.ts b/apps/desktop/src/lib/table/starrocksPhysicalOptions.ts
new file mode 100644
index 0000000000..cced9d5d62
--- /dev/null
+++ b/apps/desktop/src/lib/table/starrocksPhysicalOptions.ts
@@ -0,0 +1,111 @@
+import type { EditableStructureColumn } from "@/lib/table/tableStructureEditorSql";
+
+export type StarRocksDistribution = "auto" | "hash" | "random";
+export type StarRocksTimeGranularity = "year" | "month" | "day" | "hour";
+export type StarRocksPartitionKind = "none" | "time" | "values" | "range" | "list";
+export interface StarRocksRangeDraft {
+ id: string;
+ name: string;
+ lower: Record<string, string>;
+ upper: Record<string, string>;
+}
+export interface StarRocksListDraft {
+ id: string;
+ name: string;
+ values: Array<{ id: string; fields: Record<string, string> }>;
+}
+export interface StarRocksPhysicalOptionsDraft {
+ partitionKind: StarRocksPartitionKind;
+ partitionColumnIds: string[];
+ rangePartitions: StarRocksRangeDraft[];
+ listPartitions: StarRocksListDraft[];
+ timeInterval: string;
+ timePartitionEnabled: boolean;
+ partitionColumnId: string;
+ granularity: StarRocksTimeGranularity;
+ distribution: StarRocksDistribution;
+ distributionColumnIds: string[];
+ sortColumnIds: string[];
+ bucketCount: string;
+}
+export interface CreateTableDialectOptions {
+ starrocks?: {
+ timePartition?: { columnId: string; granularity: StarRocksTimeGranularity; interval?: number; additionalColumnIds: string[] };
+ partition?: { kind: "values"; columnIds: string[] } | { kind: "range"; columnIds: string[]; partitions: Array<{ name: string; lower: string[]; upper: string[] }> } | { kind: "list"; columnIds: string[]; partitions: Array<{ name: string; values: string[][] }> };
+ distribution: StarRocksDistribution;
+ distributionColumnIds: string[];
+ sortColumnIds: string[];
+ bucketCount?: number;
+ };
+}
+
+export function emptyStarRocksPhysicalOptions(): StarRocksPhysicalOptionsDraft {
+ return { partitionKind: "none", partitionColumnIds: [], rangePartitions: [], listPartitions: [], timeInterval: "", timePartitionEnabled: false, partitionColumnId: "", granularity: "month", distribution: "auto", distributionColumnIds: [], sortColumnIds: [], bucketCount: "" };
+}
+
+export function restoreStarRocksPhysicalOptions(saved?: StarRocksPhysicalOptionsDraft): StarRocksPhysicalOptionsDraft {
+ return {
+ ...emptyStarRocksPhysicalOptions(),
+ ...saved,
+ partitionKind: saved?.partitionKind === "none" && saved.timePartitionEnabled ? "time" : (saved?.partitionKind ?? (saved?.timePartitionEnabled ? "time" : "none")),
+ partitionColumnIds: [...(saved?.partitionColumnIds ?? [])],
+ distributionColumnIds: [...(saved?.distributionColumnIds ?? [])],
+ sortColumnIds: [...(saved?.sortColumnIds ?? [])],
+ rangePartitions: (saved?.rangePartitions ?? []).map((row) => ({ ...row, lower: { ...row.lower }, upper: { ...row.upper } })),
+ listPartitions: (saved?.listPartitions ?? []).map((row) => ({ ...row, values: row.values.map((tuple) => ({ ...tuple, fields: { ...tuple.fields } })) })),
+ };
+}
+
+export function hasStarRocksPhysicalOptions(draft: StarRocksPhysicalOptionsDraft): boolean {
+ return draft.sortColumnIds.length > 0 || draft.partitionKind !== "none" || draft.timePartitionEnabled || draft.distribution !== "auto" || !!draft.bucketCount.trim();
+}
+
+export function isStarRocksTimeColumn(column: Pick<EditableStructureColumn, "dataType">): boolean {
+ return /^(date|datetime)$/i.test(column.dataType.trim());
+}
+
+export function isStarRocksHashColumn(column: Pick<EditableStructureColumn, "dataType">): boolean {
+ return /^(tinyint|smallint|int|integer|bigint|largeint|date|datetime|char|varchar|string)$/i.test(column.dataType.split("(")[0]!.trim());
+}
+
+export function isStarRocksPartitionColumn(column: Pick<EditableStructureColumn, "dataType">, range = false): boolean {
+ const base = column.dataType.split("(")[0]!.trim();
+ return range ? /^(tinyint|smallint|int|integer|bigint|largeint|date|datetime)$/i.test(base) : isStarRocksHashColumn(column) || /^boolean$/i.test(base);
+}
+
+export function buildStarRocksDialectOptions(draft: StarRocksPhysicalOptionsDraft): CreateTableDialectOptions {
+ const rawCount = draft.bucketCount.trim();
+ const count = Number(rawCount);
+ const kind = draft.partitionKind === "none" && draft.timePartitionEnabled ? "time" : draft.partitionKind;
+ const columnIds = [...draft.partitionColumnIds];
+ const values = (fields: Record<string, string>) => columnIds.map((id) => fields[id] ?? "");
+ let partition: NonNullable<CreateTableDialectOptions["starrocks"]>["partition"];
+ if (kind === "values") partition = { kind, columnIds };
+ if (kind === "range") partition = { kind, columnIds, partitions: draft.rangePartitions.map((row) => ({ name: row.name, lower: values(row.lower), upper: values(row.upper) })) };
+ if (kind === "list") partition = { kind, columnIds, partitions: draft.listPartitions.map((row) => ({ name: row.name, values: row.values.map((tuple) => values(tuple.fields)) })) };
+ const rawInterval = draft.timeInterval.trim();
+ const interval = Number(rawInterval);
+ return {
+ starrocks: {
+ partition,
+ timePartition:
+ kind === "time"
+ ? {
+ columnId: draft.partitionColumnId,
+ granularity: draft.granularity,
+ additionalColumnIds: columnIds,
+ interval: rawInterval ? (Number.isSafeInteger(interval) && interval > 0 && interval <= 2147483647 ? interval : 0) : undefined,
+ }
+ : undefined,
+ distribution: draft.distribution,
+ // Keep stale IDs so deletion/type changes cannot silently change the table layout.
+ distributionColumnIds: draft.distribution === "hash" ? [...draft.distributionColumnIds] : [],
+ sortColumnIds: [...draft.sortColumnIds],
+ bucketCount: rawCount ? (Number.isSafeInteger(count) && count > 0 && count <= 2147483647 ? count : 0) : undefined,
+ },
+ };
+}
+
+export function isStarRocksSortColumn(column: Pick<EditableStructureColumn, "dataType">, primaryKeyTable: boolean): boolean {
+ return !primaryKeyTable || /^(boolean|tinyint|smallint|int|integer|bigint|largeint|varchar|string|date|datetime)$/i.test(column.dataType.split("(")[0]!.trim());
+}
diff --git a/apps/desktop/src/lib/table/tableStructureCapabilities.ts b/apps/desktop/src/lib/table/tableStructureCapabilities.ts
index f4bcfd5d6d..005bb3e572 100644
--- a/apps/desktop/src/lib/table/tableStructureCapabilities.ts
+++ b/apps/desktop/src/lib/table/tableStructureCapabilities.ts
@@ -1,3 +1,4 @@
+import { getStarRocksCapabilities } from "./starrocksCapabilities";
import type { DatabaseType } from "@/types/database";
import type { EditableStructureIndex } from "@/lib/table/tableStructureEditorSql";
@@ -88,6 +89,18 @@ const mysqlCapabilities = capabilities({
foreignKey: true,
});
+const starrocksCapabilities = capabilities({
+ dialect: "mysql",
+ createTable: true,
+ addColumn: true,
+ dropColumn: true,
+ alterExistingColumn: true,
+ alterType: true,
+ alterNullability: true,
+ alterDefault: false,
+ comment: true,
+});
+
const gbaseCapabilities = capabilities({
dialect: "mysql",
createTable: true,
@@ -359,7 +372,7 @@ const firebirdCapabilities = capabilities({
const capabilityByType: Partial<Record<DatabaseType, TableStructureCapabilities>> = {
mysql: mysqlCapabilities,
doris: mysqlCapabilities,
- starrocks: mysqlCapabilities,
+ starrocks: starrocksCapabilities,
goldendb: mysqlCapabilities,
sundb: mysqlCapabilities,
oscar: damengCapabilities,
@@ -407,7 +420,11 @@ function postgresMajorVersion(productVersion?: string): number | undefined {
return Number.isFinite(majorVersion) ? majorVersion : undefined;
}
-export function getTableStructureCapabilities(dbType?: DatabaseType, connectionDbType?: DatabaseType, productVersion?: string): TableStructureCapabilities {
+export function getTableStructureCapabilities(dbType?: DatabaseType, connectionDbType?: DatabaseType, productVersion?: string, starRocksModel?: string): TableStructureCapabilities {
+ if (dbType === "starrocks") {
+ const product = getStarRocksCapabilities(productVersion);
+ return { ...starrocksCapabilities, renameColumn: product.renameColumn, reorderColumn: product.versionKnown && starRocksModel === "duplicate" };
+ }
if (dbType === "sqlite" && connectionDbType === "sqlite") return nativeSqliteCapabilities;
if (dbType === "postgres") {
const majorVersion = postgresMajorVersion(productVersion);
@@ -431,8 +448,9 @@ export function supportsLocalTableColumnReorder(dbType?: DatabaseType, connectio
return canEditTableStructure(dbType) && !caps.reorderColumn;
}
-export function isPhysicalTableColumnOrderChange(dbType: DatabaseType | undefined, connectionDbType: DatabaseType | undefined, originalPosition: number | undefined, currentPosition: number): boolean {
- return getTableStructureCapabilities(dbType, connectionDbType).reorderColumn && originalPosition !== currentPosition;
+export function isPhysicalTableColumnOrderChange(dbType: DatabaseType | undefined, connectionDbType: DatabaseType | undefined, originalPosition: number | undefined, currentPosition: number, starRocksModel?: string): boolean {
+ const reorderColumn = dbType === "starrocks" ? starRocksModel === "duplicate" : getTableStructureCapabilities(dbType, connectionDbType).reorderColumn;
+ return reorderColumn && originalPosition !== currentPosition;
}
export function hasLocalTableColumnOrderChange(columns: readonly { originalPosition?: number; original?: unknown; markedForDrop?: boolean }[]): boolean {
diff --git a/apps/desktop/src/lib/table/tableStructureEditorState.ts b/apps/desktop/src/lib/table/tableStructureEditorState.ts
index a81cb8f42d..ad3b54ff77 100644
--- a/apps/desktop/src/lib/table/tableStructureEditorState.ts
+++ b/apps/desktop/src/lib/table/tableStructureEditorState.ts
@@ -1,5 +1,6 @@
import type { ColumnInfo, DatabaseConnectionInfo, DatabaseType, ForeignKeyInfo, IndexInfo, TriggerInfo } from "@/types/database.ts";
import type { ColumnExtra, EditableStructureColumn, EditableStructureForeignKey, EditableStructureIndex, EditableStructureTrigger } from "@/lib/table/tableStructureEditorSql.ts";
+import { getStarRocksCapabilities, STARROCKS_DATA_TYPES } from "@/lib/table/starrocksCapabilities";
export interface CopySourceColumnDetails {
/** Column default as shown in the copy-fields dialog, or null when there is none. */
@@ -165,6 +166,8 @@ function withPostgresArrayTypes(types: readonly string[]): string[] {
}
export const DATA_TYPE_OPTIONS: Record<string, string[]> = {
+ // Use complete nested declarations so selecting a complex type produces valid SQL.
+ starrocks: STARROCKS_DATA_TYPES,
mysql: [
"tinyint",
"tinyint unsigned",
@@ -576,7 +579,6 @@ export const DATA_TYPE_OPTIONS: Record<string, string[]> = {
const DATA_TYPE_OPTION_ALIASES: Partial<Record<DatabaseType, string>> = {
doris: "mysql",
- starrocks: "mysql",
goldendb: "mysql",
sundb: "mysql",
oscar: "oracle",
@@ -600,9 +602,22 @@ const DATA_TYPE_OPTION_ALIASES: Partial<Record<DatabaseType, string>> = {
access: "h2",
};
-export function getDataTypeOptions(dbType: DatabaseType | undefined): string[] {
+export function getDataTypeOptions(dbType: DatabaseType | undefined, dynamicOptions: readonly string[] = [], productVersion?: string): string[] {
const key = dbType ? (DATA_TYPE_OPTION_ALIASES[dbType] ?? dbType) : "";
- return DATA_TYPE_OPTIONS[key] ?? [];
+ const fallback = DATA_TYPE_OPTIONS[key] ?? [];
+ // MySQL-protocol/JDBC metadata may advertise MySQL types for StarRocks.
+ // Keep its editor choices native instead of reintroducing UNSIGNED/TIMESTAMP.
+ if (dbType === "starrocks") return getStarRocksCapabilities(productVersion).dataTypes;
+ if (dynamicOptions.length === 0) return fallback;
+ const seen = new Set<string>();
+ return [...dynamicOptions, ...fallback]
+ .map((type) => type.trim())
+ .filter((type) => {
+ const normalized = type.toLowerCase();
+ if (!type || seen.has(normalized)) return false;
+ seen.add(normalized);
+ return true;
+ });
}
export function isMysqlEnumDataType(dbType: DatabaseType | undefined, dataType: string): boolean {
@@ -1499,6 +1514,10 @@ function splitPostgresTemporalDataType(raw: string): { baseType: string; params:
}
function splitDataTypeForDatabase(dbType: DatabaseType | undefined, raw: string): { baseType: string; params: string } {
+ // Parentheses inside nested types belong to the element/field, not the column.
+ if (dbType === "starrocks" && /^(array|map|struct)\s*</i.test(raw.trim())) {
+ return { baseType: raw.trim(), params: "" };
+ }
if (dbType === "duckdb") {
const parsed = splitDuckdbScalarDataType(raw);
if (parsed) return parsed;
@@ -1762,6 +1781,7 @@ export interface DataTypeDefaultOptions {
export function getDefaultLengthForType(_dbType: DatabaseType | undefined, baseType: string, options: DataTypeDefaultOptions = {}): string {
const key = baseType.trim().toLowerCase();
+ if (_dbType === "starrocks" && isDataTypeLengthDisabled(_dbType, baseType)) return "";
if ((_dbType === "oracle" || _dbType === "oceanbase-oracle") && key === "float") return "";
if (_dbType === "duckdb" && (key === "float" || isDataTypeLengthDisabled(_dbType, baseType))) return "";
if (_dbType === "mysql" && options.omitMysqlDeprecatedDefaults && isMysqlDeprecatedDefaultParameterType(key)) return "";
@@ -1841,6 +1861,9 @@ function isMysqlDeprecatedDefaultParameterType(baseType: string): boolean {
export function isDataTypeLengthDisabled(_dbType: DatabaseType | undefined, baseType: string): boolean {
const key = baseType.trim().toLowerCase();
+ if (_dbType === "starrocks") {
+ return !["tinyint", "smallint", "int", "integer", "bigint", "largeint", "char", "varchar", "binary", "varbinary", "decimal", "decimal32", "decimal64", "decimal128", "decimal256"].includes(key);
+ }
if (_dbType === "duckdb") {
return DUCKDB_TYPE_LENGTH_DISABLES.has(key.replace(/\s+/g, " "));
} else if (_dbType === "questdb") {
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index c1691b9e5d..02e4c2aadc 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -1889,6 +1889,9 @@ export interface TableStructureEditorDraft {
mysqlTableEngine?: string;
originalMysqlTableEngine?: string;
physicalOptions?: import("@/lib/table/tablePhysicalOptions").TablePhysicalOptionsDraft;
+ starrocksLayoutDraft?: import("@/lib/table/starrocksAlterOptions").StarRocksLayoutDraft;
+ starrocksSortColumns?: string[];
+ starrocksPhysicalOptions?: import("@/lib/table/starrocksPhysicalOptions").StarRocksPhysicalOptionsDraft;
tableOwner?: string;
originalTableOwner?: string;
columns: import("@/lib/table/tableStructureEditorSql").EditableStructureColumn[];
diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rs
index 978d2ef305..b94cd84b05 100644
--- a/crates/dbx-core/src/data/transfer.rs
+++ b/crates/dbx-core/src/data/transfer.rs
@@ -14948,10 +14948,14 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;
#[test]
fn deferred_mysql_foreign_keys_follow_target_ddl_capability() {
- for target in [DatabaseType::Mysql, DatabaseType::StarRocks, DatabaseType::Goldendb, DatabaseType::Sundb] {
+ for target in [DatabaseType::Mysql, DatabaseType::Goldendb, DatabaseType::Sundb] {
assert!(supports_deferred_mysql_foreign_keys(&target), "{target:?}");
}
- assert!(!supports_deferred_mysql_foreign_keys(&DatabaseType::Doris));
+ // StarRocks uses foreign_key_constraints table properties, not MySQL-style
+ // ADD CONSTRAINT ... FOREIGN KEY statements generated by this transfer path.
+ for target in [DatabaseType::StarRocks, DatabaseType::Doris] {
+ assert!(!supports_deferred_mysql_foreign_keys(&target), "{target:?}");
+ }
}
#[test]
diff --git a/crates/dbx-driver-mysql/src/mysql.rs b/crates/dbx-driver-mysql/src/mysql.rs
index 3d22942132..5e27585f33 100644
--- a/crates/dbx-driver-mysql/src/mysql.rs
+++ b/crates/dbx-driver-mysql/src/mysql.rs
@@ -689,17 +689,34 @@ pub async fn database_connection_info(
let product_name = nonblank(product_name.into()).unwrap_or_else(|| "MySQL".to_string());
let mut conn = get_conn_with_health_check(pool).await?;
+ let server_comment = query_first_nonblank_string(&mut conn, "SELECT @@version_comment").await;
+ let version_sql = database_product_version_query(&product_name, server_comment.as_deref());
+ let mut product_version = query_first_nonblank_string(&mut conn, version_sql).await;
+ if product_version.is_none() && version_sql == "SELECT current_version()" {
+ // VERSION() reports MySQL compatibility (often 5.1.0), not StarRocks.
+ product_version = server_comment.clone();
+ }
Ok(DatabaseConnectionInfo {
product_name: Some(product_name),
- product_version: query_first_nonblank_string(&mut conn, "SELECT VERSION()").await,
+ product_version,
current_database: query_first_nonblank_string(&mut conn, "SELECT COALESCE(DATABASE(), '')").await,
- server_comment: query_first_nonblank_string(&mut conn, "SELECT @@version_comment").await,
+ server_comment,
server_charset: query_first_nonblank_string(&mut conn, "SELECT @@character_set_server").await,
server_collation: query_first_nonblank_string(&mut conn, "SELECT @@collation_server").await,
..DatabaseConnectionInfo::default()
})
}
+fn database_product_version_query(product_name: &str, server_comment: Option<&str>) -> &'static str {
+ if product_name.to_ascii_lowercase().contains("starrocks")
+ || server_comment.is_some_and(|comment| comment.to_ascii_lowercase().contains("starrocks"))
+ {
+ "SELECT current_version()"
+ } else {
+ "SELECT VERSION()"
+ }
+}
+
pub fn protocol_product_name(config: &ConnectionConfig) -> String {
config.driver_label.as_deref().map(str::trim).filter(|value| !value.is_empty()).map(str::to_string).unwrap_or_else(
|| match config.db_type {
@@ -7281,6 +7298,16 @@ pub async fn list_triggers(pool: &MySqlPool, database: &str, table: &str) -> Res
#[cfg(test)]
mod tests {
+ #[test]
+ fn product_version_uses_starrocks_function_only_for_starrocks() {
+ assert_eq!(super::database_product_version_query("StarRocks", None), "SELECT current_version()");
+ assert_eq!(
+ super::database_product_version_query("Custom label", Some("StarRocks version 3.5.0")),
+ "SELECT current_version()"
+ );
+ assert_eq!(super::database_product_version_query("MySQL", Some("MySQL Community Server")), "SELECT VERSION()");
+ }
+
use super::*;
use mysql_async::{consts::ColumnType, Column, Value};
use mysql_common::row::new_row;
diff --git a/crates/dbx-sql-data/src/data_grid_sql.rs b/crates/dbx-sql-data/src/data_grid_sql.rs
index f82fa16c70..b697b0b396 100644
--- a/crates/dbx-sql-data/src/data_grid_sql.rs
+++ b/crates/dbx-sql-data/src/data_grid_sql.rs
@@ -1683,6 +1683,9 @@ fn build_data_grid_save_statements(
return build_iotdb_data_grid_save_statements(options);
}
+ let starrocks = options.database_type == Some(DatabaseType::StarRocks)
+ || (options.database_type == Some(DatabaseType::Mysql)
+ && driver_profile.is_some_and(|profile| profile.eq_ignore_ascii_case("starrocks")));
let save_columns = effective_columns(options);
let column_info = options.table_meta.columns.as_deref().unwrap_or(&[]);
let schema = crate::sql_dialect::table_data_schema(
@@ -1828,7 +1831,7 @@ fn build_data_grid_save_statements(
false,
)
})
- .filter(|(_, value)| !value.is_null())
+ .filter(|(_, value)| starrocks || !value.is_null())
.collect();
if insert_pairs.is_empty() {
if options.database_type == Some(DatabaseType::Mysql) {
@@ -1845,6 +1848,33 @@ fn build_data_grid_save_statements(
let values = insert_pairs
.iter()
.map(|(column, value)| {
+ // A new-row NULL means unset. Keep StarRocks defaulted keys in the
+ // target list, and still emit an INSERT when every value is unset.
+ if starrocks && value.is_null() {
+ let info = column_info_for(column_info, column);
+ let default = info.and_then(|info| info.column_default.as_deref());
+ if let Some(default) = default {
+ // StarRocks can reject UUID defaults through VALUES(DEFAULT).
+ // Only emit known functions, never arbitrary metadata as SQL.
+ let normalized = default
+ .chars()
+ .filter(|ch| !ch.is_ascii_whitespace())
+ .collect::<String>()
+ .to_ascii_lowercase();
+ let mut expression = normalized.as_str();
+ while let Some(inner) = expression.strip_prefix('(').and_then(|value| value.strip_suffix(')')) {
+ expression = inner;
+ }
+ match expression {
+ "uuid()" => return "uuid()".to_string(),
+ "uuid_numeric()" => return "uuid_numeric()".to_string(),
+ _ => {}
+ }
+ } else if info.is_some_and(|info| info.is_nullable) {
+ return "NULL".to_string();
+ }
+ return "DEFAULT".to_string();
+ }
format_grid_save_sql_literal(
value,
options.database_type,
@@ -1903,7 +1933,9 @@ fn build_data_grid_rollback_statements(
let mut statements = Vec::new();
for row in &options.new_rows {
- let where_clause = if options.database_type == Some(DatabaseType::Mysql) {
+ // Server-generated keys are unknown; never invent an undo predicate from
+ // the unset draft values. Reuse the existing key-based rollback guard.
+ let where_clause = if matches!(options.database_type, Some(DatabaseType::Mysql | DatabaseType::StarRocks)) {
build_mysql_insert_rollback_where(options, &save_columns, row, column_info)
} else {
let where_clause = build_save_row_where(
@@ -4583,6 +4615,81 @@ mod tests {
}
}
+ #[test]
+ fn starrocks_insert_uses_server_defaults_for_unset_uuid_columns() {
+ for (database_type, profile) in [(DatabaseType::StarRocks, None), (DatabaseType::Mysql, Some("starrocks"))] {
+ for default in ["uuid()", "(uuid())", " (( UUID ( ) )) ", "uuid_numeric()", "(UUID_NUMERIC())"] {
+ let mut options = mysql_people_save_options(0);
+ options.database_type = Some(database_type);
+ let id = &mut options.table_meta.columns.as_mut().unwrap()[0];
+ id.data_type =
+ if default.to_ascii_lowercase().contains("numeric") { "largeint" } else { "varchar(36)" }.into();
+ id.column_default = Some(default.into());
+ options.new_rows = vec![vec![Value::Null, json!("new")], vec![Value::Null, Value::Null]];
+ let function =
+ if default.to_ascii_lowercase().contains("numeric") { "uuid_numeric()" } else { "uuid()" };
+ let result = prepare_data_grid_save_for_driver_profile(options, profile);
+ assert_eq!(result.validation_error, None);
+ assert_eq!(result.statements.len(), 2);
+ assert!(result.rollback_statements.is_empty());
+ assert!(
+ result.statements[0].contains(&format!("(`id`, `status`) VALUES ({function}, 'new')")),
+ "{:?}",
+ result.statements
+ );
+ assert!(
+ result.statements[1].contains(&format!("(`id`, `status`) VALUES ({function}, NULL)")),
+ "{:?}",
+ result.statements
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn starrocks_insert_uuid_key_with_timestamp_default() {
+ let mut options = mysql_people_save_options(0);
+ options.database_type = Some(DatabaseType::StarRocks);
+ options.table_meta.schema = None;
+ options.table_meta.table_name = "test2".into();
+ options.columns = vec!["id".into(), "name".into(), "create_at".into()];
+ let mut id = column("id", "varchar(255)", false, None);
+ id.column_default = Some("(uuid())".into());
+ let mut timestamp = column("create_at", "datetime", true, None);
+ timestamp.column_default = Some("CURRENT_TIMESTAMP".into());
+ options.table_meta.columns = Some(vec![id, column("name", "varchar(255)", true, None), timestamp]);
+ options.new_rows = vec![vec![Value::Null, json!("11"), Value::Null]];
+ let result = prepare_data_grid_save(options.clone());
+ assert_eq!(result.validation_error, None);
+ assert_eq!(
+ result.statements,
+ vec!["INSERT INTO `test2` (`id`, `name`, `create_at`) VALUES (uuid(), '11', DEFAULT);"]
+ );
+ assert!(result.rollback_statements.is_empty());
+
+ for default in ["'uuid()'", "'fixed-id'", "uuid(); SELECT 1"] {
+ options.table_meta.columns.as_mut().unwrap()[0].column_default = Some(default.into());
+ let result = prepare_data_grid_save(options.clone());
+ assert_eq!(result.validation_error, None);
+ assert!(result.statements[0].contains("VALUES (DEFAULT, '11', DEFAULT)"));
+ }
+ }
+
+ #[test]
+ fn starrocks_insert_preserves_explicit_uuid_values_and_mysql_omission() {
+ let mut options = mysql_people_save_options(0);
+ options.database_type = Some(DatabaseType::StarRocks);
+ options.table_meta.columns.as_mut().unwrap()[0].column_default = Some("uuid()".into());
+ options.new_rows = vec![vec![json!("manual-id"), json!("new")]];
+ let result = prepare_data_grid_save(options.clone());
+ assert_eq!(result.validation_error, None);
+ assert!(result.statements[0].contains("VALUES ('manual-id', 'new')"));
+ options.database_type = Some(DatabaseType::Mysql);
+ options.new_rows = vec![vec![Value::Null, json!("new")]];
+ let result = prepare_data_grid_save(options);
+ assert!(result.statements[0].contains("(`status`) VALUES ('new')"));
+ }
+
/// A MySQL grid tab keeps its namespace in `table_meta.database` (not
/// `schema`), so the save statements are the one generated-SQL surface that
/// never picked up `生成 SQL 时包含数据库名`. It must match the data-table
diff --git a/crates/dbx-sql-schema/src/table_structure_sql.rs b/crates/dbx-sql-schema/src/table_structure_sql.rs
index f528fdfe31..fabbc260d7 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql.rs
@@ -1,7 +1,11 @@
+mod alter_dialect;
+pub use alter_dialect::StarRocksAlterOptions;
mod column_alter;
mod column_format;
mod columns;
mod comments;
+mod create_dialect;
+mod create_options;
mod create_table;
mod dialect;
mod foreign_keys;
@@ -9,6 +13,8 @@ mod indexes;
mod mysql_engine;
mod owner;
mod partitions;
+mod starrocks_layout;
+mod starrocks_partition;
mod transwarp;
mod triggers;
mod types;
@@ -19,7 +25,10 @@ mod validation;
mod tests;
pub use column_alter::build_single_column_alter_sql;
-pub use create_table::build_create_table_sql;
+pub use create_options::*;
+pub use create_table::{
+ build_create_table_sql, build_create_table_sql_for_version, build_create_table_sql_with_dialect_options,
+};
pub use owner::build_table_owner_change_sql;
pub use partitions::{build_create_partitioned_table_sql, build_table_partition_operation_sql};
pub use types::*;
@@ -42,7 +51,18 @@ use triggers::build_trigger_sql;
use validation::validate_concurrent_index_scope;
pub use validation::validate_draft;
-pub fn build_table_structure_change_sql(mut options: TableStructureSqlOptions) -> TableStructureSqlResult {
+pub fn build_table_structure_change_sql(options: TableStructureSqlOptions) -> TableStructureSqlResult {
+ build_table_structure_change_sql_with_context(options, None)
+}
+
+pub fn build_table_structure_change_sql_with_context(
+ mut options: TableStructureSqlOptions,
+ starrocks: Option<StarRocksAlterOptions>,
+) -> TableStructureSqlResult {
+ if alter_dialect::is_starrocks(&options) {
+ return alter_dialect::build(&options, starrocks);
+ }
+
let mysql_engine_errors = validate_mysql_engine(&options);
if !mysql_engine_errors.is_empty() {
return TableStructureSqlResult { statements: Vec::new(), warnings: mysql_engine_errors };
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/alter_dialect.rs b/crates/dbx-sql-schema/src/table_structure_sql/alter_dialect.rs
new file mode 100644
index 0000000000..8b4128cd6d
--- /dev/null
+++ b/crates/dbx-sql-schema/src/table_structure_sql/alter_dialect.rs
@@ -0,0 +1,460 @@
+//! Product-specific ALTER strategies, independent of wire-compatible CREATE dialects.
+use super::{
+ dialect::StructureDialect,
+ types::*,
+ util::{
+ clean, format_default_for_sql, normalize_default, original_comment, original_default, qualified_table,
+ quote_ident, quote_string,
+ },
+};
+use crate::models::connection::DatabaseType;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StarRocksAlterOptions {
+ pub server_version: Option<String>,
+ pub model: Option<String>,
+ #[serde(default)]
+ pub column_names: Vec<String>,
+ #[serde(default)]
+ pub reorder_columns: bool,
+ #[serde(default)]
+ pub position_column_order: bool,
+ pub sort_columns: Option<Vec<String>>,
+ pub sort_column_names: Option<Vec<String>>,
+ #[serde(default)]
+ pub key_columns: Vec<String>,
+ #[serde(default)]
+ pub partition_columns: Vec<String>,
+ #[serde(default)]
+ pub partition_expression_columns: Vec<String>,
+ #[serde(default)]
+ pub distribution_columns: Vec<String>,
+ pub distribution: Option<super::starrocks_layout::StarRocksDistributionChange>,
+ pub partition_kind: Option<String>,
+ #[serde(default)]
+ pub colocated: bool,
+ #[serde(default)]
+ pub automatic_bucket_scaling: bool,
+ pub layout: Option<super::starrocks_layout::StarRocksLayoutChanges>,
+}
+
+pub(super) fn is_starrocks(options: &TableStructureSqlOptions) -> bool {
+ !options.is_gaussdb_m_mode
+ && (options.database_type == Some(DatabaseType::StarRocks)
+ || (options.database_type == Some(DatabaseType::Mysql)
+ && options.driver_profile.as_deref().is_some_and(|value| value.eq_ignore_ascii_case("starrocks"))))
+}
+
+trait AlterTableDialect {
+ fn build(&self, options: &TableStructureSqlOptions) -> TableStructureSqlResult;
+}
+
+pub(super) fn build(
+ options: &TableStructureSqlOptions,
+ context: Option<StarRocksAlterOptions>,
+) -> TableStructureSqlResult {
+ StarRocksAlter(context.unwrap_or_default()).build(options)
+}
+
+struct StarRocksAlter(StarRocksAlterOptions);
+impl AlterTableDialect for StarRocksAlter {
+ fn build(&self, options: &TableStructureSqlOptions) -> TableStructureSqlResult {
+ let mut warnings = super::validation::validate_draft(options);
+ let mut statements = Vec::new();
+ let mut changes = Vec::new();
+ let table = qualified_table(StructureDialect::Mysql, options.schema.as_deref(), &options.table_name);
+ let quote = |name: &str| quote_ident(StructureDialect::Mysql, name);
+ let version = super::create_dialect::parse_version(self.0.server_version.as_deref());
+ let at_least = |minimum| version.is_some_and(|current| current >= minimum);
+ let supported_model = matches!(self.0.model.as_deref(), Some("primary" | "duplicate"));
+ let contains = |names: &[String], name: &str| names.iter().any(|value| value.eq_ignore_ascii_case(name));
+ let locked = |column: &EditableStructureColumn| {
+ column.original.as_ref().is_some_and(|original| {
+ !supported_model
+ || contains(&self.0.partition_columns, &original.name)
+ || contains(&self.0.distribution_columns, &original.name)
+ || (self.0.model.as_deref() == Some("primary") && contains(&self.0.key_columns, &original.name))
+ || original.extra.as_deref().is_some_and(|extra| {
+ let lower = extra.to_ascii_lowercase();
+ lower.contains("auto_increment") || lower.contains("generated")
+ })
+ })
+ };
+ // Unchanged catalog indexes/constraints may be present, but cannot be edited through this strategy.
+ for index in &options.indexes {
+ if index.original.is_none() || index.marked_for_drop || super::indexes::has_existing_index_change(index) {
+ warnings.push("StarRocks index definitions cannot be changed from this editor.".into());
+ }
+ }
+ let foreign_sql = super::foreign_keys::build_foreign_key_sql(options, &mut warnings);
+ let trigger_sql = super::triggers::build_trigger_sql(options, &mut warnings);
+ if !foreign_sql.is_empty() || !trigger_sql.is_empty() {
+ warnings.push("StarRocks foreign keys and triggers cannot be changed from this editor.".into());
+ }
+ if options.mysql_engine.is_some() {
+ warnings.push("StarRocks does not support MySQL storage engine settings.".into());
+ }
+ for column in &options.columns {
+ if column.marked_for_drop && column.original.is_none() {
+ continue;
+ }
+ let Some(original) = &column.original else {
+ if !supported_model {
+ warnings.push(
+ "Adding StarRocks columns requires confirmed PRIMARY or DUPLICATE table metadata.".into(),
+ );
+ }
+ if column.is_primary_key
+ || column.extra.as_ref().is_some_and(|extra| {
+ extra.auto_increment == Some(true) || extra.on_update_current_timestamp == Some(true)
+ })
+ {
+ warnings.push("New StarRocks columns cannot change keys or use MySQL extra properties.".into());
+ }
+ // CREATE accepts UUID generators, but ADD cannot backfill these varying defaults.
+ static UUID_DEFAULT: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
+ regex::Regex::new(r"(?i)^\s*\(*\s*uuid(?:_numeric)?\s*\(\s*\)\s*\)*\s*$").unwrap()
+ });
+ if UUID_DEFAULT.is_match(&column.default_value) {
+ warnings.push(format!("StarRocks ADD COLUMN '{}' does not support uuid() or uuid_numeric() defaults. Use a literal or NULL; UUID defaults are only available when creating a table.", column.name));
+ }
+ changes.push(format!("ADD COLUMN {}", definition(column, false)));
+ continue;
+ };
+ if column.is_primary_key != original.is_primary_key {
+ warnings.push("StarRocks key membership cannot be changed from this editor.".into());
+ }
+ if column.marked_for_drop {
+ if locked(column) || contains(&self.0.key_columns, &original.name) || original.is_primary_key {
+ warnings.push(format!("StarRocks key, partition, distribution or protected column '{}' cannot be dropped from this editor.", original.name));
+ }
+ changes.push(format!("DROP COLUMN {}", quote(&original.name)));
+ continue;
+ }
+ let default_changed = normalize_default(Some(&column.default_value)) != original_default(column);
+ if default_changed {
+ warnings.push(format!("StarRocks cannot change the default value of existing column '{}'. Set defaults when creating a table or adding a column.", original.name));
+ }
+ let definition_changed = !column.data_type.trim().eq_ignore_ascii_case(original.data_type.trim())
+ || column.is_nullable != original.is_nullable
+ || default_changed;
+ let comment_changed = clean(&column.comment) != original_comment(column);
+ if column.name != original.name {
+ if !at_least((3, 3, 2)) {
+ warnings.push("Renaming StarRocks columns requires confirmed version 3.3.2 or newer.".into());
+ }
+ if options.columns.iter().any(|other| {
+ other.id != column.id
+ && (other.name.eq_ignore_ascii_case(&column.name)
+ || other.original.as_ref().is_some_and(|old| old.name.eq_ignore_ascii_case(&column.name)))
+ }) {
+ warnings
+ .push("Rename StarRocks columns separately when names collide with original columns.".into());
+ }
+ if options
+ .columns
+ .iter()
+ .any(|other| other.original.is_none() && other.name.eq_ignore_ascii_case(&original.name))
+ {
+ warnings.push("StarRocks does not support reusing a renamed column name.".into());
+ }
+ statements.push(format!(
+ "ALTER TABLE {table} RENAME COLUMN {} TO {};",
+ quote(&original.name),
+ quote(&column.name)
+ ));
+ }
+ if definition_changed {
+ if locked(column) {
+ warnings.push(format!("StarRocks column '{}' requires key/partition/aggregation metadata or is protected from definition changes.", original.name));
+ }
+ if original.is_nullable && !column.is_nullable {
+ warnings.push("StarRocks cannot change a nullable column to NOT NULL.".into());
+ }
+ changes.push(format!(
+ "MODIFY COLUMN {}",
+ definition(column, contains(&self.0.key_columns, &original.name))
+ ));
+ }
+ // Comment-only ALTER is synchronous and must not resubmit a complete definition.
+ if comment_changed && !definition_changed {
+ statements.push(format!(
+ "ALTER TABLE {table} MODIFY COLUMN {} COMMENT {};",
+ quote(&column.name),
+ quote_string(&clean(&column.comment))
+ ));
+ }
+ if column.extra.as_ref().is_some_and(|extra| {
+ extra.on_update_current_timestamp == Some(true)
+ || (extra.auto_increment == Some(true)
+ && !original.extra.as_deref().unwrap_or("").to_ascii_lowercase().contains("auto_increment"))
+ }) {
+ warnings.push("StarRocks column extra properties cannot be changed from this editor.".into());
+ }
+ }
+ if clean(options.table_comment.as_deref().unwrap_or(""))
+ != clean(options.original_table_comment.as_deref().unwrap_or(""))
+ {
+ if !at_least((3, 1, 0)) {
+ warnings.push("StarRocks table comments require confirmed version 3.1 or newer.".into());
+ }
+ statements.push(format!(
+ "ALTER TABLE {table} COMMENT = {};",
+ quote_string(&clean(options.table_comment.as_deref().unwrap_or("")))
+ ));
+ }
+ build_column_order(options, &self.0, &mut changes, &mut warnings);
+ if let Some(sort_columns) = &self.0.sort_column_names {
+ if !statements.is_empty() || !changes.is_empty() || self.0.layout.is_some() {
+ warnings.push("Save StarRocks sort-key changes separately from other table edits.".into());
+ }
+ validate_sort_columns(options, &self.0, sort_columns, &mut warnings);
+ changes.push(format!(
+ "ORDER BY ({})",
+ sort_columns
+ .iter()
+ .map(|name| quote_ident(StructureDialect::Mysql, name))
+ .collect::<Vec<_>>()
+ .join(", ")
+ ));
+ }
+ // Submit one asynchronous schema-change job, after synchronous metadata changes.
+ if !changes.is_empty() {
+ statements.push(format!("ALTER TABLE {table} {};", changes.join(", ")));
+ }
+ let layout_statements = super::starrocks_layout::build(options, &self.0, &mut warnings);
+ if !layout_statements.is_empty() && !statements.is_empty() {
+ warnings.push("Save StarRocks layout operations separately from column and table-comment changes; wait for schema-change completion before the next operation.".into());
+ }
+ statements.extend(layout_statements);
+ if !warnings.is_empty() {
+ statements.clear();
+ }
+ TableStructureSqlResult { statements, warnings }
+ }
+}
+
+fn definition(column: &EditableStructureColumn, key: bool) -> String {
+ let mut parts = vec![quote_ident(StructureDialect::Mysql, &column.name), column.data_type.trim().to_string()];
+ if key {
+ parts.push("KEY".into());
+ }
+ parts.push(if column.is_nullable { "NULL" } else { "NOT NULL" }.into());
+ let default = normalize_default(Some(&column.default_value));
+ if !default.is_empty() {
+ let value = if default.starts_with('\'') && default.ends_with('\'') {
+ default
+ } else {
+ format_default_for_sql(StructureDialect::Mysql, &column.data_type, &default)
+ };
+ parts.push(format!("DEFAULT {value}"));
+ }
+ parts.push(format!("COMMENT {}", quote_string(&clean(&column.comment))));
+ parts.join(" ")
+}
+
+// Position clauses are unambiguous: never use ORDER BY to change column order.
+fn build_column_order(
+ options: &TableStructureSqlOptions,
+ context: &StarRocksAlterOptions,
+ changes: &mut Vec<String>,
+ warnings: &mut Vec<String>,
+) {
+ if context.reorder_columns {
+ warnings.push("The legacy StarRocks ORDER BY column-reorder path is disabled. Refresh the editor and backend before changing column order.".into());
+ return;
+ }
+ if !context.position_column_order {
+ return;
+ }
+ let existing: Vec<_> =
+ options.columns.iter().filter(|column| column.original.is_some() && !column.marked_for_drop).collect();
+ let mut original = existing.clone();
+ original.sort_by_key(|column| column.original_position.unwrap_or(usize::MAX));
+ original.extend(options.columns.iter().filter(|column| column.original.is_none() && !column.marked_for_drop));
+ let desired: Vec<_> = options.columns.iter().filter(|column| !column.marked_for_drop).collect();
+ if desired.iter().map(|column| &column.id).eq(original.iter().map(|column| &column.id)) {
+ return;
+ }
+ if context.model.as_deref() != Some("duplicate") {
+ warnings.push(
+ "Physical column reordering is currently supported only for confirmed StarRocks DUPLICATE tables.".into(),
+ );
+ }
+ if !changes.is_empty() || options.columns.iter().any(|column| column.original.is_none() || column.marked_for_drop) {
+ warnings.push(
+ "Save StarRocks column definition changes, additions and deletions separately from column reordering."
+ .into(),
+ );
+ }
+ let source: std::collections::HashSet<_> = context.column_names.iter().map(|name| name.to_lowercase()).collect();
+ let supplied: std::collections::HashSet<_> =
+ existing.iter().map(|column| column.original.as_ref().unwrap().name.to_lowercase()).collect();
+ let positions: std::collections::HashSet<_> =
+ existing.iter().filter_map(|column| column.original_position).collect();
+ if source.is_empty()
+ || source.len() != context.column_names.len()
+ || source != supplied
+ || existing.len() != source.len()
+ || positions.len() != existing.len()
+ {
+ warnings.push("StarRocks reordering requires all existing columns and their original positions; refresh table metadata first.".into());
+ }
+ let is_key = |column: &EditableStructureColumn| {
+ context.key_columns.iter().any(|key| key.eq_ignore_ascii_case(&column.original.as_ref().unwrap().name))
+ };
+ let mut saw_value = false;
+ for column in &existing {
+ if is_key(column) {
+ if saw_value {
+ warnings.push("StarRocks key columns must precede all value columns; key columns may be reordered among themselves.".into());
+ break;
+ }
+ } else {
+ saw_value = true;
+ }
+ }
+ let protected = |column: &EditableStructureColumn| {
+ let name = &column.original.as_ref().unwrap().name;
+ // Move other columns around expression sources: even a position-only MODIFY
+ // can be rejected when the source backs a hidden generated partition column.
+ context.partition_expression_columns.iter().any(|source| source.eq_ignore_ascii_case(name))
+ || (!is_key(column)
+ && context
+ .partition_columns
+ .iter()
+ .chain(&context.distribution_columns)
+ .any(|key| key.eq_ignore_ascii_case(name)))
+ || column.original.as_ref().unwrap().extra.as_deref().is_some_and(|extra| {
+ let lower = extra.to_lowercase();
+ lower.contains("generated") || lower.contains("auto_increment")
+ })
+ };
+ if !original
+ .iter()
+ .filter(|column| column.original.is_some())
+ .filter(|column| protected(column))
+ .map(|column| &column.id)
+ .eq(existing.iter().filter(|column| protected(column)).map(|column| &column.id))
+ {
+ warnings.push("Keep StarRocks partition-expression source columns, non-key partition/distribution columns and generated/auto-increment columns in their original relative order.".into());
+ }
+ if !warnings.is_empty() {
+ return;
+ }
+ let mut simulated: Vec<_> = original.iter().map(|column| column.id.clone()).collect();
+ for (index, column) in existing.iter().enumerate() {
+ if protected(column) {
+ continue;
+ }
+ let position = simulated.iter().position(|id| id == &column.id).unwrap();
+ let predecessor = index.checked_sub(1).map(|previous| &existing[previous].id);
+ let current_predecessor = position.checked_sub(1).map(|previous| &simulated[previous]);
+ if current_predecessor == predecessor {
+ continue;
+ }
+ let placement = if index == 0 {
+ "FIRST".into()
+ } else {
+ format!("AFTER {}", quote_ident(StructureDialect::Mysql, &existing[index - 1].name))
+ };
+ changes.push(format!("MODIFY COLUMN {} {placement}", definition(column, is_key(column))));
+ simulated.remove(position);
+ let insert = predecessor.map(|id| simulated.iter().position(|value| value == id).unwrap() + 1).unwrap_or(0);
+ simulated.insert(insert, column.id.clone());
+ }
+ if !simulated.iter().eq(existing.iter().map(|column| &column.id)) {
+ warnings.push("This field order would require modifying a protected StarRocks column.".into());
+ }
+}
+
+fn validate_sort_columns(
+ options: &TableStructureSqlOptions,
+ context: &StarRocksAlterOptions,
+ names: &[String],
+ warnings: &mut Vec<String>,
+) {
+ let version = super::create_dialect::parse_version(context.server_version.as_deref());
+ let primary = context.model.as_deref() == Some("primary");
+ if !matches!(context.model.as_deref(), Some("primary" | "duplicate" | "aggregate" | "unique"))
+ || !version.is_some_and(|version| version >= if primary { (3, 0, 0) } else { (3, 3, 0) })
+ {
+ warnings.push("Changing StarRocks sort keys requires confirmed table metadata and version 3.0+ for PRIMARY or 3.3+ for other models.".into());
+ }
+ if names.is_empty() {
+ warnings.push("Select at least one StarRocks sort column.".into());
+ }
+ let selected: std::collections::HashSet<_> = names.iter().map(|name| name.to_lowercase()).collect();
+ let source: std::collections::HashSet<_> = context.column_names.iter().map(|name| name.to_lowercase()).collect();
+ if selected.len() != names.len() {
+ warnings.push("StarRocks sort columns must not repeat.".into());
+ }
+ if source.is_empty() || !selected.is_subset(&source) {
+ warnings.push("A sort column is missing. Refresh table metadata first.".into());
+ }
+ if selected == source {
+ warnings.push("Selecting every column is ambiguous with StarRocks schema reordering. Choose fewer columns for a sort-key change.".into());
+ }
+ if matches!(context.model.as_deref(), Some("aggregate" | "unique")) {
+ let keys: std::collections::HashSet<_> = context.key_columns.iter().map(|name| name.to_lowercase()).collect();
+ if selected != keys {
+ warnings.push("StarRocks AGGREGATE and UNIQUE sort keys must contain exactly all key columns.".into());
+ }
+ }
+ for name in names {
+ let Some(column) = options
+ .columns
+ .iter()
+ .find(|column| column.name == *name && column.original.is_some() && !column.marked_for_drop)
+ else {
+ warnings.push(format!("Sort column '{name}' is missing or newly added. Save column changes first."));
+ continue;
+ };
+ let base = column.data_type.split('(').next().unwrap_or("").trim().to_lowercase();
+ let valid = if primary {
+ matches!(
+ base.as_str(),
+ "boolean"
+ | "tinyint"
+ | "smallint"
+ | "int"
+ | "integer"
+ | "bigint"
+ | "largeint"
+ | "varchar"
+ | "string"
+ | "date"
+ | "datetime"
+ )
+ } else {
+ matches!(
+ base.as_str(),
+ "boolean"
+ | "tinyint"
+ | "smallint"
+ | "int"
+ | "integer"
+ | "bigint"
+ | "largeint"
+ | "float"
+ | "double"
+ | "decimal"
+ | "decimalv2"
+ | "decimal32"
+ | "decimal64"
+ | "decimal128"
+ | "decimal256"
+ | "char"
+ | "varchar"
+ | "string"
+ | "date"
+ | "datetime"
+ )
+ };
+ if !valid {
+ warnings.push(format!("Column '{name}' has an unsupported StarRocks sort-key type."));
+ }
+ }
+}
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_dialect.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_dialect.rs
new file mode 100644
index 0000000000..89165507df
--- /dev/null
+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_dialect.rs
@@ -0,0 +1,293 @@
+//! CREATE-only extension points. Existing ALTER dialects and wire options stay unchanged.
+use super::create_options::{CreateTableDialectOptions, StarRocksCreateOptions, StarRocksDistribution};
+use super::dialect::StructureDialect;
+use super::types::{EditableStructureColumn, TableStructureSqlOptions};
+use super::util::{clean, quote_ident, quote_string};
+use crate::models::connection::DatabaseType;
+
+pub(super) trait CreateTableDialect {
+ fn validate(
+ &self,
+ _options: &TableStructureSqlOptions,
+ _columns: &[&EditableStructureColumn],
+ _warnings: &mut Vec<String>,
+ ) {
+ }
+ fn primary_key_columns_first(&self) -> bool {
+ false
+ }
+ fn supports_column_charset(&self) -> bool {
+ true
+ }
+ fn primary_key_in_column_list(&self) -> bool {
+ true
+ }
+ fn explicit_primary_key_not_null(&self) -> bool {
+ false
+ }
+ fn handles_table_comment(&self) -> bool {
+ false
+ }
+ fn after_columns(&self, _options: &TableStructureSqlOptions, _primary_key: &str) -> String {
+ String::new()
+ }
+ fn partition_clause(&self, _columns: &[&EditableStructureColumn]) -> String {
+ String::new()
+ }
+ fn sort_clause(&self, _columns: &[&EditableStructureColumn]) -> String {
+ String::new()
+ }
+ fn after_partition(&self, _columns: &[&EditableStructureColumn], _primary_key: &str) -> String {
+ String::new()
+ }
+}
+
+struct GenericCreateTable {
+ unexpected_starrocks_options: bool,
+}
+impl CreateTableDialect for GenericCreateTable {
+ fn validate(
+ &self,
+ _options: &TableStructureSqlOptions,
+ _columns: &[&EditableStructureColumn],
+ warnings: &mut Vec<String>,
+ ) {
+ if self.unexpected_starrocks_options {
+ warnings.push("StarRocks physical options require a StarRocks connection.".into());
+ }
+ }
+}
+
+pub(super) fn create_table_dialect(
+ options: &TableStructureSqlOptions,
+ server_version: Option<&str>,
+ dialect_options: CreateTableDialectOptions,
+) -> Box<dyn CreateTableDialect> {
+ if !options.is_gaussdb_m_mode
+ && (options.database_type == Some(DatabaseType::StarRocks)
+ || (options.database_type == Some(DatabaseType::Mysql)
+ && options.driver_profile.as_deref().is_some_and(|profile| profile.eq_ignore_ascii_case("starrocks"))))
+ {
+ Box::new(StarRocksCreateTable {
+ version: parse_version(server_version),
+ settings: dialect_options.starrocks.unwrap_or_default(),
+ })
+ } else {
+ Box::new(GenericCreateTable { unexpected_starrocks_options: dialect_options.starrocks.is_some() })
+ }
+}
+
+pub(super) fn parse_version(raw: Option<&str>) -> Option<(u32, u32, u32)> {
+ let normalized = raw?.trim().to_ascii_lowercase();
+ let raw = normalized.as_str();
+ let raw = raw
+ .strip_prefix("starrocks version ")
+ .or_else(|| raw.strip_prefix("starrocks "))
+ .unwrap_or(raw)
+ .trim_start_matches('v');
+ let version = raw.split(|c: char| !c.is_ascii_digit() && c != '.').next()?;
+ let mut parts = version.split('.');
+ let result = (parts.next()?.parse().ok()?, parts.next()?.parse().ok()?, parts.next().unwrap_or("0").parse().ok()?);
+ // Old cached VERSION() values identify MySQL, not this product.
+ (result != (5, 1, 0)).then_some(result)
+}
+
+struct StarRocksCreateTable {
+ settings: StarRocksCreateOptions,
+ version: Option<(u32, u32, u32)>,
+}
+
+impl StarRocksCreateTable {
+ fn at_least(&self, version: (u32, u32, u32)) -> bool {
+ self.version.is_some_and(|current| current >= version)
+ }
+}
+
+impl CreateTableDialect for StarRocksCreateTable {
+ fn validate(
+ &self,
+ options: &TableStructureSqlOptions,
+ columns: &[&EditableStructureColumn],
+ warnings: &mut Vec<String>,
+ ) {
+ let has_primary_key = columns.iter().any(|column| column.is_primary_key);
+ if !self.settings.sort_column_ids.is_empty() {
+ let minimum = if has_primary_key { (3, 0, 0) } else { (3, 3, 0) };
+ if !self.at_least(minimum) {
+ warnings.push(format!("StarRocks custom sort columns require a confirmed server version of {}.{} or newer for this table model.", minimum.0, minimum.1));
+ }
+ let mut seen = std::collections::HashSet::new();
+ for id in &self.settings.sort_column_ids {
+ if !seen.insert(id) {
+ warnings.push("StarRocks sort columns must be unique.".into());
+ }
+ match columns.iter().find(|column| &column.id == id) {
+ None => warnings.push("A StarRocks sort column was removed. Select an existing column.".into()),
+ Some(column) if has_primary_key => {
+ let base = column.data_type.split('(').next().unwrap_or("").trim().to_ascii_lowercase();
+ if !matches!(
+ base.as_str(),
+ "boolean"
+ | "tinyint"
+ | "smallint"
+ | "int"
+ | "integer"
+ | "bigint"
+ | "largeint"
+ | "varchar"
+ | "string"
+ | "date"
+ | "datetime"
+ ) {
+ warnings.push(format!("StarRocks primary key table sort column '{}' must use boolean, integer, varchar, date or datetime.", column.name));
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ super::starrocks_partition::validate(&self.settings, columns, self.version, warnings);
+ if self.settings.distribution == StarRocksDistribution::Random {
+ if has_primary_key {
+ warnings.push("StarRocks primary key tables require hash distribution.".into());
+ }
+ if !self.at_least((3, 1, 0)) {
+ warnings
+ .push("StarRocks random distribution requires a confirmed server version of 3.1 or newer.".into());
+ }
+ }
+ if self.settings.distribution == StarRocksDistribution::Hash {
+ if self.settings.distribution_column_ids.is_empty() {
+ warnings.push("Select at least one StarRocks hash distribution column.".into());
+ }
+ let mut seen = std::collections::HashSet::new();
+ for id in &self.settings.distribution_column_ids {
+ if !seen.insert(id) {
+ warnings.push("StarRocks hash distribution columns must be unique.".into());
+ }
+ match columns.iter().find(|column| &column.id == id) {
+ None => warnings
+ .push("A StarRocks hash distribution column was removed. Select an existing column.".into()),
+ Some(column) => {
+ let base = column.data_type.split('(').next().unwrap_or("").trim().to_ascii_lowercase();
+ if !matches!(
+ base.as_str(),
+ "tinyint"
+ | "smallint"
+ | "int"
+ | "integer"
+ | "bigint"
+ | "largeint"
+ | "date"
+ | "datetime"
+ | "char"
+ | "varchar"
+ | "string"
+ ) {
+ warnings.push(format!(
+ "StarRocks hash distribution column '{}' must use an integer, date or string type.",
+ column.name
+ ));
+ }
+ if has_primary_key && !column.is_primary_key {
+ warnings.push(
+ "StarRocks hash distribution columns must be included in the primary key.".into(),
+ );
+ }
+ }
+ }
+ }
+ } else if !self.settings.distribution_column_ids.is_empty() {
+ warnings.push("Explicit distribution columns require hash distribution.".into());
+ }
+ if self.settings.bucket_count.is_some_and(|count| count == 0 || count > i32::MAX as u32) {
+ warnings.push("StarRocks bucket count must be a positive integer no greater than 2147483647.".into());
+ }
+ if options.mysql_engine.is_some() {
+ warnings.push("StarRocks tables do not accept MySQL storage engine options.".to_string());
+ }
+ if options.foreign_keys.iter().any(|key| !key.marked_for_drop)
+ || options.triggers.iter().any(|trigger| !trigger.marked_for_drop)
+ || options.indexes.iter().any(|index| !index.marked_for_drop && !index.is_primary)
+ {
+ warnings.push("StarRocks CREATE TABLE does not support MySQL foreign keys, triggers or secondary index definitions from this editor.".to_string());
+ }
+ for column in columns {
+ if column.extra.as_ref().is_some_and(|extra| extra.on_update_current_timestamp == Some(true)) {
+ warnings.push(format!("StarRocks column '{}' does not support MySQL ON UPDATE clauses.", column.name));
+ }
+ }
+ }
+ fn primary_key_columns_first(&self) -> bool {
+ true
+ }
+ fn supports_column_charset(&self) -> bool {
+ false
+ }
+ fn primary_key_in_column_list(&self) -> bool {
+ false
+ }
+ fn explicit_primary_key_not_null(&self) -> bool {
+ true
+ }
+ fn handles_table_comment(&self) -> bool {
+ true
+ }
+ fn after_columns(&self, options: &TableStructureSqlOptions, primary_key: &str) -> String {
+ let mut suffix = String::new();
+ if !primary_key.is_empty() {
+ suffix.push_str(&format!(" PRIMARY KEY ({primary_key})"));
+ }
+ let comment = clean(options.table_comment.as_deref().unwrap_or(""));
+ if !comment.is_empty() {
+ suffix.push_str(&format!(" COMMENT {}", quote_string(&comment)));
+ }
+ suffix
+ }
+ fn partition_clause(&self, columns: &[&EditableStructureColumn]) -> String {
+ super::starrocks_partition::render(&self.settings, columns)
+ }
+ fn sort_clause(&self, columns: &[&EditableStructureColumn]) -> String {
+ if self.settings.sort_column_ids.is_empty() {
+ return String::new();
+ }
+ let keys = self
+ .settings
+ .sort_column_ids
+ .iter()
+ .filter_map(|id| columns.iter().find(|column| &column.id == id))
+ .map(|column| quote_ident(StructureDialect::Mysql, &column.name))
+ .collect::<Vec<_>>()
+ .join(", ");
+ format!(" ORDER BY ({keys})")
+ }
+ fn after_partition(&self, columns: &[&EditableStructureColumn], primary_key: &str) -> String {
+ let distribution = if self.settings.distribution == StarRocksDistribution::Hash {
+ let keys = self
+ .settings
+ .distribution_column_ids
+ .iter()
+ .filter_map(|id| columns.iter().find(|column| &column.id == id))
+ .map(|column| quote_ident(StructureDialect::Mysql, &column.name))
+ .collect::<Vec<_>>()
+ .join(", ");
+ format!(" DISTRIBUTED BY HASH ({keys})")
+ } else if self.settings.distribution == StarRocksDistribution::Random {
+ " DISTRIBUTED BY RANDOM".into()
+ } else if !primary_key.is_empty() {
+ format!(" DISTRIBUTED BY HASH ({primary_key})")
+ } else if self.at_least((3, 1, 0)) {
+ " DISTRIBUTED BY RANDOM".to_string()
+ } else {
+ format!(" DISTRIBUTED BY HASH ({})", quote_ident(StructureDialect::Mysql, &columns[0].name))
+ };
+ // Automatic bucket counts are supported from 2.5.7 onward.
+ if let Some(count) = self.settings.bucket_count {
+ format!("{distribution} BUCKETS {count}")
+ } else if self.at_least((2, 5, 7)) {
+ distribution
+ } else {
+ format!("{distribution} BUCKETS 10")
+ }
+ }
+}
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_options.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_options.rs
new file mode 100644
index 0000000000..f46a60b11c
--- /dev/null
+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_options.rs
@@ -0,0 +1,84 @@
+//! Optional CREATE-only dialect settings. Existing table/ALTER request options remain compatible.
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateTableDialectOptions {
+ pub starrocks: Option<StarRocksCreateOptions>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StarRocksCreateOptions {
+ pub time_partition: Option<StarRocksTimePartition>,
+ pub partition: Option<StarRocksPartitionOptions>,
+ #[serde(default)]
+ pub distribution: StarRocksDistribution,
+ #[serde(default)]
+ pub distribution_column_ids: Vec<String>,
+ #[serde(default)]
+ pub sort_column_ids: Vec<String>,
+ pub bucket_count: Option<u32>,
+}
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum StarRocksDistribution {
+ #[default]
+ Auto,
+ Hash,
+ Random,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StarRocksTimePartition {
+ pub column_id: String,
+ pub granularity: StarRocksTimeGranularity,
+ pub interval: Option<u32>,
+ #[serde(default)]
+ pub additional_column_ids: Vec<String>,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum StarRocksTimeGranularity {
+ Year,
+ Month,
+ Day,
+ Hour,
+}
+
+impl StarRocksTimeGranularity {
+ pub(super) fn sql(self) -> &'static str {
+ match self {
+ Self::Year => "year",
+ Self::Month => "month",
+ Self::Day => "day",
+ Self::Hour => "hour",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "lowercase", rename_all_fields = "camelCase")]
+pub enum StarRocksPartitionOptions {
+ Values { column_ids: Vec<String> },
+ Range { column_ids: Vec<String>, partitions: Vec<StarRocksRangePartition> },
+ List { column_ids: Vec<String>, partitions: Vec<StarRocksListPartition> },
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StarRocksRangePartition {
+ pub name: String,
+ pub lower: Vec<String>,
+ pub upper: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StarRocksListPartition {
+ pub name: String,
+ pub values: Vec<Vec<String>>,
+}
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs
index 88a29b418e..b7a6ea1eac 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/create_table.rs
@@ -4,6 +4,8 @@ use super::column_format::{
mysql_on_update_current_timestamp_clause, strip_inherited_mysql_column_charsets,
};
use super::comments::{build_sqlserver_column_comment_sql_for_profile, build_sqlserver_table_comment_sql_for_profile};
+use super::create_dialect::create_table_dialect;
+use super::create_options::CreateTableDialectOptions;
use super::dialect::{capabilities_for, database_label, StructureDialect};
use super::foreign_keys::build_foreign_key_sql_for_new_table;
use super::indexes::{build_create_index_statements, mysql_inline_index_definition, normalized_index_type};
@@ -30,6 +32,22 @@ pub fn build_create_table_sql(options: TableStructureSqlOptions) -> TableStructu
build_create_table_sql_with_partition_clause(options, None)
}
+/// Optional server context for version-aware dialects; legacy callers retain conservative defaults.
+pub fn build_create_table_sql_for_version(
+ options: TableStructureSqlOptions,
+ server_version: Option<&str>,
+) -> TableStructureSqlResult {
+ build_create_table_sql_with_dialect_options(options, server_version, CreateTableDialectOptions::default())
+}
+
+pub fn build_create_table_sql_with_dialect_options(
+ options: TableStructureSqlOptions,
+ server_version: Option<&str>,
+ dialect_options: CreateTableDialectOptions,
+) -> TableStructureSqlResult {
+ build_create_table_sql_impl(options, None, server_version, dialect_options)
+}
+
/// Shared implementation for plain and partitioned `CREATE TABLE`.
///
/// `partition_clause` is a ready-made `PARTITION BY ...` body (no leading
@@ -37,9 +55,19 @@ pub fn build_create_table_sql(options: TableStructureSqlOptions) -> TableStructu
/// entry point means `build_create_table_sql`'s signature — used from ~160 call
/// sites and integration tests — stays unchanged.
pub(super) fn build_create_table_sql_with_partition_clause(
+ options: TableStructureSqlOptions,
+ partition_clause: Option<String>,
+) -> TableStructureSqlResult {
+ build_create_table_sql_impl(options, partition_clause, None, CreateTableDialectOptions::default())
+}
+
+fn build_create_table_sql_impl(
mut options: TableStructureSqlOptions,
partition_clause: Option<String>,
+ server_version: Option<&str>,
+ dialect_options: CreateTableDialectOptions,
) -> TableStructureSqlResult {
+ let create_dialect = create_table_dialect(&options, server_version, dialect_options);
let capabilities;
let dialect;
if options.is_gaussdb_m_mode {
@@ -82,7 +110,11 @@ pub(super) fn build_create_table_sql_with_partition_clause(
if options.table_name.is_empty() {
warnings.push("Table name is required.".to_string());
}
- let active_columns: Vec<_> = options.columns.iter().filter(|column| !column.marked_for_drop).collect();
+ let mut active_columns: Vec<_> = options.columns.iter().filter(|column| !column.marked_for_drop).collect();
+ if create_dialect.primary_key_columns_first() {
+ // Stable partition of references only: never mutate the editor draft or primary-key membership.
+ active_columns.sort_by_key(|column| !column.is_primary_key);
+ }
if active_columns.is_empty() {
warnings.push("At least one column is required.".to_string());
}
@@ -141,6 +173,7 @@ pub(super) fn build_create_table_sql_with_partition_clause(
validate_dameng_identity(&options, &active_columns, &mut warnings);
validate_mysql_literal_defaults(&options, &active_columns, &mut warnings);
transwarp::validate_create_options(&options, &active_columns, &mut warnings);
+ create_dialect.validate(&options, &active_columns, &mut warnings);
if !warnings.is_empty() {
return TableStructureSqlResult { statements: Vec::new(), warnings };
}
@@ -196,7 +229,10 @@ pub(super) fn build_create_table_sql_with_partition_clause(
data_type = "INTEGER".to_string();
}
let mut parts = vec![quote_new_ident(options.database_type, dialect, &column.name), data_type];
- if options.database_type == Some(DatabaseType::Mysql) && is_mysql_character_data_type(&column.data_type) {
+ if options.database_type == Some(DatabaseType::Mysql)
+ && create_dialect.supports_column_charset()
+ && is_mysql_character_data_type(&column.data_type)
+ {
if !column.character_set.trim().is_empty() {
parts.push(format!("CHARACTER SET {}", quote_ident(dialect, &column.character_set)));
}
@@ -228,9 +264,10 @@ pub(super) fn build_create_table_sql_with_partition_clause(
&& column.extra.as_ref().is_some_and(|e| e.auto_increment.unwrap_or(false))
{
parts.push("PRIMARY KEY".to_string());
- } else if !column.is_nullable
- && !column.is_primary_key
- && !matches!(dialect, StructureDialect::ClickHouse | StructureDialect::ManticoreSearch)
+ } else if (column.is_primary_key && create_dialect.explicit_primary_key_not_null())
+ || (!column.is_nullable
+ && !column.is_primary_key
+ && !matches!(dialect, StructureDialect::ClickHouse | StructureDialect::ManticoreSearch))
{
parts.push("NOT NULL".to_string());
} else if column.is_nullable
@@ -272,12 +309,12 @@ pub(super) fn build_create_table_sql_with_partition_clause(
&& column.extra.as_ref().is_some_and(|e| e.auto_increment.unwrap_or(false)))
})
.collect();
- if !pk_columns.is_empty() {
- let pk_list = pk_columns
- .iter()
- .map(|column| quote_new_ident(options.database_type, dialect, &column.name))
- .collect::<Vec<_>>()
- .join(", ");
+ let pk_list = pk_columns
+ .iter()
+ .map(|column| quote_new_ident(options.database_type, dialect, &column.name))
+ .collect::<Vec<_>>()
+ .join(", ");
+ if !pk_list.is_empty() && create_dialect.primary_key_in_column_list() {
// Optional user-supplied constraint name; empty keeps the anonymous form.
let constraint = super::columns::new_primary_key_constraint_clause(&options, dialect);
column_definitions.push(format!("{constraint}PRIMARY KEY ({pk_list})"));
@@ -288,11 +325,15 @@ pub(super) fn build_create_table_sql_with_partition_clause(
}
let mut create_table = format!("CREATE TABLE {table} (\n {}\n)", column_definitions.join(",\n "));
+ create_table.push_str(&create_dialect.after_columns(&options, &pk_list));
create_table.push_str(&transwarp::create_table_suffix(&options, &active_columns, dialect));
- let create_table = match partition_clause {
+ let mut create_table = match partition_clause {
Some(clause) => format!("{create_table} {clause}"),
None => create_table,
};
+ create_table.push_str(&create_dialect.partition_clause(&active_columns));
+ create_table.push_str(&create_dialect.after_partition(&active_columns, &pk_list));
+ create_table.push_str(&create_dialect.sort_clause(&active_columns));
statements.push(format!("{create_table};"));
if let Some(engine) = options.mysql_engine.as_deref().map(str::trim).filter(|engine| !engine.is_empty()) {
@@ -309,7 +350,10 @@ pub(super) fn build_create_table_sql_with_partition_clause(
if capabilities.comment {
let table_comment = clean(options.table_comment.as_deref().unwrap_or(""));
- if !table_comment.is_empty() && options.database_type != Some(DatabaseType::Transwarp) {
+ if !table_comment.is_empty()
+ && options.database_type != Some(DatabaseType::Transwarp)
+ && !create_dialect.handles_table_comment()
+ {
if matches!(dialect, StructureDialect::Mysql | StructureDialect::GaussdbM) {
if let Some(last) = statements.last_mut() {
append_mysql_table_option(last, &format!("COMMENT = {}", quote_string(&table_comment)));
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/dialect.rs b/crates/dbx-sql-schema/src/table_structure_sql/dialect.rs
index 8a21dffa0a..5b576a45e0 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/dialect.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/dialect.rs
@@ -99,6 +99,20 @@ pub(super) fn capabilities_for(
driver_profile: Option<&str>,
) -> TableStructureCapabilities {
let base = TableStructureCapabilities::default();
+ if database_type == Some(DatabaseType::StarRocks)
+ || (database_type == Some(DatabaseType::Mysql)
+ && driver_profile.is_some_and(|p| p.eq_ignore_ascii_case("starrocks")))
+ {
+ return TableStructureCapabilities {
+ dialect: StructureDialect::Mysql,
+ add_column: true,
+ drop_column: true,
+ rename_column: true,
+ alter_existing_column: true,
+ comment: true,
+ ..base
+ };
+ }
match database_type {
Some(
DatabaseType::Mysql
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs b/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs
index 16e6b83796..893bb3fbb1 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/indexes.rs
@@ -5,17 +5,13 @@ use super::util::{clean, qualified_table, quote_ident, quote_new_ident, quote_st
use crate::models::connection::DatabaseType;
pub(super) fn build_index_sql(options: &TableStructureSqlOptions, warnings: &mut Vec<String>) -> Vec<String> {
- let capabilities;
- let dialect;
- if options.is_gaussdb_m_mode {
+ let (capabilities, dialect) = if options.is_gaussdb_m_mode {
let caps = super::dialect::gaussdb_m_capabilities();
- capabilities = caps;
- dialect = StructureDialect::GaussdbM;
+ (caps, StructureDialect::GaussdbM)
} else {
let caps = capabilities_for(options.database_type, options.driver_profile.as_deref());
- capabilities = caps;
- dialect = caps.dialect;
- }
+ (caps, caps.dialect)
+ };
let table = qualified_table(dialect, options.schema.as_deref(), &options.table_name);
let database_label = database_label(options.database_type);
let mut statements = Vec::new();
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/starrocks_layout.rs b/crates/dbx-sql-schema/src/table_structure_sql/starrocks_layout.rs
new file mode 100644
index 0000000000..d29eab4c9d
--- /dev/null
+++ b/crates/dbx-sql-schema/src/table_structure_sql/starrocks_layout.rs
@@ -0,0 +1,211 @@
+//! Optional layout operations, kept separate from column schema-change jobs.
+use super::{alter_dialect::StarRocksAlterOptions, dialect::StructureDialect, types::*, util::*};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StarRocksLayoutChanges {
+ pub distribution: Option<StarRocksDistributionChange>,
+ #[serde(default)]
+ pub partitions: Vec<StarRocksPartitionChange>,
+}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StarRocksDistributionChange {
+ pub method: String,
+ #[serde(default)]
+ pub columns: Vec<String>,
+ pub buckets: Option<u32>,
+ #[serde(default)]
+ pub default_only: bool,
+}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum StarRocksPartitionChange {
+ AddRange { name: String, lower: Vec<String>, upper: Vec<String> },
+ AddList { name: String, values: Vec<Vec<String>> },
+ Drop { name: String },
+ Replicas { name: String, replicas: u32 },
+}
+fn ident(name: &str) -> String {
+ quote_ident(StructureDialect::Mysql, name)
+}
+fn tuple(values: &[String]) -> String {
+ values.iter().map(|value| quote_string(&value.replace('\\', "\\\\"))).collect::<Vec<_>>().join(", ")
+}
+pub(super) fn build(
+ options: &TableStructureSqlOptions,
+ context: &StarRocksAlterOptions,
+ warnings: &mut Vec<String>,
+) -> Vec<String> {
+ let Some(layout) = &context.layout else {
+ return vec![];
+ };
+ if layout.distribution.is_none() && layout.partitions.is_empty() {
+ return vec![];
+ }
+ let mut statements = vec![];
+ let table = qualified_table(StructureDialect::Mysql, options.schema.as_deref(), &options.table_name);
+ let version = super::create_dialect::parse_version(context.server_version.as_deref());
+ if context.model.is_none() || context.colocated {
+ warnings.push(
+ "StarRocks layout editing requires confirmed OLAP table metadata and a table outside a colocation group."
+ .into(),
+ );
+ }
+ if let Some(distribution) = &layout.distribution {
+ if context.automatic_bucket_scaling {
+ warnings.push("This StarRocks table uses automatic bucket scaling (bucket_size > 0); changing distribution or bucket count through ALTER is not supported. Create a new table to change distribution.".into());
+ }
+ if !version.is_some_and(|v| v >= (3, 2, 0)) {
+ warnings.push("Changing StarRocks distribution requires confirmed version 3.2 or newer.".into());
+ }
+ if !layout.partitions.is_empty() {
+ warnings.push("Save StarRocks distribution and partition operations separately.".into());
+ }
+ if distribution.buckets.is_some_and(|n| n == 0 || n > i32::MAX as u32) {
+ warnings.push("StarRocks bucket count must be a positive 32-bit integer.".into());
+ }
+ if distribution.default_only {
+ if !version.is_some_and(|v| v >= (4, 0, 1) || ((3, 5, 8)..(4, 0, 0)).contains(&v)) {
+ warnings.push("DEFAULT BUCKETS requires StarRocks 3.5.8 or 4.0.1 or newer.".into());
+ }
+ if distribution.method != "hash"
+ || distribution.buckets.is_none()
+ || context
+ .distribution
+ .as_ref()
+ .is_none_or(|old| old.method != "hash" || old.columns != distribution.columns)
+ {
+ warnings
+ .push("DEFAULT BUCKETS can only change the bucket count of the existing HASH distribution.".into());
+ }
+ }
+ let method = match distribution.method.as_str() {
+ "random" => {
+ if context.model.as_deref() != Some("duplicate") {
+ warnings.push("Random distribution is only supported for StarRocks DUPLICATE tables.".into());
+ }
+ if !distribution.columns.is_empty() {
+ warnings.push("Random distribution cannot contain hash columns.".into());
+ }
+ "RANDOM".into()
+ }
+ "hash" => {
+ if distribution.columns.is_empty() {
+ warnings.push("Select at least one StarRocks hash column.".into());
+ }
+ let mut seen = std::collections::HashSet::new();
+ for name in &distribution.columns {
+ if !seen.insert(name.to_lowercase()) {
+ warnings.push("StarRocks hash columns must not repeat.".into());
+ }
+ match options
+ .columns
+ .iter()
+ .find(|column| !column.marked_for_drop && column.original.is_some() && column.name == *name)
+ {
+ None => warnings.push(format!(
+ "Hash column '{name}' is missing or newly added. Save column changes separately."
+ )),
+ Some(column) => {
+ let base = column.data_type.split('(').next().unwrap_or("").trim().to_lowercase();
+ if !matches!(
+ base.as_str(),
+ "tinyint"
+ | "smallint"
+ | "int"
+ | "integer"
+ | "bigint"
+ | "largeint"
+ | "date"
+ | "datetime"
+ | "char"
+ | "varchar"
+ | "string"
+ ) {
+ warnings.push(format!("Column '{name}' has an unsupported hash type."));
+ }
+ if context.model.as_deref() != Some("duplicate")
+ && !context.key_columns.iter().any(|key| key.eq_ignore_ascii_case(name))
+ {
+ warnings.push(
+ "Hash columns must belong to the key for PRIMARY, UNIQUE and AGGREGATE tables."
+ .into(),
+ );
+ }
+ }
+ }
+ }
+ format!("HASH({})", distribution.columns.iter().map(|name| ident(name)).collect::<Vec<_>>().join(", "))
+ }
+ _ => {
+ warnings.push("Unknown StarRocks distribution method.".into());
+ String::new()
+ }
+ };
+ let count = distribution
+ .buckets
+ .map(|n| format!(" {}BUCKETS {n}", if distribution.default_only { "DEFAULT " } else { "" }))
+ .unwrap_or_default();
+ statements.push(format!("ALTER TABLE {table} DISTRIBUTED BY {method}{count};"));
+ }
+ for operation in &layout.partitions {
+ let name = match operation {
+ StarRocksPartitionChange::AddRange { name, .. }
+ | StarRocksPartitionChange::AddList { name, .. }
+ | StarRocksPartitionChange::Drop { name }
+ | StarRocksPartitionChange::Replicas { name, .. } => name,
+ };
+ if name.trim().is_empty() || name.contains('\0') {
+ warnings.push("Enter a valid StarRocks partition name.".into());
+ }
+ if context.partition_kind.is_none() && !matches!(operation, StarRocksPartitionChange::Replicas { .. }) {
+ warnings.push("Partition operations require an existing partitioned StarRocks table.".into());
+ }
+ let arity = context.partition_columns.len();
+ let valid_tuple = |values: &[String]| {
+ !values.is_empty() && values.len() == arity && values.iter().all(|value| !value.contains('\0'))
+ };
+ let clause = match operation {
+ StarRocksPartitionChange::AddRange { lower, upper, .. } => {
+ if context.partition_kind.as_deref() != Some("range") || !valid_tuple(lower) || !valid_tuple(upper) {
+ warnings.push(
+ "Range partition values must match every column of an existing manual RANGE partition key."
+ .into(),
+ );
+ }
+ format!("ADD PARTITION {} VALUES [({}), ({}))", ident(name), tuple(lower), tuple(upper))
+ }
+ StarRocksPartitionChange::AddList { values, .. } => {
+ if context.partition_kind.as_deref() != Some("list")
+ || values.is_empty()
+ || values.iter().any(|row| !valid_tuple(row))
+ {
+ warnings.push(
+ "List partition tuples must match every column of an existing manual LIST partition key."
+ .into(),
+ );
+ }
+ let values = values
+ .iter()
+ .map(|row| if arity == 1 { tuple(row) } else { format!("({})", tuple(row)) })
+ .collect::<Vec<_>>()
+ .join(", ");
+ format!("ADD PARTITION {} VALUES IN ({values})", ident(name))
+ }
+ StarRocksPartitionChange::Drop { .. } => format!("DROP PARTITION {}", ident(name)),
+ StarRocksPartitionChange::Replicas { replicas, .. } => {
+ if *replicas == 0 || *replicas > i16::MAX as u32 {
+ warnings.push("Replica count must be a positive integer no greater than 32767.".into());
+ }
+ format!(
+ "MODIFY PARTITION {} SET (\"replication_num\" = \"{replicas}\")",
+ if name == "*" { "(*)".into() } else { ident(name) }
+ )
+ }
+ };
+ statements.push(format!("ALTER TABLE {table} {clause};"));
+ }
+ statements
+}
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/starrocks_partition.rs b/crates/dbx-sql-schema/src/table_structure_sql/starrocks_partition.rs
new file mode 100644
index 0000000000..d406084819
--- /dev/null
+++ b/crates/dbx-sql-schema/src/table_structure_sql/starrocks_partition.rs
@@ -0,0 +1,226 @@
+//! Structured StarRocks partitions: values are quoted data, never user-supplied SQL.
+use super::create_options::*;
+use super::dialect::StructureDialect;
+use super::types::EditableStructureColumn;
+use super::util::{quote_ident, quote_string};
+use std::collections::HashSet;
+
+fn ident(value: &str) -> String {
+ quote_ident(StructureDialect::Mysql, value)
+}
+fn literal(value: &str) -> String {
+ quote_string(&value.replace('\\', "\\\\"))
+}
+fn tuple(values: &[String]) -> String {
+ values.iter().map(|value| literal(value)).collect::<Vec<_>>().join(", ")
+}
+fn base(column: &EditableStructureColumn) -> String {
+ column.data_type.split('(').next().unwrap_or("").trim().to_ascii_lowercase()
+}
+fn integer(data_type: &str) -> bool {
+ matches!(data_type, "tinyint" | "smallint" | "int" | "integer" | "bigint" | "largeint")
+}
+fn range_type(data_type: &str) -> bool {
+ integer(data_type) || matches!(data_type, "date" | "datetime")
+}
+fn value_type(data_type: &str) -> bool {
+ range_type(data_type) || matches!(data_type, "boolean" | "char" | "varchar" | "string")
+}
+
+fn validate_columns<'a>(
+ ids: &[String],
+ columns: &[&'a EditableStructureColumn],
+ range: bool,
+ warnings: &mut Vec<String>,
+) -> Vec<&'a EditableStructureColumn> {
+ let mut seen = HashSet::new();
+ let has_pk = columns.iter().any(|column| column.is_primary_key);
+ let mut selected = Vec::new();
+ if ids.is_empty() {
+ warnings.push("Select at least one StarRocks partition column.".into());
+ }
+ for id in ids {
+ if !seen.insert(id) {
+ warnings.push("Partition columns must not repeat.".into());
+ }
+ match columns.iter().find(|column| &column.id == id) {
+ None => warnings.push("A partition column was removed. Select an existing column.".into()),
+ Some(column) => {
+ if if range { !range_type(&base(column)) } else { !value_type(&base(column)) } {
+ warnings
+ .push(format!("Column '{}' has an unsupported type for this partition strategy.", column.name));
+ }
+ if has_pk && !column.is_primary_key {
+ warnings.push("StarRocks partition columns must be included in the primary key. Review uniqueness before changing the primary key.".into());
+ }
+ selected.push(*column);
+ }
+ }
+ }
+ selected
+}
+
+fn validate_values(values: &[String], columns: &[&EditableStructureColumn], warnings: &mut Vec<String>) {
+ if values.len() != columns.len() {
+ warnings.push("Each partition value tuple must contain one value for each selected column.".into());
+ return;
+ }
+ for (value, column) in values.iter().zip(columns) {
+ let data_type = base(column);
+ let valid = if integer(&data_type) {
+ value.parse::<i128>().is_ok()
+ } else if data_type == "boolean" {
+ matches!(value.to_ascii_lowercase().as_str(), "true" | "false" | "0" | "1")
+ } else if matches!(data_type.as_str(), "date" | "datetime") {
+ !value.trim().is_empty()
+ } else {
+ !value.contains('\0')
+ };
+ if !valid {
+ warnings.push(format!(
+ "Invalid partition value for column '{}'. Enter a {} value without SQL quotes.",
+ column.name, data_type
+ ));
+ }
+ }
+}
+
+pub(super) fn validate(
+ settings: &StarRocksCreateOptions,
+ columns: &[&EditableStructureColumn],
+ version: Option<(u32, u32, u32)>,
+ warnings: &mut Vec<String>,
+) {
+ let at_least = |minimum| version.is_some_and(|value| value >= minimum);
+ if settings.time_partition.is_some() && settings.partition.is_some() {
+ warnings.push("Choose only one StarRocks partition strategy.".into());
+ }
+ if let Some(time) = &settings.time_partition {
+ if !at_least((3, 1, 0)) {
+ warnings.push("Time partitioning requires a confirmed server version of 3.1 or newer. Reconnect to refresh the version.".into());
+ }
+ let mut ids = vec![time.column_id.clone()];
+ ids.extend(time.additional_column_ids.clone());
+ let selected = validate_columns(&ids, columns, false, warnings);
+ if let Some(column) = selected.first() {
+ let data_type = base(column);
+ if !matches!(data_type.as_str(), "date" | "datetime") {
+ warnings.push("Time partition columns must use date or datetime.".into());
+ }
+ if (time.interval.is_some() || matches!(time.granularity, StarRocksTimeGranularity::Hour))
+ && data_type != "datetime"
+ {
+ warnings.push("Hourly partitions and time_slice require a datetime column.".into());
+ }
+ }
+ if time.interval.is_some_and(|interval| interval == 0 || interval > i32::MAX as u32) {
+ warnings.push("Time partition interval must be a positive integer.".into());
+ }
+ if !time.additional_column_ids.is_empty() && !at_least((3, 4, 0)) {
+ warnings.push("Mixed time and dimension partitions require StarRocks 3.4 or newer.".into());
+ }
+ }
+ let Some(partition) = &settings.partition else {
+ return;
+ };
+ let (ids, range) = match partition {
+ StarRocksPartitionOptions::Values { column_ids } => (column_ids, false),
+ StarRocksPartitionOptions::Range { column_ids, .. } => (column_ids, true),
+ StarRocksPartitionOptions::List { column_ids, .. } => (column_ids, false),
+ };
+ if !range && !at_least((3, 1, 1)) {
+ warnings.push("List and automatic value partitions require a confirmed StarRocks version of 3.1.1 or newer in this editor.".into());
+ }
+ let selected = validate_columns(ids, columns, range, warnings);
+ let mut names = HashSet::new();
+ let mut check_name = |name: &str, warnings: &mut Vec<String>| {
+ if name.trim().is_empty() || name.contains('\0') || !names.insert(name.to_ascii_lowercase()) {
+ warnings.push("Partition names must be non-empty and unique.".into());
+ }
+ };
+ match partition {
+ StarRocksPartitionOptions::Values { .. } => {}
+ StarRocksPartitionOptions::Range { partitions, .. } => {
+ if partitions.is_empty() {
+ warnings.push("Add at least one range partition.".into());
+ }
+ for partition in partitions {
+ check_name(&partition.name, warnings);
+ validate_values(&partition.lower, &selected, warnings);
+ validate_values(&partition.upper, &selected, warnings);
+ if partition.lower == partition.upper {
+ warnings.push("A range partition's lower and upper bounds must differ.".into());
+ }
+ }
+ }
+ StarRocksPartitionOptions::List { partitions, .. } => {
+ if partitions.is_empty() {
+ warnings.push("Add at least one list partition.".into());
+ }
+ let mut tuples = HashSet::new();
+ for partition in partitions {
+ check_name(&partition.name, warnings);
+ if partition.values.is_empty() {
+ warnings.push("Each list partition needs at least one value tuple.".into());
+ }
+ for values in &partition.values {
+ validate_values(values, &selected, warnings);
+ if !tuples.insert(values) {
+ warnings.push("List partition value tuples must not overlap or repeat.".into());
+ }
+ }
+ }
+ }
+ }
+}
+
+pub(super) fn render(settings: &StarRocksCreateOptions, columns: &[&EditableStructureColumn]) -> String {
+ let name = |id: &String| {
+ columns.iter().find(|column| &column.id == id).map(|column| ident(&column.name)).unwrap_or_default()
+ };
+ let names = |ids: &[String]| ids.iter().map(name).collect::<Vec<_>>().join(", ");
+ if let Some(time) = &settings.time_partition {
+ let expression = match time.interval {
+ Some(interval) => {
+ format!("time_slice({}, INTERVAL {interval} {})", name(&time.column_id), time.granularity.sql())
+ }
+ None => format!("date_trunc('{}', {})", time.granularity.sql(), name(&time.column_id)),
+ };
+ let extra = if time.additional_column_ids.is_empty() {
+ String::new()
+ } else {
+ format!(", {}", names(&time.additional_column_ids))
+ };
+ return format!(" PARTITION BY {expression}{extra}");
+ }
+ match &settings.partition {
+ None => String::new(),
+ Some(StarRocksPartitionOptions::Values { column_ids }) => format!(" PARTITION BY ({})", names(column_ids)),
+ Some(StarRocksPartitionOptions::Range { column_ids, partitions }) => {
+ let definitions = partitions
+ .iter()
+ .map(|p| format!("PARTITION {} VALUES [({}), ({}))", ident(&p.name), tuple(&p.lower), tuple(&p.upper)))
+ .collect::<Vec<_>>()
+ .join(",\n ");
+ format!(" PARTITION BY RANGE ({}) (\n {definitions}\n)", names(column_ids))
+ }
+ Some(StarRocksPartitionOptions::List { column_ids, partitions }) => {
+ let definitions = partitions
+ .iter()
+ .map(|p| {
+ let values = p
+ .values
+ .iter()
+ .map(
+ |values| if column_ids.len() == 1 { tuple(values) } else { format!("({})", tuple(values)) },
+ )
+ .collect::<Vec<_>>()
+ .join(", ");
+ format!("PARTITION {} VALUES IN ({values})", ident(&p.name))
+ })
+ .collect::<Vec<_>>()
+ .join(",\n ");
+ format!(" PARTITION BY LIST ({}) (\n {definitions}\n)", names(column_ids))
+ }
+ }
+}
diff --git a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs
index 565d1eac19..13b92627df 100644
--- a/crates/dbx-sql-schema/src/table_structure_sql/tests.rs
+++ b/crates/dbx-sql-schema/src/table_structure_sql/tests.rs
@@ -286,6 +286,38 @@ fn sqlite_autoincrement_rejects_composite_primary_keys_and_non_integer_types() {
assert!(result.warnings.iter().any(|w| w.contains("must use an integer type")), "{:?}", result.warnings);
}
+#[test]
+fn starrocks_create_table_preserves_native_column_types() {
+ let types = [
+ "BIGINT",
+ "DATETIME",
+ "LARGEINT",
+ "DECIMAL(18,4)",
+ "ARRAY<INT>",
+ "MAP<INT, INT>",
+ "STRUCT<name VARCHAR(64), amount DECIMAL(18,2)>",
+ ];
+ let columns = types
+ .iter()
+ .enumerate()
+ .map(|(index, data_type)| {
+ let mut col = column(&format!("c{index}"));
+ col.data_type = data_type.to_string();
+ col
+ })
+ .collect();
+ let mut options = structure_change_options(DatabaseType::StarRocks, None, "test2", columns);
+ options.table_comment = Some("test".to_string());
+ let result = build_create_table_sql(options);
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements.len(), 1);
+ for (index, data_type) in types.iter().enumerate() {
+ assert!(result.statements[0].contains(&format!("`c{index}` {data_type}")), "{}", result.statements[0]);
+ }
+ assert!(!result.statements[0].to_lowercase().contains("unsigned"));
+ assert!(!result.statements[0].to_lowercase().contains("timestamp"));
+}
+
#[test]
fn mysql_create_table_includes_engine_before_comment() {
let mut options = structure_change_options(DatabaseType::Mysql, Some("dbx_test"), "archive", vec![column("id")]);
@@ -5859,7 +5891,7 @@ fn mysql_compatible_database_keeps_existing_primary_key_statement_sequence() {
id.extra = Some(ColumnExtra { auto_increment: Some(true), ..Default::default() });
let result = build_table_structure_change_sql(structure_change_options(
- DatabaseType::StarRocks,
+ DatabaseType::Goldendb,
None,
"users",
vec![old_pk, id],
@@ -10889,6 +10921,977 @@ fn create_partitioned_table_is_supported_for_kingbase() {
assert!(result.statements[0].ends_with(") PARTITION BY LIST (\"region\");"), "{}", result.statements[0]);
}
+#[test]
+fn starrocks_35_create_primary_key_uses_native_clauses() {
+ let mut id = column("id");
+ id.data_type = "bigint(20)".into();
+ id.is_primary_key = true;
+ let mut options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![id, column("value")]);
+ options.table_comment = Some("owner's events".into());
+ let result = build_create_table_sql_for_version(options.clone(), Some("3.5.0 abc123"));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec!["CREATE TABLE `events` (\n `id` bigint(20) NOT NULL,\n `value` varchar(255)\n) PRIMARY KEY (`id`) COMMENT 'owner''s events' DISTRIBUTED BY HASH (`id`);"]);
+ options.database_type = Some(DatabaseType::Mysql);
+ options.driver_profile = Some("starrocks".into());
+ assert_eq!(build_create_table_sql_for_version(options.clone(), Some("3.5.0")).statements, result.statements);
+ options.driver_profile = None;
+ let mysql = build_create_table_sql_for_version(options, Some("8.0.0"));
+ assert!(mysql.warnings.is_empty());
+ assert!(mysql.statements[0].contains(",\n PRIMARY KEY (`id`)\n) COMMENT ="));
+ assert!(!mysql.statements[0].contains("DISTRIBUTED"));
+}
+
+#[test]
+fn starrocks_distribution_uses_server_version() {
+ let options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![column("id")]);
+ for (version, suffix) in [
+ (None, "HASH (`id`) BUCKETS 10;"),
+ (Some("5.1.0"), "HASH (`id`) BUCKETS 10;"),
+ (Some("2.5.6"), "HASH (`id`) BUCKETS 10;"),
+ (Some("2.5.7"), "HASH (`id`);"),
+ (Some("3.0.0"), "HASH (`id`);"),
+ (Some("StarRocks version 3.5.0"), "RANDOM;"),
+ ] {
+ let result = build_create_table_sql_for_version(options.clone(), version);
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].ends_with(suffix), "{}", result.statements[0]);
+ }
+}
+
+#[test]
+fn starrocks_places_primary_keys_before_value_columns() {
+ let mut id = column("id");
+ id.is_primary_key = true;
+ let options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![column("value"), id]);
+ let result = build_create_table_sql_for_version(options, Some("3.5.0"));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ let sql = &result.statements[0];
+ assert!(sql.find("`id` varchar").unwrap() < sql.find("`value` varchar").unwrap());
+ assert!(sql.contains(") PRIMARY KEY (`id`)"));
+}
+
+fn starrocks_layout_options(granularity: StarRocksTimeGranularity) -> CreateTableDialectOptions {
+ CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions {
+ partition: None,
+ time_partition: Some(StarRocksTimePartition {
+ column_id: "ts".into(),
+ granularity,
+ interval: None,
+ additional_column_ids: vec![],
+ }),
+ distribution: StarRocksDistribution::Hash,
+ distribution_column_ids: vec!["id".into()],
+ sort_column_ids: vec![],
+ bucket_count: Some(8),
+ }),
+ }
+}
+
+fn starrocks_partitioned_table_options() -> TableStructureSqlOptions {
+ let mut id = column("id");
+ id.data_type = "bigint".into();
+ id.is_primary_key = true;
+ let mut ts = column("ts");
+ ts.data_type = "datetime".into();
+ ts.is_primary_key = true;
+ let mut options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![id, ts]);
+ options.table_comment = Some("events".into());
+ options
+}
+
+#[test]
+fn starrocks_time_partition_preserves_clause_order_and_column_identity() {
+ for (granularity, unit) in [
+ (StarRocksTimeGranularity::Year, "year"),
+ (StarRocksTimeGranularity::Month, "month"),
+ (StarRocksTimeGranularity::Day, "day"),
+ ] {
+ let mut options = starrocks_partitioned_table_options();
+ // Column ID stays stable through a rename, including quoted identifiers.
+ options.columns[1].name = "event`time".into();
+ let result =
+ build_create_table_sql_with_dialect_options(options, Some("3.5.0"), starrocks_layout_options(granularity));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements.len(), 1);
+ assert!(result.statements[0].ends_with(&format!(") PRIMARY KEY (`id`, `event``time`) COMMENT 'events' PARTITION BY date_trunc('{unit}', `event``time`) DISTRIBUTED BY HASH (`id`) BUCKETS 8;")), "{}", result.statements[0]);
+ }
+}
+
+#[test]
+fn starrocks_rejects_invalid_partition_columns_and_versions() {
+ let settings = starrocks_layout_options(StarRocksTimeGranularity::Month);
+ for version in [None, Some("5.1.0"), Some("3.0.0")] {
+ let result = build_create_table_sql_with_dialect_options(
+ starrocks_partitioned_table_options(),
+ version,
+ settings.clone(),
+ );
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.iter().any(|warning| warning.contains("confirmed server version")));
+ }
+ for change in ["drop", "type", "primary"] {
+ let mut options = starrocks_partitioned_table_options();
+ match change {
+ "drop" => options.columns[1].marked_for_drop = true,
+ "type" => options.columns[1].data_type = "varchar(255)".into(),
+ _ => options.columns[1].is_primary_key = false,
+ }
+ let result = build_create_table_sql_with_dialect_options(options, Some("3.5.0"), settings.clone());
+ assert!(result.statements.is_empty(), "{change}");
+ assert!(!result.warnings.is_empty());
+ }
+}
+
+#[test]
+fn starrocks_validates_hash_keys_and_bucket_count() {
+ for case in ["missing", "empty", "duplicate", "type", "primary", "zero", "overflow"] {
+ let mut options = starrocks_partitioned_table_options();
+ let mut settings = starrocks_layout_options(StarRocksTimeGranularity::Day);
+ let sr = settings.starrocks.as_mut().unwrap();
+ sr.time_partition = None;
+ match case {
+ "missing" => sr.distribution_column_ids = vec!["removed".into()],
+ "empty" => sr.distribution_column_ids.clear(),
+ "duplicate" => sr.distribution_column_ids = vec!["id".into(), "id".into()],
+ "type" => options.columns[0].data_type = "json".into(),
+ "primary" => {
+ options.columns[1].is_primary_key = false;
+ sr.distribution_column_ids = vec!["ts".into()];
+ }
+ "zero" => sr.bucket_count = Some(0),
+ _ => sr.bucket_count = Some(u32::MAX),
+ }
+ let result = build_create_table_sql_with_dialect_options(options, Some("3.5.0"), settings);
+ assert!(result.statements.is_empty(), "{case}");
+ assert!(!result.warnings.is_empty());
+ }
+}
+
+#[test]
+fn starrocks_random_distribution_requires_duplicate_table_and_supported_version() {
+ let settings = CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions { distribution: StarRocksDistribution::Random, ..Default::default() }),
+ };
+ let mut options = starrocks_partitioned_table_options();
+ assert!(build_create_table_sql_with_dialect_options(options.clone(), Some("3.5.0"), settings.clone())
+ .statements
+ .is_empty());
+ for column in &mut options.columns {
+ column.is_primary_key = false;
+ }
+ assert!(build_create_table_sql_with_dialect_options(options.clone(), Some("3.0.0"), settings.clone())
+ .statements
+ .is_empty());
+ let result = build_create_table_sql_with_dialect_options(options, Some("3.5.0"), settings);
+ assert!(result.warnings.is_empty());
+ assert!(result.statements[0].ends_with("DISTRIBUTED BY RANDOM;"));
+}
+
+#[test]
+fn starrocks_settings_cannot_leak_into_mysql() {
+ let mut options = starrocks_partitioned_table_options();
+ options.database_type = Some(DatabaseType::Mysql);
+ let result = build_create_table_sql_with_dialect_options(
+ options,
+ Some("8.0"),
+ starrocks_layout_options(StarRocksTimeGranularity::Month),
+ );
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.iter().any(|warning| warning.contains("require a StarRocks connection")));
+}
+
+#[test]
+fn starrocks_builds_multicolumn_value_and_list_partitions() {
+ let options =
+ structure_change_options(DatabaseType::StarRocks, None, "events", vec![column("city"), column("channel")]);
+ let values = CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions {
+ partition: Some(StarRocksPartitionOptions::Values { column_ids: vec!["city".into(), "channel".into()] }),
+ ..Default::default()
+ }),
+ };
+ let result = build_create_table_sql_with_dialect_options(options.clone(), Some("3.5.0"), values);
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].contains("PARTITION BY (`city`, `channel`) DISTRIBUTED BY RANDOM"));
+ let list = CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions {
+ partition: Some(StarRocksPartitionOptions::List {
+ column_ids: vec!["city".into(), "channel".into()],
+ partitions: vec![StarRocksListPartition {
+ name: "p`east".into(),
+ values: vec![vec!["Xi'an".into(), "web".into()], vec!["Shanghai".into(), "store".into()]],
+ }],
+ }),
+ ..Default::default()
+ }),
+ };
+ let result = build_create_table_sql_with_dialect_options(options, Some("3.5.0"), list);
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].contains("PARTITION BY LIST (`city`, `channel`) (\n PARTITION `p``east` VALUES IN (('Xi''an', 'web'), ('Shanghai', 'store'))\n)"));
+}
+
+#[test]
+fn starrocks_builds_range_bounds_and_validates_arity() {
+ let mut options = starrocks_partitioned_table_options();
+ // Intentionally interleaved primary and value columns: SQL reorders without changing membership.
+ options.columns.insert(1, column("payload"));
+ let settings = CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions {
+ partition: Some(StarRocksPartitionOptions::Range {
+ column_ids: vec!["ts".into(), "id".into()],
+ partitions: vec![StarRocksRangePartition {
+ name: "p2026".into(),
+ lower: vec!["2026-01-01".into(), "0".into()],
+ upper: vec!["2027-01-01".into(), "0".into()],
+ }],
+ }),
+ ..Default::default()
+ }),
+ };
+ let result = build_create_table_sql_with_dialect_options(options.clone(), Some("3.5.0"), settings.clone());
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].contains(
+ "PARTITION BY RANGE (`ts`, `id`) (\n PARTITION `p2026` VALUES [('2026-01-01', '0'), ('2027-01-01', '0'))\n)"
+ ));
+ assert!(
+ result.statements[0].find("`ts` datetime").unwrap() < result.statements[0].find("`payload` varchar").unwrap()
+ );
+ let mut invalid = settings;
+ if let Some(StarRocksPartitionOptions::Range { partitions, .. }) =
+ invalid.starrocks.as_mut().unwrap().partition.as_mut()
+ {
+ partitions[0].upper.pop();
+ }
+ assert!(build_create_table_sql_with_dialect_options(options, Some("3.5.0"), invalid).statements.is_empty());
+}
+
+#[test]
+fn starrocks_time_slice_and_mixed_partitions_are_version_and_type_checked() {
+ let options = starrocks_partitioned_table_options();
+ let mut settings = starrocks_layout_options(StarRocksTimeGranularity::Day);
+ let time = settings.starrocks.as_mut().unwrap().time_partition.as_mut().unwrap();
+ time.interval = Some(7);
+ time.additional_column_ids = vec!["id".into()];
+ let result = build_create_table_sql_with_dialect_options(options.clone(), Some("3.5.0"), settings.clone());
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].contains("PARTITION BY time_slice(`ts`, INTERVAL 7 day), `id` DISTRIBUTED"));
+ assert!(build_create_table_sql_with_dialect_options(options.clone(), Some("3.3.0"), settings.clone())
+ .statements
+ .is_empty());
+ let mut invalid = options;
+ invalid.columns[1].data_type = "date".into();
+ assert!(build_create_table_sql_with_dialect_options(invalid, Some("3.5.0"), settings).statements.is_empty());
+}
+
+#[test]
+fn starrocks_rejects_duplicate_list_values_and_incompatible_partition_types() {
+ let options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![column("city")]);
+ let list = CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions {
+ partition: Some(StarRocksPartitionOptions::List {
+ column_ids: vec!["city".into()],
+ partitions: vec![StarRocksListPartition {
+ name: "p1".into(),
+ values: vec![vec!["Beijing".into()], vec!["Beijing".into()]],
+ }],
+ }),
+ ..Default::default()
+ }),
+ };
+ assert!(build_create_table_sql_with_dialect_options(options.clone(), Some("3.5.0"), list).statements.is_empty());
+ let range = CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions {
+ partition: Some(StarRocksPartitionOptions::Range {
+ column_ids: vec!["city".into()],
+ partitions: vec![StarRocksRangePartition {
+ name: "p1".into(),
+ lower: vec!["a".into()],
+ upper: vec!["z".into()],
+ }],
+ }),
+ ..Default::default()
+ }),
+ };
+ assert!(build_create_table_sql_with_dialect_options(options, Some("3.5.0"), range).statements.is_empty());
+}
+
+#[test]
+fn starrocks_sort_columns_preserve_priority_and_allow_non_primary_columns() {
+ let mut options = starrocks_partitioned_table_options();
+ options.columns[1].is_primary_key = false;
+ options.columns[1].name = "event`time".into();
+ let settings = CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions {
+ sort_column_ids: vec!["ts".into(), "id".into()],
+ ..Default::default()
+ }),
+ };
+ let result = build_create_table_sql_with_dialect_options(options, Some("3.5.0"), settings);
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].ends_with("DISTRIBUTED BY HASH (`id`) ORDER BY (`event``time`, `id`);"));
+}
+
+#[test]
+fn starrocks_sort_validates_version_identity_and_primary_table_types() {
+ for case in ["old", "unknown", "missing", "duplicate", "type", "dropped"] {
+ let mut options = starrocks_partitioned_table_options();
+ let mut ids = vec!["ts".into()];
+ let version = match case {
+ "old" => Some("2.5.0"),
+ "unknown" => None,
+ _ => Some("3.5.0"),
+ };
+ match case {
+ "missing" => ids = vec!["missing".into()],
+ "duplicate" => ids.push("ts".into()),
+ "type" => {
+ options.columns[1].is_primary_key = false;
+ options.columns[1].data_type = "decimal(10,2)".into();
+ }
+ "dropped" => options.columns[1].marked_for_drop = true,
+ _ => {}
+ }
+ let settings = CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions { sort_column_ids: ids, ..Default::default() }),
+ };
+ let result = build_create_table_sql_with_dialect_options(options, version, settings);
+ assert!(result.statements.is_empty(), "{case}");
+ assert!(!result.warnings.is_empty(), "{case}");
+ }
+}
+
+#[test]
+fn starrocks_duplicate_sort_requires_33_and_allows_decimal() {
+ let mut options = starrocks_partitioned_table_options();
+ for column in &mut options.columns {
+ column.is_primary_key = false;
+ }
+ options.columns[1].data_type = "decimal(10,2)".into();
+ let settings = CreateTableDialectOptions {
+ starrocks: Some(StarRocksCreateOptions { sort_column_ids: vec!["ts".into()], ..Default::default() }),
+ };
+ let old = build_create_table_sql_with_dialect_options(options.clone(), Some("3.2.0"), settings.clone());
+ assert!(old.statements.is_empty());
+ let result = build_create_table_sql_with_dialect_options(options, Some("3.5.0"), settings);
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].ends_with("DISTRIBUTED BY RANDOM ORDER BY (`ts`);"));
+}
+
+#[test]
+fn starrocks_default_presets_keep_literals_and_function_expressions() {
+ for (data_type, default_value) in [
+ ("int", "'0'"),
+ ("decimal(10,2)", "'1'"),
+ ("boolean", "'false'"),
+ ("date", "1970-01-01"),
+ ("datetime", "CURRENT_TIMESTAMP"),
+ ("varchar(36)", "(uuid())"),
+ ("largeint", "(uuid_numeric())"),
+ ("varchar(20)", "''"),
+ ] {
+ let mut options = starrocks_partitioned_table_options();
+ options.columns[1].is_primary_key = false;
+ options.columns[1].data_type = data_type.into();
+ options.columns[1].default_value = default_value.into();
+ let result = build_create_table_sql_for_version(options, Some("3.5.0"));
+ assert!(result.warnings.is_empty(), "{data_type}: {:?}", result.warnings);
+ let expected = if data_type == "date" { format!("'{default_value}'") } else { default_value.into() };
+ assert!(result.statements[0].contains(&format!("DEFAULT {expected}")), "{data_type}: {}", result.statements[0]);
+ }
+}
+
+fn starrocks_alter_context() -> StarRocksAlterOptions {
+ StarRocksAlterOptions {
+ server_version: Some("3.5.0".into()),
+ model: Some("primary".into()),
+ key_columns: vec!["id".into()],
+ distribution_columns: vec!["id".into()],
+ ..Default::default()
+ }
+}
+
+#[test]
+fn starrocks_alter_combines_schema_changes_after_native_rename_and_comments() {
+ let mut value = existing_pk_column("value", "varchar(100)", false, false);
+ value.name = "new`value".into();
+ value.comment = "new comment".into();
+ value.default_value = "hello".into();
+ value.original.as_mut().unwrap().column_default = Some("hello".into());
+ value.original.as_mut().unwrap().data_type = "varchar(50)".into();
+ let mut added = column("more");
+ added.data_type = "int".into();
+ let mut options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![value, added]);
+ options.table_comment = Some("table comment".into());
+ let result = build_table_structure_change_sql_with_context(options, Some(starrocks_alter_context()));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements.len(), 3);
+ assert_eq!(result.statements[0], "ALTER TABLE `events` RENAME COLUMN `value` TO `new``value`;");
+ assert!(result.statements[1].contains("COMMENT = 'table comment'"));
+ assert!(result.statements[2].contains("MODIFY COLUMN `new``value` varchar(100) NOT NULL DEFAULT 'hello' COMMENT 'new comment', ADD COLUMN `more` int NULL COMMENT '';"));
+ assert!(!result.statements.join(" ").contains("CHANGE COLUMN"));
+}
+
+#[test]
+fn starrocks_alter_rejects_existing_default_changes_without_partial_sql() {
+ for (data_type, original_default, new_default) in [
+ ("decimal(7, 0)", None, "'0'"),
+ ("decimal(7, 0)", Some("'0'"), "'1'"),
+ ("datetime", None, "CURRENT_TIMESTAMP"),
+ ("datetime", Some("CURRENT_TIMESTAMP"), ""),
+ ] {
+ let mut value = existing_pk_column("value", data_type, false, false);
+ value.original.as_mut().unwrap().column_default = original_default.map(String::from);
+ value.default_value = new_default.into();
+ value.comment = "also changed".into();
+ let mut options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![value]);
+ options.table_comment = Some("must not partially execute".into());
+ let result = build_table_structure_change_sql_with_context(options, Some(starrocks_alter_context()));
+ assert!(result.statements.is_empty(), "{data_type}: {:?}", result.statements);
+ assert!(
+ result.warnings.iter().any(|warning| warning.contains("cannot change the default value")),
+ "{:?}",
+ result.warnings
+ );
+ }
+}
+
+#[test]
+fn starrocks_alter_preserves_existing_defaults_during_other_changes() {
+ for (data_type, default_value) in [("decimal(7, 0)", "'0'"), ("datetime", "CURRENT_TIMESTAMP")] {
+ let mut value = existing_pk_column("value", data_type, false, false);
+ value.original.as_mut().unwrap().column_default = Some(default_value.into());
+ value.default_value = default_value.into();
+ value.is_nullable = true;
+ let options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![value]);
+ let result = build_table_structure_change_sql_with_context(options, Some(starrocks_alter_context()));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert!(result.statements[0].contains(&format!("NULL DEFAULT {default_value}")), "{:?}", result.statements);
+ }
+}
+
+#[test]
+fn starrocks_add_column_rejects_uuid_generators_without_partial_sql() {
+ for default_value in ["(uuid())", "uuid()", " ( UUID ( ) ) ", "(uuid_numeric())", "((UUID_NUMERIC()))"] {
+ let mut value = column("dad");
+ value.data_type =
+ if default_value.to_ascii_lowercase().contains("numeric") { "largeint" } else { "varchar(255)" }.into();
+ value.default_value = default_value.into();
+ let mut options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![value]);
+ options.table_comment = Some("must not partially execute".into());
+ let result = build_table_structure_change_sql_with_context(options, Some(starrocks_alter_context()));
+ assert!(result.statements.is_empty(), "{default_value}: {:?}", result.statements);
+ assert!(
+ result.warnings.iter().any(|warning| warning.contains("does not support uuid()")),
+ "{:?}",
+ result.warnings
+ );
+ }
+}
+
+#[test]
+fn starrocks_add_column_keeps_type_specific_defaults() {
+ for (data_type, default_value) in [
+ ("decimal(7, 0)", "'0'"),
+ ("datetime", "CURRENT_TIMESTAMP"),
+ ("varchar(255)", "'uuid()'"),
+ ("varchar(255)", "NULL"),
+ ] {
+ let mut value = column("value");
+ value.data_type = data_type.into();
+ value.default_value = default_value.into();
+ let options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![value]);
+ let result = build_table_structure_change_sql_with_context(options, Some(starrocks_alter_context()));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ let expected_default =
+ if default_value == "NULL" { String::new() } else { format!(" DEFAULT {default_value}") };
+ assert!(
+ result.statements[0].contains(&format!("ADD COLUMN `value` {data_type} NULL{expected_default} COMMENT")),
+ "{:?}",
+ result.statements
+ );
+ }
+}
+
+#[test]
+fn starrocks_alter_comment_only_does_not_redefine_primary_column() {
+ let mut key = existing_pk_column("id", "bigint", true, true);
+ key.comment = "owner's id".into();
+ let mut options = structure_change_options(DatabaseType::Mysql, None, "events", vec![key]);
+ options.driver_profile = Some("starrocks".into());
+ let result = build_table_structure_change_sql_with_context(options, Some(starrocks_alter_context()));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec!["ALTER TABLE `events` MODIFY COLUMN `id` COMMENT 'owner''s id';"]);
+}
+
+#[test]
+fn starrocks_alter_rejects_unsupported_changes_without_partial_plan() {
+ for case in ["primary", "nullable", "missing", "aggregate", "old_rename", "partition", "drop"] {
+ let mut value = existing_pk_column("value", "int", false, false);
+ let mut context = starrocks_alter_context();
+ match case {
+ "primary" => value.is_primary_key = true,
+ "nullable" => value.original.as_mut().unwrap().is_nullable = true,
+ "missing" => {
+ context.model = None;
+ value.default_value = "0".into();
+ }
+ "aggregate" => {
+ context.model = Some("aggregate".into());
+ value.data_type = "bigint".into();
+ }
+ "old_rename" => {
+ context.server_version = Some("3.3.1".into());
+ value.name = "renamed".into();
+ }
+ "partition" => {
+ context.partition_columns.push("value".into());
+ value.data_type = "bigint".into();
+ }
+ "drop" => {
+ context.distribution_columns.push("value".into());
+ value.marked_for_drop = true;
+ }
+ _ => {}
+ }
+ let mut options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![value]);
+ options.table_comment = Some("would otherwise succeed".into());
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.statements.is_empty(), "{case}: {:?}", result.statements);
+ assert!(!result.warnings.is_empty(), "{case}");
+ }
+}
+
+#[test]
+fn starrocks_duplicate_key_alter_preserves_key_and_allows_not_null_to_null() {
+ let mut value = existing_pk_column("key1", "varchar(100)", false, false);
+ value.data_type = "varchar(200)".into();
+ value.is_nullable = true;
+ let mut context = starrocks_alter_context();
+ context.model = Some("duplicate".into());
+ context.key_columns = vec!["key1".into()];
+ let result = build_table_structure_change_sql_with_context(
+ structure_change_options(DatabaseType::StarRocks, None, "events", vec![value]),
+ Some(context),
+ );
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec!["ALTER TABLE `events` MODIFY COLUMN `key1` varchar(200) KEY NULL COMMENT '';"]);
+}
+
+#[test]
+fn starrocks_existing_layout_changes_use_native_sql_and_quote_values() {
+ let options = structure_change_options(
+ DatabaseType::StarRocks,
+ None,
+ "events",
+ vec![existing_pk_column("id", "bigint", true, true)],
+ );
+ let context: StarRocksAlterOptions = serde_json::from_value(serde_json::json!({
+ "serverVersion": "3.5.0", "model": "duplicate", "keyColumns": ["id"],
+ "layout": { "distribution": { "method": "hash", "columns": ["id"], "buckets": 12 } }
+ }))
+ .unwrap();
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec!["ALTER TABLE `events` DISTRIBUTED BY HASH(`id`) BUCKETS 12;"]);
+ let options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![]);
+ let context: StarRocksAlterOptions = serde_json::from_value(serde_json::json!({
+ "serverVersion": "3.5.0", "model": "duplicate", "partitionKind": "list", "partitionColumns": ["city", "channel"],
+ "layout": { "partitions": [{ "kind": "addList", "name": "p`new", "values": [["O'Brien", "app"]] }, { "kind": "replicas", "name": "*", "replicas": 2 }] }
+ })).unwrap();
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `events` ADD PARTITION `p``new` VALUES IN (('O''Brien', 'app'));",
+ "ALTER TABLE `events` MODIFY PARTITION (*) SET (\"replication_num\" = \"2\");"
+ ]
+ );
+}
+
+#[test]
+fn starrocks_layout_blocks_conflicting_jobs_invalid_buckets_and_model() {
+ for (version, model, buckets, edited, colocated) in [
+ ("3.1.9", "duplicate", 8, false, false),
+ ("3.5.0", "primary", 8, false, false),
+ ("3.5.0", "duplicate", 0, false, false),
+ ("3.5.0", "duplicate", 8, true, false),
+ ("3.5.0", "duplicate", 8, false, true),
+ ] {
+ let mut column = existing_pk_column("value", "varchar(20)", false, false);
+ if edited {
+ column.name = "new_value".into();
+ }
+ let options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![column]);
+ let context: StarRocksAlterOptions = serde_json::from_value(serde_json::json!({
+ "serverVersion": version, "model": model, "colocated": colocated,
+ "layout": { "distribution": { "method": "random", "buckets": buckets } }
+ }))
+ .unwrap();
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(!result.warnings.is_empty(), "{version} {model}");
+ assert!(result.statements.is_empty());
+ }
+}
+
+#[test]
+fn starrocks_default_buckets_are_patch_version_gated() {
+ for (version, supported) in [("3.5.7", false), ("3.5.8", true), ("4.0.0", false), ("4.0.1", true)] {
+ let options = structure_change_options(
+ DatabaseType::StarRocks,
+ None,
+ "events",
+ vec![existing_pk_column("id", "bigint", true, true)],
+ );
+ let context: StarRocksAlterOptions = serde_json::from_value(serde_json::json!({
+ "serverVersion": version, "model": "primary", "keyColumns": ["id"],
+ "distribution": { "method": "hash", "columns": ["id"], "buckets": 8 },
+ "layout": { "distribution": { "method": "hash", "columns": ["id"], "buckets": 12, "defaultOnly": true } }
+ }))
+ .unwrap();
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert_eq!(result.warnings.is_empty(), supported, "{version} {:?}", result.warnings);
+ if supported {
+ assert_eq!(result.statements, vec!["ALTER TABLE `events` DISTRIBUTED BY HASH(`id`) DEFAULT BUCKETS 12;"]);
+ }
+ }
+}
+
+#[test]
+fn starrocks_manual_range_and_partition_drop_sql() {
+ let options = structure_change_options(DatabaseType::StarRocks, None, "events", vec![]);
+ let context: StarRocksAlterOptions = serde_json::from_value(serde_json::json!({
+ "serverVersion": "3.5.0", "model": "duplicate", "partitionKind": "range", "partitionColumns": ["dt"],
+ "layout": { "partitions": [{ "kind": "addRange", "name": "p2", "lower": ["2026-01-01"], "upper": ["2026-02-01"] }, { "kind": "drop", "name": "p1" }] }
+ })).unwrap();
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `events` ADD PARTITION `p2` VALUES [('2026-01-01'), ('2026-02-01'));",
+ "ALTER TABLE `events` DROP PARTITION `p1`;"
+ ]
+ );
+}
+
+#[test]
+fn starrocks_automatic_bucket_scaling_blocks_distribution_but_not_partition_management() {
+ let options = structure_change_options(
+ DatabaseType::StarRocks,
+ None,
+ "events",
+ vec![existing_pk_column("id", "bigint", false, false)],
+ );
+ let mut context: StarRocksAlterOptions = serde_json::from_value(serde_json::json!({
+ "serverVersion": "3.5.0", "model": "duplicate", "automaticBucketScaling": true,
+ "layout": { "distribution": { "method": "hash", "columns": ["id"], "buckets": 16 } }
+ }))
+ .unwrap();
+ let result = build_table_structure_change_sql_with_context(options.clone(), Some(context.clone()));
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.iter().any(|warning| warning.contains("automatic bucket scaling")));
+ context.layout = Some(
+ serde_json::from_value(
+ serde_json::json!({ "partitions": [{ "kind": "replicas", "name": "*", "replicas": 2 }] }),
+ )
+ .unwrap(),
+ );
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec!["ALTER TABLE `events` MODIFY PARTITION (*) SET (\"replication_num\" = \"2\");"]);
+}
+
+fn starrocks_reorder_fixture() -> (TableStructureSqlOptions, StarRocksAlterOptions) {
+ let mut columns = vec![
+ existing_pk_column("id", "bigint", false, false),
+ existing_pk_column("price", "decimal(7, 0)", false, false),
+ existing_pk_column("name", "varchar(500)", false, false),
+ ];
+ for (index, column) in columns.iter_mut().enumerate() {
+ column.original_position = Some(index);
+ }
+ columns.swap(1, 2);
+ let options = structure_change_options(DatabaseType::StarRocks, None, "test4", columns);
+ let context = StarRocksAlterOptions {
+ server_version: Some("3.5.0".into()),
+ model: Some("duplicate".into()),
+ key_columns: vec!["id".into()],
+ column_names: vec!["id".into(), "price".into(), "name".into()],
+ position_column_order: true,
+ ..Default::default()
+ };
+ (options, context)
+}
+
+#[test]
+fn starrocks_reorders_values_with_position_clauses_not_sort_keys() {
+ let (options, context) = starrocks_reorder_fixture();
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(
+ result.statements,
+ vec!["ALTER TABLE `test4` MODIFY COLUMN `name` varchar(500) NOT NULL COMMENT '' AFTER `id`;"]
+ );
+ assert!(result.statements.iter().all(|sql| !sql.contains("ORDER BY")));
+}
+
+#[test]
+fn starrocks_reorder_guards_complete_schema_primary_keys_and_combined_add_drop() {
+ for case in ["primary", "missing_column", "missing_position", "add", "drop"] {
+ let (mut options, mut context) = starrocks_reorder_fixture();
+ if matches!(case, "missing_column" | "drop") {
+ let mut extra = existing_pk_column("extra", "int", false, false);
+ extra.original_position = Some(3);
+ options.columns.push(extra);
+ context.column_names.push("extra".into());
+ }
+ match case {
+ "primary" => context.model = Some("primary".into()),
+ "missing_column" => {
+ options.columns.pop();
+ }
+ "missing_position" => options.columns[1].original_position = None,
+ "add" => options.columns.push(column("more")),
+ "drop" => options.columns.last_mut().unwrap().marked_for_drop = true,
+ _ => unreachable!(),
+ }
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.statements.is_empty(), "{case} {:?}", result.statements);
+ assert!(!result.warnings.is_empty(), "{case}");
+ }
+}
+
+#[test]
+fn starrocks_reorders_partition_keys_preserving_key_identity_and_sort_keys() {
+ let mut day = existing_pk_column("day", "datetime", false, false);
+ day.is_nullable = true;
+ day.original.as_mut().unwrap().is_nullable = true;
+ day.original_position = Some(0);
+ let mut id = existing_pk_column("id", "varchar(255)", false, false);
+ id.original_position = Some(1);
+ let mut name = existing_pk_column("name", "varchar(500)", false, false);
+ name.is_nullable = true;
+ name.original.as_mut().unwrap().is_nullable = true;
+ name.original_position = Some(2);
+ let columns = [day, id, name];
+ let context = StarRocksAlterOptions {
+ server_version: Some("3.5.0".into()),
+ model: Some("duplicate".into()),
+ key_columns: vec!["day".into(), "id".into()],
+ partition_columns: vec!["day".into(), "id".into()],
+ column_names: vec!["day".into(), "id".into(), "name".into()],
+ sort_columns: Some(vec!["id".into(), "day".into()]),
+ position_column_order: true,
+ ..Default::default()
+ };
+ // Metadata's primary-key flag is false for Duplicate Key tables: use DDL key membership.
+ // Keys may swap positions, but values cannot precede or split the key prefix.
+ let options = structure_change_options(
+ DatabaseType::StarRocks,
+ None,
+ "test4",
+ [1, 0, 2].map(|index| columns[index].clone()).to_vec(),
+ );
+ let result = build_table_structure_change_sql_with_context(options, Some(context.clone()));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(
+ result.statements,
+ vec!["ALTER TABLE `test4` MODIFY COLUMN `id` varchar(255) KEY NOT NULL COMMENT '' FIRST;"]
+ );
+ for order in [[0, 2, 1], [2, 1, 0], [1, 2, 0]] {
+ let options = structure_change_options(
+ DatabaseType::StarRocks,
+ None,
+ "test4",
+ order.map(|index| columns[index].clone()).to_vec(),
+ );
+ let result = build_table_structure_change_sql_with_context(options, Some(context.clone()));
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.iter().any(|warning| warning.contains("must precede all value columns")));
+ }
+}
+
+#[test]
+fn starrocks_reorders_around_generated_partition_sources_in_both_directions() {
+ let mut day = existing_pk_column("day", "datetime", false, false);
+ day.is_nullable = true;
+ day.original.as_mut().unwrap().is_nullable = true;
+ let id = existing_pk_column("id", "varchar(255)", false, false);
+ let name = existing_pk_column("name", "varchar(500)", false, false);
+ for day_first in [false, true] {
+ let mut columns = if day_first {
+ vec![day.clone(), id.clone(), name.clone()]
+ } else {
+ vec![id.clone(), day.clone(), name.clone()]
+ };
+ for (index, column) in columns.iter_mut().enumerate() {
+ column.original_position = Some(index);
+ }
+ let names: Vec<_> = columns.iter().map(|column| column.name.clone()).collect();
+ let context = StarRocksAlterOptions {
+ server_version: Some("3.5.0".into()),
+ model: Some("duplicate".into()),
+ key_columns: names[..2].to_vec(),
+ partition_columns: vec!["day".into(), "id".into()],
+ partition_expression_columns: vec!["DAY".into()],
+ column_names: names,
+ sort_columns: Some(vec!["id".into(), "day".into()]),
+ position_column_order: true,
+ ..Default::default()
+ };
+ columns.swap(0, 1);
+ let options = structure_change_options(DatabaseType::StarRocks, None, "test4", columns);
+ let result = build_table_structure_change_sql_with_context(options.clone(), Some(context.clone()));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ let placement = if day_first { "FIRST" } else { "AFTER `day`" };
+ assert_eq!(
+ result.statements,
+ vec![format!("ALTER TABLE `test4` MODIFY COLUMN `id` varchar(255) KEY NOT NULL COMMENT '' {placement};")]
+ );
+
+ let mut blocked = context;
+ blocked.partition_expression_columns.push("id".into());
+ let result = build_table_structure_change_sql_with_context(options, Some(blocked));
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.iter().any(|warning| warning.contains("partition-expression source")));
+ }
+}
+
+#[test]
+fn starrocks_reorder_preserves_renames_but_blocks_definition_changes() {
+ let (mut options, context) = starrocks_reorder_fixture();
+ options.columns[1].name = "new`name".into();
+ let result = build_table_structure_change_sql_with_context(options.clone(), Some(context.clone()));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(
+ result.statements,
+ vec![
+ "ALTER TABLE `test4` RENAME COLUMN `name` TO `new``name`;",
+ "ALTER TABLE `test4` MODIFY COLUMN `new``name` varchar(500) NOT NULL COMMENT '' AFTER `id`;"
+ ]
+ );
+ options.columns[1].data_type = "varchar(600)".into();
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.iter().any(|warning| warning.contains("separately")));
+}
+
+#[test]
+fn starrocks_reorder_is_opt_in_and_unchanged_order_is_clean() {
+ let (options, mut context) = starrocks_reorder_fixture();
+ context.position_column_order = false;
+ let result = build_table_structure_change_sql_with_context(options.clone(), Some(context.clone()));
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.is_empty());
+ context.position_column_order = true;
+ let mut options = options;
+ options.columns.sort_by_key(|column| column.original_position);
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.is_empty());
+}
+
+#[test]
+fn starrocks_position_moves_preserve_protected_anchors_and_column_definitions() {
+ let names = ["id", "x", "bucket", "y", "z"];
+ let mut columns: Vec<_> = names
+ .iter()
+ .enumerate()
+ .map(|(index, name)| {
+ let mut column = existing_pk_column(name, "varchar(500)", false, false);
+ column.original_position = Some(index);
+ column
+ })
+ .collect();
+ let desired = [0, 4, 2, 3, 1].map(|index| columns[index].clone()).to_vec();
+ let options = structure_change_options(DatabaseType::StarRocks, None, "t", desired);
+ let context = StarRocksAlterOptions {
+ model: Some("duplicate".into()),
+ key_columns: vec!["id".into()],
+ distribution_columns: vec!["bucket".into()],
+ column_names: names.iter().map(|name| name.to_string()).collect(),
+ position_column_order: true,
+ ..Default::default()
+ };
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec!["ALTER TABLE `t` MODIFY COLUMN `z` varchar(500) NOT NULL COMMENT '' AFTER `id`, MODIFY COLUMN `x` varchar(500) NOT NULL COMMENT '' AFTER `y`;"]);
+ columns.swap(0, 2);
+ let options = structure_change_options(DatabaseType::StarRocks, None, "t", columns);
+ let context = StarRocksAlterOptions {
+ model: Some("duplicate".into()),
+ distribution_columns: vec!["id".into(), "bucket".into()],
+ column_names: names.iter().map(|name| name.to_string()).collect(),
+ position_column_order: true,
+ ..Default::default()
+ };
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.statements.is_empty());
+ assert!(!result.warnings.is_empty());
+}
+
+#[test]
+fn starrocks_legacy_order_by_reordering_is_rejected() {
+ let (options, mut context) = starrocks_reorder_fixture();
+ context.reorder_columns = true;
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.iter().any(|warning| warning.contains("legacy")));
+}
+
+#[test]
+fn starrocks_sort_keys_are_explicit_and_separate_from_column_order() {
+ let (mut options, mut context) = starrocks_reorder_fixture();
+ options.columns.sort_by_key(|column| column.original_position);
+ context.sort_column_names = Some(vec!["id".into(), "name".into()]);
+ let result = build_table_structure_change_sql_with_context(options.clone(), Some(context.clone()));
+ assert!(result.warnings.is_empty(), "{:?}", result.warnings);
+ assert_eq!(result.statements, vec!["ALTER TABLE `test4` ORDER BY (`id`, `name`);"]);
+ options.columns.swap(1, 2);
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.statements.is_empty());
+ assert!(result.warnings.iter().any(|warning| warning.contains("separately")));
+}
+
+#[test]
+fn starrocks_sort_key_validation_guards_models_types_versions_and_full_schema() {
+ for case in ["all", "empty", "repeat", "missing", "old", "primary_decimal", "aggregate_nonkey", "unknown"] {
+ let (mut options, mut context) = starrocks_reorder_fixture();
+ options.columns.sort_by_key(|column| column.original_position);
+ context.position_column_order = false;
+ context.sort_column_names = Some(vec!["id".into(), "name".into()]);
+ match case {
+ "all" => context.sort_column_names = Some(vec!["id".into(), "name".into(), "price".into()]),
+ "empty" => context.sort_column_names = Some(vec![]),
+ "repeat" => context.sort_column_names = Some(vec!["id".into(), "id".into()]),
+ "missing" => context.sort_column_names = Some(vec!["absent".into()]),
+ "old" => context.server_version = Some("3.2.9".into()),
+ "primary_decimal" => {
+ context.model = Some("primary".into());
+ context.sort_column_names = Some(vec!["price".into()]);
+ }
+ "aggregate_nonkey" => context.model = Some("aggregate".into()),
+ "unknown" => context.model = None,
+ _ => unreachable!(),
+ }
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.statements.is_empty(), "{case} {:?}", result.statements);
+ assert!(!result.warnings.is_empty(), "{case}");
+ }
+ for model in ["primary", "aggregate", "unique"] {
+ let (mut options, mut context) = starrocks_reorder_fixture();
+ options.columns.sort_by_key(|column| column.original_position);
+ context.position_column_order = false;
+ context.model = Some(model.into());
+ context.sort_column_names = Some(vec!["id".into()]);
+ let result = build_table_structure_change_sql_with_context(options, Some(context));
+ assert!(result.warnings.is_empty(), "{model} {:?}", result.warnings);
+ assert_eq!(result.statements, vec!["ALTER TABLE `test4` ORDER BY (`id`);"]);
+ }
+}
+
#[test]
fn mysql_literal_default_on_blob_text_json_geometry_is_refused() {
// (data type, default, driver profile, expected DEFAULT clause; None means refused)
diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rs
index 7c85b7a362..a93ef93266 100644
--- a/crates/dbx-web/src/routes/query.rs
+++ b/crates/dbx-web/src/routes/query.rs
@@ -287,7 +287,13 @@ pub struct BuildViewDdlRequest {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildTableStructureSqlRequest {
+ #[serde(default)]
+ pub starrocks: Option<dbx_core::table_structure_sql::StarRocksAlterOptions>,
pub options: dbx_core::table_structure_sql::TableStructureSqlOptions,
+ #[serde(default)]
+ pub server_version: Option<String>,
+ #[serde(default)]
+ pub dialect_options: Option<dbx_core::table_structure_sql::CreateTableDialectOptions>,
}
#[derive(Deserialize)]
@@ -1262,7 +1268,7 @@ pub async fn build_view_ddl_sql(Json(req): Json<BuildViewDdlRequest>) -> Json<St
pub async fn build_table_structure_change_sql(
Json(req): Json<BuildTableStructureSqlRequest>,
) -> Json<dbx_core::table_structure_sql::TableStructureSqlResult> {
- Json(dbx_core::table_structure_sql::build_table_structure_change_sql(req.options))
+ Json(dbx_core::table_structure_sql::build_table_structure_change_sql_with_context(req.options, req.starrocks))
}
pub async fn build_table_owner_change_sql(
@@ -1317,7 +1323,11 @@ pub async fn apply_sqlite_table_structure_change(
pub async fn build_create_table_sql(
Json(req): Json<BuildTableStructureSqlRequest>,
) -> Json<dbx_core::table_structure_sql::TableStructureSqlResult> {
- Json(dbx_core::table_structure_sql::build_create_table_sql(req.options))
+ Json(dbx_core::table_structure_sql::build_create_table_sql_with_dialect_options(
+ req.options,
+ req.server_version.as_deref(),
+ req.dialect_options.unwrap_or_default(),
+ ))
}
pub async fn build_single_column_alter_sql(
diff --git a/scripts/run-check.mjs b/scripts/run-check.mjs
index d820944539..928ac82253 100644
--- a/scripts/run-check.mjs
+++ b/scripts/run-check.mjs
@@ -35,7 +35,7 @@ function runTask(task) {
const command = commandSpec(task);
const child = spawn(command.program, command.args, {
cwd: process.cwd(),
- env: commandEnv(),
+ env: commandEnv(task),
stdio: ["ignore", "pipe", "pipe"],
});
const stdout = [];
@@ -73,11 +73,17 @@ function commandSpec(task) {
return { program: "cmd.exe", args: ["/d", "/c", "call", command, ...task.args] };
}
-function commandEnv() {
- return {
+function commandEnv(task) {
+ const env = {
...process.env,
PATH: [join(process.cwd(), "node_modules", ".bin"), process.env.PATH].filter(Boolean).join(delimiter),
};
+ // vue-tsc's full application graph exceeds Node's default 4 GiB heap.
+ // Keep this allowance scoped to typechecking and respect explicit limits.
+ if (task.name === "typecheck" && !/--max[-_]old[-_]space[-_]size(?:=|\s)/.test(env.NODE_OPTIONS ?? "")) {
+ env.NODE_OPTIONS = [env.NODE_OPTIONS, "--max-old-space-size=8192"].filter(Boolean).join(" ");
+ }
+ return env;
}
function outputFailureExcerpt(output) {
diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rs
index 88cb1f52c6..a370bbedb3 100644
--- a/src-tauri/src/commands/query.rs
+++ b/src-tauri/src/commands/query.rs
@@ -876,8 +876,9 @@ pub fn build_view_ddl_sql(input: dbx_core::object_source_sql::BuildViewDdlInput)
#[tauri::command]
pub fn build_table_structure_change_sql(
options: dbx_core::table_structure_sql::TableStructureSqlOptions,
+ starrocks: Option<dbx_core::table_structure_sql::StarRocksAlterOptions>,
) -> Result<dbx_core::table_structure_sql::TableStructureSqlResult, String> {
- Ok(dbx_core::table_structure_sql::build_table_structure_change_sql(options))
+ Ok(dbx_core::table_structure_sql::build_table_structure_change_sql_with_context(options, starrocks))
}
#[tauri::command]
@@ -919,8 +920,14 @@ pub async fn apply_sqlite_table_structure_change(
#[tauri::command]
pub fn build_create_table_sql(
options: dbx_core::table_structure_sql::TableStructureSqlOptions,
+ server_version: Option<String>,
+ dialect_options: Option<dbx_core::table_structure_sql::CreateTableDialectOptions>,
) -> Result<dbx_core::table_structure_sql::TableStructureSqlResult, String> {
- Ok(dbx_core::table_structure_sql::build_create_table_sql(options))
+ Ok(dbx_core::table_structure_sql::build_create_table_sql_with_dialect_options(
+ options,
+ server_version.as_deref(),
+ dialect_options.unwrap_or_default(),
+ ))
}
#[tauri::command]