feat(structure): improve type colors and index editing
This commit is contained in:
1 parent
da1094df93
commit
fa7dde7c03
33 files changed
+1631
-132
No files matched your search
@@ -16,6 +16,11 @@ import {
|
||||
draftColumnNameForSql,
|
||||
getDataTypeLengthUnitOptions,
|
||||
getDefaultLengthForType,
|
||||
generateIndexName,
|
||||
generateUniqueIndexName,
|
||||
generateShortIndexName,
|
||||
generateUniqueShortIndexName,
|
||||
specialIndexColumnIssue,
|
||||
hasExistingColumnTypeChange,
|
||||
isDataTypeLengthDisabled,
|
||||
isDamengIdentityCompatibleDataType,
|
||||
@@ -36,6 +41,74 @@ import {
|
||||
} from "@/lib/table/tableStructureEditorState";
|
||||
|
||||
describe("tableStructureEditorState", () => {
|
||||
describe("index naming", () => {
|
||||
it("uses a lowercase type prefix and the initial field name", () => {
|
||||
expect(generateShortIndexName("Prop_Code")).toBe("idx_prop_code");
|
||||
expect(generateShortIndexName("email", { isUnique: true })).toBe("uk_email");
|
||||
expect(generateShortIndexName("title", { indexType: "FULLTEXT" })).toBe("ft_title");
|
||||
expect(generateShortIndexName("location", { indexType: "SPATIAL" })).toBe("sp_location");
|
||||
expect(generateShortIndexName("id", { isPrimary: true })).toBe("PRIMARY");
|
||||
expect(generateShortIndexName("")).toBe("");
|
||||
});
|
||||
|
||||
it("keeps long names deterministic and distinguishes truncated column names", () => {
|
||||
const name = generateShortIndexName("a".repeat(90));
|
||||
expect(name).toHaveLength(63);
|
||||
expect(name).toMatch(/^idx_.*_[0-9a-f]{8}$/);
|
||||
expect(generateShortIndexName("a".repeat(90))).toBe(name);
|
||||
expect(generateShortIndexName("a".repeat(89) + "b")).not.toBe(name);
|
||||
expect(generateShortIndexName("a".repeat(90), { maxLength: 64 })).toHaveLength(64);
|
||||
});
|
||||
|
||||
it("resolves case-insensitive collisions while retaining type prefixes and limits", () => {
|
||||
expect(generateUniqueShortIndexName("email", ["IDX_EMAIL", "idx_email_2"])).toBe("idx_email_3");
|
||||
expect(generateUniqueShortIndexName("email", ["UK_EMAIL"], { isUnique: true })).toBe("uk_email_2");
|
||||
const base = generateShortIndexName("a".repeat(90));
|
||||
const next = generateUniqueShortIndexName("a".repeat(90), [base]);
|
||||
expect(next).toHaveLength(63);
|
||||
expect(next).toMatch(/^idx_.*_[0-9a-f]{8}_2$/);
|
||||
});
|
||||
|
||||
it("preserves legacy callers and table-qualified names for shared namespaces", () => {
|
||||
expect(generateIndexName("users", ["email"])).toBe("USERS_EMAIL_IDX");
|
||||
expect(generateIndexName("orders", ["email"])).toBe("ORDERS_EMAIL_IDX");
|
||||
expect(generateIndexName("users", ["email", "region"])).toBe("USERS_EMAIL_REGION_IDX");
|
||||
expect(generateUniqueIndexName("users", ["email"], ["USERS_EMAIL_IDX"])).toBe("USERS_EMAIL_IDX_2");
|
||||
});
|
||||
|
||||
it("preserves Chinese field names and provides deterministic names for symbols", () => {
|
||||
const field = "\u5c5e\u6027";
|
||||
expect(generateShortIndexName(field)).toBe(`idx_${field}`);
|
||||
expect(generateUniqueShortIndexName(field, [`uk_${field}`], { isUnique: true })).toBe(`uk_${field}_2`);
|
||||
const longName = generateShortIndexName(field.repeat(40), { maxLength: 64 });
|
||||
expect(longName).toHaveLength(64);
|
||||
expect(longName).toMatch(/_[0-9a-f]{8}$/);
|
||||
expect(generateShortIndexName("---")).toMatch(/^idx_column_[0-9a-f]{8}$/);
|
||||
expect(generateShortIndexName("---")).not.toBe(generateShortIndexName("+++"));
|
||||
expect(generateShortIndexName("\u{10400}")).toMatch(/^idx_column_[0-9a-f]{8}$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("special index columns", () => {
|
||||
const field = (dataType: string, isNullable = false) => ({ dataType, isNullable });
|
||||
|
||||
it("allows composite text searches but rejects JSON, numbers, and unique fulltext", () => {
|
||||
expect(specialIndexColumnIssue("mysql", "FULLTEXT", [field("varchar(255)"), field("longtext")])).toBeNull();
|
||||
for (const type of ["json", "int", "blob"]) expect(specialIndexColumnIssue("mysql", "FULLTEXT", [field(type)])).toBe("fulltextIndexColumns");
|
||||
expect(specialIndexColumnIssue("mysql", "FULLTEXT", [field("text")], true)).toBe("specialIndexUnique");
|
||||
});
|
||||
|
||||
it("requires one non-null geometry for MySQL spatial indexes", () => {
|
||||
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("point")])).toBeNull();
|
||||
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("polygon", true)])).toBe("spatialIndexNullable");
|
||||
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("point"), field("geometry")])).toBe("spatialIndexColumn");
|
||||
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("varchar(64)")])).toBe("spatialIndexColumn");
|
||||
expect(specialIndexColumnIssue("mysql", "SPATIAL", [field("geography")])).toBe("spatialIndexColumn");
|
||||
expect(specialIndexColumnIssue("sqlserver", "SPATIAL", [field("geography", true)])).toBeNull();
|
||||
expect(specialIndexColumnIssue("postgres", "GIST", [field("geometry", true)])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("DuckDB type parameters", () => {
|
||||
it.each([
|
||||
"TINYINT",
|
||||
|
||||
@@ -3,7 +3,7 @@ import { hasTableStructureRefreshWork, unloadedTableStructureRefreshScope, visib
|
||||
|
||||
describe("table structure metadata loading", () => {
|
||||
it.each([
|
||||
["columns", { columns: true, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true }],
|
||||
["columns", { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true }],
|
||||
["indexes", { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true }],
|
||||
["foreignKeys", { columns: true, indexes: false, foreignKeys: true, constraints: false, triggers: false, partitions: false, tableComment: true }],
|
||||
["constraints", { columns: false, indexes: false, foreignKeys: false, constraints: true, triggers: false, partitions: false, tableComment: true }],
|
||||
|
||||
@@ -38,6 +38,8 @@ export interface EditableStructureIndex {
|
||||
name: string;
|
||||
columns: string[];
|
||||
nameEdited?: boolean;
|
||||
/** First selected field, retained when a composite index's members change. */
|
||||
autoNameColumn?: string;
|
||||
isUnique: boolean;
|
||||
isPrimary: boolean;
|
||||
filter: string;
|
||||
|
||||
@@ -1257,6 +1257,35 @@ export function toColumnNames(columns: string[]): string {
|
||||
|
||||
const AUTO_INDEX_NAME_MAX_LENGTH = 63;
|
||||
|
||||
export type StructureIndexKind = "primary" | "unique" | "index" | "fulltext" | "spatial";
|
||||
type IndexNamingOptions = Partial<Pick<EditableStructureIndex, "isPrimary" | "isUnique" | "indexType">> & { maxLength?: number };
|
||||
|
||||
export function structureIndexKind(index: IndexNamingOptions): StructureIndexKind {
|
||||
if (index.isPrimary) return "primary";
|
||||
if (index.indexType?.trim().toUpperCase() === "FULLTEXT") return "fulltext";
|
||||
if (index.indexType?.trim().toUpperCase() === "SPATIAL") return "spatial";
|
||||
return index.isUnique ? "unique" : "index";
|
||||
}
|
||||
|
||||
export type SpecialIndexColumnIssue = "specialIndexUnique" | "fulltextIndexColumns" | "spatialIndexColumn" | "spatialIndexNullable";
|
||||
|
||||
export function specialIndexColumnIssue(dialect: string, indexType: string, columns: readonly Pick<EditableStructureColumn, "dataType" | "isNullable">[], isUnique = false): SpecialIndexColumnIssue | null {
|
||||
const type = indexType.trim().toUpperCase();
|
||||
const fulltext = dialect === "mysql" && type === "FULLTEXT";
|
||||
const spatial = (dialect === "mysql" || dialect === "sqlserver") && type === "SPATIAL";
|
||||
if (!fulltext && !spatial) return null;
|
||||
if (isUnique) return "specialIndexUnique";
|
||||
if (!columns.length) return null;
|
||||
const types = columns.map((column) => splitDataType(column.dataType).baseType.toLowerCase());
|
||||
if (fulltext && types.some((value) => !/^(?:char|varchar|tinytext|text|mediumtext|longtext)$/.test(value))) return "fulltextIndexColumns";
|
||||
if (spatial) {
|
||||
const validType = dialect === "mysql" ? /^(?:geometry|point|linestring|polygon|multipoint|multilinestring|multipolygon|geometrycollection|geomcollection)$/ : /^(?:geometry|geography)$/;
|
||||
if (columns.length !== 1 || !validType.test(types[0])) return "spatialIndexColumn";
|
||||
if (dialect === "mysql" && columns[0].isNullable) return "spatialIndexNullable";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeIndexNamePart(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
const unquoted = (trimmed.startsWith("[") && trimmed.endsWith("]")) || (trimmed.startsWith("`") && trimmed.endsWith("`")) || (trimmed.startsWith('"') && trimmed.endsWith('"')) ? trimmed.slice(1, -1) : trimmed;
|
||||
@@ -1275,6 +1304,7 @@ function truncateIndexName(value: string, maxLength = AUTO_INDEX_NAME_MAX_LENGTH
|
||||
return `${value.slice(0, maxLength - suffix.length).replace(/_+$/g, "")}${suffix}`;
|
||||
}
|
||||
|
||||
// Keep the original API and table-qualified naming for existing callers and dialects.
|
||||
export function generateIndexName(tableName: string, columns: string[], maxLength = AUTO_INDEX_NAME_MAX_LENGTH): string {
|
||||
const parts = [tableName, ...columns].map(normalizeIndexNamePart).filter(Boolean);
|
||||
if (parts.length === 0) return "";
|
||||
@@ -1297,6 +1327,53 @@ export function generateUniqueIndexName(tableName: string, columns: string[], ex
|
||||
return base;
|
||||
}
|
||||
|
||||
function indexNameHash(value: string): string {
|
||||
// Keep long names deterministic and distinguish columns beyond the cutoff.
|
||||
let hash = 2166136261;
|
||||
for (let i = 0; i < value.length; i++) hash = Math.imul(hash ^ value.charCodeAt(i), 16777619);
|
||||
return (hash >>> 0).toString(16).padStart(8, "0");
|
||||
}
|
||||
|
||||
function truncateShortIndexName(value: string, maxLength = AUTO_INDEX_NAME_MAX_LENGTH): string {
|
||||
if (value.length <= maxLength) return value;
|
||||
const suffix = `_${indexNameHash(value)}`;
|
||||
if (maxLength <= suffix.length) return value.slice(0, maxLength);
|
||||
return `${value.slice(0, maxLength - suffix.length).replace(/_+$/g, "")}${suffix}`;
|
||||
}
|
||||
|
||||
export function generateShortIndexName(columnName: string, options: IndexNamingOptions = {}): string {
|
||||
if (options.isPrimary) return "PRIMARY";
|
||||
if (!columnName.trim()) return "";
|
||||
// MySQL permits BMP Unicode identifiers, but not supplementary characters.
|
||||
const normalized = columnName
|
||||
.trim()
|
||||
.replace(/[^\p{L}\p{N}]+/gu, "_")
|
||||
.replace(/[\uD800-\uDFFF]/g, "_")
|
||||
.replace(/_+/g, "_")
|
||||
.replace(/^_+|_+$/g, "")
|
||||
.toLowerCase();
|
||||
const name = normalized || `column_${indexNameHash(columnName)}`;
|
||||
const prefix = { primary: "pk", unique: "uk", index: "idx", fulltext: "ft", spatial: "sp" }[structureIndexKind(options)];
|
||||
return truncateShortIndexName(`${prefix}_${name}`, options.maxLength);
|
||||
}
|
||||
|
||||
export function generateUniqueShortIndexName(columnName: string, existingNames: Iterable<string>, options: IndexNamingOptions = {}): string {
|
||||
const maxLength = options.maxLength ?? AUTO_INDEX_NAME_MAX_LENGTH;
|
||||
const base = generateShortIndexName(columnName, options);
|
||||
if (!base) return "";
|
||||
if (options.isPrimary) return base;
|
||||
|
||||
const taken = new Set([...existingNames].map((name) => name.trim().toLowerCase()).filter(Boolean));
|
||||
if (!taken.has(base.toLowerCase())) return base;
|
||||
|
||||
for (let counter = 2; ; counter++) {
|
||||
const suffix = `_${counter}`;
|
||||
const stem = generateShortIndexName(columnName, { ...options, maxLength: Math.max(1, maxLength - suffix.length) });
|
||||
const candidate = `${stem}${suffix}`;
|
||||
if (!taken.has(candidate.toLowerCase())) return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
export function splitDataType(raw: string): { baseType: string; params: string } {
|
||||
const trimmed = raw.trim();
|
||||
const parenIdx = trimmed.indexOf("(");
|
||||
|
||||
@@ -14,7 +14,7 @@ export interface TableStructureRefreshScope {
|
||||
export function visibleTableStructureRefreshScope(activeTab: TableInfoTab): TableStructureRefreshScope {
|
||||
switch (activeTab) {
|
||||
case "columns":
|
||||
return { columns: true, indexes: false, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true };
|
||||
return { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true };
|
||||
case "indexes":
|
||||
return { columns: true, indexes: true, foreignKeys: false, constraints: false, triggers: false, partitions: false, tableComment: true };
|
||||
case "foreignKeys":
|
||||
|
||||
Reference in new issue
Block a user