feat(types): add database type help

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-07-12 13:28:46 +08:00
1 parent fdb33ef477
commit 4f1997d8eb
30 files changed
+2006 -79

No files matched your search

@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { optionHelpPanelOffsetTop } from "@/lib/common/optionHelpPanelOffset";
describe("optionHelpPanelOffsetTop", () => {
it("aligns a help panel with the active option when there is room", () => {
expect(optionHelpPanelOffsetTop({ activeItemTop: 48, listCardHeight: 260, panelHeight: 80 })).toBe(48);
});
it("does not produce a negative offset", () => {
expect(optionHelpPanelOffsetTop({ activeItemTop: -12, listCardHeight: 260, panelHeight: 80 })).toBe(0);
});
it("clamps the panel upward at the list card bottom", () => {
expect(optionHelpPanelOffsetTop({ activeItemTop: 210, listCardHeight: 260, panelHeight: 80 })).toBe(180);
});
it("pins a panel taller than the list card to the top", () => {
expect(optionHelpPanelOffsetTop({ activeItemTop: 48, listCardHeight: 80, panelHeight: 120 })).toBe(0);
});
});
@@ -0,0 +1,36 @@
import { describe, expect, it } from "vitest";
import { SEARCHABLE_SELECT_HELP_PANEL_ALIGN, searchableSelectKeyboardTooltipOption, searchableSelectSelectedOrFirstHelpOption } from "@/lib/common/searchableSelectTooltip";
describe("searchableSelectKeyboardTooltipOption", () => {
it("anchors the help panel to the trigger's left edge", () => {
expect(SEARCHABLE_SELECT_HELP_PANEL_ALIGN).toBe("start");
});
it("activates the highlighted option help during Arrow-key navigation", () => {
const optionTooltip = (option: string) => (option === "json" ? "Validated JSON document" : undefined);
// ArrowDown moves highlight from int (index 0) to json (index 1) while the search input retains focus.
expect(searchableSelectKeyboardTooltipOption(["int", "json"], 0, optionTooltip)).toBeUndefined();
expect(searchableSelectKeyboardTooltipOption(["int", "json"], 1, optionTooltip)).toBe("json");
});
it("does not activate help for the initial unhighlighted list state", () => {
const optionTooltip = () => "Type help";
expect(searchableSelectKeyboardTooltipOption(["int"], -1, optionTooltip)).toBeUndefined();
});
it("activates selected help on open and the first matching option after search", () => {
const optionTooltip = (option: string) => (option === "json" || option === "int" ? `${option} help` : undefined);
expect(searchableSelectSelectedOrFirstHelpOption(["int", "json"], "json", optionTooltip)).toBe("json");
expect(searchableSelectSelectedOrFirstHelpOption(["int", "json"], "unknown", optionTooltip)).toBe("int");
expect(searchableSelectSelectedOrFirstHelpOption(["custom"], "unknown", optionTooltip)).toBeUndefined();
expect(searchableSelectSelectedOrFirstHelpOption(["dynamic_unknown", "json"], "dynamic_unknown", optionTooltip)).toBe("json");
});
it("does not activate a tooltip when the optional callback is absent or returns no content", () => {
expect(searchableSelectKeyboardTooltipOption(["int", "json"], 1)).toBeUndefined();
expect(searchableSelectKeyboardTooltipOption(["int", "json"], 0, () => undefined)).toBeUndefined();
});
});
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { REDIS_CREATE_KEY_TYPE_VALUES, getRedisCreateKeyTypeHelp, redisCreateKeyTypeHelpOptionOnOpen, shouldActivateRedisCreateKeyTypeHelpOnFocus } from "@/lib/redis/redisCreateKeyTypeHelp";
import en from "@/i18n/locales/en";
import zhCN from "@/i18n/locales/zh-CN";
function redisCreateTypeHelpMessages(locale: unknown): Record<string, unknown> {
const messages = locale as { redis?: { createKeyTypeHelp?: Record<string, unknown> } };
return messages.redis?.createKeyTypeHelp ?? {};
}
describe("getRedisCreateKeyTypeHelp", () => {
it("covers every key type offered by the Create key dialog", () => {
for (const type of REDIS_CREATE_KEY_TYPE_VALUES) {
expect(getRedisCreateKeyTypeHelp(type)).toEqual({ key: type });
}
});
it("normalizes casing and leaves unsupported types undocumented", () => {
expect(getRedisCreateKeyTypeHelp(" ZSET ")).toEqual({ key: "zset" });
expect(getRedisCreateKeyTypeHelp("bitmap")).toBeUndefined();
});
it("activates help only for focus reached through Arrow navigation", () => {
expect(shouldActivateRedisCreateKeyTypeHelpOnFocus({ openedByArrow: true, keyboardNavigating: true })).toBe(true);
expect(shouldActivateRedisCreateKeyTypeHelpOnFocus({ openedByArrow: false, keyboardNavigating: true })).toBe(true);
expect(shouldActivateRedisCreateKeyTypeHelpOnFocus({ openedByArrow: false, keyboardNavigating: false })).toBe(false);
});
it("shows the selected offered type's help when the Select opens", () => {
expect(redisCreateKeyTypeHelpOptionOnOpen("string")).toBe("string");
expect(redisCreateKeyTypeHelpOptionOnOpen(" JSON ")).toBe("json");
expect(redisCreateKeyTypeHelpOptionOnOpen("bitmap")).toBeUndefined();
});
it("has English and Simplified Chinese copy for every offered type", () => {
const english = redisCreateTypeHelpMessages(en);
const chinese = redisCreateTypeHelpMessages(zhCN);
for (const type of REDIS_CREATE_KEY_TYPE_VALUES) {
expect(english[type], `English: ${type}`).toEqual(expect.any(String));
expect(chinese[type], `Simplified Chinese: ${type}`).toEqual(expect.any(String));
}
});
});
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import { DATA_TYPE_OPTIONS } from "@/lib/table/tableStructureEditorState";
import { getMysqlDataTypeHelp } from "@/lib/table/mysqlDataTypeHelp";
import en from "@/i18n/locales/en";
import zhCN from "@/i18n/locales/zh-CN";
function mysqlHelpMessages(locale: unknown): Record<string, unknown> {
const messages = locale as { structureEditor?: { mysqlDataTypeHelp?: Record<string, unknown> } };
return messages.structureEditor?.mysqlDataTypeHelp ?? {};
}
describe("getMysqlDataTypeHelp", () => {
it("normalizes MySQL attributes, aliases, parameters, casing, and whitespace", () => {
expect(getMysqlDataTypeHelp(" INT(11) UNSIGNED ")).toEqual({ key: "int", warningKeys: ["integerDisplayWidth"] });
expect(getMysqlDataTypeHelp("integer zerofill")).toEqual({ key: "int", warningKeys: ["zerofill"] });
expect(getMysqlDataTypeHelp("NUMERIC(10, 2)")).toEqual({ key: "decimal" });
expect(getMysqlDataTypeHelp(" double precision ")).toEqual({ key: "double" });
expect(getMysqlDataTypeHelp("BOOL")).toEqual({ key: "boolean" });
expect(getMysqlDataTypeHelp("DEC(20, 6)")).toEqual({ key: "decimal" });
expect(getMysqlDataTypeHelp("CHARACTER VARYING(120)")).toEqual({ key: "varchar" });
expect(getMysqlDataTypeHelp("CHARACTER(12)")).toEqual({ key: "char" });
expect(getMysqlDataTypeHelp("CHAR VARYING(120)")).toEqual({ key: "varchar" });
expect(getMysqlDataTypeHelp("CHAR BYTE")).toEqual({ key: "char" });
});
it("covers phpMyAdmin's additional MySQL type aliases for dynamic type lists", () => {
expect(getMysqlDataTypeHelp("FIXED")?.key).toBe("decimal");
expect(getMysqlDataTypeHelp("FLOAT4")?.key).toBe("float");
expect(getMysqlDataTypeHelp("FLOAT8")?.key).toBe("double");
expect(getMysqlDataTypeHelp("INT1")?.key).toBe("tinyint");
expect(getMysqlDataTypeHelp("INT2")?.key).toBe("smallint");
expect(getMysqlDataTypeHelp("INT3")?.key).toBe("mediumint");
expect(getMysqlDataTypeHelp("INT4")?.key).toBe("int");
expect(getMysqlDataTypeHelp("INT8")?.key).toBe("bigint");
expect(getMysqlDataTypeHelp("MIDDLEINT")?.key).toBe("mediumint");
expect(getMysqlDataTypeHelp("LONG")?.key).toBe("mediumtext");
expect(getMysqlDataTypeHelp("LONG VARCHAR")?.key).toBe("mediumtext");
expect(getMysqlDataTypeHelp("LONG VARBINARY")?.key).toBe("mediumblob");
expect(getMysqlDataTypeHelp("GEOMCOLLECTION")?.key).toBe("geometrycollection");
expect(getMysqlDataTypeHelp("NCHAR(30)")?.key).toBe("nationalCharacter");
expect(getMysqlDataTypeHelp("NVARCHAR(30)")?.key).toBe("nationalCharacter");
expect(getMysqlDataTypeHelp("NATIONAL CHARACTER VARYING(30)")?.key).toBe("nationalCharacter");
});
it("documents numeric, text, binary, enum, temporal, JSON, and spatial types", () => {
expect(getMysqlDataTypeHelp("bigint unsigned")?.key).toBe("bigint");
expect(getMysqlDataTypeHelp("varchar")?.key).toBe("varchar");
expect(getMysqlDataTypeHelp("mediumblob")?.key).toBe("mediumblob");
expect(getMysqlDataTypeHelp("enum")?.key).toBe("enum");
expect(getMysqlDataTypeHelp("timestamp")?.key).toBe("timestamp");
expect(getMysqlDataTypeHelp("json")?.key).toBe("json");
expect(getMysqlDataTypeHelp("geometrycollection")?.key).toBe("geometrycollection");
});
it("uses product-specific JSON help when the connection profile identifies the server", () => {
expect(getMysqlDataTypeHelp("json")).toEqual({ key: "json" });
expect(getMysqlDataTypeHelp("json", { product: "mysql" })).toEqual({ key: "jsonMysql" });
expect(getMysqlDataTypeHelp("json", { product: "mariadb" })).toEqual({ key: "jsonMariaDb" });
});
it("warns about MySQL 8 numeric syntax based on the exact raw type", () => {
expect(getMysqlDataTypeHelp("INT(11) ZEROFILL")).toEqual({ key: "int", warningKeys: ["integerDisplayWidth", "zerofill"] });
expect(getMysqlDataTypeHelp("DECIMAL(10,2) UNSIGNED")).toEqual({ key: "decimal", warningKeys: ["unsignedNumeric"] });
expect(getMysqlDataTypeHelp("FLOAT(30)")).toEqual({ key: "float", warningKeys: ["floatPrecision"] });
expect(getMysqlDataTypeHelp("DOUBLE(10,2) UNSIGNED")).toEqual({ key: "double", warningKeys: ["unsignedNumeric", "floatingPointDisplay"] });
});
it("also recognizes compatible-server extensions and leaves unknown custom types alone", () => {
expect(getMysqlDataTypeHelp("inet4")?.key).toBe("inet4");
expect(getMysqlDataTypeHelp("inet6")?.key).toBe("inet6");
expect(getMysqlDataTypeHelp("uuid")?.key).toBe("uuid");
expect(getMysqlDataTypeHelp("vector(1536)")?.key).toBe("vector");
expect(getMysqlDataTypeHelp("xmltype")?.key).toBe("xmltype");
expect(getMysqlDataTypeHelp("my_private_type")).toBeUndefined();
});
it("covers every built-in MySQL type option", () => {
const undocumented = DATA_TYPE_OPTIONS.mysql.filter((type) => !getMysqlDataTypeHelp(type));
expect(undocumented).toEqual([]);
});
it("has an English and Simplified Chinese message for every supported help key", () => {
const options = [...DATA_TYPE_OPTIONS.mysql, "inet4", "inet6", "uuid", "vector", "xmltype", "character", "char varying", "char byte", "geomcollection", "nchar", "nvarchar", "national character varying", "int(11) zerofill", "decimal(10,2) unsigned", "float(30)", "double(10,2)"];
const english = mysqlHelpMessages(en);
const chinese = mysqlHelpMessages(zhCN);
for (const option of options) {
const key = getMysqlDataTypeHelp(option)?.key;
expect(key, option).toBeTruthy();
for (const helpKey of [key!, ...(getMysqlDataTypeHelp(option)?.warningKeys ?? [])]) {
expect(english[helpKey], `English: ${option}`).toEqual(expect.any(String));
expect(chinese[helpKey], `Simplified Chinese: ${option}`).toEqual(expect.any(String));
}
}
});
});
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";
import { DATA_TYPE_OPTIONS } from "@/lib/table/tableStructureEditorState";
import { getPostgresDataTypeHelp } from "@/lib/table/postgresDataTypeHelp";
import en from "@/i18n/locales/en";
import zhCN from "@/i18n/locales/zh-CN";
function postgresHelpMessages(locale: unknown): Record<string, unknown> {
const messages = locale as { structureEditor?: { postgresDataTypeHelp?: Record<string, unknown> } };
return messages.structureEditor?.postgresDataTypeHelp ?? {};
}
describe("getPostgresDataTypeHelp", () => {
it("covers every built-in PostgreSQL type option", () => {
expect(DATA_TYPE_OPTIONS.postgres.filter((type) => !getPostgresDataTypeHelp(type))).toEqual([]);
});
it("normalizes aliases and float precision parameters", () => {
expect(getPostgresDataTypeHelp("int2")).toEqual({ key: "smallint" });
expect(getPostgresDataTypeHelp("INT4")).toEqual({ key: "integer" });
expect(getPostgresDataTypeHelp("int8")).toEqual({ key: "bigint" });
expect(getPostgresDataTypeHelp("decimal(10, 2)")).toEqual({ key: "numeric" });
expect(getPostgresDataTypeHelp("float")).toEqual({ key: "double" });
expect(getPostgresDataTypeHelp("float(24)")).toEqual({ key: "real" });
expect(getPostgresDataTypeHelp("float(25)")).toEqual({ key: "double" });
expect(getPostgresDataTypeHelp("float(0)")).toBeUndefined();
expect(getPostgresDataTypeHelp("float(54)")).toBeUndefined();
expect(getPostgresDataTypeHelp("float(1.5)")).toBeUndefined();
expect(getPostgresDataTypeHelp("float(precision)")).toBeUndefined();
expect(getPostgresDataTypeHelp("character varying(255)")).toEqual({ key: "varchar" });
});
it("documents serial, temporal aliases, dynamic built-ins, and arrays", () => {
expect(getPostgresDataTypeHelp("bigserial")).toEqual({ key: "serial" });
expect(getPostgresDataTypeHelp("timestamp with time zone")).toEqual({ key: "timestamptz" });
expect(getPostgresDataTypeHelp("int4multirange")).toEqual({ key: "multirange" });
expect(getPostgresDataTypeHelp("jsonpath")).toEqual({ key: "jsonpath" });
expect(getPostgresDataTypeHelp("pg_lsn")).toEqual({ key: "pgLsn" });
expect(getPostgresDataTypeHelp("pg_snapshot")).toEqual({ key: "pgSnapshot" });
expect(getPostgresDataTypeHelp("uuid[][]")).toEqual({ key: "array" });
expect(getPostgresDataTypeHelp("my_schema.order_status[]")).toEqual({ key: "array" });
});
it("leaves extensions and named user types undocumented", () => {
expect(getPostgresDataTypeHelp("vector(1536)")).toBeUndefined();
expect(getPostgresDataTypeHelp("geometry(Point, 4326)")).toBeUndefined();
expect(getPostgresDataTypeHelp("citext")).toBeUndefined();
expect(getPostgresDataTypeHelp("hstore")).toBeUndefined();
expect(getPostgresDataTypeHelp("order_status")).toBeUndefined();
expect(getPostgresDataTypeHelp("order_status_multirange")).toBeUndefined();
});
it("has English and Simplified Chinese copy for every supported static key", () => {
const english = postgresHelpMessages(en);
const chinese = postgresHelpMessages(zhCN);
const dynamic = ["int4multirange", "jsonpath", "pg_lsn", "pg_snapshot", "any_type[]"];
for (const option of [...DATA_TYPE_OPTIONS.postgres, ...dynamic]) {
const key = getPostgresDataTypeHelp(option)?.key;
expect(key, option).toBeTruthy();
expect(english[key!], `English: ${option}`).toEqual(expect.any(String));
expect(chinese[key!], `Simplified Chinese: ${option}`).toEqual(expect.any(String));
}
});
});
@@ -0,0 +1,63 @@
import { describe, expect, it } from "vitest";
import { DATA_TYPE_OPTIONS } from "@/lib/table/tableStructureEditorState";
import { getSqliteDataTypeHelp } from "@/lib/table/sqliteDataTypeHelp";
import en from "@/i18n/locales/en";
import zhCN from "@/i18n/locales/zh-CN";
function sqliteHelpMessages(locale: unknown): Record<string, unknown> {
const messages = locale as { structureEditor?: { sqliteDataTypeHelp?: Record<string, unknown> } };
return messages.structureEditor?.sqliteDataTypeHelp ?? {};
}
describe("getSqliteDataTypeHelp", () => {
it("covers every built-in SQLite type option", () => {
expect(DATA_TYPE_OPTIONS.sqlite.filter((type) => !getSqliteDataTypeHelp(type))).toEqual([]);
});
it("normalizes whitespace, casing, and declared type parameters", () => {
expect(getSqliteDataTypeHelp(" INTEGER ")).toEqual({ key: "integer" });
expect(getSqliteDataTypeHelp("VARCHAR(255)")).toEqual({ key: "text" });
expect(getSqliteDataTypeHelp(" decimal(10, 2) ")).toEqual({ key: "numeric" });
});
it("applies SQLite's ordered declared-type affinity rules", () => {
expect(getSqliteDataTypeHelp("char(12)")).toEqual({ key: "text" });
expect(getSqliteDataTypeHelp("boolean")).toEqual({ key: "numeric" });
expect(getSqliteDataTypeHelp("unsigned big int")).toEqual({ key: "integer" });
expect(getSqliteDataTypeHelp("double precision")).toEqual({ key: "real" });
expect(getSqliteDataTypeHelp("date")).toEqual({ key: "numeric" });
expect(getSqliteDataTypeHelp("datetime")).toEqual({ key: "numeric" });
expect(getSqliteDataTypeHelp("time")).toEqual({ key: "numeric" });
expect(getSqliteDataTypeHelp("VARCHAR2")).toEqual({ key: "text" });
expect(getSqliteDataTypeHelp("CHARACTER")).toEqual({ key: "text" });
expect(getSqliteDataTypeHelp("INT64")).toEqual({ key: "integer" });
expect(getSqliteDataTypeHelp("FLOATING POINT")).toEqual({ key: "integer" });
expect(getSqliteDataTypeHelp("STRING")).toEqual({ key: "numeric" });
expect(getSqliteDataTypeHelp("application_status")).toEqual({ key: "numeric" });
expect(getSqliteDataTypeHelp("")).toEqual({ key: "blob" });
});
it("has English and Simplified Chinese copy for static and common help keys", () => {
const english = sqliteHelpMessages(en);
const chinese = sqliteHelpMessages(zhCN);
const types = [...DATA_TYPE_OPTIONS.sqlite, "varchar", "boolean", "datetime"];
for (const type of types) {
const key = getSqliteDataTypeHelp(type)?.key;
expect(key, type).toBeTruthy();
expect(english[key!], `English: ${type}`).toEqual(expect.any(String));
expect(chinese[key!], `Simplified Chinese: ${type}`).toEqual(expect.any(String));
}
});
it("calls out SQLite affinity and its important storage exceptions", () => {
const english = sqliteHelpMessages(en);
expect(english.integer).toContain("rowid");
expect(english.integer).toContain("does not enforce");
expect(english.real).toContain("IEEE 754");
expect(english.text).toContain("do not enforce n");
expect(english.blob).toContain("without type conversion");
expect(english.numeric).toContain("not a separate SQLite storage class");
});
});
@@ -3,6 +3,8 @@ import {
combineDataTypeForDatabase,
createColumnDrafts,
dataTypeLengthInputValue,
DATA_TYPE_OPTIONS,
defaultNewColumnDataType,
getDefaultLengthForType,
hasExistingColumnTypeChange,
isDataTypeLengthDisabled,
@@ -109,6 +111,30 @@ describe("tableStructureEditorState", () => {
expect(getDefaultLengthForType("mysql", "integer")).toBe("11");
});
it("uses MySQL 8-safe defaults only when the native MySQL profile is known", () => {
const mysql8Defaults = { omitMysqlDeprecatedDefaults: true };
expect(getDefaultLengthForType("mysql", "int", mysql8Defaults)).toBe("");
expect(getDefaultLengthForType("mysql", "bigint unsigned", mysql8Defaults)).toBe("");
expect(getDefaultLengthForType("mysql", "float", mysql8Defaults)).toBe("");
expect(getDefaultLengthForType("mysql", "double", mysql8Defaults)).toBe("");
expect(combineDataTypeForDatabase("mysql", "int", getDefaultLengthForType("mysql", "int", mysql8Defaults))).toBe("int");
expect(combineDataTypeForDatabase("mysql", "float", getDefaultLengthForType("mysql", "float", mysql8Defaults))).toBe("float");
expect(getDefaultLengthForType("mysql", "decimal", mysql8Defaults)).toBe("10,0");
// A compatibility profile cannot be version-identified, so its existing behavior is retained.
expect(getDefaultLengthForType("mysql", "int")).toBe("11");
expect(getDefaultLengthForType("mysql", "float")).toBe("10,2");
});
it("uses TEXT for a new native SQLite column without changing compatible defaults", () => {
expect(DATA_TYPE_OPTIONS.sqlite).toContain("text");
expect(defaultNewColumnDataType("sqlite")).toBe("text");
expect(defaultNewColumnDataType("rqlite")).toBe("varchar(255)");
expect(defaultNewColumnDataType("turso")).toBe("varchar(255)");
expect(defaultNewColumnDataType("mysql")).toBe("varchar(255)");
});
it("requires a SQLite rebuild only for a retained existing column type change", () => {
const [column] = createColumnDrafts(
[
@@ -0,0 +1,13 @@
export interface OptionHelpPanelOffsetInput {
activeItemTop: number;
listCardHeight: number;
panelHeight: number;
}
/** Aligns a help card to its active row without allowing it past the list card. */
export function optionHelpPanelOffsetTop({ activeItemTop, listCardHeight, panelHeight }: OptionHelpPanelOffsetInput): number {
if (![activeItemTop, listCardHeight, panelHeight].every(Number.isFinite)) return 0;
const desiredTop = Math.max(0, activeItemTop);
const maxTop = Math.max(0, listCardHeight - Math.max(0, panelHeight));
return Math.min(desiredTop, maxTop);
}
@@ -0,0 +1,19 @@
export type SearchableSelectOptionTooltip = (option: string) => string | undefined;
/** Keep the option list aligned with its trigger while help expands rightward. */
export const SEARCHABLE_SELECT_HELP_PANEL_ALIGN = "start";
/**
* Returns the option whose help panel is activated by keyboard navigation
* while focus remains in the searchable input. Empty-string options are valid.
*/
export function searchableSelectKeyboardTooltipOption(options: readonly string[], highlightIndex: number, optionTooltip?: SearchableSelectOptionTooltip): string | undefined {
const option = options[highlightIndex];
return option === undefined || !optionTooltip?.(option) ? undefined : option;
}
/** Returns the selected option's help, or the first available option's help. */
export function searchableSelectSelectedOrFirstHelpOption(options: readonly string[], selectedOption: string, optionTooltip?: SearchableSelectOptionTooltip): string | undefined {
if (options.includes(selectedOption) && optionTooltip?.(selectedOption)) return selectedOption;
return options.find((option) => !!optionTooltip?.(option));
}
@@ -0,0 +1,41 @@
export const REDIS_CREATE_KEY_TYPE_VALUES = ["string", "hash", "list", "set", "zset", "stream", "json"] as const;
export type RedisCreateKeyTypeValue = (typeof REDIS_CREATE_KEY_TYPE_VALUES)[number];
export type RedisCreateKeyTypeHelpKey = RedisCreateKeyTypeValue;
export interface RedisCreateKeyTypeHelp {
key: RedisCreateKeyTypeHelpKey;
}
export interface RedisCreateKeyTypeHelpFocusState {
openedByArrow: boolean;
keyboardNavigating: boolean;
}
const REDIS_CREATE_KEY_TYPE_HELP: Readonly<Record<RedisCreateKeyTypeValue, RedisCreateKeyTypeHelpKey>> = {
string: "string",
hash: "hash",
list: "list",
set: "set",
zset: "zset",
stream: "stream",
json: "json",
};
/** Returns help for a Redis data type offered by the Create key dialog. */
export function getRedisCreateKeyTypeHelp(rawType: string): RedisCreateKeyTypeHelp | undefined {
const type = rawType.trim().toLowerCase() as RedisCreateKeyTypeValue;
const key = REDIS_CREATE_KEY_TYPE_HELP[type];
return key ? { key } : undefined;
}
/** Returns the selected offered type whose help is shown when the Select opens. */
export function redisCreateKeyTypeHelpOptionOnOpen(rawType: string): RedisCreateKeyTypeValue | undefined {
const type = rawType.trim().toLowerCase() as RedisCreateKeyTypeValue;
return REDIS_CREATE_KEY_TYPE_HELP[type] ? type : undefined;
}
/** Determines whether a SelectItem focus event was caused by Arrow navigation. */
export function shouldActivateRedisCreateKeyTypeHelpOnFocus(state: RedisCreateKeyTypeHelpFocusState): boolean {
return state.openedByArrow || state.keyboardNavigating;
}
@@ -0,0 +1,199 @@
export type MysqlDataTypeHelpKey =
| "tinyint"
| "smallint"
| "mediumint"
| "int"
| "bigint"
| "decimal"
| "float"
| "double"
| "real"
| "bit"
| "boolean"
| "serial"
| "date"
| "datetime"
| "timestamp"
| "time"
| "year"
| "char"
| "varchar"
| "tinytext"
| "text"
| "mediumtext"
| "longtext"
| "binary"
| "varbinary"
| "tinyblob"
| "blob"
| "mediumblob"
| "longblob"
| "enum"
| "set"
| "json"
| "jsonMysql"
| "jsonMariaDb"
| "nationalCharacter"
| "geometry"
| "point"
| "linestring"
| "polygon"
| "multipoint"
| "multilinestring"
| "multipolygon"
| "geometrycollection"
| "inet4"
| "inet6"
| "uuid"
| "vector"
| "xmltype"
| "integerDisplayWidth"
| "zerofill"
| "unsignedNumeric"
| "floatPrecision"
| "floatingPointDisplay";
export interface MysqlDataTypeHelp {
key: MysqlDataTypeHelpKey;
warningKeys?: MysqlDataTypeHelpKey[];
}
export interface MysqlDataTypeHelpOptions {
/** Set only when the selected connection profile identifies the server product. */
product?: "mysql" | "mariadb";
}
const MYSQL_TYPE_HELP_KEYS: Readonly<Record<string, MysqlDataTypeHelpKey>> = {
tinyint: "tinyint",
smallint: "smallint",
mediumint: "mediumint",
int: "int",
bigint: "bigint",
decimal: "decimal",
float: "float",
double: "double",
real: "real",
bit: "bit",
boolean: "boolean",
nationalCharacter: "nationalCharacter",
serial: "serial",
date: "date",
datetime: "datetime",
timestamp: "timestamp",
time: "time",
year: "year",
char: "char",
varchar: "varchar",
tinytext: "tinytext",
text: "text",
mediumtext: "mediumtext",
longtext: "longtext",
binary: "binary",
varbinary: "varbinary",
tinyblob: "tinyblob",
blob: "blob",
mediumblob: "mediumblob",
longblob: "longblob",
enum: "enum",
set: "set",
json: "json",
geometry: "geometry",
point: "point",
linestring: "linestring",
polygon: "polygon",
multipoint: "multipoint",
multilinestring: "multilinestring",
multipolygon: "multipolygon",
geometrycollection: "geometrycollection",
inet4: "inet4",
inet6: "inet6",
uuid: "uuid",
vector: "vector",
xmltype: "xmltype",
};
const MYSQL_TYPE_ALIASES: Readonly<Record<string, string>> = {
integer: "int",
numeric: "decimal",
dec: "decimal",
fixed: "decimal",
bool: "boolean",
"character varying": "varchar",
character: "char",
"char varying": "varchar",
"char byte": "char",
nchar: "nationalCharacter",
nvarchar: "nationalCharacter",
"nchar varying": "nationalCharacter",
"national char": "nationalCharacter",
"national character": "nationalCharacter",
"national varchar": "nationalCharacter",
"national char varying": "nationalCharacter",
"national character varying": "nationalCharacter",
"double precision": "double",
float4: "float",
float8: "double",
int1: "tinyint",
int2: "smallint",
int3: "mediumint",
int4: "int",
int8: "bigint",
middleint: "mediumint",
long: "mediumtext",
"long varchar": "mediumtext",
"long varbinary": "mediumblob",
geomcollection: "geometrycollection",
};
/**
* Returns help for a MySQL-family type name without making a database request.
* The caller is responsible for limiting this to connections that use MySQL
* semantics, since several compatible databases accept similarly named types
* with different limits.
*/
export function getMysqlDataTypeHelp(rawType: string, options: MysqlDataTypeHelpOptions = {}): MysqlDataTypeHelp | undefined {
const normalized = normalizeMysqlType(rawType);
const resolvedType = MYSQL_TYPE_ALIASES[normalized] ?? normalized;
const baseKey = MYSQL_TYPE_HELP_KEYS[resolvedType];
if (!baseKey) return undefined;
const key = resolvedType === "json" ? jsonHelpKey(options.product) : baseKey;
const warningKeys = mysqlDataTypeWarningKeys(rawType, resolvedType);
return warningKeys.length > 0 ? { key, warningKeys } : { key };
}
function jsonHelpKey(product: MysqlDataTypeHelpOptions["product"]): MysqlDataTypeHelpKey {
if (product === "mysql") return "jsonMysql";
if (product === "mariadb") return "jsonMariaDb";
return "json";
}
function mysqlDataTypeWarningKeys(rawType: string, resolvedType: string): MysqlDataTypeHelpKey[] {
const lowered = rawType.trim().toLowerCase().replace(/\s+/g, " ");
const warnings: MysqlDataTypeHelpKey[] = [];
const isInteger = ["tinyint", "smallint", "mediumint", "int", "bigint"].includes(resolvedType);
const isNumeric = isInteger || ["decimal", "float", "double", "real"].includes(resolvedType);
if (isInteger && /\(\s*\d+\s*\)/.test(lowered)) warnings.push("integerDisplayWidth");
if (isNumeric && /\bzerofill\b/.test(lowered)) warnings.push("zerofill");
if (["decimal", "float", "double", "real"].includes(resolvedType) && /\bunsigned\b/.test(lowered)) warnings.push("unsignedNumeric");
const parameters = lowered.match(/\(([^)]*)\)/)?.[1]?.trim() ?? "";
if (resolvedType === "float" && /^\d+$/.test(parameters)) {
const precision = Number(parameters);
if (precision >= 25 && precision <= 53) warnings.push("floatPrecision");
}
if (["float", "double"].includes(resolvedType) && /^\d+\s*,\s*\d+$/.test(parameters)) warnings.push("floatingPointDisplay");
return warnings;
}
function normalizeMysqlType(rawType: string): string {
return rawType
.trim()
.toLowerCase()
.replace(/\([^)]*\)/g, " ")
.replace(/\b(?:unsigned|signed|zerofill)\b/g, " ")
.replace(/\s+/g, " ")
.trim();
}
@@ -0,0 +1,155 @@
export type PostgresDataTypeHelpKey =
| "smallint"
| "integer"
| "bigint"
| "serial"
| "numeric"
| "real"
| "double"
| "money"
| "boolean"
| "char"
| "varchar"
| "text"
| "bytea"
| "date"
| "time"
| "timetz"
| "timestamp"
| "timestamptz"
| "interval"
| "uuid"
| "json"
| "jsonb"
| "xml"
| "bit"
| "tsvector"
| "tsquery"
| "cidr"
| "inet"
| "macaddr"
| "geometry"
| "range"
| "oid"
| "array"
| "multirange"
| "jsonpath"
| "pgLsn"
| "pgSnapshot";
export interface PostgresDataTypeHelp {
key: PostgresDataTypeHelpKey;
}
const POSTGRES_TYPE_HELP_KEYS: Readonly<Record<string, PostgresDataTypeHelpKey>> = {
smallint: "smallint",
integer: "integer",
bigint: "bigint",
smallserial: "serial",
serial: "serial",
bigserial: "serial",
numeric: "numeric",
real: "real",
"double precision": "double",
money: "money",
boolean: "boolean",
char: "char",
varchar: "varchar",
text: "text",
bytea: "bytea",
date: "date",
time: "time",
timetz: "timetz",
timestamp: "timestamp",
timestamptz: "timestamptz",
interval: "interval",
uuid: "uuid",
json: "json",
jsonb: "jsonb",
xml: "xml",
bit: "bit",
"bit varying": "bit",
tsvector: "tsvector",
tsquery: "tsquery",
cidr: "cidr",
inet: "inet",
macaddr: "macaddr",
macaddr8: "macaddr",
point: "geometry",
line: "geometry",
lseg: "geometry",
box: "geometry",
path: "geometry",
polygon: "geometry",
circle: "geometry",
int4range: "range",
int8range: "range",
numrange: "range",
tsrange: "range",
tstzrange: "range",
daterange: "range",
oid: "oid",
jsonpath: "jsonpath",
pg_lsn: "pgLsn",
pg_snapshot: "pgSnapshot",
};
const POSTGRES_TYPE_ALIASES: Readonly<Record<string, string>> = {
int2: "smallint",
int: "integer",
int4: "integer",
int8: "bigint",
decimal: "numeric",
float4: "real",
float8: "double precision",
bool: "boolean",
character: "char",
"character varying": "varchar",
"time without time zone": "time",
"time with time zone": "timetz",
"timestamp without time zone": "timestamp",
"timestamp with time zone": "timestamptz",
varbit: "bit varying",
};
const POSTGRES_MULTIRANGE_TYPES = new Set(["int4multirange", "int8multirange", "nummultirange", "tsmultirange", "tstzmultirange", "datemultirange"]);
/**
* Returns static PostgreSQL type help without querying the server. Extension
* types and user-defined types intentionally remain undocumented.
*/
export function getPostgresDataTypeHelp(rawType: string): PostgresDataTypeHelp | undefined {
const normalized = normalizePostgresType(rawType);
if (isPostgresArrayType(normalized)) return { key: "array" };
const baseType = normalized
.replace(/\([^)]*\)/g, " ")
.replace(/\s+/g, " ")
.trim();
if (baseType === "float") {
const key = floatHelpKey(normalized);
return key ? { key } : undefined;
}
if (POSTGRES_MULTIRANGE_TYPES.has(baseType)) return { key: "multirange" };
const canonicalType = POSTGRES_TYPE_ALIASES[baseType] ?? baseType;
const key = POSTGRES_TYPE_HELP_KEYS[canonicalType];
return key ? { key } : undefined;
}
function normalizePostgresType(rawType: string): string {
return rawType.trim().toLowerCase().replace(/\s+/g, " ");
}
function isPostgresArrayType(normalizedType: string): boolean {
return /(?:\[\s*\]\s*)+$/.test(normalizedType);
}
function floatHelpKey(normalizedType: string): "real" | "double" | undefined {
if (normalizedType === "float") return "double";
const precision = normalizedType.match(/^float\(\s*(\d+)\s*\)$/)?.[1];
if (!precision) return undefined;
const value = Number(precision);
if (value >= 1 && value <= 24) return "real";
return value >= 25 && value <= 53 ? "double" : undefined;
}
@@ -0,0 +1,24 @@
export type SqliteDataTypeHelpKey = "integer" | "real" | "text" | "blob" | "numeric";
export interface SqliteDataTypeHelp {
key: SqliteDataTypeHelpKey;
}
/**
* Maps declared types using SQLite's ordered affinity rules. The order matters:
* for example, FLOATING POINT has INTEGER affinity because it contains "INT".
*/
export function getSqliteDataTypeHelp(rawType: string): SqliteDataTypeHelp | undefined {
const normalized = rawType
.trim()
.toLowerCase()
.replace(/\([^)]*\)/g, " ")
.replace(/\s+/g, " ")
.trim();
if (!normalized) return { key: "blob" };
if (normalized.includes("int")) return { key: "integer" };
if (normalized.includes("char") || normalized.includes("clob") || normalized.includes("text")) return { key: "text" };
if (normalized.includes("blob")) return { key: "blob" };
if (normalized.includes("real") || normalized.includes("floa") || normalized.includes("doub")) return { key: "real" };
return { key: "numeric" };
}
@@ -965,8 +965,17 @@ function isValidTemporalPrecision(dbType: DatabaseType | undefined, params: stri
return Number.isInteger(value) && value >= 0 && value <= max && String(value) === params;
}
export function getDefaultLengthForType(_dbType: DatabaseType | undefined, baseType: string): string {
export interface DataTypeDefaultOptions {
/**
* Native MySQL profiles use MySQL 8-safe defaults. Compatibility profiles
* retain their existing DDL defaults because their server/version is unknown.
*/
omitMysqlDeprecatedDefaults?: boolean;
}
export function getDefaultLengthForType(_dbType: DatabaseType | undefined, baseType: string, options: DataTypeDefaultOptions = {}): string {
const key = baseType.trim().toLowerCase();
if (_dbType === "mysql" && options.omitMysqlDeprecatedDefaults && isMysqlDeprecatedDefaultParameterType(key)) return "";
if (_dbType === "sqlite" || _dbType === "rqlite" || _dbType === "turso") {
return "";
} else if (_dbType === "questdb") {
@@ -978,6 +987,20 @@ export function getDefaultLengthForType(_dbType: DatabaseType | undefined, baseT
}
}
/** Default data type for a newly added structure-editor column. */
export function defaultNewColumnDataType(dbType: DatabaseType | undefined, dataTypeOptions: readonly string[] = []): string {
if (dbType === "manticoresearch") {
const baseType = dataTypeOptions[0] ?? "text";
return combineDataTypeForDatabase(dbType, baseType, getDefaultLengthForType(dbType, baseType));
}
return dbType === "sqlite" ? "text" : "varchar(255)";
}
function isMysqlDeprecatedDefaultParameterType(baseType: string): boolean {
const typeName = baseType.split(/\s+/)[0];
return ["tinyint", "smallint", "mediumint", "int", "integer", "bigint", "float", "double", "real"].includes(typeName ?? "");
}
export function isDataTypeLengthDisabled(_dbType: DatabaseType | undefined, baseType: string): boolean {
const key = baseType.trim().toLowerCase();
if (_dbType === "questdb") {