feat(database): support DuckDB SQL and browse attached catalogs (#6254)

DuckDB sources get DuckDB's SQL dialect (highlighting, completion, formatting and resolution) and the database tree lists attached catalogs with their schemas, tables and columns. The JDBC bridge gains a catalogs command and catalog-scoped schema and table metadata, matched by exact catalog and schema names; tables in another catalog open and page through the source session. DDL that attaches, detaches or changes a catalog refreshes the tree.

Co-authored-by: principalwater <[email protected]>
Цей коміт міститься в:
Vladislav Kuzmin authored and GitHub committed 2026-11-28 09:07:53 +08:00
1 джерело c04d9381be
коміт bd396485c2
38 files changed
+1743 -318

No files matched your search

+79 -29
Переглянути файл
@@ -5,8 +5,7 @@
* the caret (a statement, a table, a column expression, a join condition…).
* Purely lexical: works on half-typed statements a parser would reject.
*/
import type { DbDriver } from "@/platform/ipc";
import { CLAUSE_WORDS, isReserved } from "./dialect";
import { CLAUSE_WORDS, isReserved, nameMatcher, type SqlDriver } from "./dialect";
import { identName, inLiteral, lex, type Lexed, type Token } from "./lexer";
export interface TableRef {
@@ -38,6 +37,7 @@ export type Clause =
| "group"
| "order"
| "having"
| "qualify"
| "limit"
| "set"
| "values"
@@ -52,6 +52,7 @@ export type SqlContext =
/** Right after a FROM / JOIN item (alias, JOIN, WHERE…). */
| { kind: "afterTable"; ref: TableRef }
| { kind: "column"; clause: Clause }
| { kind: "exclude"; owner: string | null }
| { kind: "joinCondition"; ref: TableRef }
| { kind: "insertColumns"; target: TableRef }
| { kind: "afterInsertColumns" };
@@ -74,6 +75,12 @@ export interface Analysis {
lowerKeywords: boolean;
/** The token before the caret word (and its qualifier), upper-cased: `(`, `UNION`… */
previous: string | null;
/** DuckDB: whether FROM precedes the projection in this block. */
fromFirst?: boolean;
/** DuckDB: a projection star may take EXCLUDE, REPLACE or RENAME here. */
projectionStar?: boolean;
/** DuckDB: projection names available in QUALIFY. */
selectColumns?: string[];
}
const WORD_BEFORE = /[\p{L}\p{N}_$]*$/u;
@@ -100,8 +107,13 @@ const SET_OPS = new Set(["UNION", "INTERSECT", "EXCEPT"]);
const QUERY_START = new Set(["SELECT", "WITH", "VALUES", "TABLE"]);
/** The clause a keyword starts (Snowflake's QUALIFY filters like HAVING). */
const clauseOf = (t: Token, driver: DbDriver): Clause | undefined =>
CLAUSES[t.upper] ?? (driver === "snowflake" && t.upper === "QUALIFY" ? "having" : undefined);
const clauseOf = (t: Token, driver: SqlDriver): Clause | undefined => {
if (t.upper === "QUALIFY") {
if (driver === "duckdb") return "qualify";
if (driver === "snowflake") return "having";
}
return CLAUSES[t.upper];
};
const isIdent = (t: Token | undefined): t is Token =>
!!t && (t.kind === "quoted" || (t.kind === "word" && !CLAUSE_WORDS.has(t.upper)));
@@ -135,7 +147,7 @@ class Parens {
}
}
export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexed = lex(text, driver)): Analysis {
export function analyze(text: string, pos: number, driver: SqlDriver, lexed: Lexed = lex(text, driver)): Analysis {
const word = WORD_BEFORE.exec(text.slice(Math.max(0, pos - 256), pos))![0];
const prefix = { from: pos - word.length, text: word };
const all = lexed.tokens;
@@ -171,15 +183,19 @@ export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexe
if (isP(st[i], "(")) open.push(i);
else if (isP(st[i], ")")) open.pop();
}
const isQuery = (p: number) => p === -1 || (st[p + 1]?.kind === "word" && QUERY_START.has(st[p + 1]!.upper));
const duckdb = driver === "duckdb";
const isQuery = (p: number) =>
st[p + 1]?.kind === "word" && (QUERY_START.has(st[p + 1]!.upper) || (duckdb && isW(st[p + 1], "FROM")));
const blocks = [...open.filter(isQuery).reverse(), -1];
const block = blocks[0]!;
const range = blockRange(st, parens, block, nb);
const ctes = parseCtes(st, parens);
const { ctes, bodyStart } = parseCtes(st, parens, driver);
const refs: TableRef[] = [];
const refEnds = new Map<number, TableRef>();
blocks.forEach((g, depth) => {
// Within an enclosing block, the "caret" is the paren of the block nested in it.
const [ra, rb] = blockRange(st, parens, g, depth === 0 ? nb : blocks[depth - 1]!);
const [ra, rb] = depth === 0 ? range : blockRange(st, parens, g, blocks[depth - 1]!);
for (const r of parseRefs(st, parens, g, ra, rb, ctes, depth, driver)) {
refs.push(r.ref);
if (depth === 0) refEnds.set(r.end, r.ref);
@@ -199,15 +215,21 @@ export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexe
}
const p = before[k];
const pi = k;
const block = blocks[0]!;
const clause = clauseAt(st, parens, block, open.length ? open.at(-1)! : -1, nb, driver);
const innermost = open.at(-1) ?? -1;
const clause = clauseAt(st, parens, block, innermost, nb, driver);
const starAt = (i: number) => duckdb && clause === "select" && parens.parent[i] === block && isProjectionStar(st, i);
const projectionStar = starAt(pi);
const excludedStar = isW(p, "EXCLUDE") ? pi - 1 : isW(st[innermost - 1], "EXCLUDE") ? innermost - 2 : -1;
// Snowflake `col:path`: the keys of a VARIANT are not in the model.
const variantPath =
driver === "snowflake" && isP(p, ":") && p!.to === (pi + 1 < before.length ? before[pi + 1]!.from : prefix.from);
let context: SqlContext;
if (literal) context = { kind: "none" };
else if (!p) context = qualifier.length ? { kind: "column", clause: "other" } : { kind: "statement" };
else if (starAt(excludedStar)) {
const owner = st[excludedStar - 2];
context = { kind: "exclude", owner: isP(st[excludedStar - 1], ".") && owner ? identName(owner) : null };
} else if (!p) context = qualifier.length ? { kind: "column", clause: "other" } : { kind: "statement" };
else if (
p.kind === "word" &&
TABLE_INTRO.has(p.upper) &&
@@ -232,6 +254,11 @@ export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexe
else context = { kind: "column", clause };
}
const queryStart = block === -1 ? Math.max(range[0], bodyStart) : range[0];
const firstProjectionClause =
duckdb && !isW(st[queryStart], "DELETE", "UPDATE")
? parens.level(block, queryStart, Math.min(nb, range[1])).find((i) => isW(st[i], "SELECT", "FROM"))
: undefined;
return {
context,
qualifier: qualifier.length ? qualifier : null,
@@ -243,9 +270,22 @@ export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexe
fromInsert: fromInsertPos(st, parens, block, pos),
lowerKeywords,
previous: p ? p.upper : null,
...(duckdb && {
projectionStar,
fromFirst: firstProjectionClause !== undefined && isW(st[firstProjectionClause], "FROM"),
selectColumns: clause === "qualify" ? outputColumns(st, parens, block, ...range, driver) : undefined,
}),
};
}
/** A bare or qualified projection star. A multiplication operator is part of an expression. */
function isProjectionStar(st: Token[], i: number): boolean {
if (!isP(st[i], "*")) return false;
let prev = i - 1;
while (isP(st[prev], ".") && isIdent(st[prev - 1])) prev -= 2;
return isW(st[prev], "SELECT", "DISTINCT", "ALL") || isP(st[prev], ",");
}
/** Token range of block `g`, cut to the UNION / INTERSECT / EXCEPT branch containing `caret` (a token index). */
function blockRange(st: Token[], parens: Parens, g: number, caret: number): [number, number] {
let a = g + 1;
@@ -268,7 +308,7 @@ function clauseAt(
block: number,
innermost: number,
caret: number,
driver: DbDriver,
driver: SqlDriver,
): Clause {
// Inside a non-query paren (function call, IN list), the clause is the one around that paren.
const limit = innermost > block ? innermost : caret;
@@ -283,9 +323,10 @@ function clauseAt(
return clause;
}
function parseCtes(st: Token[], parens: Parens): TableRef[] {
const out: TableRef[] = [];
if (!isW(st[0], "WITH")) return out;
function parseCtes(st: Token[], parens: Parens, driver: SqlDriver): { ctes: TableRef[]; bodyStart: number } {
const ctes: TableRef[] = [];
let bodyStart = 0;
if (!isW(st[0], "WITH")) return { ctes, bodyStart };
let i = 1;
if (isW(st[i], "RECURSIVE")) i++;
while (i < st.length && isIdent(st[i])) {
@@ -305,8 +346,8 @@ function parseCtes(st: Token[], parens: Parens): TableRef[] {
while (isW(st[i], "NOT", "MATERIALIZED")) i++;
if (!isP(st[i], "(")) break;
const c = parens.close.get(i)!;
columns ??= outputColumns(st, parens, i, i + 1, c);
out.push({
columns ??= outputColumns(st, parens, i, i + 1, c, driver);
ctes.push({
schema: null,
name: identName(nameTok),
alias: null,
@@ -318,15 +359,22 @@ function parseCtes(st: Token[], parens: Parens): TableRef[] {
depth: 0,
viaJoin: false,
});
i = c + 1;
i = bodyStart = c + 1;
if (!isP(st[i], ",")) break;
i++;
}
return out;
return { ctes, bodyStart };
}
/** Output column names of the query in group `g` (`a..b`): aliases and plain column references. */
export function outputColumns(st: Token[], parens: Parens, g: number, a: number, b: number): string[] {
export function outputColumns(
st: Token[],
parens: Parens,
g: number,
a: number,
b: number,
driver: SqlDriver,
): string[] {
const level = parens.level(g, a, b);
const sel = level.find((i) => isW(st[i], "SELECT"));
if (sel === undefined) return [];
@@ -358,6 +406,7 @@ export function outputColumns(st: Token[], parens: Parens, g: number, a: number,
t.upper === "GROUP" ||
t.upper === "ORDER" ||
t.upper === "LIMIT" ||
(driver === "duckdb" && isW(t, "HAVING", "WINDOW", "QUALIFY", "OFFSET")) ||
SET_OPS.has(t.upper))
)
break;
@@ -378,10 +427,11 @@ function parseRefs(
b: number,
ctes: TableRef[],
depth: number,
driver: DbDriver,
driver: SqlDriver,
): Array<{ ref: TableRef; end: number }> {
const out: Array<{ ref: TableRef; end: number }> = [];
const level = parens.level(g, a, b);
const eq = nameMatcher(driver);
let clause: Clause = "other";
const item = (j: number, viaJoin = false, into = false) => {
while (isW(st[j], "LATERAL", "ONLY")) j++;
@@ -389,7 +439,7 @@ function parseRefs(
if (!t || j >= b) return;
if (isP(t, "(")) {
const c = parens.close.get(j)!;
const columns = outputColumns(st, parens, j, j + 1, c);
const columns = outputColumns(st, parens, j, j + 1, c, driver);
const al = alias(st, c + 1, b, driver);
if (al)
out.push({
@@ -426,10 +476,7 @@ function parseRefs(
const name = identName(last);
const schema = parts.length > 1 ? identName(parts.at(-2)!) : null;
const al = alias(st, k, b, driver);
const cte =
schema === null
? ctes.find((c) => (driver === "clickhouse" ? c.name === name : c.name.toLowerCase() === name.toLowerCase()))
: undefined;
const cte = schema === null ? ctes.find((c) => eq(c.name, name)) : undefined;
out.push({
ref: {
...(parts.length > 2 ? { database: identName(parts.at(-3)!) } : {}),
@@ -464,13 +511,16 @@ function parseRefs(
}
/** An alias at `k` (`AS x`, or a bare non-keyword identifier). */
function alias(st: Token[], k: number, b: number, driver: DbDriver): { name: string; tok: Token; end: number } | null {
function alias(st: Token[], k: number, b: number, driver: SqlDriver): { name: string; tok: Token; end: number } | null {
let j = k;
const as = isW(st[j], "AS");
if (as) j++;
const t = st[j];
if (j >= b || !t) return null;
if (t.kind === "quoted" || (t.kind === "word" && !CLAUSE_WORDS.has(t.upper) && (as || !isReserved(t.text, driver)))) {
if (
t.kind === "quoted" ||
(t.kind === "word" && !CLAUSE_WORDS.has(t.upper) && ((as && driver !== "duckdb") || !isReserved(t.text, driver)))
) {
return { name: identName(t), tok: t, end: j };
}
return null;
@@ -529,7 +579,7 @@ export interface ValuesSlot {
index: number;
}
export function valuesSlot(text: string, pos: number, driver: DbDriver): ValuesSlot | null {
export function valuesSlot(text: string, pos: number, driver: SqlDriver): ValuesSlot | null {
const a = analyze(text, pos, driver);
if (a.verb !== "INSERT" && a.verb !== "REPLACE") return null;
const target = a.refs.find((r) => r.depth === 0 && r.kind === "table");
+91 -36
Переглянути файл
@@ -5,16 +5,19 @@
* of the tables in scope with their owner and type, join conditions after ON,
* dialect functions and the keywords that may follow.
*/
import type { DbCompletion, DbCompletionColumn, DbCompletionTable, DbDriver } from "@/platform/ipc";
import type { DbCompletion, DbCompletionColumn, DbCompletionTable } from "@/platform/ipc";
import type { Analysis, Clause, TableRef } from "./analyze";
import {
DATA_TYPES,
functions,
identifierKey,
isReserved,
joinKeywords,
nameMatcher,
predicateKeywords,
statementStarters,
type SqlDriver,
type SqlFunction,
} from "./dialect";
export type CandidateKind =
@@ -69,7 +72,7 @@ const MAX_ALL_COLUMNS = 3000;
* what is not a plain word is quoted, which is right for the dialects that fold case
* neither way.
*/
export function quoteIdent(name: string, driver: DbDriver, dialect?: DbDriver | null): string {
export function quoteIdent(name: string, driver: SqlDriver, dialect?: SqlDriver | null): string {
const d = driver === "jdbc" && dialect ? dialect : driver;
const plain =
d === "postgres"
@@ -106,7 +109,7 @@ export function aliasFor(table: string, taken: ReadonlySet<string>): string {
}
/**
* What lies outside the schema model, for `database.schema.table` names (Snowflake): the data
* What lies outside the schema model, for `database.schema.table` names: the data
* source's databases, and the schemas and tables of one, as far as they are loaded. Names are
* matched the way the dialect matches them.
*/
@@ -126,9 +129,9 @@ export interface CompletionInput {
catalog?: SqlCatalog;
model: DbCompletion | null;
analysis: Analysis;
driver: DbDriver;
driver: SqlDriver;
/** The dialect a `jdbc` source speaks, from its URL (`jdbcDialect`); quoting follows it. */
dialect?: DbDriver | null;
dialect?: SqlDriver | null;
/** Data source name, shown next to tables like IDEA does. */
sourceName?: string;
}
@@ -142,6 +145,7 @@ export function sqlCandidates({
catalog,
}: CompletionInput): SqlCandidate[] {
const eq = nameMatcher(driver);
const columnKey = (name: string) => (driver === "duckdb" ? identifierKey(name, driver) : name.toLowerCase());
const ctx = a.context;
if (ctx.kind === "none") return [];
const typedLower = /[a-z]/.test(a.prefix.text) && !/[A-Z]/.test(a.prefix.text);
@@ -182,13 +186,15 @@ export function sqlCandidates({
schema
? tables.find((t) => eq(t.schema, schema) && eq(t.name, name))
: (tables.find((t) => eq(t.schema, defaultSchema) && eq(t.name, name)) ?? tables.find((t) => eq(t.name, name)));
const refTable = (r: TableRef): DbCompletionTable | undefined =>
r.kind === "table" && !(driver === "duckdb" && r.database !== undefined) ? findTable(r.schema, r.name) : undefined;
const columnsOf = (r: TableRef): Array<Pick<DbCompletionColumn, "name"> & Partial<DbCompletionColumn>> =>
r.columns ? r.columns.map((name) => ({ name })) : (findTable(r.schema, r.name)?.columns ?? []);
r.columns ? r.columns.map((name) => ({ name })) : (refTable(r)?.columns ?? []);
const refName = (r: TableRef) => r.alias ?? r.name;
/** Owner shown after a column: the alias, else the table qualified by its schema (IDEA's `(main.users)`). */
const ownerOf = (r: TableRef) => {
if (r.alias || r.kind !== "table") return refName(r);
const t = findTable(r.schema, r.name);
const t = refTable(r);
return t?.schema ? `${t.schema}.${t.name}` : r.name;
};
/** One candidate inserting several columns: `id, email, name`. */
@@ -236,30 +242,47 @@ export function sqlCandidates({
: undefined,
});
if (ctx.kind === "exclude") {
const seen = new Set<string>();
const qualifier = a.qualifier?.at(-1);
for (const r of a.refs) {
if (r.depth !== 0 || (ctx.owner && !eq(refName(r), ctx.owner)) || (qualifier && !eq(refName(r), qualifier)))
continue;
const t = refTable(r);
for (const c of columnsOf(r)) {
const key = columnKey(c.name);
if (seen.has(key)) continue;
seen.add(key);
out.push(columnCandidate(c, ownerOf(r), t, 40));
}
}
return out;
}
// ---- `qualifier.` ----------------------------------------------------------
if (a.qualifier) {
const [first, second] = a.qualifier;
if (a.qualifier.length === 1 && ctx.kind !== "table") {
const ref = a.refs.find((r) => eq(r.alias, first) || (!r.alias && eq(r.name, first)));
if (ref) {
const t = ref.kind === "table" ? findTable(ref.schema, ref.name) : undefined;
const t = refTable(ref);
return columnsOf(ref).map((c) => columnCandidate(c, refName(ref), t, 50));
}
}
if (a.qualifier.length === 1) {
const inSchema: SqlCandidate[] = tables
.filter((t) => eq(t.schema, first))
.map((t) => ({ ...tableCandidate(t, 30), insert: qn(t.name) }));
// `database.`: its schemas (a name can be a schema here and a database too).
// DuckDB rejects two-part names when a catalog and a schema share the qualifier.
const db = database(first!);
const inSchema: SqlCandidate[] =
driver === "duckdb" && db
? []
: tables.filter((t) => eq(t.schema, first)).map((t) => ({ ...tableCandidate(t, 30), insert: qn(t.name) }));
if (db) inSchema.push(...(catalog?.schemas(db) ?? []).map((s) => schemaCandidate(s, 20, `(${db})`)));
if (inSchema.length) return inSchema;
const t = findTable(null, first!);
if (t && ctx.kind !== "table") return t.columns.map((c) => columnCandidate(c, t.name, t, 50));
return [];
}
// Snowflake `database.schema.table`: the model holds the session's database only, keyed by the last two parts.
if (driver === "snowflake" && ctx.kind === "table") {
if ((driver === "snowflake" || driver === "duckdb") && ctx.kind === "table") {
// `database.schema.`: the tables of that schema, wherever the database is.
const db = a.qualifier.length === 2 ? database(first!) : undefined;
if (!db) return [];
@@ -273,6 +296,12 @@ export function sqlCandidates({
}));
}
const [schema, name] = driver === "snowflake" ? a.qualifier.slice(-2) : [first, second];
if (
driver === "duckdb" &&
(a.qualifier.length > 2 ||
a.refs.some((r) => r.database !== undefined && eq(r.schema, schema) && eq(r.name, name)))
)
return [];
const t = findTable(schema!, name!);
return t ? t.columns.map((c) => columnCandidate(c, t.name, t, 50)) : [];
}
@@ -307,6 +336,7 @@ export function sqlCandidates({
boost: -5,
});
if (ctx.join) keywords(["LATERAL"], -10);
if (driver === "duckdb") for (const f of functions(driver)) if (f.table) addFunction(f, 10);
return out;
}
@@ -334,6 +364,10 @@ export function sqlCandidates({
}
keywords(["AS", "WHERE", ...joinKeywords(driver), "GROUP BY", "ORDER BY", "LIMIT", "UNION", "UNION ALL"], 10);
if (driver === "snowflake") keywords(["QUALIFY", "SAMPLE", "PIVOT", "UNPIVOT", "MATCH_RECOGNIZE"], 10);
if (driver === "duckdb") {
keywords(["QUALIFY", "GROUP BY ALL", "ORDER BY ALL"], 10);
if (a.fromFirst) keywords(["SELECT"], 15);
}
}
return out;
}
@@ -344,7 +378,7 @@ export function sqlCandidates({
return out;
case "insertColumns": {
const t = ctx.target.kind === "table" ? findTable(ctx.target.schema, ctx.target.name) : undefined;
const t = refTable(ctx.target);
const all = columnsOf(ctx.target);
// The columns an INSERT needs (no default), then all of them.
const required = all.filter((c) => !c.hasDefault).map((c) => c.name);
@@ -380,16 +414,16 @@ export function sqlCandidates({
// Column names in several tables of the block are inserted qualified.
const count = new Map<string, number>();
for (const r of inner)
for (const c of columnsOf(r)) count.set(c.name.toLowerCase(), (count.get(c.name.toLowerCase()) ?? 0) + 1);
for (const c of columnsOf(r)) count.set(columnKey(c.name), (count.get(columnKey(c.name)) ?? 0) + 1);
const seen = new Set<string>();
for (const r of visible) {
const t = r.kind === "table" ? findTable(r.schema, r.name) : undefined;
const t = refTable(r);
const owner = ownerOf(r);
for (const c of columnsOf(r)) {
const key = `${owner}\u0000${c.name}`;
if (seen.has(key)) continue;
seen.add(key);
const ambiguous = r.depth > 0 || (count.get(c.name.toLowerCase()) ?? 0) > 1;
const ambiguous = r.depth > 0 || (count.get(columnKey(c.name)) ?? 0) > 1;
out.push(
columnCandidate(
c,
@@ -421,28 +455,38 @@ export function sqlCandidates({
}
for (const c of a.ctes)
if (!visible.some((r) => eq(r.name, c.name))) out.push({ label: c.name, kind: "table", tail: "(CTE)", boost: 0 });
const fnBoost = clause === "select" || clause === "having" ? 15 : 8;
for (const name of a.selectColumns ?? []) {
if (!out.some((c) => c.kind === "column" && eq(c.label, name)))
out.push({ label: name, kind: "column", insert: qn(name), boost: 45 });
}
const selectLike = clause === "select" || clause === "having" || clause === "qualify";
for (const f of functions(driver)) {
const name = lower || driver === "clickhouse" ? f.name : f.name.toUpperCase();
out.push({
label: name,
kind: "function",
tail: `(${f.params})`,
type: f.returns?.toUpperCase(),
snippet: f.params ? `${name}(\${})` : `${name}()\${0}`,
boost: f.aggregate && clause !== "select" && clause !== "having" ? fnBoost - 4 : fnBoost,
});
if (f.table && f.name !== "range" && f.name !== "generate_series") continue;
addFunction(f, selectLike ? 15 : f.aggregate ? 4 : 8);
}
keywords(clauseKeywords(clause, driver, a), 5);
}
function addFunction(f: SqlFunction, boost: number) {
const name = lower || driver === "clickhouse" ? f.name : f.name.toUpperCase();
out.push({
label: name,
kind: "function",
tail: `(${f.params})`,
type: f.returns?.toUpperCase(),
snippet: f.params ? `${name}(\${})` : `${name}()\${0}`,
boost,
});
}
}
function clauseKeywords(clause: Clause, driver: DbDriver, a: Analysis): string[] {
function clauseKeywords(clause: Clause, driver: SqlDriver, a: Analysis): string[] {
const pred = predicateKeywords(driver);
switch (clause) {
case "select":
return [
"FROM",
...(a.fromFirst ? [] : ["FROM"]),
...(a.projectionStar ? ["EXCLUDE", "REPLACE", "RENAME"] : []),
"DISTINCT",
"AS",
"CASE",
@@ -459,9 +503,17 @@ function clauseKeywords(clause: Clause, driver: DbDriver, a: Analysis): string[]
case "where":
case "on":
case "having":
return [...pred, "GROUP BY", "ORDER BY", "LIMIT", ...(driver === "snowflake" ? ["QUALIFY"] : [])];
return [
...pred,
"GROUP BY",
"ORDER BY",
"LIMIT",
...(driver === "snowflake" || driver === "duckdb" ? ["QUALIFY"] : []),
];
case "qualify":
return [...pred, "ORDER BY", "LIMIT"];
case "group":
return ["HAVING", "ORDER BY", "LIMIT", ...(driver === "snowflake" ? ["QUALIFY"] : [])];
return ["HAVING", "ORDER BY", "LIMIT", ...(driver === "snowflake" || driver === "duckdb" ? ["QUALIFY"] : [])];
case "order":
return ["ASC", "DESC", "LIMIT", "OFFSET", ...(driver === "mysql" ? [] : ["NULLS FIRST", "NULLS LAST"])];
case "set":
@@ -486,8 +538,8 @@ type Kw = (k: string) => string;
function joinCandidates(
a: Analysis,
model: DbCompletion | null,
driver: DbDriver,
dialect: DbDriver | null | undefined,
driver: SqlDriver,
dialect: SqlDriver | null | undefined,
taken: Set<string>,
kw: Kw,
): SqlCandidate[] {
@@ -499,6 +551,7 @@ function joinCandidates(
const local = (s: string) => eq(s, model.defaultSchema) || driver === "sqlite";
const tableText = (schema: string, name: string) => (local(schema) ? q(name) : `${q(schema)}.${q(name)}`);
for (const r of a.refs.filter((x) => x.depth === 0 && x.kind === "table")) {
if (driver === "duckdb" && r.database !== undefined) continue;
const rt = model.tables.find((t) => eq(t.name, r.name) && (r.schema ? eq(t.schema, r.schema) : true));
if (!rt) continue;
const ra = r.alias ?? r.name;
@@ -554,13 +607,15 @@ function conditionCandidates(
model: DbCompletion | null,
ref: TableRef,
kw: Kw,
driver: DbDriver,
driver: SqlDriver,
): SqlCandidate[] {
if (!model || ref.kind !== "table") return [];
const eq = nameMatcher(driver);
const out: SqlCandidate[] = [];
const find = (r: TableRef) =>
model.tables.find((t) => eq(t.name, r.name) && (r.schema ? eq(t.schema, r.schema) : true));
driver === "duckdb" && r.database !== undefined
? undefined
: model.tables.find((t) => eq(t.name, r.name) && (r.schema ? eq(t.schema, r.schema) : true));
const mine = find(ref);
if (!mine) return out;
const ma = ref.alias ?? ref.name;
+121 -12
Переглянути файл
@@ -1,5 +1,14 @@
/** Per-dialect SQL vocabulary: reserved words, statement starters and built-in functions. */
import type { DbDriver } from "@/platform/ipc";
import type { DataSource, DbDriver } from "@/platform/ipc";
/** DuckDB speaks its own SQL over the generic JDBC transport. */
export type SqlDriver = DbDriver | "duckdb";
export function sqlDriverOf(source: Pick<DataSource, "driver" | "vendor" | "url"> | null | undefined): SqlDriver {
if (source?.driver === "jdbc" && (source.vendor === "duckdb" || /^jdbc:duckdb:/i.test(source.url?.trim() ?? "")))
return "duckdb";
return source?.driver ?? "sqlite";
}
export interface SqlFunction {
name: string;
@@ -7,6 +16,7 @@ export interface SqlFunction {
params: string;
returns?: string;
aggregate?: boolean;
table?: boolean;
}
/** Words that must be quoted when used as identifiers (the common core of the three dialects). */
@@ -29,13 +39,35 @@ const SNOWFLAKE_RESERVED = new Set(
).split(" "),
);
export function isReserved(word: string, driver?: DbDriver): boolean {
const upper = word.toUpperCase();
return RESERVED.has(upper) || (driver === "snowflake" && SNOWFLAKE_RESERVED.has(upper));
// Public keyword categories from DuckDB 1.5's duckdb_keywords().
const DUCKDB_RESERVED = new Set(
(
"ANALYSE ANALYZE ARRAY ASYMMETRIC BOTH DEFERRABLE DESCRIBE DO INITIALLY LAMBDA LATERAL LEADING ONLY " +
"PIVOT PIVOT_LONGER PIVOT_WIDER PLACING QUALIFY RETURNING SHOW SOME SUMMARIZE SYMMETRIC TRAILING UNPIVOT VARIADIC"
).split(" "),
);
export function isReserved(word: string, driver?: SqlDriver): boolean {
const upper = sqlWordUpper(word, driver);
return (
RESERVED.has(upper) ||
(driver === "snowflake" && SNOWFLAKE_RESERVED.has(upper)) ||
(driver === "duckdb" && DUCKDB_RESERVED.has(upper))
);
}
export const nameMatcher = (driver: DbDriver) => (a: string | null | undefined, b: string | null | undefined) =>
!!a && !!b && (driver === "clickhouse" ? a === b : a.toLowerCase() === b.toLowerCase());
export function sqlWordUpper(word: string, driver?: SqlDriver): string {
return driver === "duckdb" ? word.replace(/[a-z]/g, (letter) => letter.toUpperCase()) : word.toUpperCase();
}
export function identifierKey(name: string, driver: SqlDriver): string {
if (driver === "clickhouse") return name;
// DuckDB folds ASCII letters in quoted and unquoted names.
return driver === "duckdb" ? name.replace(/[A-Z]/g, (letter) => letter.toLowerCase()) : name.toLowerCase();
}
export const nameMatcher = (driver: SqlDriver) => (a: string | null | undefined, b: string | null | undefined) =>
!!a && !!b && identifierKey(a, driver) === identifierKey(b, driver);
/** Clause keywords: a word in this set ends a table alias or expression. */
export const CLAUSE_WORDS = new Set(
@@ -46,7 +78,7 @@ export const CLAUSE_WORDS = new Set(
).split(" "),
);
export function statementStarters(driver: DbDriver): string[] {
export function statementStarters(driver: SqlDriver): string[] {
if (driver === "clickhouse")
return [
"SELECT",
@@ -143,6 +175,23 @@ export function statementStarters(driver: DbDriver): string[] {
"ROLLBACK",
];
if (driver === "jdbc") return common;
if (driver === "duckdb")
return [
...common,
"FROM",
"ATTACH",
"DETACH",
"USE",
"COPY",
"CREATE SCHEMA",
"CREATE MACRO",
"DESCRIBE",
"SHOW TABLES",
"SHOW DATABASES",
"SUMMARIZE",
"PIVOT",
"UNPIVOT",
];
if (driver === "sqlite") return [...common, "PRAGMA", "VACUUM", "ATTACH DATABASE", "REPLACE INTO", "CREATE TRIGGER"];
if (driver === "mysql")
return [
@@ -183,7 +232,7 @@ export function statementStarters(driver: DbDriver): string[] {
];
}
export function joinKeywords(driver: DbDriver): string[] {
export function joinKeywords(driver: SqlDriver): string[] {
const j = ["JOIN", "LEFT JOIN", "INNER JOIN", "CROSS JOIN", "RIGHT JOIN"];
if (driver !== "mysql") j.push("FULL JOIN");
if (driver === "postgres") j.push("JOIN LATERAL", "LEFT JOIN LATERAL");
@@ -193,7 +242,7 @@ export function joinKeywords(driver: DbDriver): string[] {
}
/** Comparison / predicate keywords of WHERE, ON and HAVING. */
export function predicateKeywords(driver: DbDriver): string[] {
export function predicateKeywords(driver: SqlDriver): string[] {
const k = [
"AND",
"OR",
@@ -214,10 +263,40 @@ export function predicateKeywords(driver: DbDriver): string[] {
if (driver === "sqlite") k.push("GLOB", "REGEXP");
if (driver === "oracle") k.push("CONNECT BY PRIOR", "START WITH", "NOT IN", "IS NOT NULL");
if (driver === "snowflake") k.push("ILIKE", "RLIKE", "REGEXP", "IS DISTINCT FROM", "ANY");
if (driver === "duckdb") k.push("ILIKE", "GLOB", "IS DISTINCT FROM", "SIMILAR TO");
return k;
}
export const DATA_TYPES: Record<DbDriver, string[]> = {
export const DATA_TYPES: Record<SqlDriver, string[]> = {
duckdb: [
"TINYINT",
"SMALLINT",
"INTEGER",
"BIGINT",
"HUGEINT",
"UTINYINT",
"USMALLINT",
"UINTEGER",
"UBIGINT",
"UHUGEINT",
"DECIMAL",
"FLOAT",
"DOUBLE",
"VARCHAR",
"BOOLEAN",
"DATE",
"TIME",
"TIMESTAMP",
"TIMESTAMPTZ",
"INTERVAL",
"BLOB",
"UUID",
"JSON",
"STRUCT",
"MAP",
"UNION",
"ARRAY",
],
jdbc: ["INTEGER", "BIGINT", "DECIMAL", "DOUBLE PRECISION", "VARCHAR", "BOOLEAN", "DATE", "TIME", "TIMESTAMP"],
snowflake: [
"NUMBER",
@@ -398,8 +477,38 @@ const COMMON: SqlFunction[] = [
f("cast", "expr AS type"),
];
const FUNCTIONS: Record<DbDriver, SqlFunction[]> = {
const FUNCTIONS: Record<SqlDriver, SqlFunction[]> = {
jdbc: COMMON,
duckdb: [
...COMMON,
f("count_if", "condition", "bigint", true),
f("string_agg", "expr, delimiter", "varchar", true),
f("list", "expr", undefined, true),
f("arg_max", "arg, value", undefined, true),
f("arg_min", "arg, value", undefined, true),
f("approx_count_distinct", "expr", "bigint", true),
f("quantile_cont", "expr, fraction", undefined, true),
f("regexp_matches", "text, pattern", "boolean"),
f("date_trunc", "part, timestamp"),
f("date_diff", "part, start, end", "bigint"),
f("list_transform", "list, lambda"),
f("list_filter", "list, lambda"),
f("struct_pack", "name := expr, ...", "struct"),
f("json_extract", "json, path", "json"),
f("unnest", "value"),
f("row_number", "", "bigint"),
f("rank", "", "bigint"),
f("dense_rank", "", "bigint"),
f("lag", "expr, offset, default"),
f("lead", "expr, offset, default"),
{ ...f("read_csv", "path, options..."), table: true },
{ ...f("read_parquet", "path, options..."), table: true },
{ ...f("read_json", "path, options..."), table: true },
{ ...f("range", "start, stop, step"), table: true },
{ ...f("generate_series", "start, stop, step"), table: true },
{ ...f("duckdb_tables", ""), table: true },
{ ...f("duckdb_columns", ""), table: true },
],
snowflake: [
...COMMON,
f("listagg", "expr, delimiter", "varchar", true),
@@ -654,6 +763,6 @@ const FUNCTIONS: Record<DbDriver, SqlFunction[]> = {
],
};
export function functions(driver: DbDriver): SqlFunction[] {
export function functions(driver: SqlDriver): SqlFunction[] {
return FUNCTIONS[driver];
}
+31
Переглянути файл
@@ -0,0 +1,31 @@
import { SQLDialect } from "@codemirror/lang-sql";
import type { LRLanguage } from "@codemirror/language";
import { CLAUSE_WORDS, DATA_TYPES, functions, predicateKeywords, statementStarters } from "./dialect";
let language: LRLanguage | undefined;
/** Token colouring for DuckDB; scope and completion come from the SQL editor. */
export function duckdbLanguage(): LRLanguage {
return (language ??= SQLDialect.define({
keywords: [
...CLAUSE_WORDS,
...statementStarters("duckdb"),
...predicateKeywords("duckdb"),
"ASOF ANTI SEMI EXCLUDE REPLACE RENAME COLUMNS QUALIFY OVER PARTITION FILTER NULLS FIRST LAST",
"IF RECURSIVE DESCRIBE SUMMARIZE COMMENT INSTALL LOAD EXPORT IMPORT PRAGMA RESET VACUUM",
"SAMPLE REPEATABLE PERCENT ROWS MATERIALIZED TEMPORARY LAMBDA TRY_CAST AT TIME ZONE",
]
.join(" ")
.toLowerCase(),
types: DATA_TYPES.duckdb
.filter((type) => type !== "UNION")
.join(" ")
.toLowerCase(),
builtin: functions("duckdb")
.map((f) => f.name)
.join(" "),
caseInsensitiveIdentifiers: true,
doubleDollarQuotedStrings: true,
specialVar: "?$",
}).language);
}
+9
Переглянути файл
@@ -71,6 +71,15 @@ describe("formatSql", () => {
expect(edits).toEqual([{ from: sql.lastIndexOf("select"), to: sql.length, insert: "select 1;" }]);
});
it("keeps DuckDB integer division, escaped strings and non-ASCII identifier letters", () => {
expect(
formatted(String.raw`from sales select Äscii // 2, E'it\'s ok' qualify row_number() over ()=1;`, "duckdb", {
keywords: "upper",
identifiers: "lower",
}),
).toBe("FROM sales\nSELECT Äscii // 2,\n E'it\\'s ok'\nQUALIFY row_number() OVER() = 1;");
});
it("keeps Snowflake dollar strings, comments, casts, variant paths and stages", () => {
const sf = (sql: string) => formatted(sql, "snowflake");
expect(sf("select src:customer.name::string,src['k'].v[0] from t where x=$$ a b $$ // why\n;")).toBe(
+23 -12
Переглянути файл
@@ -7,9 +7,15 @@
* take the case of Code Style › SQL › Case; each statement is replaced on its
* own, so text between statements is left alone.
*/
import type { DbDriver } from "@/platform/ipc";
import type { SqlCaseStyle, SqlWordCase } from "@/platform/editorSettings";
import { CLAUSE_WORDS, isReserved, joinKeywords, predicateKeywords, statementStarters } from "./dialect";
import {
CLAUSE_WORDS,
isReserved,
joinKeywords,
predicateKeywords,
statementStarters,
type SqlDriver,
} from "./dialect";
import { lex, type Token } from "./lexer";
export interface SqlEdit {
@@ -29,7 +35,7 @@ interface Item {
/** Edits formatting every statement (or those overlapping `range`). */
export function formatSql(
text: string,
driver: DbDriver,
driver: SqlDriver,
range: { from: number; to: number } | null = null,
wordCase: SqlCaseStyle = KEEP_CASE,
): SqlEdit[] {
@@ -122,10 +128,10 @@ const MORE_KEYWORDS =
"IF IGNORE INDEX KEY LIMIT MERGE NOTHING NULLS OFFSET OVER PARTITION RECURSIVE RENAME REPLACE RESTRICT " +
"RETURNING ROLLBACK SCHEMA TEMPORARY TRUNCATE VIEW";
const keywordSets = new Map<DbDriver, Set<string>>();
const keywordSets = new Map<SqlDriver, Set<string>>();
/** The words Reformat Code treats as keywords for `driver`. */
function keywordsOf(driver: DbDriver): Set<string> {
function keywordsOf(driver: SqlDriver): Set<string> {
let set = keywordSets.get(driver);
if (!set) {
const phrases = [...statementStarters(driver), ...joinKeywords(driver), ...predicateKeywords(driver)];
@@ -148,17 +154,19 @@ function applyCase(text: string, wordCase: SqlWordCase): string {
* the keyword case, any other unquoted name the identifier case — except on ClickHouse, whose names
* are case-sensitive, and for bind parameters (`:name`, `@name`) and Snowflake paths (`col:Key`).
*/
function casedWord(it: Item, prev: Item | null, next: Item | undefined, driver: DbDriver, wordCase: SqlCaseStyle) {
function casedWord(it: Item, prev: Item | null, next: Item | undefined, driver: SqlDriver, wordCase: SqlCaseStyle) {
if (it.kind !== "word" || (wordCase.keywords === "keep" && wordCase.identifiers === "keep")) return it.text;
if (isP(prev, ":") || isP(prev, "@") || isP(prev, "$")) return it.text;
const qualified = isP(prev, ".") || isP(next, ".") || isP(prev, "::");
const keyword = !qualified && (isReserved(it.text, driver) || keywordsOf(driver).has(it.upper));
if (keyword) return applyCase(it.text, wordCase.keywords);
if (!/^[\p{L}_][\p{L}\p{N}_$]*$/u.test(it.text)) return it.text;
return driver === "clickhouse" ? it.text : applyCase(it.text, wordCase.identifiers);
if (driver === "clickhouse") return it.text;
if (driver === "duckdb") return it.text.replace(/[A-Za-z]+/g, (part) => applyCase(part, wordCase.identifiers));
return applyCase(it.text, wordCase.identifiers);
}
function formatStatement(items: Item[], base: string, driver: DbDriver, wordCase: SqlCaseStyle): string {
function formatStatement(items: Item[], base: string, driver: SqlDriver, wordCase: SqlCaseStyle): string {
const lines: string[] = [];
let line = "";
const newline = (column: number) => {
@@ -170,8 +178,8 @@ function formatStatement(items: Item[], base: string, driver: DbDriver, wordCase
const frames: Frame[] = [{ kind: "query", indent: 0, clause: "", count: 0, between: false }];
let prev: Item | null = null;
let unary = false;
// Snowflake's QUALIFY is a clause of its own, like HAVING.
const isClause = (word: string) => NEWLINE_CLAUSES.has(word) || (driver === "snowflake" && word === "QUALIFY");
const isClause = (word: string) =>
NEWLINE_CLAUSES.has(word) || ((driver === "snowflake" || driver === "duckdb") && word === "QUALIFY");
items.forEach((it, i) => {
const frame = frames.at(-1)!;
@@ -232,7 +240,10 @@ function formatStatement(items: Item[], base: string, driver: DbDriver, wordCase
line += "(";
frames.push({ kind: "create", indent: frame.indent + 4, clause: "", count: 0, between: false });
newline(frame.indent + 4);
} else if (next?.kind === "word" && (next.upper === "SELECT" || next.upper === "WITH")) {
} else if (
next?.kind === "word" &&
(next.upper === "SELECT" || next.upper === "WITH" || (driver === "duckdb" && next.upper === "FROM"))
) {
frames.push({ kind: "query", indent: line.length, clause: "", count: 0, between: false });
} else {
frames.push({ kind: "plain", indent: frame.indent, clause: "", count: 0, between: false });
@@ -308,7 +319,7 @@ function isCreateBodyParen(items: Item[], i: number): boolean {
}
/** `text` with every statement formatted. */
export function formatted(text: string, driver: DbDriver, wordCase: SqlCaseStyle = KEEP_CASE): string {
export function formatted(text: string, driver: SqlDriver, wordCase: SqlCaseStyle = KEEP_CASE): string {
let out = text;
for (const e of formatSql(text, driver, null, wordCase).reverse())
out = out.slice(0, e.from) + e.insert + out.slice(e.to);
+23 -6
Переглянути файл
@@ -5,7 +5,7 @@
* PostgreSQL dollar quoting, Snowflake `$$` strings / `//` comments / stages /
* variant paths). Offsets are UTF-16, like the editor's.
*/
import type { DbDriver } from "@/platform/ipc";
import { sqlWordUpper, type SqlDriver } from "./dialect";
export type TokenKind = "word" | "quoted" | "string" | "number" | "param" | "punct";
@@ -33,10 +33,22 @@ const STAGE_END = /[\s(),;']/;
const PATH_OWNER = /[\p{L}\p{N}_$)\]"']/u;
const TWO_CHAR = new Set(["::", "<=", ">=", "<>", "!=", "||", "->", "=>", ":="]);
export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
function duckdbBlockCommentEnd(text: string, start: number): number {
const delimiter = /\/\*|\*\//g;
delimiter.lastIndex = start + 2;
let depth = 1;
for (let match = delimiter.exec(text); match; match = delimiter.exec(text)) {
depth += match[0] === "/*" ? 1 : -1;
if (depth === 0) return match.index;
}
return -1;
}
export function lex(text: string, driver: SqlDriver = "sqlite"): Lexed {
const mysql = driver === "mysql";
const clickhouse = driver === "clickhouse";
const snowflake = driver === "snowflake";
const duckdb = driver === "duckdb";
const tokens: Token[] = [];
const comments: Lexed["comments"] = [];
const n = text.length;
@@ -48,7 +60,7 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
text: t,
from,
to,
upper: kind === "word" ? t.toUpperCase() : t,
upper: kind === "word" ? sqlWordUpper(t, driver) : t,
...(kind === "quoted" && clickhouse
? { value: t.slice(1, t.endsWith(t[0]!) ? -1 : undefined).replace(/\\([\\'"`])/g, "$1") }
: {}),
@@ -78,10 +90,14 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
comments.push({ from: i, to, open: true });
i = to;
} else if (c === "/" && next === "*") {
const end = text.indexOf("*/", i + 2);
const end = duckdb ? duckdbBlockCommentEnd(text, i) : text.indexOf("*/", i + 2);
const to = end < 0 ? n : end + 2;
comments.push({ from: i, to, open: end < 0 });
i = to;
} else if (duckdb && (c === "E" || c === "e") && next === "'") {
const to = quoted(i + 1, "'", true);
push("string", i, to);
i = to;
} else if (c === "'") {
const to = quoted(i, "'", mysql || clickhouse || snowflake);
push("string", i, to);
@@ -94,7 +110,7 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
const to = quoted(i, "`", clickhouse);
push("quoted", i, to);
i = to;
} else if (c === "$" && driver === "postgres") {
} else if (c === "$" && (driver === "postgres" || duckdb)) {
const m = /^\$([\p{L}_][\p{L}\p{N}_]*)?\$/u.exec(text.slice(i, i + 64));
if (m) {
const tag = m[0];
@@ -155,7 +171,7 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
i = j;
} else {
const two = text.slice(i, i + 2);
const len = two === "->" && text[i + 2] === ">" ? 3 : TWO_CHAR.has(two) ? 2 : 1;
const len = two === "->" && text[i + 2] === ">" ? 3 : TWO_CHAR.has(two) || (duckdb && two === "//") ? 2 : 1;
push("punct", i, i + len);
i += len;
}
@@ -177,6 +193,7 @@ export function inLiteral(lexed: Lexed, pos: number): "string" | "quoted" | "com
function closed(t: Token): boolean {
if (t.text.length < 2) return false;
const open = t.text[0]!;
if ((open === "E" || open === "e") && t.text[1] === "'") return t.text.length > 2 && t.text.endsWith("'");
if (open === "$") {
const tag = /^\$[\p{L}\p{N}_]*\$/u.exec(t.text)?.[0] ?? "$";
return t.text.length >= tag.length * 2 && t.text.endsWith(tag);
+34 -13
Переглянути файл
@@ -5,9 +5,9 @@
* as lexical and forgiving as completion; names it cannot judge (unknown
* tables' columns, dialect pseudo-columns) are left alone.
*/
import type { DbCompletion, DbCompletionColumn, DbCompletionTable, DbDriver } from "@/platform/ipc";
import type { DbCompletion, DbCompletionColumn, DbCompletionTable } from "@/platform/ipc";
import { analyze, type TableRef } from "./analyze";
import { CLAUSE_WORDS, DATA_TYPES, functions, isReserved, nameMatcher } from "./dialect";
import { CLAUSE_WORDS, DATA_TYPES, functions, identifierKey, isReserved, nameMatcher, type SqlDriver } from "./dialect";
import { identName, lex, type Lexed, type Token } from "./lexer";
export type SqlSymbol =
@@ -25,6 +25,7 @@ export interface Span {
export interface Resolved extends Span {
symbol: SqlSymbol | null;
catalogTable?: { catalog: string; schema: string; table: string };
/** Set when the name should resolve but doesn't. */
problem?: string;
}
@@ -61,7 +62,7 @@ export function findTable(
model: DbCompletion | null,
schema: string | null,
name: string,
driver: DbDriver = "sqlite",
driver: SqlDriver = "sqlite",
): DbCompletionTable | undefined {
const eq = nameMatcher(driver);
const tables = model?.tables ?? [];
@@ -84,7 +85,7 @@ export class SqlResolver {
constructor(
readonly text: string,
readonly driver: DbDriver,
readonly driver: SqlDriver,
readonly model: DbCompletion | null,
) {
this.lexed = lex(text, driver);
@@ -143,7 +144,7 @@ export class SqlResolver {
const name = identName(t);
const span = { from: t.from, to: t.to };
const a = analyze(this.text, t.from, this.driver, this.lexedFor(i));
const checked = CHECKED.has(a.verb);
const checked = CHECKED.has(a.verb) || (this.driver === "duckdb" && a.verb === "FROM");
const loaded = !!this.model?.tables.length;
const ctx = a.context;
const qualifier = a.qualifier;
@@ -157,8 +158,13 @@ export class SqlResolver {
if (cte) return { ...span, symbol: { kind: "cte", name: cte.name, def: { from: cte.from, to: cte.to } } };
if (this.model?.tables.some((x) => eq(x.schema, name))) return this.schema(name, span);
if (!checked || PSEUDO_TABLES.has(name.toUpperCase()) || ctx.kind === "none") return { ...span, symbol: null };
// Snowflake `database.schema.table.column`: other databases are not in the model.
if (this.driver === "snowflake" && isP(toks[i + 3], ".") && isP(toks[i + 5], ".") && isName(toks[i + 6]))
// A fully qualified column may live in a catalog the model does not hold.
if (
(this.driver === "snowflake" || this.driver === "duckdb") &&
isP(toks[i + 3], ".") &&
isP(toks[i + 5], ".") &&
isName(toks[i + 6])
)
return { ...span, symbol: null };
return { ...span, symbol: null, problem: `Unable to resolve symbol '${name}'` };
}
@@ -175,6 +181,11 @@ export class SqlResolver {
// Table functions (`generate_series(1, 3)`), `DROP TABLE IF EXISTS`.
if (isP(next, "(") && !isIntoTarget(toks, i)) return null;
if (t.kind === "word" && (t.upper === "IF" || t.upper === "ONLY" || t.upper === "LATERAL")) return null;
if (this.driver === "duckdb" && qualifier && qualifier.length > 1) {
const catalogTable =
qualifier.length === 2 ? { catalog: qualifier[0]!, schema: qualifier[1]!, table: name } : undefined;
return { ...span, symbol: null, catalogTable };
}
const schema = qualifier?.at(-1) ?? null;
const cte = schema ? undefined : a.ctes.find((c) => eq(c.name, name));
if (cte) return { ...span, symbol: { kind: "cte", name: cte.name, def: { from: cte.from, to: cte.to } } };
@@ -198,11 +209,13 @@ export class SqlResolver {
case "afterInsertColumns":
return null;
case "column":
case "exclude":
case "joinCondition":
break;
}
if (qualifier) {
if (this.driver === "duckdb" && qualifier.length > 2) return { ...span, symbol: null };
const ref =
qualifier.length === 1
? this.findRef(a.refs, null, qualifier[0]!)
@@ -223,6 +236,7 @@ export class SqlResolver {
(isReserved(t.text, this.driver) ||
NOT_COLUMNS.has(t.upper) ||
this.words.has(t.upper) ||
(this.driver === "duckdb" && t.upper === "EXCLUDE" && isP(prev, "*")) ||
(this.driver === "snowflake" && (SNOWFLAKE_NOT_COLUMNS.has(t.upper) || t.upper.startsWith("METADATA$"))))
)
return null;
@@ -233,7 +247,9 @@ export class SqlResolver {
prev.kind === "number" ||
prev.kind === "string" ||
isP(prev, ")") ||
(prev.kind === "word" && !CLAUSE_WORDS.has(prev.upper)))
(prev.kind === "word" &&
!CLAUSE_WORDS.has(prev.upper) &&
!(this.driver === "duckdb" && prev.upper === "QUALIFY")))
)
return null;
for (const ref of a.refs) {
@@ -251,7 +267,7 @@ export class SqlResolver {
clause !== "other" &&
clause !== "values" &&
clause !== "limit" &&
!this.outputAliases(i).has(this.driver === "clickhouse" ? name : name.toLowerCase());
!this.outputAliases(i).has(identifierKey(name, this.driver));
return judged
? { ...span, symbol: null, problem: `Unable to resolve column '${name}'` }
: { ...span, symbol: null };
@@ -279,8 +295,13 @@ export class SqlResolver {
return refs.find((r) => (r.alias ? eq(r.alias, name) : eq(r.name, name) && (!schema || eq(r.schema, schema))));
}
private refTable(ref: TableRef): DbCompletionTable | undefined {
if (ref.kind !== "table" || (this.driver === "duckdb" && ref.database !== undefined)) return undefined;
return findTable(this.model, ref.schema, ref.name, this.driver);
}
private refSymbol(ref: TableRef): SqlSymbol {
const table = ref.kind === "table" ? findTable(this.model, ref.schema, ref.name, this.driver) : undefined;
const table = this.refTable(ref);
if (ref.alias && ref.aliasAt) return { kind: "alias", name: ref.alias, def: ref.aliasAt, table };
if (table) return { kind: "table", table };
return { kind: "cte", name: ref.name, def: { from: ref.from, to: ref.to } };
@@ -289,13 +310,13 @@ export class SqlResolver {
/** Columns of a FROM item; `null` when unknown (not in the model, `select *` subqueries). */
private columnsOf(ref: TableRef): Array<{ name: string; column?: DbCompletionColumn }> | null {
if (ref.columns) return ref.columns.length ? ref.columns.map((name) => ({ name })) : null;
const table = findTable(this.model, ref.schema, ref.name, this.driver);
const table = this.refTable(ref);
// A table listed without columns is one whose columns were not read (a large Snowflake database).
return table?.columns.length ? table.columns.map((c) => ({ name: c.name, column: c })) : null;
}
private columnSymbol(ref: TableRef, col: { name: string; column?: DbCompletionColumn }): SqlSymbol {
const table = ref.kind === "table" ? findTable(this.model, ref.schema, ref.name, this.driver) : undefined;
const table = this.refTable(ref);
return { kind: "column", name: col.name, column: col.column, table, owner: ref.alias ?? ref.name };
}
@@ -313,7 +334,7 @@ export class SqlResolver {
prev.kind === "number" ||
prev.kind === "string"
)
out.add(this.driver === "clickhouse" ? identName(t) : identName(t).toLowerCase());
out.add(identifierKey(identName(t), this.driver));
}
return out;
}
+116 -4
Переглянути файл
@@ -1,11 +1,11 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { snippet } from "@codemirror/autocomplete";
import type { DbCompletion, DbDriver } from "@/platform/ipc";
import type { DbCompletion } from "@/platform/ipc";
import { analyze, templateContexts, valuesSlot } from "./analyze";
import { aliasFor, quoteIdent, sqlCandidates, type SqlCandidate } from "./complete";
import { identName, inLiteral, lex } from "./lexer";
import { DATA_TYPES, statementStarters } from "./dialect";
import { DATA_TYPES, statementStarters, type SqlDriver } from "./dialect";
import { bindParams, findParams, unbindRange } from "./params";
import { SqlResolver } from "./resolve";
import { jdbcDialect } from "../vendors";
@@ -69,13 +69,13 @@ const model: DbCompletion = {
};
/** Analysis at the `|` of `sql`. */
function at(sql: string, driver: DbDriver = "sqlite") {
function at(sql: string, driver: SqlDriver = "sqlite") {
const pos = sql.indexOf("|");
const text = sql.slice(0, pos) + sql.slice(pos + 1);
return analyze(text, pos, driver);
}
function complete(sql: string, driver: DbDriver = "sqlite", m: DbCompletion = model): SqlCandidate[] {
function complete(sql: string, driver: SqlDriver = "sqlite", m: DbCompletion = model): SqlCandidate[] {
return sqlCandidates({ model: m, analysis: at(sql, driver), driver, sourceName: "shop" }).sort(
(a, b) => b.boost - a.boost,
);
@@ -97,6 +97,118 @@ const sf: DbCompletion = {
const labels = (c: SqlCandidate[], kind?: string) => c.filter((x) => !kind || x.kind === kind).map((x) => x.label);
describe("DuckDB SQL", () => {
it("recognizes FROM-first query blocks and keeps their source columns in scope", () => {
expect(statementStarters("duckdb")).toContain("FROM");
expect(labels(complete("from orders |", "duckdb"), "keyword")).toContain("select");
expect(labels(complete("from orders select |", "duckdb"), "column")).toContain("total");
expect(labels(complete("from orders select |", "duckdb"), "keyword")).not.toContain("from");
const nested = at("select * from (from orders select |) as o", "duckdb");
expect(nested.refs.find((r) => r.name === "orders")?.depth).toBe(0);
expect(nested.fromInsert).toBeNull();
});
it.each(["delete from orders |", "update orders set total = 1 from users |"])(
"omits a SELECT continuation after %s",
(sql) => {
const withCte = "with source as (select id from users) " + sql;
expect(labels(complete(withCte, "duckdb"), "keyword")).not.toContain("select");
expect(at(sql, "duckdb").fromFirst).toBe(false);
},
);
it("offers SELECT when a query begins with FROM after a CTE or a set operator", () => {
expect(labels(complete("with source as (select id from users) from source |", "duckdb"), "keyword")).toContain(
"select",
);
expect(labels(complete("select 1 union all from orders |", "duckdb"), "keyword")).toContain("select");
expect(at("insert into orders from users |", "duckdb").fromFirst).toBe(true);
});
it("recognizes QUALIFY and suggests the window result alias", () => {
const sql = "select row_number() over (order by id) as WinRank from orders qualify |";
expect(at(sql, "duckdb").context).toEqual({ kind: "column", clause: "qualify" });
expect(at(sql, "duckdb").refs[0]?.alias).toBeNull();
expect(labels(complete(sql, "duckdb"))).toContain("WinRank");
expect(labels(complete(sql, "duckdb"), "keyword")).not.toContain("qualify");
expect(new SqlResolver(sql.replace("|", "winrank = 1"), "duckdb", model).problems()).toEqual([]);
});
it("completes EXCLUDE after a projection star and its list from catalog columns", () => {
expect(labels(complete("select * excl| from orders", "duckdb"), "keyword")).toContain("exclude");
expect(labels(complete("select id * ex| from orders", "duckdb"), "keyword")).not.toContain("exclude");
const candidates = complete("select o.* exclude (|) from orders o join users u on o.user_id = u.id", "duckdb");
expect(labels(candidates)).toContain("total");
expect(labels(candidates)).not.toContain("email");
expect(candidates.every((c) => c.kind === "column")).toBe(true);
expect(labels(complete("select * excl| from orders", "jdbc"), "keyword")).not.toContain("exclude");
});
it("completes table functions and preserves spelling of identifiers using DuckDB quoting", () => {
expect(labels(complete("from read_par|", "duckdb"), "function")).toContain("read_parquet");
expect(quoteIdent("MixedCase", "duckdb")).toBe("MixedCase");
expect(quoteIdent("qualify", "duckdb")).toBe('"qualify"');
expect(quoteIdent("exclude", "duckdb")).toBe("exclude");
expect(quoteIdent('a"b', "duckdb")).toBe('"a""b"');
const sql = 'from orders as "ÄÖrder" select "ÄörDER".|';
expect(labels(complete(sql, "duckdb"), "column")).toEqual([]);
expect(labels(complete(sql.replace("ÄörDER", "ÄÖrDER"), "duckdb"), "column")).toContain("total");
});
it("inserts three-part DuckDB paths and keeps columns from same-named local tables out of them", () => {
const database = "Archive.db:1";
const schema = "Mixed.Schema";
const catalog = {
databases: [database, "memory"],
schemas: (name: string) => (name === database ? [schema, "main"] : null),
tables: (name: string, namespace: string) =>
name === database && namespace.toLowerCase() === schema.toLowerCase()
? [{ name: 'Remote "view"', view: true }]
: null,
};
const local = {
...model,
tables: [...model.tables, { ...model.tables[0]!, schema: database, name: "local_table" }],
};
const run = (sql: string) =>
sqlCandidates({ model: local, analysis: at(sql, "duckdb"), driver: "duckdb", catalog });
expect(run("from Arch|")).toContainEqual(
expect.objectContaining({ label: database, insert: '"Archive.db:1".', retrigger: true }),
);
expect(run('from "ARCHIVE.db:1".|')).toEqual([
expect.objectContaining({ label: schema, insert: '"Mixed.Schema".', retrigger: true }),
expect.objectContaining({ label: "main", insert: "main." }),
]);
expect(run('from "archive.db:1"."mixed.schema".|')).toEqual([
expect.objectContaining({ kind: "view", insert: '"Remote ""view"""' }),
]);
expect(run('from "archive.db:1".missing.|')).toEqual([]);
expect(run("from main.|").map((c) => c.label)).toContain("orders");
const remote = '"Archive.db:1".main.orders';
for (const select of ["select |", "select o.|", "select main.orders.|", 'select "Archive.db:1".main.orders.|']) {
expect(labels(run(select + " from " + remote + " o"), "column")).toEqual([]);
}
expect(labels(run("select o.| from main.orders o"), "column")).toContain("total");
const sql = "select o.total from " + remote + " o";
const resolver = new SqlResolver(sql, "duckdb", model);
expect(resolver.resolveAt(sql.indexOf(".orders") + 2)?.catalogTable).toEqual({
catalog: database,
schema: "main",
table: "orders",
});
expect(resolver.problems()).toEqual([]);
expect(resolver.resolveAt(sql.indexOf("total"))?.symbol).toBeNull();
expect(resolver.resolveAt(sql.indexOf("orders"))?.symbol).toBeNull();
});
it("keeps nested comments and dollar-quoted SQL out of caret analysis", () => {
expect(at("select /* outer /* nested */ here| */ 1", "duckdb").context.kind).toBe("none");
expect(at("select $body$ from not_a_table; here| $body$", "duckdb").context.kind).toBe("none");
expect(at("select 5 // 2, | from orders", "duckdb").refs[0]?.name).toBe("orders");
});
});
describe("lexer", () => {
it("reads ClickHouse backticks and escaped quotes without exposing literal parameters", () => {
const sql = String.raw`select "a\\b\"c", ` + "`my column`" + String.raw`, 'it\'s ?; text', ?`;