Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(query-ast): resolve FROM/JOIN items through one relation describer (#19035)

Niklas Semmler1b1d7359cfa5
diff --git a/packages/shared/src/server/query-ast/README.md b/packages/shared/src/server/query-ast/README.md
index bd6638a0d2..2a7093d83b 100644
--- a/packages/shared/src/server/query-ast/README.md
+++ b/packages/shared/src/server/query-ast/README.md
@@ -201,13 +201,13 @@ need a fork. Instead each ClickHouse-only construct rides as an extra field or a
special-cased node, and the compiler/transformer are overridden to emit and
preserve it:
-| Clause | How it lands | Fork? |
-| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
-| ARRAY JOIN | Plugin attaches `ArrayJoinNode` as an extra field on `SelectQueryNode`. `ClickHouseOperationNodeTransformer` preserves it. `ClickHouseQueryCompiler.visitSelectQuery` emits it after JOINs / before WHERE. | no |
-| LIMIT BY | Plugin attaches `LimitByNode` the same way. Compiler emits it after ORDER BY / before LIMIT. | no |
-| FINAL | Plugin wraps a FROM/JOIN table expression in `FinalTableNode`. Compiler emits `final` after that expression (`scores as s final`). `$call(useFinal(["scores"]))`. Tables declared `dedup: none` throw. | no |
-| metadata subscript | Helper builds an `ArrayIndexNode` over the `metadataMap` `FunctionNode`, indexed by a string key expression (a bound value or a `literal(...)`). Transformer + compiler special-case the node. No plugin. | no |
-| Virtual view | Plugin rewrites `selectFrom(viewName)` into a WITH CTE. Outer types only expose the view's selected columns. | no |
+| Clause | How it lands | Fork? |
+| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| ARRAY JOIN | Plugin attaches `ArrayJoinNode` as an extra field on `SelectQueryNode`. `ClickHouseOperationNodeTransformer` preserves it. `ClickHouseQueryCompiler.visitSelectQuery` emits it after JOINs / before WHERE. | no |
+| LIMIT BY | Plugin attaches `LimitByNode` the same way. Compiler emits it after ORDER BY / before LIMIT. | no |
+| FINAL | Plugin wraps a FROM/JOIN table expression in `FinalTableNode`. Compiler emits `final` after that expression (`scores as s final`). `$call(useFinal(["scores"]))`. Tables declared `dedup: none` throw; so does FINAL on a `limitBy` table at compile (drop the `useFinal`). | no |
+| metadata subscript | Helper builds an `ArrayIndexNode` over the `metadataMap` `FunctionNode`, indexed by a string key expression (a bound value or a `literal(...)`). Transformer + compiler special-case the node. No plugin. | no |
+| Virtual view | Plugin rewrites `selectFrom(viewName)` into a WITH CTE. Outer types only expose the view's selected columns. | no |
These are real node objects whose children are traced Kysely
`FunctionNode`/`ColumnNode`/`ValueNode`/`IdentifierNode` values — not `RawNode`
@@ -253,7 +253,9 @@ and it is where tenancy is enforced:
FINAL. `limitBy` is
the existing legacy `ORDER BY <version> DESC LIMIT 1 BY <key>`.
`final` remains fail-closed on the auto-lowering pass; callers opt in
- with `$call(useFinal(["scores"]))`. The pass restamps the rewritten root.
+ with `$call(useFinal(["scores"]))`. FINAL on a table that declares
+ `limitBy` throws: the registry already picks the latest version, so drop
+ the `useFinal`. The pass restamps the rewritten root.
5. `ClickHouseQueryCompiler` refuses to emit SQL unless that identity stamp is
present, so `qb.compile()` without the plugin also fails. Value binds take
their ClickHouse type from the compared column's registry entry when one is
@@ -264,6 +266,12 @@ and it is where tenancy is enforced:
(table functions such as `remote()`, `clusterAllReplicas()`, `merge()`).
Kysely's own keyword fragments (`asc`/`desc`) are not relations.
+Every pass and the compiler read a FROM/JOIN item through `describeRelation`
+(`relations.ts`): it peels one FINAL and then one alias, so `scores as s final`
+is the table `scores` under alias `s`. Any other nesting (an alias around
+FINAL, FINAL around FINAL) is neither a table nor a subquery, and step 6
+rejects it. A new relation shape is handled there, once.
+
So query bodies here never filter `project_id` by hand — it is redundant, and
forgetting it is impossible.
diff --git a/packages/shared/src/server/query-ast/compiler.ts b/packages/shared/src/server/query-ast/compiler.ts
index def1e47dcd..098339dbd1 100644
--- a/packages/shared/src/server/query-ast/compiler.ts
+++ b/packages/shared/src/server/query-ast/compiler.ts
@@ -34,6 +34,7 @@ import {
type LimitByNode,
} from "./nodes";
import { QueryCompileError } from "./errors";
+import { selectRelations } from "./relations";
import { COLUMN_BIND_TYPES, TABLE_BIND_TYPES } from "./schema";
import { assertTenancyStamped } from "./tenancy";
import { cteName } from "./transformer";
@@ -386,31 +387,20 @@ export class ClickHouseQueryCompiler extends DefaultQueryCompiler {
relations: new Map(),
};
const scopes = [...enclosing, scope];
- const relations = [
- ...(node.from?.froms ?? []),
- ...(node.joins ?? []).map((join) => join.table),
- ];
- for (const wrapped of relations) {
- // FINAL wraps the whole relation, alias included: `scores AS s FINAL`.
- const maybeFinal: { kind: string } = wrapped;
- const relation = FinalTableNode.is(maybeFinal)
- ? maybeFinal.table
- : wrapped;
- const aliased = AliasNode.is(relation) ? relation : undefined;
- const inner = aliased ? aliased.node : relation;
- const columns = TableNode.is(inner)
- ? relationBindTypes(inner, scopes)
- : this.outputBindTypes(inner, scopes);
+ for (const { source, table, alias } of selectRelations(node)) {
+ const columns = table
+ ? relationBindTypes(table, scopes)
+ : this.outputBindTypes(source, scopes);
// 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);
+ if (table) {
+ scope.relations.set(table.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);
+ if (alias) {
+ scope.relations.set(alias, columns);
}
}
return scope;
diff --git a/packages/shared/src/server/query-ast/dedup.test.ts b/packages/shared/src/server/query-ast/dedup.test.ts
index dceaa79e5f..b326692374 100644
--- a/packages/shared/src/server/query-ast/dedup.test.ts
+++ b/packages/shared/src/server/query-ast/dedup.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { compileClickhouseQuery } from "./compile";
import { getClickhouseKysely } from "./dialect";
-import { limitBy } from "./extensions";
+import { limitBy, useFinal } from "./extensions";
import { DEDUP_SPECS } from "./schema";
const projectId = "proj-1";
@@ -98,6 +98,77 @@ describe("per-table dedup lowering", () => {
}
});
+ it("qualifies the version sort and LIMIT BY key with the FROM alias", () => {
+ DEDUP_SPECS.traces = {
+ strategy: "limitBy",
+ key: ["id"],
+ version: "event_ts",
+ };
+ try {
+ const { sql } = compile(
+ getClickhouseKysely().selectFrom("traces as t").select("t.id"),
+ );
+ expect(sql).toBe(
+ "select t.id from traces as t where t.project_id = {p1:String} order by t.event_ts desc limit 1 by t.id",
+ );
+ } finally {
+ delete DEDUP_SPECS.traces;
+ }
+ });
+
+ it("rejects a declared final strategy, which has no emitter", () => {
+ DEDUP_SPECS.traces = { strategy: "final" };
+ try {
+ expect(() =>
+ compile(getClickhouseKysely().selectFrom("traces").select("id")),
+ ).toThrow(/Dedup strategy "final" is declared on traces/);
+ } finally {
+ delete DEDUP_SPECS.traces;
+ }
+ });
+
+ it("keeps the FROM alias when it wraps an aggregate", () => {
+ DEDUP_SPECS.scores = {
+ strategy: "limitBy",
+ key: ["id"],
+ version: "event_ts",
+ };
+ try {
+ const { sql } = compile(
+ getClickhouseKysely()
+ .selectFrom("scores as s")
+ .select((eb) => eb.fn.countAll().as("n")),
+ );
+ expect(sql).toBe(
+ "select count(*) as n from (select * from scores as s where s.project_id = {p1:String} order by s.event_ts desc limit 1 by s.id) as s",
+ );
+ } finally {
+ delete DEDUP_SPECS.scores;
+ }
+ });
+
+ it("rejects FINAL on a table that declares limitBy dedup", () => {
+ // FINAL and LIMIT 1 BY both pick the latest version, and the aggregate
+ // wrap would move the FROM item into a subquery, so the pair is refused.
+ DEDUP_SPECS.scores = {
+ strategy: "limitBy",
+ key: ["id"],
+ version: "event_ts",
+ };
+ try {
+ expect(() =>
+ compile(
+ getClickhouseKysely()
+ .selectFrom("scores as s")
+ .$call(useFinal(["scores"]))
+ .select((eb) => eb.fn.countAll().as("n")),
+ ),
+ ).toThrow(/FINAL cannot be combined with the limitBy dedup/);
+ } finally {
+ delete DEDUP_SPECS.scores;
+ }
+ });
+
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 6580d5e45f..08be4c1d04 100644
--- a/packages/shared/src/server/query-ast/dedup.ts
+++ b/packages/shared/src/server/query-ast/dedup.ts
@@ -44,16 +44,15 @@ import { QueryCompileError } from "./errors";
import {
FinalTableNode,
LimitByNode,
- unwrapFinalTable,
type ClickHouseSelectQueryNode,
} from "./nodes";
+import { describeRelation } from "./relations";
import { DEDUP_SPECS, type DedupSpec } from "./schema";
import { stampCompiledTree } from "./tenancy";
import { CteScopedTransformer } from "./transformer";
type PhysicalFrom = {
tableName: string;
- table: TableNode;
alias?: string;
fromItem: OperationNode;
};
@@ -92,12 +91,7 @@ function lowerSelect(
const spec = DEDUP_SPECS[from.tableName];
if (!spec || spec.strategy === "none") return node;
-
- if (spec.strategy === "final") {
- throw new QueryCompileError(
- `Dedup strategy "final" is declared on ${from.tableName} but has no emitter. Use strategy "limitBy" or implement FINAL lowering before declaring it.`,
- );
- }
+ assertLowerable(from, spec);
if (node.limitBy) {
// Caller already attached LIMIT BY. Still pin the version sort so the
@@ -111,6 +105,23 @@ function lowerSelect(
return attachRowDedup(node, from, spec);
}
+/** Narrows `spec` to `limitBy`: throws on the shapes the pass cannot lower. */
+function assertLowerable(
+ from: PhysicalFrom,
+ spec: DedupSpec,
+): asserts spec is LimitBySpec {
+ if (spec.strategy === "final") {
+ throw new QueryCompileError(
+ `Dedup strategy "final" is declared on ${from.tableName} but has no emitter. Use strategy "limitBy" or implement FINAL lowering before declaring it.`,
+ );
+ }
+ if (FinalTableNode.is(from.fromItem)) {
+ throw new QueryCompileError(
+ `FINAL cannot be combined with the limitBy dedup declared on ${from.tableName}: the registry already picks the latest version. Remove useFinal().`,
+ );
+ }
+}
+
function singlePhysicalFrom(
node: SelectQueryNode,
isCte: (table: TableNode) => boolean,
@@ -118,30 +129,13 @@ function singlePhysicalFrom(
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 (isCte(described.table)) return undefined;
- return described;
-}
-
-function describeFrom(node: OperationNode): PhysicalFrom | undefined {
- if (FinalTableNode.is(node)) {
- return describeFrom(unwrapFinalTable(node));
- }
- if (AliasNode.is(node)) {
- const inner = describeFrom(node.node);
- if (!inner) return undefined;
- const alias = IdentifierNode.is(node.alias) ? node.alias.name : undefined;
- return { ...inner, alias, fromItem: node };
- }
- if (TableNode.is(node)) {
- return {
- tableName: node.table.identifier.name,
- table: node,
- fromItem: node,
- };
- }
- return undefined;
+ const { node: fromItem, table, alias } = describeRelation(froms[0]);
+ if (!table || isCte(table)) return undefined;
+ return {
+ tableName: table.table.identifier.name,
+ alias,
+ fromItem,
+ };
}
type QueryShape = "row" | "aggregate" | "skip";
diff --git a/packages/shared/src/server/query-ast/eventsRouting.test.ts b/packages/shared/src/server/query-ast/eventsRouting.test.ts
index 60cc9c1712..7a647c80aa 100644
--- a/packages/shared/src/server/query-ast/eventsRouting.test.ts
+++ b/packages/shared/src/server/query-ast/eventsRouting.test.ts
@@ -1,7 +1,11 @@
import {
+ AliasNode,
+ FromNode,
+ SelectQueryNode,
sql,
type Expression,
type ExpressionBuilder,
+ type KyselyPlugin,
type SqlBool,
} from "kysely";
import { describe, expect, it } from "vitest";
@@ -24,6 +28,7 @@ import {
startsWith,
useFinal,
} from "./extensions";
+import { finalTable } from "./nodes";
import type { ClickHouseDatabase } from "./schema";
// Raw compiler output, so these run without a `clickhouse` binary.
@@ -229,6 +234,48 @@ describe("logical events routing", () => {
).toThrow(QueryCompileError);
});
+ it("gives an unaliased schema-qualified table no qualifier name", () => {
+ // `default.events_core` is named by neither `events_core` nor
+ // `default.events_core` here, so the read is rejected, not resolved.
+ expect(() =>
+ compile(
+ db
+ .selectFrom("events as e")
+ .select("e.span_id")
+ .where(
+ "e.span_id",
+ "in",
+ db
+ .withSchema("default")
+ .selectFrom("events_core")
+ .select(sql.ref<string>("events_core.input").as("x")),
+ ),
+ ),
+ ).toThrow(/Qualify by the relation's alias/);
+ });
+
+ it("rejects FINAL around the logical relation", () => {
+ // useFinal() refuses `events` (dedup: none), so FINAL is wrapped by hand;
+ // routing would otherwise swap the table and drop the FINAL silently.
+ const wrapFinal: KyselyPlugin = {
+ transformQuery(args) {
+ const node = args.node;
+ if (!SelectQueryNode.is(node) || !node.from) return node;
+ const [from] = node.from.froms;
+ if (!AliasNode.is(from)) return node;
+ return { ...node, from: FromNode.create([finalTable(from)]) };
+ },
+ async transformResult(args) {
+ return args.result;
+ },
+ };
+ expect(() =>
+ compile(
+ db.withPlugin(wrapFinal).selectFrom("events as e").select("e.span_id"),
+ ),
+ ).toThrow(/FINAL cannot wrap the logical "events" relation/);
+ });
+
it("keeps a physical events qualifier when no logical relation is in scope", () => {
expect(
routedTables(
diff --git a/packages/shared/src/server/query-ast/eventsRouting.ts b/packages/shared/src/server/query-ast/eventsRouting.ts
index 88b64aac86..21fcd76dbb 100644
--- a/packages/shared/src/server/query-ast/eventsRouting.ts
+++ b/packages/shared/src/server/query-ast/eventsRouting.ts
@@ -57,7 +57,8 @@ import {
import { metadataFilterIsEventsCoreSafe } from "../queries/clickhouse-sql/events-core-truncation";
import { QueryCompileError } from "./errors";
-import { ArrayIndexNode, FinalTableNode, unwrapFinalTable } from "./nodes";
+import { ArrayIndexNode, FinalTableNode } from "./nodes";
+import { describeRelation, selectRelations, type Relation } from "./relations";
import { EVENTS_CORE_TRUNCATED_COLUMNS } from "./schema";
import { ClickHouseOperationNodeTransformer } from "./transformer";
@@ -105,7 +106,7 @@ class EventsReadAnalysis extends ClickHouseOperationNodeTransformer {
/** Logical relations that read a truncated column. */
readonly fullRelations = new Set<OperationNode>();
/** Relations of each enclosing select, innermost last. */
- private readonly scopes: Relation[][] = [];
+ private readonly scopes: RoutingRelation[][] = [];
protected override transformNodeImpl<T extends OperationNode>(
node: T,
@@ -124,10 +125,7 @@ class EventsReadAnalysis extends ClickHouseOperationNodeTransformer {
node: SelectQueryNode,
queryId?: QueryId,
): SelectQueryNode {
- const relations = [
- ...(node.from?.froms ?? []),
- ...(node.joins ?? []).map((join) => join.table),
- ].map(describeRelation);
+ const relations = selectRelations(node).map(routingRelation);
if (relations.some((relation) => relation.logical)) {
this.readsLogicalEvents = true;
}
@@ -227,7 +225,7 @@ class EventsReadAnalysis extends ClickHouseOperationNodeTransformer {
if (relation?.logical) this.fullRelations.add(relation.node);
}
- private resolveQualified(qualifier: string): Relation | undefined {
+ private resolveQualified(qualifier: string): RoutingRelation | undefined {
for (const relations of this.scopes.toReversed()) {
const match = relations.find((relation) => relation.name === qualifier);
if (match) return match;
@@ -240,7 +238,7 @@ class EventsReadAnalysis extends ClickHouseOperationNodeTransformer {
return undefined;
}
- private resolveUnqualified(column: string): Relation | undefined {
+ private resolveUnqualified(column: string): RoutingRelation | undefined {
if (this.readsLogicalInScope()) {
throw new QueryCompileError(
`Qualify "${column}": it is truncated in events_core, so the routing pass needs to know which relation reads it while the logical "${LOGICAL_EVENTS}" relation is in scope.`,
@@ -315,39 +313,41 @@ class EventsTableRouter extends ClickHouseOperationNodeTransformer {
const table = TableNode.create(
this.fullRelations.has(node) ? "events_full" : "events_core",
);
- if (isLogicalEventsTable(node)) {
- return AliasNode.create(table, IdentifierNode.create(LOGICAL_EVENTS));
+ const { source, alias } = describeRelation(node);
+ if (!isLogicalEventsTable(source)) {
+ return this.transformNode(node, queryId);
}
- if (AliasNode.is(node) && isLogicalEventsTable(node.node)) {
- return AliasNode.create(table, node.alias);
+ if (FinalTableNode.is(node)) {
+ throw new QueryCompileError(
+ `FINAL cannot wrap the logical "${LOGICAL_EVENTS}" relation: events_core and events_full are immutable at read time. Drop the FINAL.`,
+ );
}
- return this.transformNode(node, queryId);
+ return AliasNode.create(
+ table,
+ IdentifierNode.create(alias ?? LOGICAL_EVENTS),
+ );
}
}
-// FINAL wraps the aliased item: `scores as s FINAL`.
-function describeRelation(node: OperationNode): Relation {
- const item = FinalTableNode.is(node) ? unwrapFinalTable(node) : node;
- const table = AliasNode.is(item) ? item.node : item;
+/**
+ * Named by its alias, else by its table name unless schema-qualified:
+ * `events as e` → `e`, `events` → `events`, `default.events_core` → none.
+ */
+function routingRelation({
+ node,
+ source,
+ table,
+ alias,
+}: Relation): RoutingRelation {
return {
node,
- name: relationName(item, table),
- logical: isLogicalEventsTable(table),
+ name:
+ alias ??
+ (table && !table.table.schema ? table.table.identifier.name : undefined),
+ logical: isLogicalEventsTable(source),
};
}
-function relationName(
- item: OperationNode,
- table: OperationNode,
-): string | undefined {
- if (AliasNode.is(item)) {
- return IdentifierNode.is(item.alias) ? item.alias.name : undefined;
- }
- return TableNode.is(table) && table.table.schema === undefined
- ? table.table.identifier.name
- : undefined;
-}
-
function isLogicalEventsTable(node: OperationNode): boolean {
return (
TableNode.is(node) &&
@@ -407,7 +407,7 @@ function coreSafe(
}
/** A FROM/JOIN source of one select. */
-type Relation = {
+type RoutingRelation = {
/** The FROM item or join table, as the router meets it. */
node: OperationNode;
/** Alias, or the table name of an unaliased table. */
diff --git a/packages/shared/src/server/query-ast/extensions.ts b/packages/shared/src/server/query-ast/extensions.ts
index 08b546bf38..3236aa8af9 100644
--- a/packages/shared/src/server/query-ast/extensions.ts
+++ b/packages/shared/src/server/query-ast/extensions.ts
@@ -20,7 +20,6 @@
import type { TupleParam } from "@clickhouse/client";
import {
AggregateFunctionNode,
- AliasNode,
BinaryOperationNode,
ColumnNode,
ExpressionWrapper,
@@ -47,11 +46,12 @@ import {
ArrayJoinNode,
FinalTableNode,
LimitByNode,
- unwrapFinalTable,
+ finalTable,
type ArrayJoinVariant,
type ClickHouseSelectQueryNode,
} from "./nodes";
import { QueryCompileError } from "./errors";
+import { describeRelation } from "./relations";
import { DEDUP_SPECS, type ClickHouseDatabase } from "./schema";
import { ClickHouseOperationNodeTransformer } from "./transformer";
@@ -725,22 +725,13 @@ export function limitBy(spec: LimitBySpec) {
): SelectQueryBuilder<DB, TB, O> => qb.withPlugin(new LimitByPlugin(spec));
}
-function physicalTableName(node: OperationNode): string | undefined {
- if (FinalTableNode.is(node)) return physicalTableName(unwrapFinalTable(node));
- if (AliasNode.is(node)) return physicalTableName(node.node);
- if (TableNode.is(node)) return node.table.identifier.name;
- return undefined;
-}
-
function wrapFinal(
node: OperationNode,
tables: ReadonlySet<string>,
): OperationNode {
if (FinalTableNode.is(node)) return node;
- const name = physicalTableName(node);
- return name && tables.has(name)
- ? (FinalTableNode.create(node) as unknown as OperationNode)
- : node;
+ const name = describeRelation(node).table?.table.identifier.name;
+ return name && tables.has(name) ? finalTable(node) : node;
}
/**
diff --git a/packages/shared/src/server/query-ast/nodes.test.ts b/packages/shared/src/server/query-ast/nodes.test.ts
index a7428ac39f..5eeffa42ae 100644
--- a/packages/shared/src/server/query-ast/nodes.test.ts
+++ b/packages/shared/src/server/query-ast/nodes.test.ts
@@ -1,4 +1,11 @@
-import { createQueryId, sql, type KyselyPlugin } from "kysely";
+import {
+ AliasNode,
+ FromNode,
+ SelectQueryNode,
+ createQueryId,
+ sql,
+ type KyselyPlugin,
+} from "kysely";
import { describe, expect, it } from "vitest";
import { compileClickhouseQuery } from "./compile";
@@ -10,6 +17,7 @@ import {
ArrayJoinNode,
FinalTableNode,
LimitByNode,
+ finalTable,
isClickHouseSelectQueryNode,
} from "./nodes";
import { TenancyInjectionPlugin } from "./tenancy";
@@ -97,6 +105,9 @@ describe("tenancy injection", () => {
expect(() => compileClickhouseQuery(qb, projectId)).toThrow(
UnscopedRelationError,
);
+ expect(() => compileClickhouseQuery(qb, projectId)).toThrow(
+ /Raw SQL table sources are rejected/,
+ );
});
it("rejects aliased raw SQL that would introduce an unscoped relation", () => {
@@ -148,6 +159,40 @@ describe("tenancy injection", () => {
},
);
+ // FINAL wraps the aliased item (`scores as s final`); the relation describer
+ // peels one FINAL and then one alias, so any other nesting is no table
+ // reference and cannot be scoped. No builder emits these; they are built by
+ // hand.
+ it.each([
+ [
+ "an alias around FINAL",
+ (alias: AliasNode) =>
+ AliasNode.create(finalTable(alias.node), alias.alias),
+ ],
+ ["FINAL around FINAL", (alias: AliasNode) => finalTable(finalTable(alias))],
+ ])("rejects %s as a FROM source", (_shape, wrap) => {
+ const rewrap: KyselyPlugin = {
+ transformQuery(args) {
+ const node = args.node;
+ if (!SelectQueryNode.is(node) || !node.from) return node;
+ const [from] = node.from.froms;
+ if (!AliasNode.is(from)) return node;
+ return { ...node, from: FromNode.create([wrap(from)]) };
+ },
+ async transformResult(args) {
+ return args.result;
+ },
+ };
+ const qb = getClickhouseKysely()
+ .withPlugin(rewrap)
+ .selectFrom("scores as s")
+ .select("s.id");
+
+ expect(() => compileClickhouseQuery(qb, projectId)).toThrow(
+ UnscopedRelationError,
+ );
+ });
+
it("rejects raw SQL fragments in SELECT and WHERE, not only FROM/JOIN", () => {
const selectRaw = getClickhouseKysely()
.selectFrom("events_core")
diff --git a/packages/shared/src/server/query-ast/nodes.ts b/packages/shared/src/server/query-ast/nodes.ts
index 1688d6ce8b..6eadb3744f 100644
--- a/packages/shared/src/server/query-ast/nodes.ts
+++ b/packages/shared/src/server/query-ast/nodes.ts
@@ -155,6 +155,11 @@ export const FinalTableNode = {
},
};
+/** {@link FinalTableNode.create}, typed as the FROM/JOIN item it stands in for. */
+export function finalTable(table: OperationNode): OperationNode {
+ return FinalTableNode.create(table) as unknown as OperationNode;
+}
+
/**
* Read the wrapped table expression. `FinalTableNode.kind` is outside
* Kysely's closed `OperationNodeKind`, so a narrowed
diff --git a/packages/shared/src/server/query-ast/relations.ts b/packages/shared/src/server/query-ast/relations.ts
new file mode 100644
index 0000000000..d77509f84c
--- /dev/null
+++ b/packages/shared/src/server/query-ast/relations.ts
@@ -0,0 +1,55 @@
+import {
+ AliasNode,
+ IdentifierNode,
+ TableNode,
+ type OperationNode,
+ type SelectQueryNode,
+} from "kysely";
+
+import { FinalTableNode, unwrapFinalTable } from "./nodes";
+
+/**
+ * One FROM item or JOIN table of a select, as every pass and the compiler
+ * read it:
+ *
+ * scores as s final → { source: scores, table: scores, alias: "s" }
+ * (select …) as sub → { source: (select …), alias: "sub" }
+ *
+ * FINAL wraps the aliased item, so one FINAL and then one alias are peeled.
+ * Any other nesting (an alias around FINAL, FINAL around FINAL) stays in
+ * `source`, which is then neither a table nor a subquery, and the tenancy
+ * pass rejects it.
+ */
+export type Relation = {
+ /** The item as the select holds it: `scores as s final`. */
+ node: OperationNode;
+ /** What the item reads: a table, a subquery, raw SQL or a table function. */
+ source: OperationNode;
+ /** `source` when it is a table reference, schema-qualified or not. */
+ table?: TableNode;
+ /** The alias, when it is a plain name. */
+ alias?: string;
+};
+
+/** The FROM items of `node`, then its JOIN tables. */
+export function selectRelations(node: SelectQueryNode): Relation[] {
+ return [
+ ...(node.from?.froms ?? []),
+ ...(node.joins ?? []).map((join) => join.table),
+ ].map(describeRelation);
+}
+
+export function describeRelation(node: OperationNode): Relation {
+ const withoutFinal = FinalTableNode.is(node) ? unwrapFinalTable(node) : node;
+ const aliased = AliasNode.is(withoutFinal) ? withoutFinal : undefined;
+ const source = aliased ? aliased.node : withoutFinal;
+ return {
+ node,
+ source,
+ table: TableNode.is(source) ? source : undefined,
+ alias:
+ aliased && IdentifierNode.is(aliased.alias)
+ ? aliased.alias.name
+ : undefined,
+ };
+}
diff --git a/packages/shared/src/server/query-ast/softDelete.test.ts b/packages/shared/src/server/query-ast/softDelete.test.ts
index 60145fe0d9..64346fd08f 100644
--- a/packages/shared/src/server/query-ast/softDelete.test.ts
+++ b/packages/shared/src/server/query-ast/softDelete.test.ts
@@ -1,16 +1,11 @@
-import {
- createQueryId,
- FromNode,
- SelectQueryNode,
- type OperationNode,
-} from "kysely";
+import { createQueryId, FromNode, SelectQueryNode } from "kysely";
import { describe, expect, it } from "vitest";
import { compileClickhouseQuery } from "./compile";
import { getClickhouseKysely } from "./dialect";
import { QueryCompileError } from "./errors";
import { includeDeleted, limitBy, softDeleteAfterLimit } from "./extensions";
-import { FinalTableNode } from "./nodes";
+import { finalTable } from "./nodes";
import { SOFT_DELETE_COLUMNS } from "./schema";
import { SoftDeleteFilterPlugin } from "./softDelete";
@@ -191,16 +186,17 @@ describe("soft-delete filtering", () => {
it("filters a soft-delete table wrapped in FINAL", () => {
// No soft-delete table allows FINAL yet, so the node is built by hand.
- // FinalTableNode is outside Kysely's node union, hence the cast.
const node = getClickhouseKysely()
.selectFrom("events_core as e")
.select("e.span_id")
.toOperationNode();
if (!SelectQueryNode.is(node) || !node.from)
throw new Error("not a select");
- const final = FinalTableNode.create(node.from.froms[0]) as unknown;
const filtered = new SoftDeleteFilterPlugin().transformQuery({
- node: { ...node, from: FromNode.create([final as OperationNode]) },
+ node: {
+ ...node,
+ from: FromNode.create([finalTable(node.from.froms[0])]),
+ },
queryId: createQueryId(),
});
expect(SelectQueryNode.is(filtered) && filtered.where).toBeTruthy();
diff --git a/packages/shared/src/server/query-ast/softDelete.ts b/packages/shared/src/server/query-ast/softDelete.ts
index e89ae881b7..c837bb3604 100644
--- a/packages/shared/src/server/query-ast/softDelete.ts
+++ b/packages/shared/src/server/query-ast/softDelete.ts
@@ -35,11 +35,8 @@ import {
} from "kysely";
import { QueryCompileError } from "./errors";
-import {
- FinalTableNode,
- unwrapFinalTable,
- type ClickHouseSelectQueryNode,
-} from "./nodes";
+import { type ClickHouseSelectQueryNode } from "./nodes";
+import { describeRelation } from "./relations";
import { SOFT_DELETE_COLUMNS } from "./schema";
import { CteScopedTransformer } from "./transformer";
@@ -71,10 +68,7 @@ function filterSelect(
node: ClickHouseSelectQueryNode,
isCte: (table: TableNode) => boolean,
): ClickHouseSelectQueryNode {
- const describe = (item: OperationNode) => {
- const relation = describeRelation(item);
- return relation && !isCte(relation.node) ? relation : undefined;
- };
+ const describe = (item: OperationNode) => softDeleteRelation(item, isCte);
const froms = (node.from?.froms ?? []).map(describe);
const joins = (node.joins ?? []).map((join) => ({
join,
@@ -273,28 +267,23 @@ function outputName(node: OperationNode): string | undefined {
return undefined;
}
-function describeRelation(node: OperationNode): SoftDeleteRelation | undefined {
- if (FinalTableNode.is(node)) {
- return describeRelation(unwrapFinalTable(node));
- }
- if (AliasNode.is(node)) {
- const inner = describeRelation(node.node);
- if (!inner || !IdentifierNode.is(node.alias)) return inner;
- return { ...inner, alias: node.alias.name };
- }
- if (TableNode.is(node)) {
- const tableName = node.table.identifier.name;
- const flag = SOFT_DELETE_COLUMNS[tableName];
- return flag ? { tableName, flag, node } : undefined;
- }
- return undefined;
+/** The soft-delete table `item` reads, unless it reads a CTE. */
+function softDeleteRelation(
+ item: OperationNode,
+ isCte: (table: TableNode) => boolean,
+): SoftDeleteRelation | undefined {
+ const { table, alias } = describeRelation(item);
+ if (!table || isCte(table)) return undefined;
+ const tableName = table.table.identifier.name;
+ const flag = SOFT_DELETE_COLUMNS[tableName];
+ return flag ? { tableName, alias, flag } : undefined;
}
/**
* Always qualified (by alias, else table name): a bare flag column would bind
* to a same-named SELECT alias, e.g. `0 AS is_deleted`.
*/
-function notDeleted(relation: FlagColumn): OperationNode {
+function notDeleted(relation: SoftDeleteRelation): OperationNode {
return BinaryOperationNode.create(
qualifiedFlag(relation),
OperatorNode.create("="),
@@ -302,7 +291,7 @@ function notDeleted(relation: FlagColumn): OperationNode {
);
}
-function qualifiedFlag(relation: FlagColumn): ReferenceNode {
+function qualifiedFlag(relation: SoftDeleteRelation): ReferenceNode {
return ReferenceNode.create(
ColumnNode.create(relation.flag),
TableNode.create(relation.alias ?? relation.tableName),
@@ -313,8 +302,4 @@ type SoftDeleteRelation = {
tableName: string;
alias?: string;
flag: string;
- node: TableNode;
};
-
-/** No `node`: {@link filterAfterLimit} filters a derived table, not a TableNode. */
-type FlagColumn = Pick<SoftDeleteRelation, "tableName" | "alias" | "flag">;
diff --git a/packages/shared/src/server/query-ast/tenancy.ts b/packages/shared/src/server/query-ast/tenancy.ts
index 86ec2db1ea..f33cab9bbd 100644
--- a/packages/shared/src/server/query-ast/tenancy.ts
+++ b/packages/shared/src/server/query-ast/tenancy.ts
@@ -1,9 +1,7 @@
import {
- AliasNode,
AndNode,
BinaryOperationNode,
ColumnNode,
- IdentifierNode,
JoinNode,
OperatorNode,
OrNode,
@@ -22,11 +20,8 @@ import {
} from "kysely";
import { QueryCompileError, UnscopedRelationError } from "./errors";
-import {
- FinalTableNode,
- unwrapFinalTable,
- type ClickHouseSelectQueryNode,
-} from "./nodes";
+import { type ClickHouseSelectQueryNode } from "./nodes";
+import { describeRelation } from "./relations";
import { TENANTED_TABLES } from "./schema";
import { CteScopedTransformer } from "./transformer";
@@ -39,9 +34,9 @@ const PROJECT_ID_COLUMN = "project_id";
*/
const TENANCY_STAMPED = new WeakSet<object>();
-type Relation =
+type ScopedRelation =
| { kind: "table"; tableName: string; alias?: string; node: TableNode }
- | { kind: "subquery"; node: SelectQueryNode }
+ | { kind: "subquery" }
| { kind: "raw" }
| { kind: "other" };
@@ -90,10 +85,10 @@ function injectSelect(
projectId: string,
isCte: (table: TableNode) => boolean,
): ClickHouseSelectQueryNode {
- const fromRelations = (node.from?.froms ?? []).map(describeRelation);
+ const fromRelations = (node.from?.froms ?? []).map(classifyRelation);
const joinRelations = (node.joins ?? []).map((join) => ({
join,
- relation: describeRelation(join.table),
+ relation: classifyRelation(join.table),
}));
for (const relation of fromRelations) {
@@ -104,8 +99,8 @@ function injectSelect(
}
const isTenantedTable = (
- r: Relation,
- ): r is Extract<Relation, { kind: "table" }> =>
+ r: ScopedRelation,
+ ): r is Extract<ScopedRelation, { kind: "table" }> =>
r.kind === "table" && TENANTED_TABLES.has(r.tableName) && !isCte(r.node);
const tenantedFrom = fromRelations.filter(isTenantedTable);
@@ -158,7 +153,7 @@ function injectSelect(
};
}
-function assertRelationAllowed(relation: Relation): void {
+function assertRelationAllowed(relation: ScopedRelation): void {
if (relation.kind === "raw") {
throw new UnscopedRelationError(
"Raw SQL table sources are rejected: they can introduce an unscoped relation that the tenancy pass cannot prove. Use a traced table reference instead.",
@@ -171,27 +166,13 @@ function assertRelationAllowed(relation: Relation): void {
}
}
-function describeRelation(node: OperationNode): Relation {
- if (FinalTableNode.is(node)) {
- return describeRelation(unwrapFinalTable(node));
- }
- if (RawNode.is(node)) {
- return { kind: "raw" };
- }
- if (AliasNode.is(node)) {
- const inner = describeRelation(node.node);
- if (inner.kind === "table") {
- const alias = identifierName(node.alias);
- return { ...inner, alias };
- }
- return inner;
- }
- if (TableNode.is(node)) {
- return { kind: "table", tableName: tableNameOf(node), node };
- }
- if (SelectQueryNode.is(node)) {
- return { kind: "subquery", node };
+function classifyRelation(node: OperationNode): ScopedRelation {
+ const { source, table, alias } = describeRelation(node);
+ if (table) {
+ return { kind: "table", tableName: tableNameOf(table), alias, node: table };
}
+ if (RawNode.is(source)) return { kind: "raw" };
+ if (SelectQueryNode.is(source)) return { kind: "subquery" };
return { kind: "other" };
}
@@ -199,13 +180,8 @@ function tableNameOf(node: TableNode): string {
return node.table.identifier.name;
}
-function identifierName(node: OperationNode): string | undefined {
- if (IdentifierNode.is(node)) return node.name;
- return undefined;
-}
-
function projectIdColumn(
- table: Extract<Relation, { kind: "table" }>,
+ table: Extract<ScopedRelation, { kind: "table" }>,
): OperationNode {
const column = ColumnNode.create(PROJECT_ID_COLUMN);
return table.alias
@@ -214,7 +190,7 @@ function projectIdColumn(
}
function projectIdPredicate(
- table: Extract<Relation, { kind: "table" }>,
+ table: Extract<ScopedRelation, { kind: "table" }>,
projectId: string,
): OperationNode {
return BinaryOperationNode.create(
@@ -235,7 +211,7 @@ function projectIdPredicate(
*/
function predicateCovers(
expr: OperationNode | undefined,
- table: Extract<Relation, { kind: "table" }>,
+ table: Extract<ScopedRelation, { kind: "table" }>,
projectId: string,
requireQualified: boolean,
): boolean {
@@ -269,7 +245,7 @@ function predicateCovers(
function isProjectIdColumn(
node: OperationNode,
- table: Extract<Relation, { kind: "table" }>,
+ table: Extract<ScopedRelation, { kind: "table" }>,
requireQualified: boolean,
): boolean {
if (ColumnNode.is(node)) {
diff --git a/packages/shared/src/server/query-ast/transformer.ts b/packages/shared/src/server/query-ast/transformer.ts
index aff947e4d1..f879b3b8f8 100644
--- a/packages/shared/src/server/query-ast/transformer.ts
+++ b/packages/shared/src/server/query-ast/transformer.ts
@@ -1,5 +1,4 @@
import {
- AliasNode,
OperationNodeTransformer,
SelectQueryNode,
TableNode,
@@ -15,9 +14,9 @@ import {
ArrayIndexNode,
FinalTableNode,
LimitByNode,
- unwrapFinalTable,
type ClickHouseSelectQueryNode,
} from "./nodes";
+import { selectRelations } from "./relations";
/**
* Transformer that knows the ClickHouse extra fields on SelectQueryNode.
@@ -300,12 +299,7 @@ function relationNames(
}
// 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);
+ for (const { table } of selectRelations(value)) {
const name = table?.table.identifier.name;
if (table && name && !table.table.schema && !inner.has(name)) {
found.add(name);
@@ -321,9 +315,3 @@ function relationNames(
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;
-}
diff --git a/packages/shared/src/server/query-ast/views.ts b/packages/shared/src/server/query-ast/views.ts
index 103b80dc39..6564cb5963 100644
--- a/packages/shared/src/server/query-ast/views.ts
+++ b/packages/shared/src/server/query-ast/views.ts
@@ -1,12 +1,9 @@
import {
- AliasNode,
CommonTableExpressionNameNode,
CommonTableExpressionNode,
Kysely,
- TableNode,
WithNode,
type KyselyPlugin,
- type OperationNode,
type PluginTransformQueryArgs,
type PluginTransformResultArgs,
type RootOperationNode,
@@ -16,6 +13,7 @@ import {
import type { ClickhouseCompilable } from "./compile";
import { ClickHouseCompileDialect } from "./dialect";
+import { describeRelation } from "./relations";
import { ClickHouseOperationNodeTransformer } from "./transformer";
export type ClickHouseView<N extends string, O> = {
@@ -55,7 +53,7 @@ class VirtualViewPlugin implements KyselyPlugin {
const froms = node.from?.froms ?? [];
const viewNames = froms
- .map(tableNameOfFrom)
+ .map((from) => describeRelation(from).table?.table.identifier.name)
.filter((name): name is string => Boolean(name && this.views.has(name)));
if (viewNames.length === 0) return node;
@@ -81,16 +79,6 @@ class VirtualViewPlugin implements KyselyPlugin {
}
}
-function tableNameOfFrom(node: OperationNode): string | undefined {
- if (TableNode.is(node)) {
- return node.table.identifier.name;
- }
- if (AliasNode.is(node)) {
- return tableNameOfFrom(node.node);
- }
- return undefined;
-}
-
/**
* Open a query against a named view as if it were a table. Only the view's
* exposed columns are in the type.