Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(query-ast): resolve CTE names like ClickHouse in tenancy, soft-delete, dedup and bind typing (#18865)

Niklas Semmler88d0c7856a73
diff --git a/packages/shared/src/server/query-ast/binds.test.ts b/packages/shared/src/server/query-ast/binds.test.ts
index 4e62bb23ed..9f83bba260 100644
--- a/packages/shared/src/server/query-ast/binds.test.ts
+++ b/packages/shared/src/server/query-ast/binds.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest";
import { compileClickhouseQuery } from "./compile";
import { getClickhouseKysely } from "./dialect";
+import { UnscopedRelationError } from "./errors";
import { tupleIn, useFinal } from "./extensions";
const projectId = "proj-1";
@@ -279,6 +280,122 @@ describe("typed params from the column registry", () => {
expect(sql).toMatch(/(start_time|ts) >= \{p\d+:DateTime64\(6\)\}/);
});
+ // `observations.start_time` is DateTime64(3); `events_core.start_time` is
+ // DateTime64(6). Which one a bind gets shows which relation a name resolved to.
+ describe("CTE name resolution", () => {
+ const db = getClickhouseKysely();
+ const eventsAsObservations = db.with("observations", (qb) =>
+ qb.selectFrom("events_core").select("start_time"),
+ );
+
+ it("resolves a later sibling CTE name to the CTE", () => {
+ const { sql } = compile(
+ db
+ .with("early", (qb) =>
+ qb.selectFrom("observations").select("start_time"),
+ )
+ .with("observations", (qb) =>
+ qb.selectFrom("events_core").select("start_time"),
+ )
+ .selectFrom("early")
+ .select("start_time")
+ .where("start_time", ">=", START),
+ );
+ expect(sql).toMatch(/start_time >= \{p\d+:DateTime64\(6\)\}$/);
+ });
+
+ it("resolves a CTE body's read of its own name to the table", () => {
+ const { sql } = compile(
+ db
+ .with("observations", (qb) =>
+ qb
+ .selectFrom("events_core as e")
+ .innerJoin("observations as o", "o.trace_id", "e.trace_id")
+ .select("e.start_time")
+ .where("o.start_time", ">=", START),
+ )
+ .selectFrom("observations")
+ .select("start_time"),
+ );
+ expect(sql).toMatch(/o\.start_time >= \{p\d+:DateTime64\(3\)\}/);
+ });
+
+ it("types a CTE that reads its own name when it is first read in a subquery", () => {
+ const { sql } = compile(
+ db
+ .with("observations", (qb) =>
+ qb.selectFrom("observations").select(["trace_id", "start_time"]),
+ )
+ .selectFrom("traces")
+ .select("id")
+ .where(
+ "id",
+ "in",
+ db
+ .selectFrom("observations")
+ .select("trace_id")
+ .where("start_time", ">=", START),
+ ),
+ );
+ expect(sql).toMatch(/start_time >= \{p\d+:DateTime64\(3\)\}/);
+ });
+
+ it("resolves a nested CTE body's own name to an outer CTE of that name", () => {
+ const { sql } = compile(
+ eventsAsObservations
+ .selectFrom(
+ db
+ .with("observations", (qb) =>
+ qb.selectFrom("observations").select("start_time"),
+ )
+ .selectFrom("observations")
+ .select("start_time")
+ .as("sub"),
+ )
+ .select("sub.start_time")
+ .where("sub.start_time", ">=", START),
+ );
+ expect(sql).toMatch(/sub\.start_time >= \{p\d+:DateTime64\(6\)\}$/);
+ });
+
+ it("resolves a schema-qualified table to the table, not a CTE of its name", () => {
+ const { sql } = compile(
+ eventsAsObservations
+ .selectFrom("observations")
+ .select("start_time")
+ .where(
+ "start_time",
+ "in",
+ db
+ .withSchema("default")
+ .selectFrom("observations")
+ .select("start_time")
+ .where("start_time", ">=", START),
+ ),
+ );
+ expect(sql).toMatch(
+ /from default\.observations where project_id = \{p\d+:String\} and start_time >= \{p\d+:DateTime64\(3\)\}/,
+ );
+ });
+
+ it("rejects CTEs that read each other", () => {
+ expect(() =>
+ compile(
+ db
+ .with("observations", (qb) =>
+ qb.selectFrom("traces").select("timestamp as start_time"),
+ )
+ .with("traces", (qb) =>
+ qb.selectFrom("observations").select("start_time as timestamp"),
+ )
+ .selectFrom("traces")
+ .select("timestamp")
+ .where("timestamp", ">=", START),
+ ),
+ ).toThrow(UnscopedRelationError);
+ });
+ });
+
// When the column's table can't be resolved, the bind type falls back to the
// JS value: a Date binds as DateTime64(3), even against events.
it.each([
diff --git a/packages/shared/src/server/query-ast/compiler.ts b/packages/shared/src/server/query-ast/compiler.ts
index 8e5428b5ec..f9a40c7397 100644
--- a/packages/shared/src/server/query-ast/compiler.ts
+++ b/packages/shared/src/server/query-ast/compiler.ts
@@ -16,6 +16,7 @@ import {
SetOperationNode,
TableNode,
ValueNode,
+ type CommonTableExpressionNode,
type OperationNode,
type PrimitiveValueListNode,
type RootOperationNode,
@@ -34,6 +35,7 @@ import {
import { QueryCompileError } from "./errors";
import { COLUMN_BIND_TYPES, TABLE_BIND_TYPES } from "./schema";
import { assertTenancyStamped } from "./tenancy";
+import { cteName } from "./transformer";
const ARRAY_JOIN_SQL: Record<ArrayJoinNode["variant"], string> = {
default: "array join",
@@ -97,16 +99,20 @@ function inferClickHouseType(value: unknown): string {
}
/**
- * Column bind types of the relation `name` resolves to: the innermost CTE of
- * that name, else the registry table, else undefined.
+ * Column bind types of the relation `table` resolves to: the innermost CTE of
+ * that name, else the registry table, else undefined. A schema-qualified table
+ * (`default.traces`) is never a CTE.
*/
function relationBindTypes(
- name: string,
- scopes: readonly { ctes: Map<string, ColumnBindTypes> }[],
+ table: TableNode,
+ scopes: readonly SelectScope[],
): ColumnBindTypes | undefined {
- for (const scope of [...scopes].reverse()) {
- const cte = scope.ctes.get(name);
- if (cte) return cte;
+ const name = table.table.identifier.name;
+ if (!table.table.schema) {
+ for (const scope of [...scopes].reverse()) {
+ const cte = scope.cte(name);
+ if (cte) return cte;
+ }
}
return TABLE_BIND_TYPES[name];
}
@@ -164,8 +170,8 @@ function columnReference(
type ColumnBindTypes = Readonly<Record<string, string>>;
type SelectScope = {
- /** CTEs declared by this SELECT's WITH β†’ bind types of their output columns. */
- ctes: Map<string, ColumnBindTypes>;
+ /** Bind types of the output columns of the CTE `name` this SELECT's WITH declares, or undefined if it declares none. */
+ cte: (name: string) => ColumnBindTypes | undefined;
/** FROM/JOIN names and aliases β†’ the relation's column bind types, or undefined when unknown. */
relations: Map<string, ColumnBindTypes | undefined>;
};
@@ -347,15 +353,11 @@ export class ClickHouseQueryCompiler extends DefaultQueryCompiler {
node: SelectQueryNode,
enclosing: readonly SelectScope[],
): SelectScope {
- const scope: SelectScope = { ctes: new Map(), relations: new Map() };
+ const scope: SelectScope = {
+ cte: this.cteLookup(node, enclosing),
+ relations: new Map(),
+ };
const scopes = [...enclosing, scope];
- // In declaration order, so a CTE can read an earlier one.
- for (const cte of node.with?.expressions ?? []) {
- scope.ctes.set(
- cte.name.table.table.identifier.name,
- this.outputBindTypes(cte.expression, scopes) ?? COLUMN_BIND_TYPES,
- );
- }
const relations = [
...(node.from?.froms ?? []),
...(node.joins ?? []).map((join) => join.table),
@@ -368,13 +370,17 @@ export class ClickHouseQueryCompiler extends DefaultQueryCompiler {
: wrapped;
const aliased = AliasNode.is(relation) ? relation : undefined;
const inner = aliased ? aliased.node : relation;
- const table = TableNode.is(inner)
- ? inner.table.identifier.name
- : undefined;
- const columns = table
- ? relationBindTypes(table, scopes)
+ const columns = TableNode.is(inner)
+ ? relationBindTypes(inner, scopes)
: this.outputBindTypes(inner, scopes);
- if (table) scope.relations.set(table, columns);
+ // A table, aliased or not, is reachable by its name:
+ // `FROM traces` and `FROM traces AS t` both register `traces`.
+ if (TableNode.is(inner)) {
+ scope.relations.set(inner.table.identifier.name, columns);
+ }
+ // An aliased relation is also reachable by its alias: `FROM traces AS t`
+ // registers `t`, and `FROM (SELECT …) AS sub`, which has no name of
+ // its own, registers only `sub`.
if (aliased && IdentifierNode.is(aliased.alias)) {
scope.relations.set(aliased.alias.name, columns);
}
@@ -382,6 +388,65 @@ export class ClickHouseQueryCompiler extends DefaultQueryCompiler {
return scope;
}
+ /**
+ * Lookup of the CTEs `node`'s WITH declares. A body is typed on its first
+ * read, against `enclosing` plus {@link withoutCte}, so it can read an
+ * earlier or a later sibling as ClickHouse does.
+ *
+ * Typing a body recurses into the siblings it reads, and each body is typed
+ * without its own name, so the recursion only follows sibling reads. Those
+ * never form a cycle: the transformer passes reject
+ * `WITH a AS (… FROM b), b AS (… FROM a)` before the compiler runs.
+ */
+ private cteLookup(
+ node: SelectQueryNode,
+ enclosing: readonly SelectScope[],
+ ): SelectScope["cte"] {
+ const bodies = new Map(
+ (node.with?.expressions ?? []).map((cte) => [cteName(cte), cte]),
+ );
+ // `enclosing` may be the compiler's live scope stack; a body typed on a
+ // later read must not see the scopes pushed since this SELECT's own.
+ const outer = [...enclosing];
+ const typed = new Map<string, ColumnBindTypes>();
+ const lookup = (name: string): ColumnBindTypes | undefined => {
+ const cte = bodies.get(name);
+ if (!cte) return undefined;
+ const known = typed.get(name);
+ if (known) return known;
+ const bodyScope = withoutCte({ cte: lookup, relations: new Map() }, name);
+ // A body that is not a select (raw SQL) has no columns the compiler
+ // can type, so it gets the name-only types, like an opaque relation.
+ const columns =
+ this.outputBindTypes(cte.expression, [...outer, bodyScope]) ??
+ COLUMN_BIND_TYPES;
+ typed.set(name, columns);
+ return columns;
+ };
+ return lookup;
+ }
+
+ /**
+ * The declaring SELECT's scope declares this CTE, so a body reading its own
+ * name would otherwise bind against the CTE instead of the table.
+ */
+ protected override visitCommonTableExpression(
+ node: CommonTableExpressionNode,
+ ): void {
+ const declaring = this.selectScopes.pop();
+ if (!declaring) {
+ super.visitCommonTableExpression(node);
+ return;
+ }
+ this.selectScopes.push(withoutCte(declaring, cteName(node)));
+ try {
+ super.visitCommonTableExpression(node);
+ } finally {
+ this.selectScopes.pop();
+ this.selectScopes.push(declaring);
+ }
+ }
+
/**
* Bind types of the columns a CTE body or FROM subquery outputs. A selected
* column keeps the type it has in its source relation, under its alias if it
@@ -658,3 +723,16 @@ export class ClickHouseQueryCompiler extends DefaultQueryCompiler {
return `{${name}:${inferred}}`;
}
}
+
+/**
+ * The scope a body of CTE `name` sees in place of its declaring SELECT: every
+ * sibling CTE but itself, as ClickHouse resolves `WITH traces AS (SELECT …
+ * FROM traces)` to the table, or to an enclosing CTE of that name. The
+ * declaring SELECT's FROM relations are not visible to the body.
+ */
+function withoutCte(scope: SelectScope, name: string): SelectScope {
+ return {
+ cte: (other) => (other === name ? undefined : scope.cte(other)),
+ relations: new Map(),
+ };
+}
diff --git a/packages/shared/src/server/query-ast/dedup.test.ts b/packages/shared/src/server/query-ast/dedup.test.ts
index 4ecd6aa343..dceaa79e5f 100644
--- a/packages/shared/src/server/query-ast/dedup.test.ts
+++ b/packages/shared/src/server/query-ast/dedup.test.ts
@@ -66,6 +66,38 @@ describe("per-table dedup lowering", () => {
expect(sql.toLowerCase().split("limit 1 by").length - 1).toBe(1);
});
+ it("lowers a physical read but not a nested read of an outer CTE of that name", () => {
+ DEDUP_SPECS.traces = {
+ strategy: "limitBy",
+ key: ["id"],
+ version: "event_ts",
+ };
+ try {
+ const db = getClickhouseKysely();
+ const { sql } = compile(
+ db
+ .with("traces", (qb) =>
+ qb.selectFrom("scores").select("trace_id as id"),
+ )
+ .selectFrom("scores as s")
+ .select("s.id")
+ .where("s.trace_id", "in", (eb) =>
+ eb.selectFrom("traces").select("id"),
+ )
+ .where(
+ "s.trace_id",
+ "in",
+ db.withSchema("default").selectFrom("traces").select("id"),
+ ),
+ );
+ expect(sql).toBe(
+ "with traces as (select trace_id as id from scores where project_id = {p1:String}) select s.id from scores as s where s.project_id = {p1:String} and s.trace_id in (select id from traces) and s.trace_id in (select id from default.traces where project_id = {p1:String} order by event_ts desc limit 1 by id)",
+ );
+ } finally {
+ delete DEDUP_SPECS.traces;
+ }
+ });
+
it("does not rewrite undeclared tables", () => {
const { sql } = compile(
getClickhouseKysely().selectFrom("traces").select("id"),
diff --git a/packages/shared/src/server/query-ast/dedup.ts b/packages/shared/src/server/query-ast/dedup.ts
index 9a86e6195c..6580d5e45f 100644
--- a/packages/shared/src/server/query-ast/dedup.ts
+++ b/packages/shared/src/server/query-ast/dedup.ts
@@ -37,7 +37,6 @@ import {
type OperationNode,
type PluginTransformQueryArgs,
type PluginTransformResultArgs,
- type QueryId,
type RootOperationNode,
} from "kysely";
@@ -50,10 +49,11 @@ import {
} from "./nodes";
import { DEDUP_SPECS, type DedupSpec } from "./schema";
import { stampCompiledTree } from "./tenancy";
-import { ClickHouseOperationNodeTransformer } from "./transformer";
+import { CteScopedTransformer } from "./transformer";
type PhysicalFrom = {
tableName: string;
+ table: TableNode;
alias?: string;
fromItem: OperationNode;
};
@@ -75,32 +75,19 @@ export class DedupLoweringPlugin implements KyselyPlugin {
}
}
-class DedupLoweringTransformer extends ClickHouseOperationNodeTransformer {
- protected override transformSelectQuery(
- node: SelectQueryNode,
- queryId?: QueryId,
- ): SelectQueryNode {
- const withChildren = super.transformSelectQuery(
- node,
- queryId,
- ) as ClickHouseSelectQueryNode;
- return lowerSelect(withChildren, collectCteNames(withChildren));
+class DedupLoweringTransformer extends CteScopedTransformer {
+ protected rewriteSelect(
+ node: ClickHouseSelectQueryNode,
+ ): ClickHouseSelectQueryNode {
+ return lowerSelect(node, (table) => this.isCte(table));
}
}
-function collectCteNames(node: SelectQueryNode): Set<string> {
- const names = new Set<string>();
- for (const expr of node.with?.expressions ?? []) {
- names.add(expr.name.table.table.identifier.name);
- }
- return names;
-}
-
function lowerSelect(
node: ClickHouseSelectQueryNode,
- cteNames: Set<string>,
+ isCte: (table: TableNode) => boolean,
): ClickHouseSelectQueryNode {
- const from = singlePhysicalFrom(node, cteNames);
+ const from = singlePhysicalFrom(node, isCte);
if (!from) return node;
const spec = DEDUP_SPECS[from.tableName];
@@ -126,14 +113,14 @@ function lowerSelect(
function singlePhysicalFrom(
node: SelectQueryNode,
- cteNames: Set<string>,
+ isCte: (table: TableNode) => boolean,
): PhysicalFrom | undefined {
if (node.joins?.length) return undefined;
const froms = node.from?.froms ?? [];
if (froms.length !== 1) return undefined;
const described = describeFrom(froms[0]);
if (!described) return undefined;
- if (cteNames.has(described.tableName)) return undefined;
+ if (isCte(described.table)) return undefined;
return described;
}
@@ -150,6 +137,7 @@ function describeFrom(node: OperationNode): PhysicalFrom | undefined {
if (TableNode.is(node)) {
return {
tableName: node.table.identifier.name,
+ table: node,
fromItem: node,
};
}
diff --git a/packages/shared/src/server/query-ast/nodes.test.ts b/packages/shared/src/server/query-ast/nodes.test.ts
index 8098e49796..4f16dffff0 100644
--- a/packages/shared/src/server/query-ast/nodes.test.ts
+++ b/packages/shared/src/server/query-ast/nodes.test.ts
@@ -263,6 +263,481 @@ describe("tenancy injection", () => {
const matches = compiled.match(/project_id/gi) ?? [];
expect(matches.length).toBeGreaterThanOrEqual(2);
});
+
+ describe("CTE named like a tenanted table", () => {
+ const db = getClickhouseKysely();
+ const tracesCte = db.with("traces", (qb) =>
+ qb.selectFrom("scores").select("trace_id as id"),
+ );
+ const compile = (
+ query: Parameters<typeof compileClickhouseQuery>[0],
+ ): string => compileClickhouseQuery(query, projectId).sql;
+
+ it("leaves a scalar subquery's read of an outer CTE unscoped", () => {
+ expect(
+ compile(
+ tracesCte
+ .selectFrom("scores as s")
+ .select((eb) => [
+ eb.selectFrom("traces").select("id").limit(1).as("first_id"),
+ ]),
+ ),
+ ).toBe(
+ "with traces as (select trace_id as id from scores where project_id = {p1:String}) select (select id from traces limit {p2:Int64}) as first_id from scores as s where s.project_id = {p1:String}",
+ );
+ });
+
+ it("leaves IN-subquery, FROM-subquery and UNION reads of an outer CTE unscoped", () => {
+ expect(
+ compile(
+ tracesCte
+ .selectFrom((eb) => eb.selectFrom("traces").select("id").as("sub"))
+ .select("sub.id")
+ .where("sub.id", "in", (eb) => eb.selectFrom("traces").select("id"))
+ .unionAll(db.selectFrom("traces").select("id")),
+ ),
+ ).toBe(
+ "with traces as (select trace_id as id from scores where project_id = {p1:String}) select sub.id from (select id from traces) as sub where sub.id in (select id from traces) union all select id from traces",
+ );
+ });
+
+ it("leaves a nested CTE body's read of an outer CTE unscoped", () => {
+ expect(
+ compile(
+ tracesCte
+ .selectFrom(
+ db
+ .with("inner", (qb) => qb.selectFrom("traces").select("id"))
+ .selectFrom("inner")
+ .select("id")
+ .as("sub"),
+ )
+ .select("sub.id"),
+ ),
+ ).toBe(
+ "with traces as (select trace_id as id from scores where project_id = {p1:String}) select sub.id from (with inner as (select id from traces) select id from inner) as sub",
+ );
+ });
+
+ it("scopes a CTE body's read of its own name, which is the table", () => {
+ expect(
+ compile(
+ db
+ .with("traces", (qb) =>
+ qb
+ .selectFrom("traces")
+ .select("id")
+ .where("id", "in", (eb) =>
+ eb.selectFrom("traces").select("id"),
+ ),
+ )
+ .selectFrom("traces")
+ .select("id"),
+ ),
+ ).toBe(
+ "with traces as (select id from traces where project_id = {p1:String} and id in (select id from traces where project_id = {p1:String})) select id from traces",
+ );
+ });
+
+ it("resolves a nested CTE body's own name to an outer CTE of that name", () => {
+ expect(
+ compile(
+ tracesCte
+ .selectFrom(
+ db
+ .with("traces", (qb) => qb.selectFrom("traces").select("id"))
+ .selectFrom("traces")
+ .select("id")
+ .as("sub"),
+ )
+ .select("sub.id"),
+ ),
+ ).toBe(
+ "with traces as (select trace_id as id from scores where project_id = {p1:String}) select sub.id from (with traces as (select id from traces) select id from traces) as sub",
+ );
+ });
+
+ it("resolves earlier and later sibling CTE names to the CTE", () => {
+ expect(
+ compile(
+ db
+ .with("before", (qb) => qb.selectFrom("traces").select("id"))
+ .with("traces", (qb) =>
+ qb.selectFrom("scores").select("trace_id as id"),
+ )
+ .with("after", (qb) => qb.selectFrom("traces").select("id"))
+ .selectFrom("before")
+ .innerJoin("after", (join) =>
+ join.onRef("before.id", "=", "after.id"),
+ )
+ .select("before.id"),
+ ),
+ ).toBe(
+ "with before as (select id from traces), traces as (select trace_id as id from scores where project_id = {p1:String}), after as (select id from traces) select before.id from before inner join after on before.id = after.id",
+ );
+ });
+
+ // Each case is a cycle between sibling CTEs. Reading `traces` reads
+ // `observations`, which reads `traces` while it is still being resolved,
+ // so ClickHouse reads the physical `traces` table there. The pass treats
+ // that read as the CTE and would leave it unscoped, so the cycle is
+ // rejected whether or not the main select reads it.
+ it.each([
+ [
+ // traces β†’ observations β†’ traces.
+ "directly",
+ () =>
+ db
+ .with("traces", (qb) =>
+ qb.selectFrom("observations").select("trace_id as id"),
+ )
+ .with("observations", (qb) =>
+ qb.selectFrom("traces").select("id as trace_id"),
+ )
+ .selectFrom("traces")
+ .select("id"),
+ ],
+ [
+ // traces β†’ observations (in an IN subquery of its body) β†’ traces.
+ "through a nested subquery",
+ () =>
+ db
+ .with("traces", (qb) =>
+ qb
+ .selectFrom("scores")
+ .select("trace_id as id")
+ .where("trace_id", "in", (eb) =>
+ eb.selectFrom("observations").select("trace_id"),
+ ),
+ )
+ .with("observations", (qb) =>
+ qb.selectFrom("traces").select("id as trace_id"),
+ )
+ .selectFrom("scores")
+ .select("id"),
+ ],
+ [
+ // traces β†’ observations β†’ scores β†’ traces.
+ "through a third CTE",
+ () =>
+ db
+ .with("traces", (qb) =>
+ qb.selectFrom("observations").select("trace_id as id"),
+ )
+ .with("observations", (qb) =>
+ qb.selectFrom("scores").select("trace_id"),
+ )
+ .with("scores", (qb) =>
+ qb.selectFrom("traces").select("id as trace_id"),
+ )
+ .selectFrom("traces")
+ .select("id"),
+ ],
+ [
+ // traces β†’ observations (read as `o`) β†’ traces.
+ "through an aliased read",
+ () =>
+ db
+ .with("traces", (qb) =>
+ qb.selectFrom("observations as o").select("o.trace_id as id"),
+ )
+ .with("observations", (qb) =>
+ qb.selectFrom("traces").select("id as trace_id"),
+ )
+ .selectFrom("traces")
+ .select("id"),
+ ],
+ [
+ // traces β†’ scores (read with FINAL) β†’ traces.
+ "through a FINAL read",
+ () =>
+ db
+ .with("traces", (qb) =>
+ qb
+ .selectFrom("scores")
+ .select("trace_id as id")
+ .$call(useFinal(["scores"])),
+ )
+ .with("scores", (qb) =>
+ qb.selectFrom("traces").select("id as trace_id"),
+ )
+ .selectFrom("traces")
+ .select("id"),
+ ],
+ [
+ // traces β†’ observations (the joined side) β†’ traces.
+ "through a JOIN",
+ () =>
+ db
+ .with("traces", (qb) =>
+ qb
+ .selectFrom("scores as s")
+ .innerJoin("observations as o", "o.trace_id", "s.trace_id")
+ .select("s.trace_id as id"),
+ )
+ .with("observations", (qb) =>
+ qb.selectFrom("traces").select("id as trace_id"),
+ )
+ .selectFrom("traces")
+ .select("id"),
+ ],
+ ])("rejects sibling CTEs that read each other %s", (_, build) => {
+ expect(() => compile(build())).toThrow(UnscopedRelationError);
+ });
+
+ it("scopes a recursive CTE body's read of its own name as the table", () => {
+ expect(
+ compile(
+ db
+ .withRecursive("traces(id)", (qb) =>
+ qb.selectFrom("traces").select("id"),
+ )
+ .selectFrom("traces")
+ .select("id"),
+ ),
+ ).toBe(
+ "with recursive traces(id) as (select id from traces where project_id = {p1:String}) select id from traces",
+ );
+ });
+
+ it("rejects a CTE body written as raw SQL that reads a relation", () => {
+ expect(() =>
+ compile(
+ db
+ .with("a", () => sql<{ id: string }>`select id from traces`)
+ .selectFrom("a")
+ .select("id"),
+ ),
+ ).toThrow(UnscopedRelationError);
+ });
+
+ it("rejects a nested WITH that redirects an enclosing CTE body's read", () => {
+ // Read inside `sub`, `traces` reads the inner `observations`, which reads
+ // `a`, which reads `traces` while it is still being resolved: the table.
+ expect(() =>
+ compile(
+ db
+ .with("traces", (qb) =>
+ qb.selectFrom("observations").select("trace_id as id"),
+ )
+ .with("observations", (qb) =>
+ qb.selectFrom("scores").select("trace_id"),
+ )
+ .with("a", (qb) => qb.selectFrom("traces").select("id"))
+ .selectFrom(
+ db
+ .withTables<{ a: { id: string } }>()
+ .with("observations", (qb) =>
+ qb.selectFrom("a").select("id as trace_id"),
+ )
+ .selectFrom("traces")
+ .select("id")
+ .as("sub"),
+ )
+ .select("sub.id"),
+ ),
+ ).toThrow(UnscopedRelationError);
+ });
+
+ it("rejects a nested WITH that redirects a CTE body's own-name read", () => {
+ // The `traces` CTE inside `a` reads its own name, which escapes to the
+ // `traces` CTE in scope where `a` is read.
+ expect(() =>
+ compile(
+ db
+ .with("a", (qb) =>
+ qb
+ .selectFrom(
+ db
+ .with("traces", (inner) =>
+ inner.selectFrom("traces").select("id"),
+ )
+ .selectFrom("traces")
+ .select("id")
+ .as("sub"),
+ )
+ .select("sub.id"),
+ )
+ .selectFrom(
+ db
+ .withTables<{ a: { id: string } }>()
+ .with("traces", (qb) =>
+ qb.selectFrom("scores").select("trace_id as id"),
+ )
+ .selectFrom("a")
+ .select("id")
+ .as("u"),
+ )
+ .select("u.id"),
+ ),
+ ).toThrow(UnscopedRelationError);
+ });
+
+ it("accepts a CTE body that reads its own nested CTE", () => {
+ expect(
+ compile(
+ db
+ .with("a", (qb) =>
+ qb
+ .selectFrom(
+ db
+ .with("x", (inner) =>
+ inner.selectFrom("scores").select("trace_id"),
+ )
+ .selectFrom("x")
+ .select("trace_id")
+ .as("sub"),
+ )
+ .select("sub.trace_id"),
+ )
+ .selectFrom("a")
+ .select("trace_id"),
+ ),
+ ).toBe(
+ "with a as (select sub.trace_id from (with x as (select trace_id from scores where project_id = {p1:String}) select trace_id from x) as sub) select trace_id from a",
+ );
+ });
+
+ it("accepts a CTE body that reads its own nested CTE from a deeper subquery", () => {
+ expect(
+ compile(
+ db
+ .with("a", (qb) =>
+ qb
+ .selectFrom(
+ db
+ .with("x", (inner) =>
+ inner.selectFrom("scores").select("trace_id"),
+ )
+ .selectFrom((eb) =>
+ eb.selectFrom("x").select("trace_id").as("s2"),
+ )
+ .select("s2.trace_id")
+ .as("sub"),
+ )
+ .select("sub.trace_id"),
+ )
+ .selectFrom("a")
+ .select("trace_id"),
+ ),
+ ).toBe(
+ "with a as (select sub.trace_id from (with x as (select trace_id from scores where project_id = {p1:String}) select s2.trace_id from (select trace_id from x) as s2) as sub) select trace_id from a",
+ );
+ });
+
+ it("accepts a nested CTE body that reads an enclosing nested CTE", () => {
+ expect(
+ compile(
+ db
+ .with("a", (qb) =>
+ qb
+ .selectFrom(
+ db
+ .with("x", (inner) =>
+ inner.selectFrom("scores").select("trace_id"),
+ )
+ .selectFrom(
+ db
+ .withTables<{ x: { trace_id: string } }>()
+ .with("y", (inner) =>
+ inner.selectFrom("x").select("trace_id"),
+ )
+ .selectFrom("y")
+ .select("trace_id")
+ .as("s2"),
+ )
+ .select("s2.trace_id")
+ .as("sub"),
+ )
+ .select("sub.trace_id"),
+ )
+ .selectFrom("a")
+ .select("trace_id"),
+ ),
+ ).toBe(
+ "with a as (select sub.trace_id from (with x as (select trace_id from scores where project_id = {p1:String}) select s2.trace_id from (with y as (select trace_id from x) select trace_id from y) as s2) as sub) select trace_id from a",
+ );
+ });
+
+ it("does not count a schema-qualified read as a sibling read", () => {
+ expect(
+ compile(
+ db
+ .with("traces", (qb) =>
+ qb
+ .withSchema("default")
+ .selectFrom("observations")
+ .select("trace_id as id"),
+ )
+ .with("observations", (qb) =>
+ qb.selectFrom("traces").select("id as trace_id"),
+ )
+ .selectFrom("observations")
+ .select("trace_id"),
+ ),
+ ).toBe(
+ "with traces as (select trace_id as id from default.observations where project_id = {p1:String}), observations as (select id as trace_id from traces) select trace_id from observations",
+ );
+ });
+
+ it("does not count a column qualifier named like a sibling as a read", () => {
+ expect(
+ compile(
+ db
+ .with("a", (qb) =>
+ qb.selectFrom("scores as traces").select("traces.id"),
+ )
+ .with("traces", (qb) => qb.selectFrom("a").select("id"))
+ .selectFrom("traces")
+ .select("id"),
+ ),
+ ).toBe(
+ "with a as (select traces.id from scores as traces where traces.project_id = {p1:String}), traces as (select id from a) select id from traces",
+ );
+ });
+
+ it("scopes a schema-qualified table named like a CTE in scope", () => {
+ expect(
+ compile(
+ tracesCte
+ .selectFrom("traces")
+ .select("id")
+ .where(
+ "id",
+ "in",
+ db.withSchema("default").selectFrom("traces").select("id"),
+ ),
+ ),
+ ).toBe(
+ "with traces as (select trace_id as id from scores where project_id = {p1:String}) select id from traces where id in (select id from default.traces where project_id = {p1:String})",
+ );
+ });
+
+ it("scopes the table again once a subquery leaves the CTE's select", () => {
+ expect(
+ compile(
+ db
+ .selectFrom("scores as s")
+ .select("s.id")
+ .where(
+ "s.trace_id",
+ "in",
+ db
+ .with("traces", (qb) =>
+ qb.selectFrom("scores").select("trace_id as id"),
+ )
+ .selectFrom("traces")
+ .select("id"),
+ )
+ .where("s.trace_id", "in", (eb) =>
+ eb.selectFrom("traces").select("id"),
+ ),
+ ),
+ ).toBe(
+ "select s.id from scores as s where s.project_id = {p1:String} and s.trace_id in (with traces as (select trace_id as id from scores where project_id = {p1:String}) select id from traces) and s.trace_id in (select id from traces where project_id = {p1:String})",
+ );
+ });
+ });
});
describe("ARRAY JOIN and LIMIT BY nodes", () => {
diff --git a/packages/shared/src/server/query-ast/softDelete.test.ts b/packages/shared/src/server/query-ast/softDelete.test.ts
index 77b9eb05b8..4446cca18f 100644
--- a/packages/shared/src/server/query-ast/softDelete.test.ts
+++ b/packages/shared/src/server/query-ast/softDelete.test.ts
@@ -132,6 +132,30 @@ describe("soft-delete filtering", () => {
).not.toContain("is_deleted");
});
+ it("filters a schema-qualified table named like a CTE in scope", () => {
+ const db = getClickhouseKysely();
+ expect(
+ compile(
+ db
+ .with("events_core", (qb) =>
+ qb.selectFrom("scores").select("trace_id"),
+ )
+ .selectFrom("events_core")
+ .select("trace_id")
+ .where(
+ "trace_id",
+ "in",
+ db
+ .withSchema("default")
+ .selectFrom("events_core")
+ .select("trace_id"),
+ ),
+ ),
+ ).toContain(
+ "(select trace_id from default.events_core where project_id = {p1:String} and events_core.is_deleted = {p2:UInt8})",
+ );
+ });
+
it("resolves a CTE body's own name to the table, and sibling CTE names to the CTE", () => {
const sql = compile(
getClickhouseKysely()
diff --git a/packages/shared/src/server/query-ast/softDelete.ts b/packages/shared/src/server/query-ast/softDelete.ts
index 2e043758fc..ad24332d93 100644
--- a/packages/shared/src/server/query-ast/softDelete.ts
+++ b/packages/shared/src/server/query-ast/softDelete.ts
@@ -23,16 +23,12 @@ import {
TableNode,
ValueNode,
WhereNode,
- type CommonTableExpressionNode,
type JoinType,
type KyselyPlugin,
type OperationNode,
type PluginTransformQueryArgs,
type PluginTransformResultArgs,
- type QueryId,
type RootOperationNode,
- type SelectQueryNode,
- type WithNode,
} from "kysely";
import { QueryCompileError } from "./errors";
@@ -42,7 +38,7 @@ import {
type ClickHouseSelectQueryNode,
} from "./nodes";
import { SOFT_DELETE_COLUMNS } from "./schema";
-import { ClickHouseOperationNodeTransformer } from "./transformer";
+import { CteScopedTransformer } from "./transformer";
const OUTER_PRESERVING_JOINS = new Set<JoinType>(["RightJoin", "FullJoin"]);
@@ -58,77 +54,21 @@ export class SoftDeleteFilterPlugin implements KyselyPlugin {
}
}
-class SoftDeleteFilterTransformer extends ClickHouseOperationNodeTransformer {
- /**
- * CTE names visible to the select being transformed: one set per enclosing
- * select that declares a WITH. A relation named like a CTE in scope is that
- * CTE, not the physical table. A CTE body sees every sibling CTE except
- * itself, matching ClickHouse: `WITH events_core AS (SELECT … FROM
- * events_core)` reads the table. Under WITH RECURSIVE only the recursive
- * UNION member reads the CTE; it is still filtered, so ClickHouse rejects
- * the unknown column instead of the anchor returning deleted rows.
- * Pushed before a select's children are transformed and popped after, so
- * it is empty between compiles.
- */
- private readonly cteScopes: Set<string>[] = [];
-
- protected override transformSelectQuery(
- node: SelectQueryNode,
- queryId?: QueryId,
- ): SelectQueryNode {
- const ctes = cteNames(node.with);
- if (ctes.size > 0) this.cteScopes.push(ctes);
- try {
- const withChildren = super.transformSelectQuery(
- node,
- queryId,
- ) as ClickHouseSelectQueryNode;
- return filterSelect(withChildren, (name) =>
- this.cteScopes.some((scope) => scope.has(name)),
- );
- } finally {
- if (ctes.size > 0) this.cteScopes.pop();
- }
- }
-
- protected override transformWith(
- node: WithNode,
- queryId?: QueryId,
- ): WithNode {
- const full = this.cteScopes.pop() ?? new Set<string>();
- try {
- const expressions = node.expressions.map((expr) => {
- const visible = new Set(full);
- visible.delete(cteName(expr));
- this.cteScopes.push(visible);
- try {
- return this.transformNode(expr, queryId);
- } finally {
- this.cteScopes.pop();
- }
- });
- return { ...node, expressions };
- } finally {
- if (full.size > 0) this.cteScopes.push(full);
- }
+class SoftDeleteFilterTransformer extends CteScopedTransformer {
+ protected rewriteSelect(
+ node: ClickHouseSelectQueryNode,
+ ): ClickHouseSelectQueryNode {
+ return filterSelect(node, (table) => this.isCte(table));
}
}
-function cteName(expr: CommonTableExpressionNode): string {
- return expr.name.table.table.identifier.name;
-}
-
-function cteNames(node: WithNode | undefined): Set<string> {
- return new Set((node?.expressions ?? []).map(cteName));
-}
-
function filterSelect(
node: ClickHouseSelectQueryNode,
- isCte: (name: string) => boolean,
+ isCte: (table: TableNode) => boolean,
): ClickHouseSelectQueryNode {
const describe = (item: OperationNode) => {
const relation = describeRelation(item);
- return relation && !isCte(relation.tableName) ? relation : undefined;
+ return relation && !isCte(relation.node) ? relation : undefined;
};
const froms = (node.from?.froms ?? []).map(describe);
const joins = (node.joins ?? []).map((join) => ({
@@ -198,7 +138,7 @@ function describeRelation(node: OperationNode): SoftDeleteRelation | undefined {
if (TableNode.is(node)) {
const tableName = node.table.identifier.name;
const flag = SOFT_DELETE_COLUMNS[tableName];
- return flag ? { tableName, flag } : undefined;
+ return flag ? { tableName, flag, node } : undefined;
}
return undefined;
}
@@ -222,4 +162,5 @@ type SoftDeleteRelation = {
tableName: string;
alias?: string;
flag: string;
+ node: TableNode;
};
diff --git a/packages/shared/src/server/query-ast/tenancy.ts b/packages/shared/src/server/query-ast/tenancy.ts
index efe295f20c..86ec2db1ea 100644
--- a/packages/shared/src/server/query-ast/tenancy.ts
+++ b/packages/shared/src/server/query-ast/tenancy.ts
@@ -18,7 +18,6 @@ import {
type OperationNode,
type PluginTransformQueryArgs,
type PluginTransformResultArgs,
- type QueryId,
type RootOperationNode,
} from "kysely";
@@ -29,7 +28,7 @@ import {
type ClickHouseSelectQueryNode,
} from "./nodes";
import { TENANTED_TABLES } from "./schema";
-import { ClickHouseOperationNodeTransformer } from "./transformer";
+import { CteScopedTransformer } from "./transformer";
const PROJECT_ID_COLUMN = "project_id";
@@ -41,7 +40,7 @@ const PROJECT_ID_COLUMN = "project_id";
const TENANCY_STAMPED = new WeakSet<object>();
type Relation =
- | { kind: "table"; tableName: string; alias?: string }
+ | { kind: "table"; tableName: string; alias?: string; node: TableNode }
| { kind: "subquery"; node: SelectQueryNode }
| { kind: "raw" }
| { kind: "other" };
@@ -74,39 +73,22 @@ export class TenancyInjectionPlugin implements KyselyPlugin {
}
}
-class TenancyInjectionTransformer extends ClickHouseOperationNodeTransformer {
+class TenancyInjectionTransformer extends CteScopedTransformer {
constructor(private readonly projectId: string) {
super();
}
- protected override transformSelectQuery(
- node: SelectQueryNode,
- queryId?: QueryId,
- ): SelectQueryNode {
- const withChildren = super.transformSelectQuery(
- node,
- queryId,
- ) as ClickHouseSelectQueryNode;
- return injectSelect(
- withChildren,
- this.projectId,
- collectCteNames(withChildren),
- );
- }
-}
-
-function collectCteNames(node: SelectQueryNode): Set<string> {
- const names = new Set<string>();
- for (const expr of node.with?.expressions ?? []) {
- names.add(tableNameOf(expr.name.table));
+ protected rewriteSelect(
+ node: ClickHouseSelectQueryNode,
+ ): ClickHouseSelectQueryNode {
+ return injectSelect(node, this.projectId, (table) => this.isCte(table));
}
- return names;
}
function injectSelect(
node: ClickHouseSelectQueryNode,
projectId: string,
- cteNames: Set<string>,
+ isCte: (table: TableNode) => boolean,
): ClickHouseSelectQueryNode {
const fromRelations = (node.from?.froms ?? []).map(describeRelation);
const joinRelations = (node.joins ?? []).map((join) => ({
@@ -124,9 +106,7 @@ function injectSelect(
const isTenantedTable = (
r: Relation,
): r is Extract<Relation, { kind: "table" }> =>
- r.kind === "table" &&
- TENANTED_TABLES.has(r.tableName) &&
- !cteNames.has(r.tableName);
+ r.kind === "table" && TENANTED_TABLES.has(r.tableName) && !isCte(r.node);
const tenantedFrom = fromRelations.filter(isTenantedTable);
const tenantedJoinCount = joinRelations.filter(({ relation }) =>
@@ -202,12 +182,12 @@ function describeRelation(node: OperationNode): Relation {
const inner = describeRelation(node.node);
if (inner.kind === "table") {
const alias = identifierName(node.alias);
- return { kind: "table", tableName: inner.tableName, alias };
+ return { ...inner, alias };
}
return inner;
}
if (TableNode.is(node)) {
- return { kind: "table", tableName: tableNameOf(node) };
+ return { kind: "table", tableName: tableNameOf(node), node };
}
if (SelectQueryNode.is(node)) {
return { kind: "subquery", node };
diff --git a/packages/shared/src/server/query-ast/transformer.ts b/packages/shared/src/server/query-ast/transformer.ts
index 7df35c20ab..2b745427cd 100644
--- a/packages/shared/src/server/query-ast/transformer.ts
+++ b/packages/shared/src/server/query-ast/transformer.ts
@@ -1,15 +1,21 @@
import {
+ AliasNode,
OperationNodeTransformer,
+ SelectQueryNode,
+ TableNode,
+ type CommonTableExpressionNode,
type OperationNode,
type QueryId,
- type SelectQueryNode,
+ type WithNode,
} from "kysely";
+import { UnscopedRelationError } from "./errors";
import {
ArrayJoinNode,
ArrayIndexNode,
FinalTableNode,
LimitByNode,
+ unwrapFinalTable,
type ClickHouseSelectQueryNode,
} from "./nodes";
@@ -91,3 +97,231 @@ export class ClickHouseOperationNodeTransformer extends OperationNodeTransformer
);
}
}
+
+/**
+ * Transformer for passes that rewrite physical relations: it tracks which
+ * names resolve to a CTE, so a relation named like a registry table is left
+ * alone when it reads a CTE of that name. Subclasses rewrite each select in
+ * {@link rewriteSelect}, after its children, and ask {@link isCte}. The
+ * compiler's bind-type scopes (`compiler.ts`) resolve names the same way.
+ */
+export abstract class CteScopedTransformer extends ClickHouseOperationNodeTransformer {
+ /**
+ * CTE names visible to the select being transformed: one set per enclosing
+ * select that declares a WITH. Subqueries, nested WITH bodies and UNION
+ * branches see every enclosing set. A CTE body sees every sibling CTE except
+ * itself, matching ClickHouse: `WITH events_core AS (SELECT … FROM
+ * events_core)` reads the table, unless an enclosing select declares
+ * `events_core` too. Under WITH RECURSIVE only the recursive UNION member
+ * reads the CTE; it is still treated as the table, so a rewrite errs toward
+ * ClickHouse rejecting the query. Pushed before a select's children are
+ * transformed and popped after, so it is empty between compiles.
+ */
+ private readonly cteScopes: Set<string>[] = [];
+
+ /**
+ * Names the CTE bodies of each enclosing WITH read in FROM/JOIN, one set
+ * per enclosing select that declares a WITH. ClickHouse resolves a CTE body
+ * where the CTE is read, not where it is declared, so a nested WITH that
+ * declares one of these names would redirect that read. Pushed and popped
+ * with {@link cteScopes}.
+ */
+ private readonly enclosingBodyReads: Set<string>[] = [];
+
+ protected abstract rewriteSelect(
+ node: ClickHouseSelectQueryNode,
+ ): ClickHouseSelectQueryNode;
+
+ /** A schema-qualified table (`default.traces`) is never a CTE. */
+ protected isCte(table: TableNode): boolean {
+ if (table.table.schema) return false;
+ const name = table.table.identifier.name;
+ return this.cteScopes.some((scope) => scope.has(name));
+ }
+
+ protected override transformSelectQuery(
+ node: SelectQueryNode,
+ queryId?: QueryId,
+ ): SelectQueryNode {
+ const ctes = cteNames(node.with);
+ if (ctes.size > 0) {
+ assertNoRedirectedRead(ctes, this.enclosingBodyReads);
+ this.cteScopes.push(ctes);
+ this.enclosingBodyReads.push(
+ relationNames(node.with?.expressions.map((expr) => expr.expression)),
+ );
+ }
+ try {
+ return this.rewriteSelect(
+ super.transformSelectQuery(node, queryId) as ClickHouseSelectQueryNode,
+ );
+ } finally {
+ if (ctes.size > 0) {
+ this.cteScopes.pop();
+ this.enclosingBodyReads.pop();
+ }
+ }
+ }
+
+ protected override transformWith(
+ node: WithNode,
+ queryId?: QueryId,
+ ): WithNode {
+ assertNoSiblingCycle(node);
+ const full = this.cteScopes.pop() ?? new Set<string>();
+ try {
+ const expressions = node.expressions.map((expr) => {
+ const visible = new Set(full);
+ visible.delete(cteName(expr));
+ this.cteScopes.push(visible);
+ try {
+ return this.transformNode(expr, queryId);
+ } finally {
+ this.cteScopes.pop();
+ }
+ });
+ return { ...node, expressions };
+ } finally {
+ if (full.size > 0) this.cteScopes.push(full);
+ }
+ }
+}
+
+export function cteName(expr: CommonTableExpressionNode): string {
+ return expr.name.table.table.identifier.name;
+}
+
+function cteNames(node: WithNode | undefined): Set<string> {
+ return new Set((node?.expressions ?? []).map(cteName));
+}
+
+/**
+ * Rejects a WITH that declares a name a CTE body of an enclosing WITH reads:
+ *
+ * WITH a AS (SELECT … FROM m)
+ * SELECT …
+ * FROM (
+ * WITH m AS (…)
+ * SELECT … FROM a -- `a` is read here, so its `m` is the inner `m`
+ * )
+ *
+ * With this rule every name in a CTE body resolves where the CTE is declared,
+ * which is what
+ * {@link CteScopedTransformer} and the compiler's bind-type scopes assume.
+ * The rule is conservative: it also rejects a nested WITH under which the
+ * enclosing CTE is never read.
+ */
+function assertNoRedirectedRead(
+ declared: Set<string>,
+ enclosingBodyReads: readonly Set<string>[],
+): void {
+ for (const name of declared) {
+ if (enclosingBodyReads.some((reads) => reads.has(name))) {
+ throw new UnscopedRelationError(
+ `A nested WITH may not declare ${name}: an enclosing CTE reads ${name}, and if that CTE is read inside this select, ClickHouse resolves its read to the nested CTE, so the tenancy pass cannot scope it.`,
+ );
+ }
+ }
+}
+
+/**
+ * Rejects sibling CTEs that read each other (`a` β†’ `b` β†’ `a`). ClickHouse
+ * resolves a read of a CTE that is still being resolved as if that CTE were
+ * not declared, to an enclosing CTE of that name or else the table, so one
+ * reference reads the CTE on one path and something else on another, and no
+ * scope can tell a pass which. A body reading its own name is not a cycle,
+ * and neither is a body reading a CTE it declares itself in a nested WITH:
+ * reads are those {@link relationNames} returns.
+ */
+function assertNoSiblingCycle(node: WithNode): void {
+ const names = cteNames(node);
+ const reads = new Map(
+ node.expressions.map((expr) => {
+ const name = cteName(expr);
+ const read = relationNames(expr.expression);
+ return [
+ name,
+ [...read].filter((other) => other !== name && names.has(other)),
+ ];
+ }),
+ );
+ const done = new Set<string>();
+ const path: string[] = [];
+ const visit = (name: string) => {
+ if (path.includes(name)) {
+ throw new UnscopedRelationError(
+ `CTEs that read each other (${[...path.slice(path.indexOf(name)), name].join(" β†’ ")}) are rejected: ClickHouse reads the table, not the CTE, on part of the cycle, so the tenancy pass cannot scope it.`,
+ );
+ }
+ if (done.has(name)) return;
+ path.push(name);
+ for (const next of reads.get(name) ?? []) visit(next);
+ path.pop();
+ done.add(name);
+ };
+ for (const name of names) visit(name);
+}
+
+/**
+ * Unqualified table names read in FROM/JOIN anywhere under `value`, except
+ * reads of a CTE that a select under `value` declares: those always resolve
+ * to that CTE. A CTE body's read of its own name escapes its WITH, so it
+ * counts.
+ *
+ * relationNames(SELECT … FROM a JOIN (WITH x AS (SELECT … FROM b)
+ * SELECT … FROM x) AS s)
+ * β†’ {a, b} -- `x` is declared under `value`, so it is not a read
+ *
+ * `shadowed` holds the CTE names declared by the selects between `value`'s
+ * root and the current node.
+ */
+function relationNames(
+ value: unknown,
+ found = new Set<string>(),
+ shadowed: ReadonlySet<string> = new Set(),
+): Set<string> {
+ if (!value || typeof value !== "object") return found;
+ // Not a select (an array, a WHERE, a join, …): look for selects below it.
+ if (!isOperationNode(value) || !SelectQueryNode.is(value)) {
+ for (const child of Object.values(value)) {
+ relationNames(child, found, shadowed);
+ }
+ return found;
+ }
+ // A CTE body sees its siblings as CTEs, but not itself: inside its body,
+ // its own name is the table or an enclosing CTE.
+ const declared = cteNames(value.with);
+ for (const expr of value.with?.expressions ?? []) {
+ const siblings = new Set(declared);
+ siblings.delete(cteName(expr));
+ relationNames(expr.expression, found, new Set([...shadowed, ...siblings]));
+ }
+ // The rest of this select (FROM, JOIN, WHERE, …) sees all of its CTEs.
+ const inner = new Set([...shadowed, ...declared]);
+ const relations = [
+ ...(value.from?.froms ?? []),
+ ...(value.joins ?? []).map((join) => join.table),
+ ];
+ for (const relation of relations) {
+ const table = relationTable(relation);
+ const name = table?.table.identifier.name;
+ if (table && name && !table.table.schema && !inner.has(name)) {
+ found.add(name);
+ }
+ }
+ // Subqueries anywhere in this select; the WITH bodies were walked above.
+ for (const [key, child] of Object.entries(value)) {
+ if (key !== "with") relationNames(child, found, inner);
+ }
+ return found;
+}
+
+function isOperationNode(value: object): value is OperationNode {
+ return "kind" in value && typeof value.kind === "string";
+}
+
+function relationTable(node: OperationNode): TableNode | undefined {
+ if (FinalTableNode.is(node)) return relationTable(unwrapFinalTable(node));
+ if (AliasNode.is(node)) return relationTable(node.node);
+ return TableNode.is(node) ? node : undefined;
+}