fix(mysql): edit enum column values
This commit is contained in:
@@ -90,7 +90,7 @@ import { createColumnDrafts } from "@/lib/table/tableStructureEditorState";
|
||||
import type { BuildSingleColumnAlterSqlOptions } from "@/lib/table/tableStructureEditorSql";
|
||||
import { buildTableSelectSql, quoteTableIdentifier } from "@/lib/table/tableSelectSql";
|
||||
import { uuid } from "@/lib/common/utils";
|
||||
import { resolveHeaderColumnType } from "@/lib/dataGrid/dataGridColumnType";
|
||||
import { compactHeaderColumnType, resolveHeaderColumnType } from "@/lib/dataGrid/dataGridColumnType";
|
||||
import { canEditExistingTableRows, canInsertTableRows, canUseKeylessRowPredicate, hiveTablePropertiesIndicateTransactional, isClickHouseExistingRowReadonlyColumn, isHiddenGridColumn, isTdengineExistingRowReadonlyColumn, usesSyntheticRowIdKey } from "@/lib/table/tableEditing";
|
||||
import { buildDataGridColumnDistinctValuesSql, buildDataGridContextFilterCondition, buildDataGridCountSql, buildHiveTablePropertiesSql, type DataGridContextFilterMode } from "@/lib/dataGrid/dataGridSql";
|
||||
import {
|
||||
@@ -379,7 +379,7 @@ function headerColumnType(column: string, actualColIdx: number): string {
|
||||
resultColumnTypes: props.result.column_types,
|
||||
actualColIdx,
|
||||
});
|
||||
return resolved ? shortTypeName(resolved) : "";
|
||||
return resolved ? shortTypeName(compactHeaderColumnType(resolved)) : "";
|
||||
}
|
||||
|
||||
function shortTypeName(t: string): string {
|
||||
@@ -4124,6 +4124,11 @@ function isEnumGridColumnNullable(columnIndex: number): boolean {
|
||||
return tableColumnForGridColumn(columnIndex)?.is_nullable ?? false;
|
||||
}
|
||||
|
||||
function isEnumEditorInitialNull(rowId: number | undefined, columnIndex: number): boolean {
|
||||
if (rowId === undefined) return false;
|
||||
return getRowItem(rowId)?.data[columnIndex] === null;
|
||||
}
|
||||
|
||||
function cellEditInputModeForColumn(columnIndex: number): "decimal" | "numeric" | undefined {
|
||||
const dataType = normalizedColumnDataType(tableColumnForGridColumn(columnIndex));
|
||||
if (isIntegerColumnType(dataType)) return "numeric";
|
||||
@@ -6752,8 +6757,8 @@ function deleteCurrentRow(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
function commitGridEdit() {
|
||||
void commitEditAndMaybeAutoSave().finally(() => nextTick(() => gridRef.value?.focus({ preventScroll: true })));
|
||||
function commitGridEdit(value?: string | null) {
|
||||
void commitEditAndMaybeAutoSave(value === undefined ? undefined : { explicitValue: value }).finally(() => nextTick(() => gridRef.value?.focus({ preventScroll: true })));
|
||||
}
|
||||
|
||||
async function commitEditFromCellBlur() {
|
||||
@@ -9257,7 +9262,16 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
@cancel="cancelEdit"
|
||||
@commit="commitGridEdit"
|
||||
/>
|
||||
<EnumCellEditor v-else-if="isEnumGridColumn(cell.valueIndex)" v-model="editValue" :values="enumValuesForGridColumn(cell.valueIndex)" :nullable="isEnumGridColumnNullable(cell.valueIndex)" cell-layout="transpose" @cancel="cancelEdit" @commit="commitGridEdit" />
|
||||
<EnumCellEditor
|
||||
v-else-if="isEnumGridColumn(cell.valueIndex)"
|
||||
v-model="editValue"
|
||||
:values="enumValuesForGridColumn(cell.valueIndex)"
|
||||
:nullable="isEnumGridColumnNullable(cell.valueIndex)"
|
||||
:initial-null="isEnumEditorInitialNull(displayItems[cell.recordIndex]?.id, cell.valueIndex)"
|
||||
cell-layout="transpose"
|
||||
@cancel="cancelEdit"
|
||||
@commit="commitGridEdit"
|
||||
/>
|
||||
<textarea
|
||||
v-else-if="cellUsesExpandedEditor(displayItems[cell.recordIndex]?.id, cell.valueIndex)"
|
||||
v-model="editValue"
|
||||
@@ -9744,6 +9758,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
v-model="editValue"
|
||||
:values="enumValuesForGridColumn(canvasEditingCell.actualColIdx)"
|
||||
:nullable="isEnumGridColumnNullable(canvasEditingCell.actualColIdx)"
|
||||
:initial-null="isEnumEditorInitialNull(canvasEditingCell.rowId, canvasEditingCell.actualColIdx)"
|
||||
@cancel="cancelEdit"
|
||||
@commit="commitGridEdit"
|
||||
/>
|
||||
@@ -9889,7 +9904,15 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
|
||||
@cancel="cancelEdit"
|
||||
@commit="commitGridEdit"
|
||||
/>
|
||||
<EnumCellEditor v-else-if="isEnumGridColumn(col.actualColIdx)" v-model="editValue" :values="enumValuesForGridColumn(col.actualColIdx)" :nullable="isEnumGridColumnNullable(col.actualColIdx)" @cancel="cancelEdit" @commit="commitGridEdit" />
|
||||
<EnumCellEditor
|
||||
v-else-if="isEnumGridColumn(col.actualColIdx)"
|
||||
v-model="editValue"
|
||||
:values="enumValuesForGridColumn(col.actualColIdx)"
|
||||
:nullable="isEnumGridColumnNullable(col.actualColIdx)"
|
||||
:initial-null="isEnumEditorInitialNull(item.id, col.actualColIdx)"
|
||||
@cancel="cancelEdit"
|
||||
@commit="commitGridEdit"
|
||||
/>
|
||||
<textarea
|
||||
v-else-if="cellUsesExpandedEditor(item.id, col.actualColIdx)"
|
||||
v-model="editValue"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { FocusOutsideEvent, PointerDownOutsideEvent } from "reka-ui";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
|
||||
@@ -8,40 +9,47 @@ const props = withDefaults(
|
||||
modelValue: string;
|
||||
values: string[];
|
||||
nullable?: boolean;
|
||||
initialNull?: boolean;
|
||||
cellLayout?: "grid" | "transpose";
|
||||
}>(),
|
||||
{
|
||||
nullable: false,
|
||||
initialNull: false,
|
||||
cellLayout: "grid",
|
||||
},
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: string];
|
||||
commit: [];
|
||||
commit: [value?: string | null];
|
||||
cancel: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const open = ref(true);
|
||||
const triggerRef = ref<HTMLButtonElement | null>(null);
|
||||
let closeHandled = false;
|
||||
|
||||
const triggerClass = computed(() => ["cell-edit-input absolute inset-0 z-10 flex items-center gap-1 border-2 border-primary bg-background py-0 text-left text-xs outline-none", props.cellLayout === "transpose" ? "px-1.5" : "px-2.5"].join(" "));
|
||||
|
||||
const displayValue = computed(() => props.modelValue || "(NULL)");
|
||||
const displayValue = computed(() => {
|
||||
if (props.initialNull && props.modelValue === "") return t("grid.nullValue");
|
||||
return props.modelValue === "" ? "''" : props.modelValue;
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
nextTick(() => triggerRef.value?.focus());
|
||||
});
|
||||
|
||||
function selectValue(value: string) {
|
||||
emit("update:modelValue", value);
|
||||
finishCommit();
|
||||
function selectValue(value: string | null) {
|
||||
if (value !== null) emit("update:modelValue", value);
|
||||
finishCommit(value);
|
||||
}
|
||||
|
||||
function finishCommit() {
|
||||
function finishCommit(value?: string | null) {
|
||||
closeHandled = true;
|
||||
emit("commit");
|
||||
emit("commit", value);
|
||||
}
|
||||
|
||||
function finishCancel() {
|
||||
@@ -87,9 +95,22 @@ function onPopoverInteractOutside(event: PointerDownOutsideEvent | FocusOutsideE
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" side="bottom" class="w-auto min-w-[120px] rounded-md p-1" @click.stop @keydown.stop="onKeydown" @interact-outside="onPopoverInteractOutside">
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<button v-if="nullable" type="button" class="flex items-center rounded-sm px-2 py-1 text-xs text-muted-foreground hover:bg-accent hover:text-accent-foreground" :class="{ 'bg-accent text-accent-foreground': modelValue === '' }" @click="selectValue('')">(NULL)</button>
|
||||
<button v-for="val in values" :key="val" type="button" class="flex items-center rounded-sm px-2 py-1 text-xs hover:bg-accent hover:text-accent-foreground" :class="{ 'bg-accent text-accent-foreground': modelValue === val }" @click="selectValue(val)">
|
||||
{{ val }}
|
||||
<button v-if="nullable" type="button" class="flex min-h-7 w-full items-center rounded-sm px-2 py-1 text-left text-xs italic text-muted-foreground hover:bg-accent hover:text-accent-foreground" :class="{ 'bg-accent text-accent-foreground': initialNull }" @click="selectValue(null)">
|
||||
{{ t("grid.nullValue") }}
|
||||
</button>
|
||||
<button
|
||||
v-for="val in values"
|
||||
:key="val"
|
||||
type="button"
|
||||
class="flex min-h-7 w-full items-center rounded-sm px-2 py-1 text-left text-xs hover:bg-accent hover:text-accent-foreground"
|
||||
:class="{ 'bg-accent text-accent-foreground': modelValue === val && !(initialNull && val === '') }"
|
||||
@click="selectValue(val)"
|
||||
>
|
||||
<template v-if="val === ''">
|
||||
<code>''</code>
|
||||
<span class="ml-2 text-muted-foreground">{{ t("grid.emptyStringValue") }}</span>
|
||||
</template>
|
||||
<template v-else>{{ val }}</template>
|
||||
</button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
|
||||
@@ -45,9 +45,11 @@ import {
|
||||
getDataTypeOptions,
|
||||
getDefaultLengthForType,
|
||||
isDataTypeLengthDisabled,
|
||||
isMysqlEnumDataType,
|
||||
isMysqlCharacterDataType,
|
||||
isProtectedManticoreIdColumn,
|
||||
isSqlServerIdentityCompatibleDataType,
|
||||
mysqlEnumDataType,
|
||||
parseExtraToColumnExtra,
|
||||
rehydrateColumnDraftsFromMetadata,
|
||||
splitDataType,
|
||||
@@ -1247,6 +1249,7 @@ async function addColumn() {
|
||||
id: `new:${uuid()}`,
|
||||
name: "",
|
||||
dataType,
|
||||
enumValues: [],
|
||||
isNullable: true,
|
||||
defaultValue: "",
|
||||
comment: "",
|
||||
@@ -1377,7 +1380,12 @@ function updateSqlServerIdentityIncrement(column: EditableStructureColumn, value
|
||||
}
|
||||
|
||||
function updateColumnDataType(column: EditableStructureColumn, baseType: string) {
|
||||
column.dataType = combineDataTypeForDatabase(databaseType.value, baseType, getDefaultLengthForType(databaseType.value, baseType));
|
||||
if (isMysqlEnumDataType(databaseType.value, baseType)) {
|
||||
if (!column.enumValues?.length) column.enumValues = [""];
|
||||
column.dataType = mysqlEnumDataType(column.enumValues);
|
||||
} else {
|
||||
column.dataType = combineDataTypeForDatabase(databaseType.value, baseType, getDefaultLengthForType(databaseType.value, baseType));
|
||||
}
|
||||
syncSqlServerIdentityForDataType(column);
|
||||
// Clear charset/collation when switching to a non-character MySQL type
|
||||
if (showCharacterSet.value && !isMysqlCharacterDataType(column.dataType)) {
|
||||
@@ -1386,6 +1394,24 @@ function updateColumnDataType(column: EditableStructureColumn, baseType: string)
|
||||
}
|
||||
}
|
||||
|
||||
function updateMysqlEnumValue(column: EditableStructureColumn, index: number, value: string | number) {
|
||||
if (!column.enumValues || index < 0 || index >= column.enumValues.length) return;
|
||||
column.enumValues[index] = String(value);
|
||||
column.dataType = mysqlEnumDataType(column.enumValues);
|
||||
}
|
||||
|
||||
function addMysqlEnumValue(column: EditableStructureColumn) {
|
||||
column.enumValues ??= [];
|
||||
column.enumValues.push("");
|
||||
column.dataType = mysqlEnumDataType(column.enumValues);
|
||||
}
|
||||
|
||||
function removeMysqlEnumValue(column: EditableStructureColumn, index: number) {
|
||||
if (!column.enumValues || column.enumValues.length <= 1) return;
|
||||
column.enumValues.splice(index, 1);
|
||||
column.dataType = mysqlEnumDataType(column.enumValues);
|
||||
}
|
||||
|
||||
function updateColumnDataTypeLength(column: EditableStructureColumn, value: string | number) {
|
||||
column.dataType = combineDataTypeForDatabase(databaseType.value, splitDataType(column.dataType).baseType, String(value));
|
||||
syncSqlServerIdentityForDataType(column);
|
||||
@@ -2385,7 +2411,32 @@ watch(activeTab, (tab) => {
|
||||
<Input v-else :model-value="splitDataType(column.dataType).baseType" :class="[structureMonoControlClass, 'w-full']" disabled />
|
||||
</td>
|
||||
<td v-if="columnEditorControls.length" :class="structureCellClass">
|
||||
<Input :model-value="dataTypeLengthInputValue(databaseType, column.dataType)" :class="structureMonoControlClass" :disabled="isColumnLengthDisabled(column)" @update:model-value="updateColumnDataTypeLength(column, $event)" />
|
||||
<Popover v-if="isMysqlEnumDataType(databaseType, column.dataType)">
|
||||
<PopoverTrigger as-child>
|
||||
<Button variant="outline" size="sm" :class="[structureMonoControlClass, 'w-full justify-between px-2']" :disabled="isColumnTypeDisabled(column)">
|
||||
<span>{{ t("structureEditor.enumValueCount", { count: column.enumValues?.length ?? 0 }) }}</span>
|
||||
<ListChevronsUpDown :class="structureIconClass" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent class="w-80 p-3" align="start">
|
||||
<div class="mb-2 flex items-center justify-between gap-2">
|
||||
<span class="text-sm font-medium">{{ t("structureEditor.enumValues") }}</span>
|
||||
<Button variant="outline" size="sm" class="h-7 px-2" @click="addMysqlEnumValue(column)">
|
||||
<Plus class="mr-1 h-3.5 w-3.5" />
|
||||
{{ t("structureEditor.addEnumValue") }}
|
||||
</Button>
|
||||
</div>
|
||||
<div class="max-h-64 space-y-1.5 overflow-y-auto pr-1">
|
||||
<div v-for="(value, valueIndex) in column.enumValues" :key="valueIndex" class="flex items-center gap-1.5">
|
||||
<Input :model-value="value" :class="structureMonoControlClass" :placeholder="t('structureEditor.enumValuePlaceholder')" @update:model-value="updateMysqlEnumValue(column, valueIndex, $event)" />
|
||||
<Button variant="ghost" size="icon" class="h-8 w-8 shrink-0" :disabled="(column.enumValues?.length ?? 0) <= 1" :title="t('structureEditor.removeEnumValue')" @click="removeMysqlEnumValue(column, valueIndex)">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<Input v-else :model-value="dataTypeLengthInputValue(databaseType, column.dataType)" :class="structureMonoControlClass" :disabled="isColumnLengthDisabled(column)" @update:model-value="updateColumnDataTypeLength(column, $event)" />
|
||||
</td>
|
||||
<td v-if="columnEditorControls.nullable" :class="structureCellClass">
|
||||
<label class="flex items-center gap-1.5">
|
||||
|
||||
@@ -39,6 +39,7 @@ type CommitEditResult =
|
||||
|
||||
interface CommitEditOptions {
|
||||
promoteDraft?: boolean;
|
||||
explicitValue?: string | null;
|
||||
}
|
||||
|
||||
type GridScrollerRef =
|
||||
@@ -624,7 +625,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
if (item.isDraft) {
|
||||
ensureQuickEntryDraftRow();
|
||||
const oldVal = quickEntryDraftRow.value[col] ?? null;
|
||||
const newVal = coerceCellValue(editValue.value, oldVal, col);
|
||||
const newVal = options.explicitValue !== undefined ? options.explicitValue : coerceCellValue(editValue.value, oldVal, col);
|
||||
const nextDraftRow = [...quickEntryDraftRow.value];
|
||||
nextDraftRow[col] = newVal;
|
||||
if (newVal !== oldVal) pushUndoSnapshot();
|
||||
@@ -650,7 +651,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
|
||||
if (item.isNew && item.newIndex !== undefined) {
|
||||
const oldVal = newRows.value[item.newIndex]?.[col];
|
||||
const newVal = coerceCellValue(editValue.value, oldVal, col);
|
||||
const newVal = options.explicitValue !== undefined ? options.explicitValue : coerceCellValue(editValue.value, oldVal, col);
|
||||
const changed = newVal !== oldVal;
|
||||
if (changed) pushUndoSnapshot();
|
||||
if (newRows.value[item.newIndex]) {
|
||||
@@ -675,7 +676,7 @@ export function useDataGridEditor(options: UseDataGridEditorOptions) {
|
||||
}
|
||||
|
||||
const oldVal = result.value.rows[item.sourceIndex]?.[col];
|
||||
const newVal = coerceCellValue(editValue.value, oldVal, col);
|
||||
const newVal = options.explicitValue !== undefined ? options.explicitValue : coerceCellValue(editValue.value, oldVal, col);
|
||||
const changed = newVal !== item.data[col];
|
||||
if (newVal !== oldVal) {
|
||||
if (changed) pushUndoSnapshot();
|
||||
|
||||
@@ -915,6 +915,7 @@ export default {
|
||||
rowNumber: "Row",
|
||||
valueLength: "Length",
|
||||
nullValue: "NULL",
|
||||
emptyStringValue: "Empty string",
|
||||
noComment: "No comment",
|
||||
formattedJson: "Formatted JSON",
|
||||
formattedValue: "Formatted Value",
|
||||
@@ -1835,6 +1836,11 @@ export default {
|
||||
typePlaceholder: "Select or type...",
|
||||
noMatchingType: "No matching type",
|
||||
length: "Length",
|
||||
enumValues: "Enum values",
|
||||
enumValueCount: "{count} values",
|
||||
addEnumValue: "Add value",
|
||||
removeEnumValue: "Remove enum value",
|
||||
enumValuePlaceholder: "Value (empty is allowed)",
|
||||
nullable: "Nullable",
|
||||
primaryKey: "Primary Key",
|
||||
defaultValue: "Default",
|
||||
|
||||
@@ -916,6 +916,7 @@ export default withEnglishFallback({
|
||||
rowNumber: "行号",
|
||||
valueLength: "长度",
|
||||
nullValue: "NULL",
|
||||
emptyStringValue: "空字符串",
|
||||
noComment: "暂无注释",
|
||||
formattedJson: "格式化 JSON",
|
||||
formattedValue: "格式化值",
|
||||
@@ -1832,6 +1833,11 @@ export default withEnglishFallback({
|
||||
columnName: "字段名",
|
||||
dataType: "类型",
|
||||
length: "长度",
|
||||
enumValues: "枚举值",
|
||||
enumValueCount: "{count} 个值",
|
||||
addEnumValue: "添加值",
|
||||
removeEnumValue: "删除枚举值",
|
||||
enumValuePlaceholder: "枚举值(允许空字符串)",
|
||||
typePlaceholder: "选择或输入...",
|
||||
noMatchingType: "无匹配类型",
|
||||
nullable: "可为空",
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { combineDataTypeForDatabase, createColumnDrafts, dataTypeLengthInputValue, isDataTypeLengthDisabled, isMysqlCharacterDataType, isSqlServerIdentityCompatibleDataType, splitDataType } from "@/lib/table/tableStructureEditorState";
|
||||
import {
|
||||
combineDataTypeForDatabase,
|
||||
createColumnDrafts,
|
||||
dataTypeLengthInputValue,
|
||||
isDataTypeLengthDisabled,
|
||||
isMysqlCharacterDataType,
|
||||
isMysqlEnumDataType,
|
||||
isSqlServerIdentityCompatibleDataType,
|
||||
mysqlEnumDataType,
|
||||
rehydrateColumnDraftsFromMetadata,
|
||||
splitDataType,
|
||||
} from "@/lib/table/tableStructureEditorState";
|
||||
|
||||
describe("tableStructureEditorState", () => {
|
||||
it("keeps mysql unsigned attributes in the editable base type", () => {
|
||||
@@ -28,6 +39,55 @@ describe("tableStructureEditorState", () => {
|
||||
expect(dataTypeLengthInputValue("mysql", "set('manual','auto')")).toBe("");
|
||||
});
|
||||
|
||||
it("hydrates mysql enum values into an editable canonical type", () => {
|
||||
const [draft] = createColumnDrafts(
|
||||
[
|
||||
{
|
||||
name: "status",
|
||||
data_type: "enum",
|
||||
enum_values: ["", "pending", "it's", "path\\name"],
|
||||
is_nullable: false,
|
||||
column_default: "'pending'",
|
||||
is_primary_key: false,
|
||||
extra: null,
|
||||
},
|
||||
],
|
||||
"mysql",
|
||||
);
|
||||
|
||||
expect(draft?.enumValues).toEqual(["", "pending", "it's", "path\\name"]);
|
||||
expect(draft?.dataType).toBe("enum('','pending','it''s','path\\\\name')");
|
||||
expect(draft?.original?.data_type).toBe(draft?.dataType);
|
||||
});
|
||||
|
||||
it("builds mysql enum types without confusing values with length", () => {
|
||||
expect(isMysqlEnumDataType("mysql", "ENUM('a','b')")).toBe(true);
|
||||
expect(isMysqlEnumDataType("postgres", "enum")).toBe(false);
|
||||
expect(mysqlEnumDataType(["", "a'b", "a\\b"])).toBe("enum('','a''b','a\\\\b')");
|
||||
});
|
||||
|
||||
it("rehydrates enum values into drafts saved before enum editing existed", () => {
|
||||
const metadata = {
|
||||
name: "status",
|
||||
data_type: "enum",
|
||||
enum_values: ["pending", "active"],
|
||||
is_nullable: false,
|
||||
column_default: "'pending'",
|
||||
is_primary_key: false,
|
||||
extra: null,
|
||||
};
|
||||
const [legacyDraft] = createColumnDrafts([metadata], "mysql");
|
||||
legacyDraft!.dataType = "enum";
|
||||
legacyDraft!.enumValues = undefined;
|
||||
legacyDraft!.original = { ...metadata };
|
||||
|
||||
const [rehydrated] = rehydrateColumnDraftsFromMetadata([legacyDraft!], [metadata], "mysql");
|
||||
|
||||
expect(rehydrated?.enumValues).toEqual(["pending", "active"]);
|
||||
expect(rehydrated?.dataType).toBe("enum('pending','active')");
|
||||
expect(rehydrated?.original?.data_type).toBe("enum('pending','active')");
|
||||
});
|
||||
|
||||
it("does not expose Oracle-like integer display widths as editable length", () => {
|
||||
expect(isDataTypeLengthDisabled("dameng", "integer")).toBe(true);
|
||||
expect(dataTypeLengthInputValue("dameng", "integer(11)")).toBe("");
|
||||
|
||||
@@ -27,3 +27,7 @@ export function resolveHeaderColumnType({ tableColumnType, resultColumnTypes, ac
|
||||
const fromResult = resultColumnTypes?.[actualColIdx]?.trim();
|
||||
return fromResult ? fromResult : undefined;
|
||||
}
|
||||
|
||||
export function compactHeaderColumnType(dataType: string): string {
|
||||
return /^enum\s*\(/i.test(dataType.trim()) ? "enum" : dataType;
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ function templateColumn(createId: () => string, name: string, dataType: string,
|
||||
id: `new:${createId()}`,
|
||||
name,
|
||||
dataType,
|
||||
enumValues: [],
|
||||
isNullable,
|
||||
defaultValue,
|
||||
comment,
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface EditableStructureColumn {
|
||||
id: string;
|
||||
name: string;
|
||||
dataType: string;
|
||||
enumValues?: string[];
|
||||
isNullable: boolean;
|
||||
defaultValue: string;
|
||||
comment: string;
|
||||
|
||||
@@ -296,6 +296,16 @@ export function getDataTypeOptions(dbType: DatabaseType | undefined): string[] {
|
||||
return DATA_TYPE_OPTIONS[key] ?? [];
|
||||
}
|
||||
|
||||
export function isMysqlEnumDataType(dbType: DatabaseType | undefined, dataType: string): boolean {
|
||||
return dbType === "mysql" && splitDataType(dataType).baseType.trim().toLowerCase() === "enum";
|
||||
}
|
||||
|
||||
export function mysqlEnumDataType(values: readonly string[]): string {
|
||||
// Match MySQL's canonical ENUM literal escaping, including values returned by SHOW CREATE TABLE.
|
||||
const literals = values.map((value) => `'${value.replace(/\\/g, "\\\\").replace(/'/g, "''")}'`);
|
||||
return `enum(${literals.join(",")})`;
|
||||
}
|
||||
|
||||
export interface ColumnEditorControls {
|
||||
length: boolean;
|
||||
nullable: boolean;
|
||||
@@ -606,10 +616,13 @@ function columnDefaultForEditor(column: ColumnInfo, databaseType?: DatabaseType)
|
||||
export function createColumnDrafts(columns: ColumnInfo[], databaseType?: DatabaseType): EditableStructureColumn[] {
|
||||
return columns.map((column, index) => {
|
||||
const defaultValue = columnDefaultForEditor(column, databaseType);
|
||||
const enumValues = isMysqlEnumDataType(databaseType, column.data_type) ? [...(column.enum_values ?? [])] : undefined;
|
||||
const dataType = enumValues?.length ? mysqlEnumDataType(enumValues) : column.data_type;
|
||||
return {
|
||||
id: `existing:${column.name}`,
|
||||
name: column.name,
|
||||
dataType: column.data_type,
|
||||
dataType,
|
||||
enumValues,
|
||||
isNullable: column.is_nullable,
|
||||
defaultValue,
|
||||
comment: column.comment ?? "",
|
||||
@@ -617,7 +630,7 @@ export function createColumnDrafts(columns: ColumnInfo[], databaseType?: Databas
|
||||
characterSet: column.character_set ?? "",
|
||||
collation: column.collation ?? "",
|
||||
extra: parseExtraToColumnExtra(column.extra, databaseType),
|
||||
original: { ...column, column_default: column.column_default === null ? null : defaultValue },
|
||||
original: { ...column, data_type: dataType, column_default: column.column_default === null ? null : defaultValue },
|
||||
originalPosition: index,
|
||||
markedForDrop: false,
|
||||
};
|
||||
@@ -674,12 +687,15 @@ export function rehydrateColumnDraftsFromMetadata(draftColumns: EditableStructur
|
||||
const metadataIndex = findColumnDraftByName(metadataDrafts, candidates, usedMetadataIndexes);
|
||||
if (metadataIndex === undefined) return column;
|
||||
usedMetadataIndexes.add(metadataIndex);
|
||||
if (!needsHydration) return column;
|
||||
|
||||
const metadataDraft = metadataDrafts[metadataIndex]!;
|
||||
const shouldHydrateEnum = isMysqlEnumDataType(databaseType, column.dataType) && column.enumValues === undefined && metadataDraft.enumValues !== undefined;
|
||||
if (!needsHydration && !shouldHydrateEnum) return column;
|
||||
|
||||
return {
|
||||
...column,
|
||||
original: column.original ?? metadataDraft.original,
|
||||
dataType: shouldHydrateEnum ? metadataDraft.dataType : column.dataType,
|
||||
enumValues: column.enumValues ?? metadataDraft.enumValues,
|
||||
original: shouldHydrateEnum ? metadataDraft.original : (column.original ?? metadataDraft.original),
|
||||
originalPosition: column.originalPosition ?? metadataDraft.originalPosition,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import { test } from "vitest";
|
||||
import { resolveHeaderColumnType } from "../../apps/desktop/src/lib/dataGrid/dataGridColumnType.ts";
|
||||
import { compactHeaderColumnType, resolveHeaderColumnType } from "../../apps/desktop/src/lib/dataGrid/dataGridColumnType.ts";
|
||||
|
||||
test("prefers table-metadata type over the result type", () => {
|
||||
const type = resolveHeaderColumnType({
|
||||
@@ -53,3 +53,9 @@ test("treats blank/whitespace types as absent and falls through", () => {
|
||||
|
||||
assert.equal(resolveHeaderColumnType({ tableColumnType: "", resultColumnTypes: [""], actualColIdx: 0 }), undefined);
|
||||
});
|
||||
|
||||
test("hides MySQL enum values from the compact header type", () => {
|
||||
assert.equal(compactHeaderColumnType("enum('pending','active')"), "enum");
|
||||
assert.equal(compactHeaderColumnType("ENUM('', 'normal')"), "enum");
|
||||
assert.equal(compactHeaderColumnType("varchar(255)"), "varchar(255)");
|
||||
});
|
||||
|
||||
@@ -103,7 +103,14 @@ function column(name: string, isPrimaryKey = false, extra: string | null = null)
|
||||
};
|
||||
}
|
||||
|
||||
function createQuickEntryEditor(options: { quickEntryEnabled: boolean; cacheKey?: string; rowStatusFilter?: ReturnType<typeof ref<RowStatusFilter>>; filterRowsInGetRowItem?: boolean; supportsInsert?: boolean; save?: (changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][] }) => Promise<void> }) {
|
||||
function createQuickEntryEditor(options: {
|
||||
quickEntryEnabled: boolean;
|
||||
cacheKey?: string;
|
||||
rowStatusFilter?: ReturnType<typeof ref<RowStatusFilter>>;
|
||||
filterRowsInGetRowItem?: boolean;
|
||||
supportsInsert?: boolean;
|
||||
save?: (changes: { dirtyRows: Map<number, Map<number, CellValue>>; newRows: CellValue[][] }) => Promise<void>;
|
||||
}) {
|
||||
const result = computed(() => ({
|
||||
columns: ["id", "name"],
|
||||
rows: [[1, "Ada"] as CellValue[]],
|
||||
@@ -668,11 +675,7 @@ test("batch row delete records a single undo snapshot", () => {
|
||||
|
||||
const result = computed(() => ({
|
||||
columns: ["id", "name"],
|
||||
rows: [
|
||||
[1, "Ada"] as CellValue[],
|
||||
[2, "Linus"] as CellValue[],
|
||||
[3, "Grace"] as CellValue[],
|
||||
],
|
||||
rows: [[1, "Ada"] as CellValue[], [2, "Linus"] as CellValue[], [3, "Grace"] as CellValue[]],
|
||||
}));
|
||||
const rowStatusFilter = ref<"all" | "changed" | "edited" | "new" | "deleted">("all");
|
||||
let editor: ReturnType<typeof useDataGridEditor>;
|
||||
@@ -1064,6 +1067,26 @@ test("quick entry off keeps blur edits pending without saving", async () => {
|
||||
assert.equal(editor.dirtyRows.value.get(0)?.get(1), "Ada Lovelace");
|
||||
});
|
||||
|
||||
test("explicit enum commits distinguish NULL, empty string, and the literal NULL", async () => {
|
||||
setActivePinia(createPinia());
|
||||
installBrowserTestGlobals();
|
||||
|
||||
const nullEditor = createPeopleGridEditor();
|
||||
nullEditor.startEdit(0, 1);
|
||||
await nullEditor.commitEditAndMaybeAutoSave({ explicitValue: null });
|
||||
assert.equal(nullEditor.dirtyRows.value.get(0)?.get(1), null);
|
||||
|
||||
const emptyEditor = createPeopleGridEditor();
|
||||
emptyEditor.startEdit(0, 1);
|
||||
await emptyEditor.commitEditAndMaybeAutoSave({ explicitValue: "" });
|
||||
assert.equal(emptyEditor.dirtyRows.value.get(0)?.get(1), "");
|
||||
|
||||
const literalEditor = createPeopleGridEditor();
|
||||
literalEditor.startEdit(0, 1);
|
||||
await literalEditor.commitEditAndMaybeAutoSave({ explicitValue: "NULL" });
|
||||
assert.equal(literalEditor.dirtyRows.value.get(0)?.get(1), "NULL");
|
||||
});
|
||||
|
||||
test("quick entry on saves existing row edits on blur", async () => {
|
||||
setActivePinia(createPinia());
|
||||
installBrowserTestGlobals();
|
||||
@@ -1158,10 +1181,7 @@ test("quick entry queues blur saves made while a save is running", async () => {
|
||||
await firstCommit;
|
||||
|
||||
assert.equal(saveCalls, 2);
|
||||
assert.deepEqual(savedDirtyRows, [
|
||||
[[0, [[1, "Ada 1"]]]],
|
||||
[[0, [[1, "Ada 2"]]]],
|
||||
]);
|
||||
assert.deepEqual(savedDirtyRows, [[[0, [[1, "Ada 1"]]]], [[0, [[1, "Ada 2"]]]]]);
|
||||
assert.equal(editor.dirtyRows.value.size, 0);
|
||||
assert.equal(editor.saveError.value, "");
|
||||
});
|
||||
@@ -1212,10 +1232,7 @@ test("quick entry replays queued saves when row-status filters hide the saved ro
|
||||
await firstCommit;
|
||||
|
||||
assert.equal(saveCalls, 2);
|
||||
assert.deepEqual(savedDirtyRows, [
|
||||
[[0, [[1, "Ada 1"]]]],
|
||||
[[0, [[1, "Ada 2"]]]],
|
||||
]);
|
||||
assert.deepEqual(savedDirtyRows, [[[0, [[1, "Ada 1"]]]], [[0, [[1, "Ada 2"]]]]]);
|
||||
assert.equal(editor.dirtyRows.value.size, 0);
|
||||
assert.equal(editor.saveError.value, "");
|
||||
});
|
||||
@@ -1267,10 +1284,7 @@ test("quick entry preserves an active edit when auto-save clears the row from a
|
||||
await editor.commitEditFromBlur();
|
||||
|
||||
assert.equal(saveCalls, 2);
|
||||
assert.deepEqual(savedDirtyRows, [
|
||||
[[0, [[1, "Ada 1"]]]],
|
||||
[[0, [[0, 2]]]],
|
||||
]);
|
||||
assert.deepEqual(savedDirtyRows, [[[0, [[1, "Ada 1"]]]], [[0, [[0, 2]]]]]);
|
||||
assert.equal(editor.dirtyRows.value.size, 0);
|
||||
});
|
||||
|
||||
@@ -1316,10 +1330,7 @@ test("quick entry keeps queued blur save after an earlier auto-save fails", asyn
|
||||
await firstCommit;
|
||||
|
||||
assert.equal(saveCalls, 2);
|
||||
assert.deepEqual(savedDirtyRows, [
|
||||
[[0, [[1, "Ada 1"]]]],
|
||||
[[0, [[1, "Ada 2"]]]],
|
||||
]);
|
||||
assert.deepEqual(savedDirtyRows, [[[0, [[1, "Ada 1"]]]], [[0, [[1, "Ada 2"]]]]]);
|
||||
assert.equal(editor.dirtyRows.value.size, 0);
|
||||
assert.equal(editor.saveError.value, "");
|
||||
});
|
||||
@@ -1365,10 +1376,7 @@ test("quick entry saves a queued revert made while an earlier auto-save is runni
|
||||
await firstCommit;
|
||||
|
||||
assert.equal(saveCalls, 2);
|
||||
assert.deepEqual(savedDirtyRows, [
|
||||
[[0, [[1, "Ada 1"]]]],
|
||||
[[0, [[1, "Ada"]]]],
|
||||
]);
|
||||
assert.deepEqual(savedDirtyRows, [[[0, [[1, "Ada 1"]]]], [[0, [[1, "Ada"]]]]]);
|
||||
assert.equal(editor.dirtyRows.value.size, 0);
|
||||
assert.equal(editor.saveError.value, "");
|
||||
});
|
||||
|
||||
@@ -13,7 +13,9 @@ import {
|
||||
getColumnEditorControls,
|
||||
getDataTypeOptions,
|
||||
isProtectedManticoreIdColumn,
|
||||
isMysqlEnumDataType,
|
||||
isSqlServerIdentityCompatibleDataType,
|
||||
mysqlEnumDataType,
|
||||
normalizeDataTypeParams,
|
||||
parseExtraToColumnExtra,
|
||||
rehydrateColumnDraftsFromMetadata,
|
||||
@@ -292,6 +294,29 @@ test("does not add MySQL-style display widths to SQL Server integer types", () =
|
||||
assert.equal(combineDataTypeForDatabase("sqlserver", "float", "53"), "float(53)");
|
||||
});
|
||||
|
||||
test("hydrates and serializes MySQL enum values for structure editing", () => {
|
||||
const [draft] = createColumnDrafts(
|
||||
[
|
||||
{
|
||||
name: "status",
|
||||
data_type: "enum",
|
||||
enum_values: ["", "pending", "it's", "path\\name"],
|
||||
is_nullable: false,
|
||||
column_default: "'pending'",
|
||||
is_primary_key: false,
|
||||
extra: null,
|
||||
},
|
||||
],
|
||||
"mysql",
|
||||
);
|
||||
|
||||
assert.deepEqual(draft?.enumValues, ["", "pending", "it's", "path\\name"]);
|
||||
assert.equal(draft?.dataType, "enum('','pending','it''s','path\\\\name')");
|
||||
assert.equal(draft?.original?.data_type, draft?.dataType);
|
||||
assert.equal(isMysqlEnumDataType("mysql", draft?.dataType ?? ""), true);
|
||||
assert.equal(mysqlEnumDataType(["a'b", "a\\b"]), "enum('a''b','a\\\\b')");
|
||||
});
|
||||
|
||||
test("parses Manticore Search text properties to ColumnExtra", () => {
|
||||
assert.deepEqual(parseExtraToColumnExtra("stored indexed", "manticoresearch"), {
|
||||
manticoreStored: true,
|
||||
|
||||
Reference in New Issue
Block a user