feat(database): add Snowflake data sources (#2972)

Snowflake is a built-in data source kind: connection dialog, key-pair, browser single sign-on, password or token sign-in, the database tree, SQL consoles, and Snowflake-aware SQL assistance and syntax colours. The driver speaks Snowflake's session protocol over the existing reqwest + rustls stack, with no JDBC/ODBC or native library and no new package. Metadata is read with SHOW / DESCRIBE, which need no running warehouse; introspected names are kept on disk for completion.

Co-authored-by: vvnadolskyy <12991410+vvnadolskyy@users.noreply.github.com>
This commit is contained in:
pH
2026-11-12 23:06:10 +08:00
committed by GitHub
co-authored by vvnadolskyy
parent 51c14d3b03
commit 59eb6446d4
89 changed files with 12461 additions and 139 deletions
+26 -9
View File
@@ -10,6 +10,8 @@ import { CLAUSE_WORDS, isReserved } from "./dialect";
import { identName, inLiteral, lex, type Lexed, type Token } from "./lexer";
export interface TableRef {
/** Database of a three-part name (`database.schema.table`), as written. */
database?: string;
/** Schema as written (`null`: unqualified). */
schema: string | null;
/** Table / CTE name; a derived table's alias. */
@@ -97,6 +99,10 @@ const CLAUSES: Record<string, Clause> = {
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 isIdent = (t: Token | undefined): t is Token =>
!!t && (t.kind === "quoted" || (t.kind === "word" && !CLAUSE_WORDS.has(t.upper)));
const isP = (t: Token | undefined, p: string) => !!t && t.kind === "punct" && t.text === p;
@@ -194,7 +200,10 @@ 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);
const clause = clauseAt(st, parens, block, open.length ? open.at(-1)! : -1, nb, driver);
// 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" };
@@ -208,7 +217,7 @@ export function analyze(text: string, pos: number, driver: DbDriver, lexed: Lexe
else if (isW(p, "LATERAL", "ONLY") && isW(before[pi - 1], "JOIN", "FROM"))
context = { kind: "table", join: isW(before[pi - 1], "JOIN") };
else if (isP(p, ",") && clause === "from" && parens.parent[pi] === block) context = { kind: "table", join: false };
else if (isW(p, "AS") || isP(p, "::")) context = { kind: "none" };
else if (isW(p, "AS") || isP(p, "::") || variantPath) context = { kind: "none" };
else if (refEnds.has(pi) && !qualifier.length && (clause === "from" || clause === "other")) {
const ref = refEnds.get(pi)!;
context = { kind: "afterTable", ref };
@@ -253,7 +262,14 @@ function blockRange(st: Token[], parens: Parens, g: number, caret: number): [num
}
/** The clause the caret is in: the last clause keyword of its block before it. */
function clauseAt(st: Token[], parens: Parens, block: number, innermost: number, caret: number): Clause {
function clauseAt(
st: Token[],
parens: Parens,
block: number,
innermost: number,
caret: number,
driver: DbDriver,
): Clause {
// Inside a non-query paren (function call, IN list), the clause is the one around that paren.
const limit = innermost > block ? innermost : caret;
let clause: Clause = "other";
@@ -261,7 +277,7 @@ function clauseAt(st: Token[], parens: Parens, block: number, innermost: number,
const t = st[i]!;
if (t.kind !== "word") continue;
if (SET_OPS.has(t.upper)) clause = "other";
const c = CLAUSES[t.upper];
const c = clauseOf(t, driver);
if (c) clause = c;
}
return clause;
@@ -374,7 +390,7 @@ function parseRefs(
if (isP(t, "(")) {
const c = parens.close.get(j)!;
const columns = outputColumns(st, parens, j, j + 1, c);
const al = alias(st, c + 1, b);
const al = alias(st, c + 1, b, driver);
if (al)
out.push({
ref: {
@@ -409,13 +425,14 @@ function parseRefs(
const last = parts.at(-1)!;
const name = identName(last);
const schema = parts.length > 1 ? identName(parts.at(-2)!) : null;
const al = alias(st, k, b);
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;
out.push({
ref: {
...(parts.length > 2 ? { database: identName(parts.at(-3)!) } : {}),
schema,
name,
alias: al?.name ?? null,
@@ -439,7 +456,7 @@ function parseRefs(
item(i + 1, t.upper === "JOIN" || t.upper === "STRAIGHT_JOIN", t.upper === "INTO");
continue;
}
const c = CLAUSES[t.upper];
const c = clauseOf(t, driver);
if (c) clause = c;
} else if (isP(t, ",") && clause === "from") item(i + 1);
}
@@ -447,13 +464,13 @@ function parseRefs(
}
/** An alias at `k` (`AS x`, or a bare non-keyword identifier). */
function alias(st: Token[], k: number, b: number): { name: string; tok: Token; end: number } | null {
function alias(st: Token[], k: number, b: number, driver: DbDriver): { 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)))) {
if (t.kind === "quoted" || (t.kind === "word" && !CLAUSE_WORDS.has(t.upper) && (as || !isReserved(t.text, driver)))) {
return { name: identName(t), tok: t, end: j };
}
return null;
+89 -18
View File
@@ -68,13 +68,13 @@ export function quoteIdent(name: string, driver: DbDriver): string {
const plain =
driver === "postgres"
? /^[a-z_][a-z0-9_$]*$/
: // Oracle folds unquoted names to upper case; a lower-case name must stay quoted.
driver === "oracle"
: // Oracle and Snowflake fold unquoted names to upper case; a lower-case name must stay quoted.
driver === "oracle" || driver === "snowflake"
? /^[A-Z_][A-Z0-9_$]*$/
: driver === "clickhouse"
? /^[A-Za-z_][A-Za-z0-9_]*$/
: /^[A-Za-z_][A-Za-z0-9_$]*$/;
if (plain.test(name) && !isReserved(name)) return name;
if (plain.test(name) && !isReserved(name, driver)) return name;
if (driver === "clickhouse") return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
const q = driver === "mysql" ? "`" : '"';
return q + name.split(q).join(q + q) + q;
@@ -99,7 +99,25 @@ export function aliasFor(table: string, taken: ReadonlySet<string>): string {
return a;
}
/**
* What lies outside the schema model, for `database.schema.table` names (Snowflake): 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.
*/
export interface SqlCatalog {
databases: readonly string[];
/** Schemas of a database (`null`: not a database, or not loaded). */
schemas(database: string): readonly string[] | null;
tables(database: string, schema: string): ReadonlyArray<{ name: string; view: boolean }> | null;
/** Tables of the other databases whose name starts with `prefix` (at most `limit`). */
search?(
prefix: string,
limit: number,
): ReadonlyArray<{ database: string; schema: string; name: string; view: boolean }>;
}
export interface CompletionInput {
catalog?: SqlCatalog;
model: DbCompletion | null;
analysis: Analysis;
driver: DbDriver;
@@ -107,7 +125,7 @@ export interface CompletionInput {
sourceName?: string;
}
export function sqlCandidates({ model, analysis: a, driver, sourceName }: CompletionInput): SqlCandidate[] {
export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog }: CompletionInput): SqlCandidate[] {
const eq = nameMatcher(driver);
const ctx = a.context;
if (ctx.kind === "none") return [];
@@ -117,7 +135,29 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName }: Comple
const kw = (k: string) => (lower ? k.toLowerCase() : k);
const tables = model?.tables ?? [];
const defaultSchema = model?.defaultSchema ?? "";
const q = (n: string) => quoteIdent(n, driver);
const exact = (n: string) => quoteIdent(n, driver);
// Snowflake folds unquoted names to upper case, so a name typed in lower case may stay lower case.
const lowerQualifier = !!a.qualifier?.length && a.qualifier.every((p) => /[a-z]/.test(p) && p === p.toLowerCase());
// What is typed decides: the name's own prefix, else the qualifier before it, else the statement's keywords.
const upperQualifier = !!a.qualifier?.length && a.qualifier.every((p) => /[A-Z]/.test(p) && p === p.toUpperCase());
const lowerNames =
driver === "snowflake" && (typedLower || (!typedUpper && (lowerQualifier || (!upperQualifier && a.lowerKeywords))));
/** A database, schema or table name as it is written here. */
const qn = (n: string) => {
const text = exact(n);
return lowerNames && text === n ? n.toLowerCase() : text;
};
const q = qn;
const database = (name: string) => catalog?.databases.find((d) => eq(d, name));
const schemaCandidate = (s: string, boost: number, tail?: string): SqlCandidate => ({
label: s,
kind: "schema",
tail,
type: sourceName,
insert: `${qn(s)}.`,
retrigger: true,
boost,
});
const out: SqlCandidate[] = [];
const keywords = (list: readonly string[], boost: number) => {
for (const k of list) out.push({ label: kw(k), kind: "keyword", boost });
@@ -141,7 +181,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName }: Comple
label: names.join(", "),
kind: "columns",
tail: `(${ownerOf(r)})`,
insert: names.map((n) => (qualify ? `${q(refName(r))}.${q(n)}` : q(n))).join(", "),
insert: names.map((n) => (qualify ? `${qn(refName(r))}.${qn(n)}` : qn(n))).join(", "),
boost,
});
const fkColumns = new Set(
@@ -151,13 +191,13 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName }: Comple
!!t && fkColumns.has(`${t.schema}\u0000${t.name}\u0000${c}`);
/** How a table is written from here: unqualified in the default schema. */
const tableText = (t: DbCompletionTable) =>
eq(t.schema, defaultSchema) || driver === "sqlite" ? q(t.name) : `${q(t.schema)}.${q(t.name)}`;
eq(t.schema, defaultSchema) || driver === "sqlite" ? qn(t.name) : `${qn(t.schema)}.${qn(t.name)}`;
const tableCandidate = (t: DbCompletionTable, boost: number, qualified = false): SqlCandidate => ({
label: t.name,
kind: t.kind !== "table" ? "view" : "table",
tail: t.schema ? `(${t.schema})` : undefined,
type: sourceName,
insert: qualified ? `${q(t.schema)}.${q(t.name)}` : tableText(t),
insert: qualified ? `${qn(t.schema)}.${qn(t.name)}` : tableText(t),
boost,
doc: tableDoc(t),
});
@@ -172,7 +212,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName }: Comple
kind: "column",
tail: `(${owner})`,
type: c.dataType ? c.dataType.toUpperCase() : undefined,
insert: insert ?? q(c.name),
insert: insert ?? qn(c.name),
boost,
primaryKey: !!c.primaryKey,
foreignKey: isFk(table, c.name),
@@ -192,13 +232,33 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName }: Comple
}
}
if (a.qualifier.length === 1) {
const inSchema = tables.filter((t) => eq(t.schema, first));
if (inSchema.length) return inSchema.map((t) => ({ ...tableCandidate(t, 30), insert: q(t.name) }));
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).
const db = database(first!);
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 [];
}
const t = findTable(first!, second!);
// Snowflake `database.schema.table`: the model holds the session's database only, keyed by the last two parts.
if (driver === "snowflake" && 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 [];
return (catalog?.tables(db, second!) ?? []).map((t) => ({
label: t.name,
kind: t.view ? "view" : "table",
tail: `(${db})`,
type: sourceName,
insert: qn(t.name),
boost: t.view ? 28 : 30,
}));
}
const [schema, name] = driver === "snowflake" ? a.qualifier.slice(-2) : [first, second];
const t = findTable(schema!, name!);
return t ? t.columns.map((c) => columnCandidate(c, t.name, t, 50)) : [];
}
@@ -218,9 +278,19 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName }: Comple
const local = eq(t.schema, defaultSchema) || driver === "sqlite";
out.push(tableCandidate(t, local ? (t.kind !== "table" ? 28 : 30) : 0, !local));
}
for (const s of schemas)
if (!eq(s, defaultSchema) || schemas.size > 1)
out.push({ label: s, kind: "schema", type: sourceName, insert: `${q(s)}.`, retrigger: true, boost: 5 });
for (const s of schemas) if (!eq(s, defaultSchema) || schemas.size > 1) out.push(schemaCandidate(s, 5));
for (const d of catalog?.databases ?? []) out.push(schemaCandidate(d, 3, "(database)"));
// Tables of the other databases, once enough is typed to tell which: written fully qualified.
if (a.prefix.text.length >= 2)
for (const t of catalog?.search?.(a.prefix.text, 200) ?? [])
out.push({
label: t.name,
kind: t.view ? "view" : "table",
tail: `(${t.database}.${t.schema})`,
type: sourceName,
insert: `${qn(t.database)}.${qn(t.schema)}.${qn(t.name)}`,
boost: -5,
});
if (ctx.join) keywords(["LATERAL"], -10);
return out;
}
@@ -248,6 +318,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName }: Comple
keywords(["ON", "USING"], 25);
}
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);
}
return out;
}
@@ -373,9 +444,9 @@ function clauseKeywords(clause: Clause, driver: DbDriver, a: Analysis): string[]
case "where":
case "on":
case "having":
return [...pred, "GROUP BY", "ORDER BY", "LIMIT"];
return [...pred, "GROUP BY", "ORDER BY", "LIMIT", ...(driver === "snowflake" ? ["QUALIFY"] : [])];
case "group":
return ["HAVING", "ORDER BY", "LIMIT"];
return ["HAVING", "ORDER BY", "LIMIT", ...(driver === "snowflake" ? ["QUALIFY"] : [])];
case "order":
return ["ASC", "DESC", "LIMIT", "OFFSET", ...(driver === "mysql" ? [] : ["NULLS FIRST", "NULLS LAST"])];
case "set":
@@ -383,7 +454,7 @@ function clauseKeywords(clause: Clause, driver: DbDriver, a: Analysis): string[]
case "values":
return ["DEFAULT", "NULL", "TRUE", "FALSE"];
case "limit":
return ["OFFSET"];
return ["OFFSET", ...(driver === "snowflake" ? ["FETCH"] : [])];
case "returning":
return ["AS"];
default:
+194 -2
View File
@@ -20,8 +20,18 @@ const RESERVED = new Set(
).split(" "),
);
export function isReserved(word: string): boolean {
return RESERVED.has(word.toUpperCase());
/** Snowflake's reserved words, and the keywords that end a FROM item there (never an implicit alias). */
const SNOWFLAKE_RESERVED = new Set(
(
"ACCOUNT ALTER ASOF CONNECT CONNECTION CURRENT CURRENT_USER DATABASE FOLLOWING GSCLUSTER ILIKE INCREMENT ISSUE " +
"LATERAL LOCALTIME LOCALTIMESTAMP MATCH_RECOGNIZE MINUS OF ORGANIZATION PIVOT QUALIFY REGEXP REVOKE RLIKE ROW " +
"ROWS SAMPLE SCHEMA SOME START TABLESAMPLE TRIGGER TRY_CAST UNPIVOT VIEW WHENEVER"
).split(" "),
);
export function isReserved(word: string, driver?: DbDriver): boolean {
const upper = word.toUpperCase();
return RESERVED.has(upper) || (driver === "snowflake" && SNOWFLAKE_RESERVED.has(upper));
}
export const nameMatcher = (driver: DbDriver) => (a: string | null | undefined, b: string | null | undefined) =>
@@ -61,6 +71,59 @@ export function statementStarters(driver: DbDriver): string[] {
"SET",
"OPTIMIZE TABLE",
];
if (driver === "snowflake")
return [
"SELECT",
"INSERT INTO",
"UPDATE",
"DELETE FROM",
"MERGE INTO",
"WITH",
"CREATE TABLE",
"CREATE OR REPLACE TABLE",
"CREATE OR REPLACE VIEW",
"CREATE VIEW",
"CREATE SCHEMA",
"CREATE DATABASE",
"CREATE STAGE",
"CREATE FILE FORMAT",
"CREATE SEQUENCE",
"CREATE OR REPLACE FUNCTION",
"CREATE OR REPLACE PROCEDURE",
"ALTER TABLE",
"ALTER SESSION SET",
"ALTER WAREHOUSE",
"DROP TABLE",
"DROP VIEW",
"UNDROP TABLE",
"TRUNCATE TABLE",
"COPY INTO",
"PUT",
"GET",
"LIST",
"REMOVE",
"CALL",
"EXECUTE IMMEDIATE",
"USE DATABASE",
"USE SCHEMA",
"USE WAREHOUSE",
"USE ROLE",
"SHOW TABLES",
"SHOW VIEWS",
"SHOW SCHEMAS",
"SHOW DATABASES",
"SHOW WAREHOUSES",
"SHOW PARAMETERS",
"DESCRIBE TABLE",
"EXPLAIN",
"GRANT",
"REVOKE",
"SET",
"UNSET",
"BEGIN",
"COMMIT",
"ROLLBACK",
];
const common = [
"SELECT",
"INSERT INTO",
@@ -124,6 +187,7 @@ export function joinKeywords(driver: DbDriver): string[] {
if (driver !== "mysql") j.push("FULL JOIN");
if (driver === "postgres") j.push("JOIN LATERAL", "LEFT JOIN LATERAL");
if (driver === "oracle") j.push("JOIN", "(+)");
if (driver === "snowflake") j.push("NATURAL JOIN", "ASOF JOIN", "LATERAL FLATTEN");
return j;
}
@@ -148,10 +212,42 @@ export function predicateKeywords(driver: DbDriver): string[] {
if (driver === "mysql") k.push("REGEXP");
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");
return k;
}
export const DATA_TYPES: Record<DbDriver, string[]> = {
snowflake: [
"NUMBER",
"INTEGER",
"BIGINT",
"FLOAT",
"DOUBLE",
"VARCHAR",
"STRING",
"TEXT",
"BOOLEAN",
"DATE",
"TIME",
"TIMESTAMP",
"TIMESTAMP_NTZ",
"TIMESTAMP_LTZ",
"TIMESTAMP_TZ",
"VARIANT",
"OBJECT",
"ARRAY",
"BINARY",
"GEOGRAPHY",
"GEOMETRY",
"VECTOR",
"DECIMAL",
"NUMERIC",
"SMALLINT",
"REAL",
"CHAR",
"DATETIME",
"DECFLOAT",
],
sqlite: ["INTEGER", "TEXT", "REAL", "BLOB", "NUMERIC", "BOOLEAN", "DATETIME"],
postgres: [
"integer",
@@ -301,6 +397,102 @@ const COMMON: SqlFunction[] = [
];
const FUNCTIONS: Record<DbDriver, SqlFunction[]> = {
snowflake: [
...COMMON,
f("listagg", "expr, delimiter", "varchar", true),
f("array_agg", "expr", "array", true),
f("object_agg", "key, value", "object", true),
f("count_if", "condition", "number", true),
f("approx_count_distinct", "expr", "number", true),
f("any_value", "expr", undefined, true),
f("median", "expr", undefined, true),
f("iff", "condition, then, else"),
f("ifnull", "a, b"),
f("nvl", "a, b"),
f("nvl2", "expr, not_null, null"),
f("zeroifnull", "expr"),
f("decode", "expr, search, result, ..."),
f("try_cast", "expr AS type"),
f("to_varchar", "expr, format", "varchar"),
f("to_number", "expr, format", "number"),
f("to_date", "expr, format", "date"),
f("to_timestamp", "expr, format", "timestamp"),
f("try_to_number", "expr", "number"),
f("try_to_date", "expr", "date"),
f("current_date", "", "date"),
f("current_timestamp", "", "timestamp_ltz"),
f("current_user", "", "varchar"),
f("current_role", "", "varchar"),
f("current_warehouse", "", "varchar"),
f("current_database", "", "varchar"),
f("current_schema", "", "varchar"),
f("dateadd", "part, value, date"),
f("datediff", "part, start, end", "number"),
f("date_trunc", "part, date"),
f("date_part", "part, date", "number"),
f("last_day", "date, part", "date"),
f("convert_timezone", "source_tz, target_tz, timestamp"),
f("concat", "value, ...", "varchar"),
f("concat_ws", "separator, value, ...", "varchar"),
f("split", "text, separator", "array"),
f("split_part", "text, delimiter, part", "varchar"),
f("regexp_replace", "subject, pattern, replacement", "varchar"),
f("regexp_substr", "subject, pattern", "varchar"),
f("regexp_like", "subject, pattern", "boolean"),
f("startswith", "text, prefix", "boolean"),
f("contains", "text, search", "boolean"),
f("ilike", "subject, pattern", "boolean"),
f("parse_json", "text", "variant"),
f("try_parse_json", "text", "variant"),
f("to_json", "variant", "varchar"),
f("object_construct", "key, value, ...", "object"),
f("array_construct", "value, ...", "array"),
f("array_size", "array", "number"),
f("array_contains", "value, array", "boolean"),
f("get", "variant, key_or_index", "variant"),
f("get_path", "variant, path", "variant"),
f("flatten", "input => expr"),
f("typeof", "variant", "varchar"),
f("row_number", "", "number"),
f("rank", "", "number"),
f("dense_rank", "", "number"),
f("lag", "expr, offset, default"),
f("lead", "expr, offset, default"),
f("first_value", "expr"),
f("last_value", "expr"),
f("hash", "expr, ...", "number"),
f("md5", "text", "varchar"),
f("sha2", "text, digest_size", "varchar"),
f("uuid_string", "", "varchar"),
f("seq4", "", "number"),
f("uniform", "min, max, gen"),
f("random", "", "number"),
f("generator", "rowcount => n"),
f("result_scan", "query_id"),
f("last_query_id", "", "varchar"),
f("get_ddl", "object_type, name", "varchar"),
f("system$wait", "amount, unit", "varchar"),
f("to_variant", "expr", "variant"),
f("to_array", "expr", "array"),
f("to_object", "expr", "object"),
f("to_boolean", "expr", "boolean"),
f("to_double", "expr", "float"),
f("to_time", "expr, format", "time"),
f("try_to_timestamp", "expr", "timestamp"),
f("object_keys", "object", "array"),
f("array_to_string", "array, separator", "varchar"),
f("array_distinct", "array", "array"),
f("endswith", "text, suffix", "boolean"),
f("charindex", "search, text", "number"),
f("equal_null", "a, b", "boolean"),
f("div0", "dividend, divisor", "number"),
f("ratio_to_report", "expr", "number"),
f("conditional_true_event", "condition", "number"),
f("sysdate", "", "timestamp_ntz"),
f("current_account", "", "varchar"),
f("current_region", "", "varchar"),
f("current_session", "", "varchar"),
],
sqlite: [
...COMMON,
f("group_concat", "expr, separator", "text", true),
+17 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { formatSql } from "./format";
import { formatSql, formatted } from "./format";
const fmt = (sql: string) => {
let out = sql;
@@ -70,4 +70,20 @@ describe("formatSql", () => {
const edits = formatSql(sql, "sqlite", { from: sql.length - 2, to: sql.length - 1 });
expect(edits).toEqual([{ from: sql.lastIndexOf("select"), to: sql.length, insert: "select 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(
"select src:customer.name::string,\n src['k'].v[0]\nfrom t\nwhere x = $$ a b $$ // why\n;",
);
expect(sf("select $1 from @my_stage/path/f.csv (file_format=>'ff') t where y='it\\'s; ok';")).toBe(
"select $1\nfrom @my_stage/path/f.csv (file_format => 'ff') t\nwhere y = 'it\\'s; ok';",
);
expect(sf("select a from t qualify row_number() over (order by a)=1 and a>0;")).toBe(
"select a\nfrom t\nqualify row_number() over(order by a) = 1\n and a > 0;",
);
expect(sf("show tables ->> select $1 from $1;")).toBe("show tables ->>\nselect $1\nfrom $1;");
const body = "create procedure p() returns int language sql as $$ begin return 1; end $$;";
expect(sf(body)).toContain("$$ begin return 1; end $$;");
});
});
+26 -7
View File
@@ -56,7 +56,7 @@ export function formatSql(
const line = text.lastIndexOf("\n", first.from - 1) + 1;
const lead = text.slice(line, first.from);
const indent = /^[ \t]*$/.test(lead) ? lead : "";
edits.push({ from: first.from, to: last.to, insert: formatStatement(items.slice(a, end), indent) });
edits.push({ from: first.from, to: last.to, insert: formatStatement(items.slice(a, end), indent, driver) });
};
items.forEach((it, i) => {
if (it.kind === "punct" && it.text === "(") depth++;
@@ -89,6 +89,8 @@ const NEWLINE_CLAUSES = new Set([
]);
const JOIN_START = new Set(["JOIN", "LEFT", "RIGHT", "FULL", "INNER", "CROSS", "NATURAL", "STRAIGHT_JOIN"]);
const JOIN_MODIFIERS = new Set(["LEFT", "RIGHT", "FULL", "INNER", "CROSS", "NATURAL", "OUTER"]);
/** Clauses whose AND / OR start a line. */
const AND_OR_CLAUSES = new Set(["WHERE", "HAVING", "QUALIFY"]);
/** Where a list item continues: the width of `select `, `from `, `set `, `values `. */
const ITEM_COLUMN: Record<string, number> = { SELECT: 7, FROM: 5, SET: 4, VALUES: 7 };
/** Keywords written like functions: `cast(x as int)`. */
@@ -105,7 +107,7 @@ interface Frame {
between: boolean;
}
function formatStatement(items: Item[], base: string): string {
function formatStatement(items: Item[], base: string, driver: DbDriver): string {
const lines: string[] = [];
let line = "";
const newline = (column: number) => {
@@ -117,6 +119,8 @@ function formatStatement(items: Item[], base: string): string {
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");
items.forEach((it, i) => {
const frame = frames.at(-1)!;
@@ -124,19 +128,19 @@ function formatStatement(items: Item[], base: string): string {
const isQuery = frame.kind === "query";
// Line breaks before the token.
const afterLineComment = prev?.kind === "comment" && /^(--|#)/.test(prev.text);
const afterLineComment = prev?.kind === "comment" && /^(--|#|\/\/)/.test(prev.text);
if (afterLineComment) {
newline(isQuery && frame.clause in ITEM_COLUMN ? frame.indent + ITEM_COLUMN[frame.clause]! : frame.indent);
} else if (it.kind === "punct" && it.text === ")" && frame.kind === "create") {
newline(frames.at(-2)!.indent);
} else if (isQuery && word && frame.count > 0) {
if (NEWLINE_CLAUSES.has(word)) {
if (isClause(word)) {
if (!atLineStart()) newline(frame.indent);
} else if (word === "ON" && frame.clause === "VALUES") {
newline(frame.indent);
} else if (JOIN_START.has(word) && !JOIN_MODIFIERS.has(prev?.upper ?? "") && frame.clause === "FROM") {
newline(frame.indent + 9);
} else if ((word === "AND" || word === "OR") && (frame.clause === "WHERE" || frame.clause === "HAVING")) {
} else if ((word === "AND" || word === "OR") && AND_OR_CLAUSES.has(frame.clause)) {
if (word === "AND" && frame.between) frame.between = false;
else newline(frame.indent + (word === "AND" ? 2 : 3));
} else if ((word === "INSERT" || word === "UPDATE" || word === "DELETE") && isP(prev, ")")) {
@@ -151,7 +155,12 @@ function formatStatement(items: Item[], base: string): string {
const at = last.lastIndexOf(prev!.text);
lines[lines.length - 1] = `${last.slice(0, at).trimEnd()}, ${last.slice(at)}`;
} else {
if (!atLineStart() && spaceBefore(prev, it, items[i - 2], unary)) line += " ";
if (
!atLineStart() &&
!(driver === "snowflake" && isTightPath(prev, it)) &&
spaceBefore(prev, it, items[i - 2], unary)
)
line += " ";
line += it.text;
}
unary = it.kind === "punct" && (it.text === "-" || it.text === "+") && (!prev || isOperatorLike(prev));
@@ -159,7 +168,7 @@ function formatStatement(items: Item[], base: string): string {
// Bookkeeping and breaks after the token.
frame.count++;
if (isQuery && word) {
if (NEWLINE_CLAUSES.has(word)) frame.clause = word;
if (isClause(word)) frame.clause = word;
else if (word === "ON" && frame.clause === "VALUES") frame.clause = "CONFLICT";
if (word === "BETWEEN") frame.between = true;
}
@@ -198,6 +207,16 @@ function isOperatorLike(t: Item): boolean {
return t.kind === "word" && isReserved(t.text);
}
/** Snowflake `col:key` / `col['key']`: a colon or bracket written without spaces stays so. */
function isTightPath(prev: Item | null, it: Item): boolean {
return (
!!prev &&
prev.to === it.from &&
// `name!member` is a service role or a model's method.
(isP(it, ":") || isP(prev, ":") || isP(it, "[") || isP(prev, "[") || isP(it, "]") || isP(it, "!") || isP(prev, "!"))
);
}
function spaceBefore(prev: Item | null, it: Item, beforePrev: Item | undefined, unary: boolean): boolean {
if (!prev) return false;
if (unary) return false;
+36 -6
View File
@@ -2,7 +2,8 @@
* SQL tokens for completion and resolution: words, quoted identifiers, string
* literals, numbers and punctuation, with comments and whitespace dropped.
* Dialect-aware (MySQL backticks / `#` comments / backslash escapes,
* PostgreSQL dollar quoting). Offsets are UTF-16, like the editor's.
* PostgreSQL dollar quoting, Snowflake `$$` strings / `//` comments / stages /
* variant paths). Offsets are UTF-16, like the editor's.
*/
import type { DbDriver } from "@/platform/ipc";
@@ -27,11 +28,15 @@ export interface Lexed {
const WORD_START = /[\p{L}_]/u;
const WORD_PART = /[\p{L}\p{N}_$]/u;
const STAGE_START = /[\p{L}_~%"]/u;
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 {
const mysql = driver === "mysql";
const clickhouse = driver === "clickhouse";
const snowflake = driver === "snowflake";
const tokens: Token[] = [];
const comments: Lexed["comments"] = [];
const n = text.length;
@@ -67,7 +72,7 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
const next = text[i + 1];
if (c === " " || c === "\t" || c === "\n" || c === "\r") {
i++;
} else if ((c === "-" && next === "-") || (c === "#" && mysql)) {
} else if ((c === "-" && next === "-") || (c === "#" && mysql) || (c === "/" && next === "/" && snowflake)) {
const end = text.indexOf("\n", i);
const to = end < 0 ? n : end;
comments.push({ from: i, to, open: true });
@@ -78,7 +83,7 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
comments.push({ from: i, to, open: end < 0 });
i = to;
} else if (c === "'") {
const to = quoted(i, "'", mysql || clickhouse);
const to = quoted(i, "'", mysql || clickhouse || snowflake);
push("string", i, to);
i = to;
} else if (c === '"') {
@@ -103,6 +108,25 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
push("param", i, j);
i = j;
}
} else if (c === "$" && snowflake) {
if (next === "$") {
const close = text.indexOf("$$", i + 2);
const to = close < 0 ? n : close + 2;
push("string", i, to);
i = to;
} else {
// `$1` (positional column) / `$name` (session variable).
let j = i + 1;
while (j < n && WORD_PART.test(text[j]!)) j++;
push(j > i + 1 ? "param" : "punct", i, j);
i = j;
}
} else if (c === "@" && snowflake && next !== undefined && STAGE_START.test(next)) {
// A stage reference with its path: `@stage/dir/file.csv`, `@~/x`, `@%table`.
let j = i + 1;
while (j < n && !STAGE_END.test(text[j]!)) j++;
push("param", i, j);
i = j;
} else if (/\d/.test(c) || (c === "." && next !== undefined && /\d/.test(next))) {
let j = i + 1;
while (j < n && /[\d.eE_xXa-fA-F]/.test(text[j]!)) j++;
@@ -111,13 +135,19 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
} else if (WORD_START.test(c)) {
let j = i + 1;
while (j < n && WORD_PART.test(text[j]!)) j++;
push("word", i, j);
if (snowflake && text.startsWith("://", j)) {
// A location of PUT / GET (`file:///tmp/data.csv`): one token, and its `//` no comment.
while (j < n && !STAGE_END.test(text[j]!)) j++;
push("param", i, j);
} else push("word", i, j);
i = j;
} else if (
(c === "?" || c === ":" || c === "@") &&
next !== undefined &&
WORD_START.test(next) &&
!(c === ":" && text[i - 1] === ":")
!(c === ":" && text[i - 1] === ":") &&
// Snowflake `col:path` (also after `)`, `]` and quotes) reads a VARIANT.
!(c === ":" && snowflake && i > 0 && PATH_OWNER.test(text[i - 1]!))
) {
let j = i + 1;
while (j < n && WORD_PART.test(text[j]!)) j++;
@@ -125,7 +155,7 @@ export function lex(text: string, driver: DbDriver = "sqlite"): Lexed {
i = j;
} else {
const two = text.slice(i, i + 2);
const len = TWO_CHAR.has(two) ? 2 : 1;
const len = two === "->" && text[i + 2] === ">" ? 3 : TWO_CHAR.has(two) ? 2 : 1;
push("punct", i, i + len);
i += len;
}
+2
View File
@@ -36,6 +36,8 @@ export function findParams(text: string, driver: DbDriver, numbered = 0): SqlPar
if (t.kind === "param") {
// MySQL `@var` / `@@var` are session variables.
if (driver === "mysql" && t.text.startsWith("@")) return;
// Snowflake `@stage` references, `$1` columns, `$name` session variables and `file://` locations.
if (driver === "snowflake" && /^[@$]|^\w+:\/\//.test(t.text)) return;
if (toks[i - 1]?.text === "@") return;
out.push({ name: t.text, from: t.from, to: t.to });
} else if (t.kind === "punct" && t.text === "?" && driver !== "postgres") {
@@ -25,4 +25,54 @@ describe("isReadOnlyQuery", () => {
])
expect(isReadOnlyQuery(text, "postgres"), text).toBe(false);
});
it("classifies Snowflake statements", () => {
for (const text of [
"SELECT src:a::string FROM t // insert",
"with x as (select 1) select * from x",
"SHOW TABLES IN SCHEMA db.public",
"describe table t",
"DESC VIEW v",
"EXPLAIN SELECT 1",
"LIST @my_stage/path",
"ls @~",
"TABLE t",
"VALUES (1), (2)",
"select $1 from @my_stage/data (file_format => 'ff')",
])
expect(isReadOnlyQuery(text, "snowflake"), text).toBe(true);
for (const text of [
"COPY INTO t FROM @my_stage",
"PUT file:///tmp/a.csv @my_stage",
"GET @my_stage file:///tmp/",
"REMOVE @my_stage/path",
"rm @~/x",
"MERGE INTO t USING s ON t.id = s.id WHEN MATCHED THEN UPDATE SET a = 1",
"CALL my_proc()",
"EXECUTE IMMEDIATE $$ select 1 $$",
"USE SCHEMA public",
"ALTER SESSION SET TIMEZONE = 'UTC'",
"CREATE OR REPLACE TABLE t (a int)",
"DROP TABLE t",
"UNDROP TABLE t",
"TRUNCATE TABLE t",
"GRANT SELECT ON t TO ROLE r",
"REVOKE SELECT ON t FROM ROLE r",
"BEGIN",
"COMMIT",
"ROLLBACK",
"SET v = 1",
"UNSET v",
"INSERT INTO t VALUES (1)",
"UPDATE t SET a = 1",
"DELETE FROM t",
"select seq.nextval",
"select system$cancel_query('x')",
"select * from table(result_scan(last_query_id()))",
"show tables ->> delete from t",
])
expect(isReadOnlyQuery(text, "snowflake"), text).toBe(false);
// Stage listings are Snowflake's alone.
expect(isReadOnlyQuery("LIST @my_stage", "postgres")).toBe(false);
});
});
+11 -2
View File
@@ -6,10 +6,19 @@ const READ_VERBS = new Set(["SELECT", "WITH", "VALUES", "TABLE", "SHOW", "DESCRI
/** Words that make a reading statement write (data-modifying CTEs, SELECT INTO, row locks, sequences). */
const WRITES = new Set(["INSERT", "UPDATE", "DELETE", "MERGE", "INTO", "NEXTVAL", "SETVAL", "CALL", "EXEC", "EXECUTE"]);
/** Snowflake's stage listings read too. */
const SNOWFLAKE_READ_VERBS = new Set(["LIST", "LS"]);
/** Snowflake functions that act on the account or depend on the statements run before. */
const SNOWFLAKE_WRITES = /^(SYSTEM\$.*|LAST_QUERY_ID|RESULT_SCAN)$/;
/** Whether running `text` again only reads (paging a result re-runs its query). */
export function isReadOnlyQuery(text: string, driver: DbDriver): boolean {
const tokens = lex(text, driver).tokens;
const first = tokens.find((t) => t.text !== "(");
if (!first || first.kind !== "word" || !READ_VERBS.has(first.upper)) return false;
return !tokens.some((t) => t.kind === "word" && WRITES.has(t.upper));
const snowflake = driver === "snowflake";
if (!first || first.kind !== "word") return false;
if (!READ_VERBS.has(first.upper) && !(snowflake && SNOWFLAKE_READ_VERBS.has(first.upper))) return false;
return !tokens.some(
(t) => t.kind === "word" && (WRITES.has(t.upper) || (snowflake && SNOWFLAKE_WRITES.test(t.upper))),
);
}
+41 -6
View File
@@ -48,6 +48,14 @@ const NOT_COLUMNS = new Set(
"TRAILING BOTH NOWAIT SKIP LOCKED SHARE MODE BINARY UNSIGNED SIGNED"
).split(" "),
);
/** Snowflake: select-list modifiers, sampling words, pseudo-columns and date parts. */
const SNOWFLAKE_NOT_COLUMNS = new Set(
(
"EXCLUDE RENAME REPLACE BERNOULLI SYSTEM BLOCK SEED REPEATABLE LEVEL RESPECT QUARTER WEEK WEEKOFYEAR DAYOFWEEK " +
"DAYOFYEAR DAYOFMONTH MILLISECOND MICROSECOND NANOSECOND YEARS MONTHS DAYS HOURS MINUTES SECONDS WEEKS YY YYYY " +
"MM MON DD HH MI SS MS US NS"
).split(" "),
);
export function findTable(
model: DbCompletion | null,
@@ -129,6 +137,7 @@ export class SqlResolver {
const toks = this.lexed.tokens;
const t = toks[i]!;
if (!isName(t) || (t.kind === "word" && CLAUSE_WORDS.has(t.upper))) return null;
if (this.driver === "snowflake" && isVariantKey(toks, i)) return null;
const prev = toks[i - 1];
const next = toks[i + 1];
const name = identName(t);
@@ -148,6 +157,9 @@ 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]))
return { ...span, symbol: null };
return { ...span, symbol: null, problem: `Unable to resolve symbol '${name}'` };
}
@@ -170,6 +182,8 @@ export class SqlResolver {
if (table) return { ...span, symbol: { kind: "table", table } };
if (!loaded || (a.verb !== "DROP" && a.verb !== "ALTER" && !checked)) return { ...span, symbol: null };
if (schema && !this.model!.tables.some((x) => eq(x.schema, schema))) return { ...span, symbol: null };
// Snowflake `database.schema.table`: the table may live in a database the model does not hold.
if (this.driver === "snowflake" && qualifier && qualifier.length > 1) return { ...span, symbol: null };
return { ...span, symbol: null, problem: `Unable to resolve table '${name}'` };
}
case "afterTable":
@@ -177,7 +191,8 @@ export class SqlResolver {
case "insertColumns": {
const cols = this.columnsOf(ctx.target);
const col = cols?.find((c) => eq(c.name, name));
if (col || !cols) return { ...span, symbol: col ? this.columnSymbol(ctx.target, col) : null };
if (col || !cols || ctx.target.database)
return { ...span, symbol: col ? this.columnSymbol(ctx.target, col) : null };
return { ...span, symbol: null, problem: `Unable to resolve column '${name}'` };
}
case "afterInsertColumns":
@@ -196,13 +211,21 @@ export class SqlResolver {
const cols = this.columnsOf(ref);
const col = cols?.find((c) => eq(c.name, name));
if (col) return { ...span, symbol: this.columnSymbol(ref, col) };
if (!cols || !checked) return { ...span, symbol: null };
if (!cols || !checked || ref.database) return { ...span, symbol: null };
return { ...span, symbol: null, problem: `Unable to resolve column '${name}'` };
}
// A bare word: a column unless it is a function, a type, a keyword or an alias being defined.
if (isP(next, "(") || isP(prev, "::") || (prev?.kind === "word" && prev.upper === "AS")) return null;
if (t.kind === "word" && (isReserved(t.text) || NOT_COLUMNS.has(t.upper) || this.words.has(t.upper))) return null;
if (isP(next, "(") || isP(next, "=>") || isP(prev, "::") || (prev?.kind === "word" && prev.upper === "AS"))
return null;
if (
t.kind === "word" &&
(isReserved(t.text, this.driver) ||
NOT_COLUMNS.has(t.upper) ||
this.words.has(t.upper) ||
(this.driver === "snowflake" && (SNOWFLAKE_NOT_COLUMNS.has(t.upper) || t.upper.startsWith("METADATA$"))))
)
return null;
// `count(*) n`, `x total`: an alias after an expression.
if (
prev &&
@@ -224,7 +247,7 @@ export class SqlResolver {
checked &&
loaded &&
a.refs.length > 0 &&
a.refs.every((r) => this.columnsOf(r) !== null) &&
a.refs.every((r) => this.columnsOf(r) !== null && !r.database) &&
clause !== "other" &&
clause !== "values" &&
clause !== "limit" &&
@@ -267,7 +290,8 @@ export class SqlResolver {
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);
return table ? table.columns.map((c) => ({ name: c.name, column: c })) : null;
// 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 {
@@ -295,6 +319,17 @@ export class SqlResolver {
}
}
/** Whether name token `i` is a key of a Snowflake VARIANT path: `src:a.b`, `src['a'].b`. */
function isVariantKey(toks: readonly Token[], i: number): boolean {
let j = i;
while (isP(toks[j - 1], ".")) {
if (isP(toks[j - 2], "]")) return true;
if (!isName(toks[j - 2])) return false;
j -= 2;
}
return isP(toks[j - 1], ":") && toks[j - 1]!.to === toks[j]!.from;
}
/** Whether token `i` follows INSERT / REPLACE INTO (so a `(` after it lists columns). */
function isIntoTarget(toks: readonly Token[], i: number): boolean {
let j = i - 1;
@@ -0,0 +1,79 @@
/**
* Every SQL command of Snowflake's reference through the console's SQL assistance. The samples
* are the ones the driver's tests run (`crates/ide-db/src/snowflake/commands.rs`): one statement
* per documented command.
*/
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { formatted } from "./format";
import { lex } from "./lexer";
import { findParams } from "./params";
import { isReadOnlyQuery } from "./readOnly";
interface Command {
command: string;
sql: string;
/** Running it again for another page of its result changes nothing. */
rerunnable: boolean;
}
const fixture = resolve(process.cwd(), "crates/ide-db/tests/fixtures/snowflake/commands.json");
const commands = (JSON.parse(readFileSync(fixture, "utf8")) as { commands: Command[] }).commands;
/** What a statement is made of, whatever its layout and letter case. */
const shape = (sql: string) =>
lex(sql, "snowflake")
.tokens.map((t) => (t.kind === "word" ? t.upper : t.text))
.join(" ");
describe("Snowflake commands", () => {
it("has the whole reference", () => {
expect(commands.length).toBeGreaterThanOrEqual(786);
});
it("lexes every command to its end", () => {
for (const c of commands) {
const { tokens, comments } = lex(c.sql, "snowflake");
// The samples' only comments are inside `$$` bodies; `file://` is a path, not a comment.
expect(comments, c.command).toEqual([]);
expect(tokens.length, c.command).toBeGreaterThan(0);
expect(tokens[0]!.kind, c.command).toBe("word");
// No token runs past the statement or overlaps the one before.
let end = 0;
for (const t of tokens) {
expect(t.from, c.command).toBeGreaterThanOrEqual(end);
end = t.to;
}
expect(end, c.command).toBeLessThanOrEqual(c.sql.length);
}
});
it("pages only what is safe to run again", () => {
for (const c of commands) expect(isReadOnlyQuery(c.sql, "snowflake"), `${c.command}: ${c.sql}`).toBe(c.rerunnable);
});
it("asks for no parameter values", () => {
// Stage paths, variant paths, `$1`, `:=`, `file://` and `=>` are not parameters.
for (const c of commands) {
if (c.command === "CALL") continue; // `INTO :result` is a bind variable
expect(
findParams(c.sql, "snowflake").map((p) => p.name),
`${c.command}: ${c.sql}`,
).toEqual([]);
}
});
it("formats every command without changing it, and settles", () => {
for (const c of commands) {
const once = formatted(c.sql, "snowflake");
expect(shape(once), c.command).toBe(shape(c.sql));
expect(formatted(once, "snowflake"), c.command).toBe(once);
// Paths, casts, stages and scoped names stay in one piece: a space inside breaks them.
for (const piece of c.sql.split(/\s+/)) {
if (/[:!@$]/.test(piece) && !/['"(),;]/.test(piece) && !/^(:=|\$\$)$/.test(piece)) {
expect(once, `${c.command}: ${piece}`).toContain(piece);
}
}
}
});
});
@@ -0,0 +1,106 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { StandardSQL } from "@codemirror/lang-sql";
import { ensureSyntaxTree } from "@codemirror/language";
import { EditorState, Prec } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { snowflakeLanguage } from "./snowflakeHighlight";
interface Piece {
name: string;
text: string;
}
/** The leaves of the syntax tree: what each run of text is coloured as. */
function pieces(sql: string): Piece[] {
const out: Piece[] = [];
snowflakeLanguage()
.parser.parse(sql)
.iterate({
enter: (node) => {
if (!node.node.firstChild) out.push({ name: node.name, text: sql.slice(node.from, node.to) });
},
});
return out;
}
const named = (sql: string, name: string) =>
pieces(sql)
.filter((p) => p.name === name)
.map((p) => p.text);
const fixture = resolve(process.cwd(), "crates/ide-db/tests/fixtures/snowflake/commands.json");
const commands = (JSON.parse(readFileSync(fixture, "utf8")) as { commands: Array<{ command: string; sql: string }> })
.commands;
describe("Snowflake syntax colours", () => {
it("colours the words of every documented command as keywords", () => {
for (const c of commands) {
const all = pieces(c.sql);
// `GET` is a function as well as a command.
expect(["Keyword", "Builtin"], `${c.command}: ${c.sql}`).toContain(all[0]?.name);
// The command's own words (`ALTER ICEBERG TABLE`), wherever the sample uses them.
const words = c.command.replace(/\([^)]*\)|<[^>]*>/g, "").match(/\b[A-Z][A-Z_0-9]+\b/g) ?? [];
const coloured = new Set(
all.filter((p) => ["Keyword", "Type", "Builtin"].includes(p.name)).map((p) => p.text.toUpperCase()),
);
const plain = new Set(all.filter((p) => p.name === "Identifier").map((p) => p.text.toUpperCase()));
for (const word of words) {
if (plain.has(word)) expect(coloured.has(word), `${c.command}: ${word} in ${c.sql}`).toBe(true);
}
expect(named(c.sql, "⚠"), `${c.command}: ${c.sql}`).toEqual([]);
}
});
it("reads comments, bodies, strings and stages the way Snowflake does", () => {
expect(named("select 1 // note; here\n, 2 -- other\n/* block */", "LineComment")).toEqual([
"// note; here",
"-- other",
]);
const body = "$$\nbegin\n return 'x'; -- inside\nend;\n$$";
expect(named(`create procedure p() returns string language sql as ${body}; select 1`, "String")).toEqual([body]);
// A doubled quote reads as two strings side by side: the same colour throughout.
expect(named("select 'it''s', 'a\\'b', 'c;d'", "String")).toEqual(["'it'", "'s'", "'a\\'b'", "'c;d'"]);
expect(named('select "My Col" from "DB"."S"."T"', "QuotedIdentifier")).toEqual(['"My Col"', '"DB"', '"S"', '"T"']);
expect(named("select $1, $2:name, $my_var from @my_stage/dir/f.csv.gz, @~/x, @%t", "SpecialVar")).toEqual([
"$1",
"$2",
"$my_var",
"@my_stage/dir/f.csv.gz",
"@~/x",
"@%t",
]);
// A location is not a comment, and what follows it is still read.
const put = pieces("put file:///tmp/data.csv @my_stage auto_compress = true; select 1");
expect(put.filter((p) => p.name === "LineComment")).toEqual([]);
expect(put.filter((p) => p.name === "Keyword").map((p) => p.text)).toEqual(["put", "file", "true", "select"]);
expect(put.some((p) => p.name === "Identifier" && p.text === "tmp")).toBe(true);
expect(put.some((p) => p.name === "SpecialVar" && p.text === "@my_stage")).toBe(true);
});
it("colours Snowflake's own clauses, types and functions", () => {
const sql =
"select iff(a, 1, 2)::number, payload:k::varchar from t qualify row_number() over (order by a) = 1 limit 5";
expect(named(sql, "Keyword")).toEqual(["select", "from", "qualify", "over", "order", "by", "limit"]);
expect(named(sql, "Type")).toEqual(["number", "varchar"]);
expect(named(sql, "Builtin")).toEqual(["iff", "row_number"]);
for (const word of ["warehouse", "iceberg", "undrop", "variant", "ilike", "pivot", "asof", "clone", "stream"]) {
expect(pieces(`x ${word} y`)[1]?.name, word).not.toBe("Identifier");
}
});
it("takes over from the editor's standard SQL mode", () => {
const doc = "select 1 // a note\n";
const tree = (config: Parameters<typeof EditorState.create>[0]) =>
ensureSyntaxTree(EditorState.create(config), doc.length, 1000)!;
const comments = (config: Parameters<typeof EditorState.create>[0]) => {
const found: string[] = [];
tree(config).iterate({ enter: (n) => void (n.name === "LineComment" && found.push(doc.slice(n.from, n.to))) });
return found;
};
expect(comments({ doc, extensions: [StandardSQL.extension] })).toEqual([]);
expect(comments({ doc, extensions: [StandardSQL.extension, Prec.high(snowflakeLanguage().extension)] })).toEqual([
"// a note",
]);
});
});
@@ -0,0 +1,73 @@
/**
* Syntax colours for consoles of a Snowflake data source. The editor's SQL mode is standard SQL;
* Snowflake adds `//` comments, `$$` bodies, stages (`@stage/path`), `$1` / `$name`, backslash
* escapes and several hundred command words.
*/
import { SQLDialect } from "@codemirror/lang-sql";
import type { LRLanguage } from "@codemirror/language";
import { ExternalTokenizer, type InputStream, type LRParser, type Stack } from "@lezer/lr";
import { DATA_TYPES, functions } from "./dialect";
import { SNOWFLAKE_KEYWORDS } from "./snowflakeKeywords";
/** A grammar tokenizer as the parser calls it. */
interface Tokenizer {
token(input: InputStream, stack: Stack): void;
}
const SLASH = 47;
const COLON = 58;
const DOLLAR = 36;
const AT = 64;
/** A stage reference ends at whitespace, a bracket, a comma, a semicolon or a quote. */
const STAGE_END = /[\s(),;']/;
const WORD = /[\p{L}\p{N}_]/u;
function build(): LRLanguage {
const spec = {
keywords: SNOWFLAKE_KEYWORDS.toLowerCase(),
types: DATA_TYPES.snowflake.join(" ").toLowerCase(),
builtin: functions("snowflake")
.map((f) => f.name)
.join(" ")
.toLowerCase(),
doubleDollarQuotedStrings: true,
backslashEscapes: true,
identifierQuotes: '"',
specialVar: "@",
};
const slashes = SQLDialect.define({ ...spec, slashComments: true }).language;
const plain = SQLDialect.define({ ...spec, slashComments: false }).language;
// The grammar's tokenizer is built per dialect: the one that differs between the two.
const tokenizers = (language: LRLanguage) =>
(language.parser as LRParser & { tokenizers: readonly ExternalTokenizer[] }).tokenizers;
const index = tokenizers(slashes).findIndex((t, i) => t !== tokenizers(plain)[i]);
const withComments = tokenizers(slashes)[index];
const without = tokenizers(plain)[index];
if (!withComments || !without) return slashes;
const special = slashes.parser.nodeSet.types.find((type) => type.name === "SpecialVar")?.id;
const tokens = new ExternalTokenizer((input, stack) => {
const next = input.next;
if (special !== undefined && (next === AT || next === DOLLAR)) {
const first = String.fromCharCode(Math.max(input.peek(1), 0));
// `$$` opens a body; `$1` is a column and `$name` a session variable.
if (next === DOLLAR ? WORD.test(first) : !STAGE_END.test(first) && input.peek(1) >= 0) {
input.advance();
const part = next === AT ? (c: string) => !STAGE_END.test(c) : (c: string) => WORD.test(c);
while (input.next >= 0 && part(String.fromCharCode(input.next))) input.advance();
input.acceptToken(special);
return;
}
}
// The `//` of `file://…` (PUT, GET) starts no comment.
const url = next === SLASH && input.peek(1) === SLASH && input.peek(-1) === COLON;
((url ? without : withComments) as unknown as Tokenizer).token(input, stack);
});
return slashes.configure({ tokenizers: [{ from: withComments, to: tokens }] });
}
let built: LRLanguage | undefined;
/** The Snowflake SQL language (built on first use). */
export function snowflakeLanguage(): LRLanguage {
return (built ??= build());
}
@@ -0,0 +1,48 @@
/**
* Words the Snowflake console colours as keywords: Snowflake's reserved words
* (https://docs.snowflake.com/en/sql-reference/reserved-keywords), every word of the command names of its SQL
* reference (https://docs.snowflake.com/en/sql-reference/sql-all), and the clause and Scripting words.
*/
export const SNOWFLAKE_KEYWORDS =
"DBT DCM " +
"ABORT ACCESS ACCOUNT ACCOUNTS ADD AFTER AGENT AGENTS AGGREGATION AI ALERT ALERTS ALL ALTER ANALYZE " +
"AND ANY API APPEND_ONLY APPLICATION APPLICATIONS APPROVAL APPROVE ARTIFACT AS ASC ASOF AT " +
"AUTHENTICATION AUTHORIZATIONS AUTOCOMMIT AUTOINCREMENT AVAILABLE BACKUP BACKUPS BASE BEFORE BEGIN " +
"BERNOULLI BETWEEN BLOCK BRANCHES BREAK BUNDLE BUNDLES BY CALL CALLED CALLER CASCADE CASE CAST " +
"CATALOG CHANGES CHANNEL CHANNELS CHECK CLASSES CLONE CLOSE CLUSTER CODE COLLATE COLUMN COLUMNS " +
"COMMENT COMMIT COMMITTED COMPUTE CONDITION CONFIGURATION CONFIGURATIONS CONNECT CONNECTION " +
"CONNECTIONS CONNECTOR CONNECTORS CONSTRAINT CONSUMER CONSUMERS CONTACT CONTACTS CONTAINERS CONTENT " +
"CONTINUE CONTRACTS CONVERT COPY CORTEX CREATE CROSS CUBE CURRENT CURRENT_DATE CURRENT_TIME " +
"CURRENT_TIMESTAMP CURRENT_USER CURSOR CYCLE DATA DATABASE DATABASES DATASET DATASETS DECLARE DECLINE " +
"DEFAULT DEFINER DEFINITION DEFINITIONS DELEGATED DELETE DEPLOYMENT DEPLOYMENTS DESC DESCRIBE " +
"DIMENSIONS DIRECTIVE DIRECTIVES DISABLE DISTINCT DO DROP DYNAMIC ELSE ELSEIF ENABLE END ENDIF " +
"ENDPOINTS ENFORCED ENTITIES EVENT EXCEPT EXCEPTION EXCLUDE EXECUTE EXISTS EXPERIMENT EXPERIMENTS " +
"EXPLAIN EXPORTED EXTENDED EXTERNAL FACTS FAILOVER FALSE FAMILIES FEATURE FETCH FILE FILES " +
"FILE_FORMAT FINALIZE FIRST FLATTEN FOLLOWING FOR FORCE FOREIGN FORMAT FORMATS FROM FULL FUNCTION " +
"FUNCTIONS FUTURE GATEWAY GATEWAYS GET GIT GLOBAL GRANT GRANTS GRAPH GRAPHS GROUP GROUPING GROUPS " +
"GSCLUSTER HANDLER HAVING HISTORY HYBRID ICEBERG IDENTITY IF ILIKE IMAGE IMAGES IMMEDIATE IMMUTABLE " +
"IMPORTED IMPORTS IN INCREMENT INDEX INDEXES INFERENCE INGRESS INHERITED INITIALIZE INNER INPUT " +
"INSERT INSTANCE INSTANCES INTEGRATION INTEGRATIONS INTERACTIVE INTERSECT INTERVAL INTO IS ISOLATION " +
"ISSUE JOB JOIN JSON KEY KEYS LAG LANGUAGE LAST LATERAL LEFT LET LEVEL LIFECYCLE LIKE LIMIT LIST " +
"LISTING LISTINGS LOCAL LOCALTIME LOCALTIMESTAMP LOCKS LOOP MAINTENANCE MANAGED MASKING MATCHED " +
"MATCH_CONDITION MATCH_RECOGNIZE MATERIALIZED MAXVALUE MCP MEMOIZABLE MERGE METHODS METRIC METRICS " +
"MFA MINUS MINVALUE MODEL MODELS MODIFY MONITOR MONITORS MOVEMENT MULTI NAME NATURAL NETWORK NEXT " +
"NOCYCLE NODES NOORDER NOT NOTEBOOK NOTEBOOKS NOTIFICATION NULL NULLS OBJECTS OF OFFERS OFFSET ON " +
"ONLINE ONLY ON_ERROR OPEN OPENFLOW OPERATE OPTIMIZATION OPTIMIZE OPTION OR ORDER ORGANIZATION OTHER " +
"OUTER OVER OVERWRITE OWNED OWNER OWNERSHIP PACKAGE PACKAGES PAIR PAIRS PARAMETERS PARTITION PARTY " +
"PASSWORD PATTERN PIPE PIPES PIVOT PLANE PLANS POLICIES POLICY POOL POOLS POSTGRES PRECEDING PRICING " +
"PRIMARY PRIVACY PRIVILEGES PROCEDURE PROCEDURES PROFILE PROFILES PROGRAMMATIC PROJECT PROJECTION " +
"PROJECTS PROVISIONED PURGE PUT QUALIFY RAISE RANGE READ RECURSIVE REFERENCES REFRESH REGEXP REGIONS " +
"RELEASE REMOVE RENAME REPEAT REPEATABLE REPLACE REPLICATION REPOSITORIES REPOSITORY RESOURCE " +
"RESTRICT RESTRICTED RESULT RESULTSET RESUME RETENTION_TIME_IN_DAYS RETURN RETURNS REVOKE RIGHT RLIKE " +
"ROLE ROLES ROLLBACK ROLLUP ROTATE ROUTING ROW ROWCOUNT ROWS RULE RULES RUN RUNS RUNTIME RUNTIMES " +
"SAMPLE SCHEDULE SCHEMA SCHEMAS SCOPE SCOPES SEARCH SECONDARY SECRET SECRETS SECURE SECURITY SEED " +
"SELECT SEMANTIC SEQUENCE SEQUENCES SERVER SERVERS SERVICE SERVICES SESSION SET SETS SHARE SHARED " +
"SHARES SHOW SNAPSHOT SNAPSHOTS SOME SPECIFICATION SPECIFICATIONS STAGE STAGES START STARTS STATEMENT " +
"STORAGE STREAM STREAMLIT STREAMLITS STREAMS STRICT SUSPEND SUSPENDED SWAP SYSTEM TABLE TABLES " +
"TABLESAMPLE TABULAR TAG TAGS TARGET_LAG TASK TASKS TELEMETRY TEMP TEMPORARY TERSE TEXT THEN " +
"THROUGHPUT TIMESTAMP TO TOKEN TOKENS TOP TRANSACTION TRANSACTIONS TRANSIENT TRIGGER TRUE TRUNCATE " +
"TRY_CAST TYPE TYPES UNBOUNDED UNDROP UNION UNIQUE UNPIVOT UNSET UNTIL UPDATE USAGE USE USER USERS " +
"USING VALIDATION_MODE VALUE VALUES VARIABLE VARIABLES VERSION VERSIONED VERSIONS VERSION_TAG VIEW " +
"VIEWS VOLATILE VOLUME VOLUMES WAREHOUSE WAREHOUSES WHEN WHENEVER WHERE WHILE WINDOW WITH WITHIN WORK " +
"WORKLOAD WORKSPACES WRITE ";
+271
View File
@@ -79,6 +79,21 @@ function complete(sql: string, driver: DbDriver = "sqlite", m: DbCompletion = mo
(a, b) => b.boost - a.boost,
);
}
/** A Snowflake schema model: names as the server stores them. */
const sf: DbCompletion = {
defaultSchema: "PUBLIC",
tables: [
{
schema: "PUBLIC",
name: "USERS",
kind: "table",
columns: [col("ID", "NUMBER", true), col("SRC", "VARIANT"), col("mixedCase", "VARCHAR")],
},
{ schema: "RAW", name: "EVENTS", kind: "table", columns: [col("ID", "NUMBER", true), col("PAYLOAD", "VARIANT")] },
],
foreignKeys: [],
};
const labels = (c: SqlCandidate[], kind?: string) => c.filter((x) => !kind || x.kind === kind).map((x) => x.label);
describe("lexer", () => {
@@ -116,6 +131,46 @@ describe("lexer", () => {
expect(lex("do $x$ begin; end $x$", "postgres").tokens.map((t) => t.kind)).toEqual(["word", "string"]);
expect(inLiteral(lex("select 'abc"), 11)).toBe("string");
});
it("reads Snowflake dollar strings, comments, escapes, variant paths and stages", () => {
const texts = (sql: string) => lex(sql, "snowflake").tokens.map((t) => t.text);
const l = lex("select $$ it's; -- $$ // c ' \n, 'a\\'b' /* d */ -- e", "snowflake");
expect(l.tokens.map((t) => t.kind)).toEqual(["word", "string", "punct", "string"]);
expect(l.tokens[3]!.text).toBe("'a\\'b'");
expect(l.comments).toHaveLength(3);
expect(inLiteral(lex("select $$ open", "snowflake"), 14)).toBe("string");
expect(texts('select src:a.b::string, "V":k, f(x):y, a[0]:z, $1, $var')).toEqual(
["select", "src", ":", "a", ".", "b", "::", "string", ",", '"V"', ":", "k", ","].concat([
"f",
"(",
"x",
")",
":",
"y",
",",
"a",
"[",
"0",
"]",
":",
"z",
",",
"$1",
",",
"$var",
]),
);
expect(texts("from @db.sch.stg/dir/f.csv, @~/x, @%t (pattern => '.*') where a = :id")).toEqual(
["from", "@db.sch.stg/dir/f.csv", ",", "@~/x", ",", "@%t", "(", "pattern", "=>", "'.*'", ")"].concat([
"where",
"a",
"=",
":id",
]),
);
// Only Snowflake reads `//` as a comment.
expect(lex("select 1 // 2", "postgres").comments).toEqual([]);
});
});
describe("analysis", () => {
@@ -225,6 +280,181 @@ describe("completion candidates", () => {
expect(quoteIdent('a"b', "oracle")).toBe('"a""b"');
});
it("offers Snowflake vocabulary and quotes names the server folds to upper case", () => {
expect(statementStarters("snowflake")).toEqual(
expect.arrayContaining([
"COPY INTO",
"MERGE INTO",
"SHOW TABLES",
"USE SCHEMA",
"EXECUTE IMMEDIATE",
"UNDROP TABLE",
]),
);
expect(statementStarters("snowflake")).not.toContain("CREATE INDEX");
expect(DATA_TYPES.snowflake).toEqual(expect.arrayContaining(["VARIANT", "TIMESTAMP_NTZ", "NUMBER"]));
expect(new Set(DATA_TYPES.snowflake).size).toBe(DATA_TYPES.snowflake.length);
const afterTable = labels(complete("SELECT * FROM USERS U |", "snowflake", sf), "keyword");
expect(afterTable).toEqual(
expect.arrayContaining(["QUALIFY", "ASOF JOIN", "NATURAL JOIN", "LATERAL FLATTEN", "PIVOT"]),
);
expect(labels(complete("SELECT * FROM USERS WHERE |", "snowflake", sf), "keyword")).toEqual(
expect.arrayContaining(["ILIKE", "RLIKE", "QUALIFY"]),
);
expect(complete("SELECT | FROM USERS", "snowflake", sf).find((c) => c.label === "IFF")).toMatchObject({
snippet: "IFF(${})",
});
// Upper-case names are plain; anything else needs quotes (the server folds unquoted names).
expect(quoteIdent("ORDERS", "snowflake")).toBe("ORDERS");
expect(quoteIdent("ORDER_2$", "snowflake")).toBe("ORDER_2$");
expect(quoteIdent("orders", "snowflake")).toBe('"orders"');
expect(quoteIdent('a"b', "snowflake")).toBe('"a""b"');
expect(quoteIdent("QUALIFY", "snowflake")).toBe('"QUALIFY"');
expect(quoteIdent("QUALIFY", "oracle")).toBe("QUALIFY");
const columns = complete("SELECT | FROM USERS", "snowflake", sf);
expect(columns.find((c) => c.label === "ID")?.insert).toBe("ID");
expect(columns.find((c) => c.label === "mixedCase")?.insert).toBe('"mixedCase"');
const tables = complete("SELECT * FROM |", "snowflake", sf);
expect(tables.find((c) => c.label === "USERS")?.insert).toBe("USERS");
expect(tables.find((c) => c.label === "EVENTS")?.insert).toBe("RAW.EVENTS");
});
it("completes fully qualified Snowflake names through databases and schemas, in either case", () => {
const catalog = {
databases: ["ANALYTICS", "OTHER_DB", "Mixed Db"],
schemas: (db: string) => (db === "OTHER_DB" ? ["RAW", "STAGING"] : db === "ANALYTICS" ? ["PUBLIC", "RAW"] : null),
tables: (db: string, schema: string) =>
db === "OTHER_DB" && schema.toUpperCase() === "RAW"
? [
{ name: "CLICKS", view: false },
{ name: "CLICKS_V", view: true },
{ name: "mixedTable", view: false },
]
: null,
};
const run = (sql: string) =>
sqlCandidates({ model: sf, analysis: at(sql, "snowflake"), driver: "snowflake", catalog }).sort(
(a, b) => b.boost - a.boost,
);
const inserts = (sql: string, kind?: string) =>
run(sql)
.filter((c) => !kind || c.kind === kind)
.map((c) => c.insert ?? c.label);
// Databases are offered where a table may start, below the tables and schemas.
const top = run("SELECT * FROM |");
expect(top.filter((c) => c.tail === "(database)").map((c) => c.insert)).toEqual([
"ANALYTICS.",
"OTHER_DB.",
'"Mixed Db".',
]);
expect(top.find((c) => c.label === "OTHER_DB")).toMatchObject({ kind: "schema", retrigger: true });
expect(top[0]!.label).toBe("USERS");
// `database.` lists its schemas, `database.schema.` its tables and views.
expect(inserts("select * from OTHER_DB.|")).toEqual(["RAW.", "STAGING."]);
expect(run("select * from OTHER_DB.|").every((c) => c.kind === "schema" && c.retrigger)).toBe(true);
expect(inserts("select * from OTHER_DB.RAW.|")).toEqual(["CLICKS", '"mixedTable"', "CLICKS_V"]);
expect(run("select * from OTHER_DB.RAW.|").map((c) => c.kind)).toEqual(["table", "table", "view"]);
expect(inserts("select * from OTHER_DB.RAW.CL|")).toContain("CLICKS");
expect(inserts("select * from a join OTHER_DB.RAW.|")).toContain("CLICKS");
// Lower case finds the same names and keeps what is typed in lower case.
expect(inserts("select * from other_db.|")).toEqual(["raw.", "staging."]);
expect(inserts("select * from other_db.raw.|")).toEqual(["clicks", '"mixedTable"', "clicks_v"]);
expect(inserts("select * from other_db.raw.cl|")).toContain("clicks");
expect(inserts("select * from OTHER_DB.RAW.cl|")).toContain("clicks");
expect(inserts("select * from other_db.raw.CL|")).toContain("CLICKS");
expect(inserts("select * from raw.|")).toEqual(["events"]);
expect(inserts("select * from us|", "table")).toContain("users");
// Names follow the case being typed: the prefix first, then the qualifier, then the statement's keywords.
expect(inserts("select * from |", "table")).toEqual(expect.arrayContaining(["users", "raw.events"]));
expect(inserts("SELECT * FROM |", "table")).toEqual(expect.arrayContaining(["USERS", "RAW.EVENTS"]));
expect(inserts("SELECT * FROM us|", "table")).toContain("users");
expect(inserts("select * from US|", "table")).toContain("USERS");
expect(inserts("select | from USERS", "column")).toEqual(expect.arrayContaining(["id", "src", '"mixedCase"']));
expect(inserts("SELECT | FROM users", "column")).toEqual(expect.arrayContaining(["ID", "SRC", '"mixedCase"']));
expect(inserts("select u.| from USERS u")).toEqual(["id", "src", '"mixedCase"']);
expect(
run("select * from |")
.filter((c) => c.tail === "(database)")
.map((c) => c.insert),
).toEqual(["analytics.", "other_db.", '"Mixed Db".']);
// Introspected tables of other databases complete by name, written fully qualified.
const searched = sqlCandidates({
model: sf,
analysis: at("select * from cli|", "snowflake"),
driver: "snowflake",
catalog: {
...catalog,
search: (prefix: string, limit: number) =>
[
{ database: "OTHER_DB", schema: "RAW", name: "CLICKS", view: false },
{ database: "OTHER_DB", schema: "RAW", name: "CLICKS_V", view: true },
{ database: "Mixed Db", schema: "PUBLIC", name: "Clients", view: false },
]
.filter((t) => t.name.toLowerCase().startsWith(prefix.toLowerCase()))
.slice(0, limit),
},
});
expect(
searched.filter((c) => c.tail?.startsWith("(OTHER_DB") || c.tail?.startsWith("(Mixed")).map((c) => c.insert),
).toEqual(["other_db.raw.clicks", "other_db.raw.clicks_v", '"Mixed Db".public."Clients"']);
// One typed letter is too little to search every database with.
expect(
sqlCandidates({
model: sf,
analysis: at("select * from c|", "snowflake"),
driver: "snowflake",
catalog: { ...catalog, search: () => [{ database: "OTHER_DB", schema: "RAW", name: "CLICKS", view: false }] },
}).some((c) => c.label === "CLICKS"),
).toBe(false);
// A schema of the session's database that is also a database name lists both.
const both = sqlCandidates({
model: sf,
analysis: at("select * from RAW.|", "snowflake"),
driver: "snowflake",
catalog: { ...catalog, databases: ["RAW"], schemas: () => ["LANDING"] },
});
expect(both.map((c) => c.insert)).toEqual(["EVENTS", "LANDING."]);
// Unknown databases and schemas that are not loaded offer nothing rather than something wrong.
expect(run("select * from NO_SUCH_DB.|")).toEqual([]);
expect(run("select * from OTHER_DB.STAGING.|")).toEqual([]);
expect(run("select * from A.B.C.|")).toEqual([]);
});
it("completes Snowflake names by their last two parts and stays out of other databases", () => {
expect(labels(complete("select * from RAW.|", "snowflake", sf))).toEqual(["EVENTS"]);
expect(complete("select * from OTHER_DB.|", "snowflake", sf)).toEqual([]);
expect(complete("select * from OTHER_DB.RAW.|", "snowflake", sf)).toEqual([]);
expect(complete("select * from PUBLIC.USERS.|", "snowflake", sf)).toEqual([]);
expect(labels(complete("select DB.PUBLIC.USERS.| from DB.PUBLIC.USERS", "snowflake", sf))).toEqual([
"ID",
"SRC",
"mixedCase",
]);
expect(labels(complete("select u.| from DB.PUBLIC.USERS u", "snowflake", sf))).toEqual(["ID", "SRC", "mixedCase"]);
expect(at("select * from DB.PUBLIC.USERS u where |", "snowflake").refs[0]).toMatchObject({
database: "DB",
schema: "PUBLIC",
name: "USERS",
alias: "u",
});
// The keys of a VARIANT path and its cast are not names of the model.
expect(complete("select SRC:| from USERS", "snowflake", sf)).toEqual([]);
expect(complete("select SRC:a.| from USERS", "snowflake", sf)).toEqual([]);
expect(complete("select SRC:a::| from USERS", "snowflake", sf)).toEqual([]);
// QUALIFY is a clause, not the alias of the table before it.
const q = at("select * from USERS qualify |", "snowflake");
expect(q.refs[0]).toMatchObject({ name: "USERS", alias: null });
expect(q.context).toEqual({ kind: "column", clause: "having" });
expect(at("select * from USERS sample (10) where |", "snowflake").refs[0]).toMatchObject({ alias: null });
});
it("offers tables after FROM, with schema and data source", () => {
const c = complete("select * from |");
expect(labels(c, "table")).toEqual(expect.arrayContaining(["users", "orders", "order_items", "products"]));
@@ -441,6 +671,33 @@ describe("resolve", () => {
expect(problems("select rowid, * from users;")).toEqual([]);
});
it("judges Snowflake names without flagging variant paths, stages or other databases", () => {
const snow = (sql: string) =>
new SqlResolver(sql, "snowflake", sf).problems().map((p) => `${sql.slice(p.from, p.to)}: ${p.message}`);
for (const sql of [
"select src:customer.name::string, src['a'].b, u.src:x[0].y, $1 from users u where id = :id;",
"select id from users qualify row_number() over (order by id) = 1;",
"select f.value:x, f.index from users, lateral flatten(input => src, outer => true) f;",
"select $1, metadata$filename from @my_stage/path (file_format => 'ff', pattern => '.*csv') t;",
"select * exclude id from users sample (10); select dateadd(day, 1, id), date_trunc(quarter, id) from users;",
"select * from other_db.public.users; select * from other_db.sch.missing;",
"select o.nope from other_db.public.users o; select other_db.public.users.nope from other_db.public.users;",
"insert into other_db.public.users (nope) values (1);",
"select id from users where src:a ilike 'x%' and $$ nope $$ = 'a\\'nope' // nope\n;",
'select "mixedCase", ID from PUBLIC.USERS;',
])
expect(snow(sql), sql).toEqual([]);
expect(snow("select nope from users;")).toEqual(["nope: Unable to resolve column 'nope'"]);
expect(snow("select u.nope from public.users u;")).toEqual(["nope: Unable to resolve column 'nope'"]);
expect(snow("select * from public.missing;")).toEqual(["missing: Unable to resolve table 'missing'"]);
expect(snow("select * from missing;")).toEqual(["missing: Unable to resolve table 'missing'"]);
const sql = "select id from db.public.users";
expect(new SqlResolver(sql, "snowflake", sf).resolveAt(sql.length - 1)?.symbol).toMatchObject({
kind: "table",
table: { schema: "PUBLIC", name: "USERS" },
});
});
it("resolves symbols for navigation and documentation", () => {
const sql = "select u.email from users u join orders o on o.user_id = u.id;";
const r = new SqlResolver(sql, "sqlite", model);
@@ -485,4 +742,18 @@ describe("params", () => {
);
expect(bindParams("select ?", findParams("select ?", "sqlite"), {})).toBe("select NULL");
});
it("leaves Snowflake variant paths, casts, stages and session variables alone", () => {
const names = (sql: string) => findParams(sql, "snowflake").map((p) => p.name);
const sql = "SELECT src:customer.name::string, $1 FROM @my_stage/path (FILE_FORMAT => 'ff') t WHERE x = :id";
expect(names(sql)).toEqual([":id"]);
expect(bindParams(sql, findParams(sql, "snowflake"), { ":id": "7" })).toBe(sql.replace(":id", "7"));
expect(
names(
"select src:a.b, \"V\":k, f(x):y, a[0]:z, {'k':v}, $1, $var, t.$2 from @~/dir, @%tbl, @db.sch.stg t " +
"where a = $$ :no ? $$ and b = 'it\\'s :no' // :no ?\n",
),
).toEqual([]);
expect(names("select * from t where a = ? and b=:name and c in (:x, ?)")).toEqual(["?1", ":name", ":x", "?2"]);
});
});