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(grid): complete operators and typed values in the WHERE input (#12879)

HARRISON0dc6de17769c
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index f7c6a2059a..94b929e11e 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -1225,7 +1225,7 @@ const filterBuilderColumns = computed(() =>
resultColumnTypes: props.result.column_types,
}),
);
-const conditionColumns = computed(() => dataGridConditionColumnOptions(props.tableMeta ? filterBuilderColumns.value.map((column) => column.columnInfo ?? column.name) : props.result.columns, resolvedDatabaseType.value));
+const conditionColumns = computed(() => dataGridConditionColumnOptions(props.tableMeta ? filterBuilderColumns.value.map((column) => ({ name: column.name, dataType: column.columnInfo?.data_type, comment: column.columnInfo?.comment ?? undefined })) : props.result.columns, resolvedDatabaseType.value));
const conditionIdentifierQuote = computed(() => dataGridConditionIdentifierQuote(resolvedDatabaseType.value, connectionStore.connectionIdentifierQuote?.(props.connectionId)));
const conditionHistoryScope = computed(() => ({
connectionId: props.connectionId,
diff --git a/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts
index 17ca56cf74..58c8cbb6ce 100644
--- a/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDataGridConditionEditor.spec.ts
@@ -855,4 +855,161 @@ describe("useDataGridConditionEditor", () => {
await nextTick();
await vi.waitFor(() => expect(editor.suggestions.value).toEqual([{ value: "ILIKE", kind: "keyword" }]));
});
+
+ it("suggests comparison operators after a complete column and inserts the trailing space", async () => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({ kind: "where", value, columns: ["status"], historyScope: {}, suggestionDebounceMs: 1 });
+
+ value.value = "status ";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["=", "<>", ">", ">=", "<", "<=", "LIKE", "NOT LIKE", "IN", "BETWEEN", "IS NULL", "IS NOT NULL"]));
+ // 运算符不预选:回车仍然是执行查询,不会悄悄改写条件
+ expect(editor.highlightedIndex.value).toBe(-1);
+
+ expect(editor.accept(1)).toBe(true);
+ expect(value.value).toBe("status <> ");
+
+ // 关键字运算符仍然可用,且不会和符号运算符重复
+ value.value = "status li";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["LIKE"]));
+ });
+
+ it("suggests dialect-aware value expressions after an operator for temporal columns", async () => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({
+ kind: "where",
+ value,
+ columns: [
+ { name: "CREATE_TIME", dataType: "TIMESTAMP(6)" },
+ { name: "AMOUNT", dataType: "NUMBER" },
+ ],
+ databaseType: "oracle",
+ historyScope: {},
+ suggestionDebounceMs: 1,
+ });
+
+ value.value = "CREATE_TIME > ";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["SYSTIMESTAMP", "TRUNC(SYSDATE)", "TRUNC(SYSDATE) - 1", "SYSTIMESTAMP - INTERVAL '7' DAY", "SYSTIMESTAMP - INTERVAL '30' DAY"]));
+
+ expect(editor.accept(3)).toBe(true);
+ expect(value.value).toBe("CREATE_TIME > SYSTIMESTAMP - INTERVAL '7' DAY");
+
+ // 非时间列仍然是空建议:绝不在这里提示列名(issue #10595)
+ value.value = "AMOUNT <> ";
+ await nextTick();
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ expect(editor.suggestions.value).toEqual([]);
+ });
+
+ it("keeps offering the next layer after accepting a column and an operator", async () => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({
+ kind: "where",
+ value,
+ columns: [{ name: "CREATE_TIME", dataType: "DATE" }],
+ databaseType: "oracle",
+ historyScope: {},
+ suggestionDebounceMs: 1,
+ });
+
+ value.value = "CREA";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["CREATE_TIME"]));
+ expect(editor.handleKeydown(keyboardEvent("Enter"))).toBe("accept");
+ expect(value.value).toBe("CREATE_TIME");
+
+ value.value = "CREATE_TIME ";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toContain(">="));
+ expect(editor.accept(3)).toBe(true);
+ expect(value.value).toBe("CREATE_TIME >= ");
+
+ // 接受带尾随空格的运算符后光标已经在值位置,候选要立刻接上,不用再敲一个字
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["SYSTIMESTAMP", "TRUNC(SYSDATE)", "TRUNC(SYSDATE) - 1", "SYSTIMESTAMP - INTERVAL '7' DAY", "SYSTIMESTAMP - INTERVAL '30' DAY"]));
+ });
+
+ it.each([
+ ["mysql", "DATETIME", "NOW()"],
+ ["postgres", "timestamptz", "now()"],
+ ["sqlite", "TEXT DATE", "datetime('now')"],
+ ["sqlserver", "datetime2", "GETDATE()"],
+ ["hive", "TIMESTAMP", "CURRENT_TIMESTAMP"],
+ ] as const)("uses %s value snippets for %s columns", async (databaseType, dataType, firstSnippet) => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({
+ kind: "where",
+ value,
+ columns: [{ name: "created_at", dataType }],
+ databaseType,
+ historyScope: {},
+ suggestionDebounceMs: 1,
+ });
+
+ value.value = "created_at >= ";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value[0]?.value).toBe(firstSnippet));
+ });
+
+ it("suggests numeric literals for SQL Server bit columns", async () => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({
+ kind: "where",
+ value,
+ columns: [{ name: "enabled", dataType: "bit" }],
+ databaseType: "sqlserver",
+ historyScope: {},
+ suggestionDebounceMs: 1,
+ });
+ value.value = "enabled = ";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["1", "0"]));
+ expect(editor.accept(0)).toBe(true);
+ expect(value.value).toBe("enabled = 1");
+ });
+
+ it("does not suggest boolean literals for PostgreSQL bit strings", async () => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({
+ kind: "where",
+ value,
+ columns: [{ name: "mask", dataType: "bit(8)" }],
+ databaseType: "postgres",
+ historyScope: {},
+ suggestionDebounceMs: 1,
+ });
+ value.value = "mask = ";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestionsLoading.value).toBe(false));
+ expect(editor.suggestions.value).toEqual([]);
+ });
+
+ it("suggests TRUE/FALSE for boolean columns and opens an IN list without value snippets", async () => {
+ const value = ref("");
+ const editor = useDataGridConditionEditor({
+ kind: "where",
+ value,
+ columns: [{ name: "enabled", dataType: "boolean" }],
+ databaseType: "postgres",
+ historyScope: {},
+ suggestionDebounceMs: 1,
+ });
+
+ value.value = "enabled = ";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toEqual(["TRUE", "FALSE"]));
+
+ value.value = "enabled ";
+ await nextTick();
+ await vi.waitFor(() => expect(editor.suggestions.value.map((item) => item.value)).toContain("IN"));
+ expect(editor.accept(8)).toBe(true);
+ expect(value.value).toBe("enabled IN (");
+
+ // IN 列表里只写值,不再给单个表达式建议
+ value.value = "enabled IN (";
+ await nextTick();
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ expect(editor.suggestions.value).toEqual([]);
+ });
});
diff --git a/apps/desktop/src/composables/useDataGridConditionEditor.ts b/apps/desktop/src/composables/useDataGridConditionEditor.ts
index 3dfc4b9d74..4bbe8a54ba 100644
--- a/apps/desktop/src/composables/useDataGridConditionEditor.ts
+++ b/apps/desktop/src/composables/useDataGridConditionEditor.ts
@@ -1,5 +1,6 @@
import { computed, getCurrentScope, onScopeDispose, ref, toValue, watch, type MaybeRefOrGetter, type Ref } from "vue";
import { forgetDataGridConditionHistory, loadDataGridConditionHistory, rememberDataGridConditionHistory, type DataGridConditionHistoryKind, type DataGridConditionHistoryScope } from "@/lib/dataGrid/dataGridConditionHistory";
+import { dataGridConditionValueSnippets } from "@/lib/dataGrid/dataGridConditionValueSnippets";
import { pinyinAwareMatchScore } from "@/lib/common/pinyin";
import { matchesIdentifierSearch } from "@/lib/sql/identifierSearch";
import type { DatabaseType } from "@/types/database";
@@ -10,6 +11,8 @@ export interface DataGridConditionColumnSuggestion {
name: string;
insertText?: string;
comment?: string | null;
+ /** Column type, used to offer dialect-correct value expressions (dates, booleans). */
+ dataType?: string;
}
export type DataGridConditionColumnOption = string | DataGridConditionColumnSuggestion;
@@ -125,7 +128,10 @@ function filterKeywordSuggestions(keywords: readonly (DataGridConditionKeyword |
const WHERE_CONNECTOR_KEYWORDS = ["AND", "OR"] as const;
const WHERE_IS_NOT_OPERATOR_PATTERN = /(?:^|[\s(])IS\s+NOT$/i;
const WHERE_IS_OPERATOR_PATTERN = /(?:^|[\s(])IS$/i;
-const WHERE_VALUE_OPERATOR_PATTERN = /(?:^|[\s(])(?:(?:NOT\s+)?(?:LIKE|ILIKE|IN|BETWEEN)|SIMILAR\s+TO|REGEXP|RLIKE|GLOB|MATCH)\s*$/i;
+const WHERE_VALUE_OPERATOR_PATTERN = /(?:^|[\s(])(?:(?:NOT\s+)?(?:LIKE|ILIKE|BETWEEN)|SIMILAR\s+TO|REGEXP|RLIKE|GLOB|MATCH)\s*$/i;
+/** `IN` / `NOT IN` 后面是括号列表,不是单个表达式值位置。 */
+const WHERE_IN_OPERATOR_PATTERN = /(?:^|[\s(])(?:NOT\s+)?IN\s*$/i;
+const CONDITION_TRAILING_IDENTIFIER_PATTERN = /("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[(?:\]\]|[^\]])*\]|[A-Za-z_][\w$]*)$/;
/**
* 比较类符号运算符。它们后面同样是「值」位置,不应再提示列名,
* 否则用户输入值时会看到列名补全、回车/接受后输入被改写(issue #10595)。
@@ -133,6 +139,24 @@ const WHERE_VALUE_OPERATOR_PATTERN = /(?:^|[\s(])(?:(?:NOT\s+)?(?:LIKE|ILIKE|IN|
const WHERE_SYMBOLIC_COMPARISON_PATTERN = /(?:<>|!=|<=|>=|=|<|>)$/;
/** ORDER BY 中排序列之后的位置只应提示排序方向。 */
const ORDER_BY_DIRECTION_KEYWORDS = ["ASC", "DESC"] as const;
+/**
+ * 列名之后的运算符补全。选中后带上尾随空格,光标直接落到值位置,
+ * 所以「列名 → 运算符 → 值」可以一路回车选下来。
+ */
+const WHERE_COMPARISON_OPERATORS: readonly { value: string; insertText: string }[] = [
+ { value: "=", insertText: "= " },
+ { value: "<>", insertText: "<> " },
+ { value: ">", insertText: "> " },
+ { value: ">=", insertText: ">= " },
+ { value: "<", insertText: "< " },
+ { value: "<=", insertText: "<= " },
+ { value: "LIKE", insertText: "LIKE " },
+ { value: "NOT LIKE", insertText: "NOT LIKE " },
+ { value: "IN", insertText: "IN (" },
+ { value: "BETWEEN", insertText: "BETWEEN " },
+ { value: "IS NULL", insertText: "IS NULL" },
+ { value: "IS NOT NULL", insertText: "IS NOT NULL" },
+];
interface DataGridConditionCompletionTarget {
value: string;
@@ -294,19 +318,75 @@ function insideInValueList(value: string, cursor: number, identifierQuote: strin
return /(?:^|[\s(])IN$/i.test(before) || /(?:^|[\s(])NOT\s+IN$/i.test(before);
}
-function whereSuggestionRole(target: DataGridConditionCompletionTarget, identifierQuote: string | undefined): "field" | "connector" | "is_value" | "is_not_value" | "after_not" | "none" {
+function unquotedConditionIdentifier(identifier: string): string {
+ const open = identifier[0];
+ if ((open !== '"' && open !== "`" && open !== "[") || identifier.length < 2) return identifier;
+ const close = identifierCloseQuote(open);
+ if (!identifier.endsWith(close)) return identifier;
+ return identifier.slice(1, -1).replaceAll(close + close, close);
+}
+
+function findConditionColumn(columns: readonly DataGridConditionColumnOption[], name: string): DataGridConditionColumnOption | undefined {
+ const lowered = name.toLowerCase();
+ return columns.find((column) => (typeof column === "string" ? column : column.name).toLowerCase() === lowered);
+}
+
+/** 光标前最后一个标识符是否是完整列名(例如 `status ` 已经在写运算符)。 */
+function isColumnReferencePosition(prefix: string, columns: readonly DataGridConditionColumnOption[]): boolean {
+ const match = CONDITION_TRAILING_IDENTIFIER_PATTERN.exec(prefix);
+ if (!match) return false;
+ if (!findConditionColumn(columns, unquotedConditionIdentifier(match[1]))) return false;
+ const before = prefix.slice(0, match.index).trimEnd();
+ // 只有左操作数位置(开头、括号/逗号后、AND/OR/NOT 后)才是运算符位置;
+ // `a = status ` 已经是完整表达式,接下来该写 AND/OR。
+ return !before || /[,(]$/.test(before) || /(?:^|\s)(?:AND|OR|NOT)$/i.test(before);
+}
+
+/** 值位置对应的列名:跳过紧贴光标的运算符,再取它前面的标识符。 */
+function valuePositionColumnName(value: string, from: number): string | undefined {
+ const prefix = value.slice(0, from).trimEnd();
+ const operator = WHERE_VALUE_OPERATOR_PATTERN.exec(prefix) ?? WHERE_SYMBOLIC_COMPARISON_PATTERN.exec(prefix);
+ if (!operator) return undefined;
+ const identifier = CONDITION_TRAILING_IDENTIFIER_PATTERN.exec(prefix.slice(0, operator.index).trimEnd());
+ return identifier ? unquotedConditionIdentifier(identifier[1]) : undefined;
+}
+
+function comparisonOperatorSuggestions(normalizedToken: string, databaseType: DatabaseType | undefined): DataGridConditionSuggestion[] {
+ // 列名之后除了符号运算符,还有 REGEXP / ILIKE / SIMILAR TO 这类关键字运算符;
+ // AND/OR 在这里不合法,留给连接符位置。
+ const keywordOperators = normalizedToken
+ ? filterKeywordSuggestions(
+ WHERE_SYNTAX_KEYWORDS.filter((keyword) => {
+ const value = typeof keyword === "string" ? keyword : keyword.value;
+ return value !== "AND" && value !== "OR";
+ }),
+ normalizedToken,
+ (value) => isConditionKeywordSupported(value, databaseType),
+ )
+ : [];
+ const suggestions = WHERE_COMPARISON_OPERATORS.filter((operator) => !normalizedToken || operator.value.toLowerCase().startsWith(normalizedToken)).map((operator) => ({ value: operator.value, insertText: operator.insertText, kind: "keyword" as const }));
+ const seen = new Set(keywordOperators.map((keyword) => keyword.value));
+ // 已经打出关键字前缀时保留原有的关键字提示(带说明、不改写后续输入);
+ // 只在空 token(刚打完列名)时补上带尾随空格的符号运算符。
+ return [...keywordOperators, ...suggestions.filter((suggestion) => !seen.has(suggestion.value))];
+}
+
+function whereSuggestionRole(target: DataGridConditionCompletionTarget, identifierQuote: string | undefined, columns: readonly DataGridConditionColumnOption[]): "field" | "connector" | "operator" | "value" | "is_value" | "is_not_value" | "after_not" | "none" {
if (target.insideString) return "none";
if (target.quotedIdentifier) return "field";
const prefix = target.value.slice(0, target.from).trimEnd();
if (WHERE_IS_NOT_OPERATOR_PATTERN.test(prefix)) return "is_not_value";
if (WHERE_IS_OPERATOR_PATTERN.test(prefix)) return "is_value";
- if (WHERE_VALUE_OPERATOR_PATTERN.test(prefix)) return "none";
- // 符号比较运算符之后是值位置:`v_id = v` 时不提示列名,只在 AND/OR 等字段位置提示
- if (WHERE_SYMBOLIC_COMPARISON_PATTERN.test(prefix)) return "none";
- // `mi_id IN (v` / `mi_id IN ('a', v` 同样是值列表,不能提示列名
+ // `mi_id IN (v` / `mi_id IN ('a', v` 是值列表,不能提示列名,也不提示单个表达式
+ if (WHERE_IN_OPERATOR_PATTERN.test(prefix)) return "none";
+ if (WHERE_VALUE_OPERATOR_PATTERN.test(prefix)) return "value";
+ // 符号比较运算符之后是值位置:`v_id = v` 时不提示列名(issue #10595),
+ // 改为按列类型提示日期/布尔表达式。
+ if (WHERE_SYMBOLIC_COMPARISON_PATTERN.test(prefix)) return "value";
if (insideInValueList(target.value, target.from, identifierQuote)) return "none";
if (!prefix || /(?:^|\s)(?:AND|OR)$/i.test(prefix) || /[,(+\-*/~]$/.test(prefix)) return "field";
if (/(?:^|\s)NOT$/i.test(prefix)) return "after_not";
+ if (isColumnReferencePosition(prefix, columns)) return "operator";
return "connector";
}
@@ -430,18 +510,30 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
return scored.map((entry) => entry.suggestion);
}
+ function valueSuggestions(target: DataGridConditionCompletionTarget, columns: readonly DataGridConditionColumnOption[]): DataGridConditionSuggestion[] {
+ const columnName = valuePositionColumnName(target.value, target.from);
+ if (!columnName) return [];
+ const column = findConditionColumn(columns, columnName);
+ const dataType = typeof column === "string" ? undefined : column?.dataType;
+ const normalizedToken = target.token.toLowerCase();
+ return dataGridConditionValueSnippets(dataType, toValue(options.databaseType))
+ .filter((snippet) => !normalizedToken || snippet.toLowerCase().startsWith(normalizedToken))
+ .map((snippet) => ({ value: snippet, kind: "keyword" }));
+ }
+
function defaultSuggestions(target: DataGridConditionCompletionTarget): DataGridConditionSuggestion[] {
- const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target);
+ const columns = toValue(options.columns) ?? [];
+ const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote), columns) : orderBySuggestionRole(target);
if (role === "none") return [];
const normalizedToken = target.token.toLowerCase();
const seen = new Set<string>();
const isKeywordSupported = (keyword: string) => isConditionKeywordSupported(keyword, toValue(options.databaseType));
+ if (role === "operator") return comparisonOperatorSuggestions(normalizedToken, toValue(options.databaseType));
+ if (role === "value") return valueSuggestions(target, columns);
if (role === "field") {
- const columns = toValue(options.columns) ?? [];
return columnSuggestions(columns, normalizedToken, target, seen);
}
if (role === "after_not") {
- const columns = toValue(options.columns) ?? [];
const suggestions = columnSuggestions(columns, normalizedToken, target, seen);
if (normalizedToken) {
suggestions.push(...filterKeywordSuggestions(WHERE_AFTER_NOT_KEYWORDS, normalizedToken, isKeywordSupported));
@@ -467,14 +559,15 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
if (!target.token && (options.kind !== "where" || !target.value.trim())) return;
suggestionsLoading.value = true;
try {
- const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote)) : orderBySuggestionRole(target);
+ const role = options.kind === "where" ? whereSuggestionRole(target, toValue(options.identifierQuote), toValue(options.columns) ?? []) : orderBySuggestionRole(target);
const values =
options.suggestionProvider && target.token && (role === "field" || role === "after_not")
? await options.suggestionProvider({ kind: options.kind, value: target.value, valueBeforeCursor: target.valueBeforeCursor, token: target.token, from: target.from, to: target.to, selectionStart: target.selectionStart, selectionEnd: target.selectionEnd, signal: controller.signal })
: undefined;
// A slower request must never replace suggestions for a newer editor value.
if (controller.signal.aborted || requestId !== suggestionRequestId || options.value.value !== target.value || historyOpen.value) return;
- const limit = options.suggestionLimit ?? 8;
+ const defaultLimit = role === "operator" ? WHERE_COMPARISON_OPERATORS.length : 8;
+ const limit = options.suggestionLimit ?? defaultLimit;
const providerValues = values ? [...new Set(values)] : undefined;
suggestions.value = providerValues ? (providerValues.some((value) => value.toLowerCase() === target.token.toLowerCase()) ? [] : providerValues.slice(0, limit).map((suggestion) => ({ value: suggestion, kind: "column" }))) : defaultSuggestions(target).slice(0, limit);
replacementRange.value = { from: target.from, to: target.to };
@@ -561,7 +654,9 @@ export function useDataGridConditionEditor(options: UseDataGridConditionEditorOp
options.value.value = `${options.value.value.slice(0, range.from)}${replacement}${options.value.value.slice(range.to)}`;
caret = range.from + replacement.length;
}
- suppressedSuggestionValue = options.value.value;
+ // 运算符补全把光标送进值位置,应当立刻给出下一层候选(日期/布尔表达式);
+ // 其他补全仍然保持折叠,避免同一批候选再弹一次。
+ suppressedSuggestionValue = !suggestion.insertText?.endsWith(" ") ? options.value.value : undefined;
if (options.selectionStart) options.selectionStart.value = caret;
if (options.selectionEnd) options.selectionEnd.value = caret;
dismiss();
diff --git a/apps/desktop/src/lib/dataGrid/dataGridConditionCompletion.ts b/apps/desktop/src/lib/dataGrid/dataGridConditionCompletion.ts
index 87d74e2d7a..b880531eea 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridConditionCompletion.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridConditionCompletion.ts
@@ -57,7 +57,8 @@ export function dataGridConditionColumnOptions(columns: readonly DataGridConditi
const name = typeof column === "string" ? column : column.name;
const insertText = quoteSqlIdentifier(name, dialect);
const comment = typeof column === "string" ? undefined : column.comment;
- return { name, insertText, ...(comment !== undefined ? { comment } : {}) };
+ const dataType = typeof column === "string" ? undefined : column.dataType;
+ return { name, insertText, ...(comment !== undefined ? { comment } : {}), ...(dataType ? { dataType } : {}) };
});
}
diff --git a/apps/desktop/src/lib/dataGrid/dataGridConditionValueSnippets.ts b/apps/desktop/src/lib/dataGrid/dataGridConditionValueSnippets.ts
new file mode 100644
index 0000000000..f4f5fd6edf
--- /dev/null
+++ b/apps/desktop/src/lib/dataGrid/dataGridConditionValueSnippets.ts
@@ -0,0 +1,66 @@
+import type { DatabaseType } from "@/types/database";
+
+/**
+ * Value-position suggestions for the hand-written WHERE input. The caret sits
+ * right after a comparison operator, so the only useful hints are complete,
+ * dialect-correct expressions for the column type in front of it.
+ *
+ * 手写 WHERE 时最常忘的是日期函数的写法(Oracle 甚至不接受裸 ISO 字符串,
+ * 会报 ORA-01843)。这里只给「插进去就能跑」的完整表达式,不再套一层面板。
+ */
+const TEMPORAL_TYPE_PATTERN = /(?:^|[^a-z])(?:date|datetime|datetime2|datetimeoffset|smalldatetime|time|timestamp|timestamptz|timetz|year)(?:$|[^a-z])/;
+
+export function isDataGridConditionTemporalType(dataType?: string): boolean {
+ return dataType ? TEMPORAL_TYPE_PATTERN.test(dataType.toLowerCase()) : false;
+}
+
+export function isDataGridConditionBooleanType(dataType?: string, databaseType?: DatabaseType): boolean {
+ if (!dataType) return false;
+ // Mirrors the filter builder's rule: PostgreSQL "bit" is a bit string, not a boolean.
+ return dataType
+ .toLowerCase()
+ .split(/[^a-z0-9]+/)
+ .some((part) => part === "bool" || part === "boolean" || (part === "bit" && databaseType !== "postgres"));
+}
+
+function temporalValueSnippets(databaseType?: DatabaseType): string[] {
+ switch (databaseType) {
+ case "oracle":
+ case "oceanbase-oracle":
+ return ["SYSTIMESTAMP", "TRUNC(SYSDATE)", "TRUNC(SYSDATE) - 1", "SYSTIMESTAMP - INTERVAL '7' DAY", "SYSTIMESTAMP - INTERVAL '30' DAY"];
+ case "mysql":
+ case "doris":
+ case "starrocks":
+ case "goldendb":
+ case "databend":
+ return ["NOW()", "CURDATE()", "CURDATE() - INTERVAL 1 DAY", "NOW() - INTERVAL 7 DAY", "NOW() - INTERVAL 30 DAY"];
+ case "postgres":
+ case "redshift":
+ case "kingbase":
+ case "highgo":
+ case "uxdb":
+ case "vastbase":
+ case "gaussdb":
+ case "opengauss":
+ case "gbase8c":
+ case "questdb":
+ case "vertica":
+ return ["now()", "CURRENT_DATE", "CURRENT_DATE - 1", "now() - interval '7 days'", "now() - interval '30 days'"];
+ case "sqlite":
+ case "rqlite":
+ case "turso":
+ case "cloudflare-d1":
+ return ["datetime('now')", "date('now')", "date('now','-1 day')", "datetime('now','-7 days')", "datetime('now','-30 days')"];
+ case "sqlserver":
+ return ["GETDATE()", "CAST(GETDATE() AS DATE)", "CAST(DATEADD(day,-1,GETDATE()) AS DATE)", "DATEADD(day,-7,GETDATE())", "DATEADD(day,-30,GETDATE())"];
+ default:
+ // Portable fallback; relative offsets are skipped rather than guessed.
+ return ["CURRENT_TIMESTAMP", "CURRENT_DATE"];
+ }
+}
+
+export function dataGridConditionValueSnippets(dataType: string | undefined, databaseType?: DatabaseType): string[] {
+ if (isDataGridConditionBooleanType(dataType, databaseType)) return databaseType === "sqlserver" ? ["1", "0"] : ["TRUE", "FALSE"];
+ if (!isDataGridConditionTemporalType(dataType)) return [];
+ return temporalValueSnippets(databaseType);
+}