From 6e5f40690865b055c31fc07b55396995aa4b107f Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Fri, 27 Nov 2026 23:30:31 +0800 Subject: [PATCH 1/9] fix: names a SELECT list writes, and repeats beside any star - A `_N`/`_col_N` counts as written only in a SELECT list; a table alias or WHERE column with that name is not an alias - A repeat beside a qualified or CTE-wrapped star unsettles the model, as beside a bare `*` - dbt_lineage names a model's own cast like the column answer on Postgres/Redshift Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvqLZuTJdDJ1Ku2ZMDY --- .../src/altimate/native/dbt/lineage.ts | 34 ++++- .../altimate/native/dbt/project-lineage.ts | 126 ++++++++++++++---- .../test/altimate/column-answer.test.ts | 53 ++++++++ 3 files changed, 186 insertions(+), 27 deletions(-) diff --git a/packages/opencode/src/altimate/native/dbt/lineage.ts b/packages/opencode/src/altimate/native/dbt/lineage.ts index 0f5f3efaf6..3c7a250485 100644 --- a/packages/opencode/src/altimate/native/dbt/lineage.ts +++ b/packages/opencode/src/altimate/native/dbt/lineage.ts @@ -8,7 +8,38 @@ import * as core from "@altimateai/altimate-core" import type { DbtLineageParams, DbtLineageResult } from "../types" import { loadRawManifest, findModel, detectDialect, buildSchemaContext } from "./helpers" import { lineageGraph } from "./graph" -import { projectLineage } from "./project-lineage" +import { projectLineage, stripSql, warehouseNames } from "./project-lineage" + +/** + * The lineage with the model's own unaliased casts of a column under the column's name on Postgres and Redshift, as + * impact_analysis's column answer names them (`warehouseNames`): a renamed `_col_N` takes the name, and its `_N` + * twin goes. Every other output, and every other dialect, is left as the engine gives it. + */ +function withWarehouseNames(lineage: Record, sql: string, dialect: string): Record { + if ((dialect !== "postgres" && dialect !== "redshift") || !Array.isArray(lineage.column_lineage)) return lineage + const lower = (text: unknown) => String(text ?? "").toLowerCase() + const edges = lineage.column_lineage.map((e: any) => ({ source: lower(e?.source), to: lower(e?.target) })) + const names = warehouseNames(edges, stripSql(sql), dialect) + const renamed = new Map() + for (const [i, e] of edges.entries()) if (names[i] && names[i] !== e.to) renamed.set(e.to, names[i]!) + if (!renamed.size) return lineage + // The `_N` twin of a renamed `_col_N` goes with it. + const dropped = new Set([...renamed.keys()].map((label) => `_${label.slice(5)}`)) + const target = (text: unknown) => (dropped.has(lower(text)) ? null : (renamed.get(lower(text)) ?? String(text))) + const out: Record = { ...lineage } + out.column_lineage = lineage.column_lineage.flatMap((e: any) => (target(e?.target) === null ? [] : [{ ...e, target: target(e?.target) }])) + if (lineage.column_dict && typeof lineage.column_dict === "object") { + const dict: Record = {} + for (const [key, sources] of Object.entries(lineage.column_dict)) { + const name = target(key) + if (name === null) continue + const had = dict[name] + dict[name] = Array.isArray(had) && Array.isArray(sources) ? [...new Set([...had, ...sources])] : sources + } + out.column_dict = dict + } + return out +} /** * The lineage with the placeholder columns taken out, and the parents whose placeholder reached the @@ -173,6 +204,7 @@ export function dbtLineage(params: DbtLineageParams): DbtLineageResult { const schema = Object.keys(tables).length ? core.Schema.fromJson(JSON.stringify({ version: "1", tables })) : undefined const result = core.columnLineage(sql, dialect, schema) ;({ lineage: rawLineage, starred: missed } = withoutPlaceholders(JSON.parse(JSON.stringify(result)), placeholders)) + rawLineage = withWarehouseNames(rawLineage, String(sql), dialect) } catch (e) { rawLineage = { error: String(e) } } diff --git a/packages/opencode/src/altimate/native/dbt/project-lineage.ts b/packages/opencode/src/altimate/native/dbt/project-lineage.ts index b99b1f47b5..ab1a10be95 100644 --- a/packages/opencode/src/altimate/native/dbt/project-lineage.ts +++ b/packages/opencode/src/altimate/native/dbt/project-lineage.ts @@ -96,10 +96,21 @@ const COLUMNS_CALL = /(?>() + +/** The output names the SELECT lists of literal- and comment-stripped SQL write (aliases and bare columns), lower-cased. */ +function writtenNames(stripped: string): Set { + return remember(writtenCache, hash("written", stripped), () => { + const names = everySelectItems(stripped).flat().map(itemName) + return new Set(names.filter((name): name is string => !!name && name !== "*")) + }) } /** @@ -145,7 +156,7 @@ export function selectItems(stripped: string): string[] { if (ch === ",") { items.push(stripped.slice(from, i).trim()) from = i + 1 - } else if (boundary && word && /^(from|into|where|union|intersect|except|group|order|limit|qualify|having|window)$/.test(word)) { + } else if (boundary && word && LIST_ENDS.test(word)) { items.push(stripped.slice(from, i).trim()) return items.filter((one) => one !== "") } @@ -154,6 +165,45 @@ export function selectItems(stripped: string): string[] { return items.filter((one) => one !== "") } +/** A SELECT item that is a bare column reference (`id`, `t.id`, `"T"."Id"`). */ +const BARE_REF = new RegExp(`^(?:(?:${QUOTED}|[\\w$]+)\\.)*(?:${QUOTED}|[\\w$]+)$`) + +/** Words that end a SELECT list. */ +const LIST_ENDS = /^(?:from|into|where|union|intersect|except|group|order|limit|qualify|having|window)$/ + +/** + * The items of every SELECT list in literal- and comment-stripped SQL, in text order (so CTEs and subqueries before + * the outer list that reads them), each split at its own top-level commas. A list ends at a word that ends a SELECT + * list, or at the `)` that closes the parentheses it sits in. + */ +export function everySelectItems(stripped: string): string[][] { + const text = stripped.replace(new RegExp(QUOTED, "g"), (q) => " ".repeat(q.length)) + const lists: string[][] = [] + for (const m of text.matchAll(/(? one !== "")) + } + return lists +} + /** Words that end an expression (`x is null`, `case … end`) rather than alias it. */ const ENDS_EXPRESSION = /^(?:null|true|false|end)$/i /** Words after which the next word is an operand (`a and b`, `sum(x) over w`), not an alias. */ @@ -584,6 +634,7 @@ export function clearLineageCaches() { lineageCache.clear() outputColumnsCache.clear() readsCache.clear() + writtenCache.clear() } // --------------------------------------------------------------------------------------------- @@ -804,13 +855,29 @@ export class ProjectLineage { return out } - /** Whether a bare `*` sits beside an output that repeats a name the star brings in (`select *, val as id`). */ + /** + * Whether a SELECT list with a star, the outer one or one in a CTE or subquery, names an output twice or gives an + * output a name the star brings in (`select *, val as id`, `select f.*, val as id`): the warehouse renames the + * repeat. A bare `*` brings every parent's columns. A qualified `t.*` brings a name when the model passes a column + * of that name on unchanged from more sources than the list's own bare references to it. + */ private renamesBesideStar(id: string, stripped: string): boolean { - const items = selectItems(stripped) - if (!items.some((item) => /^\*(?:\s|$)/.test(item))) return false - const brought = new Set(this.parents(id).flatMap((p) => [...(this.settledColumns(p) ?? [])])) - const explicit = items.map(itemName).filter((name): name is string => !!name && name !== "*") - return new Set(explicit).size !== explicit.length || explicit.some((name) => brought.has(name)) + const parentColumns = new Set(this.parents(id).flatMap((p) => [...(this.settledColumns(p) ?? [])])) + const unchanged = new Map>() + for (const e of this.lineage(id).edges) + if (e.how === "=" && e.fromCol === e.to) unchanged.set(e.to, (unchanged.get(e.to) ?? new Set()).add(`${e.from}|${e.fromCol}`)) + for (const items of everySelectItems(stripped)) { + const names = items.map(itemName) + if (!names.includes("*")) continue + const explicit = names.filter((name): name is string => !!name && name !== "*") + if (new Set(explicit).size !== explicit.length) return true + const bareStar = items.some((item) => /^\*(?:\s|$)/.test(item)) + for (const name of explicit) { + if (bareStar ? parentColumns.has(name) : (unchanged.get(name)?.size ?? 0) > items.filter((item, i) => names[i] === name && BARE_REF.test(item)).length) + return true + } + } + return false } lineage(id: string): ModelLineage { @@ -890,24 +957,11 @@ export class ProjectLineage { seen.add(dedupe) edges.push({ from, fromCol, to, ...howOfEdge(e, fromCol, to) }) } - // The engine names an unaliased expression twice: `_N`, as if the value passed through unchanged, and - // `_col_N`, how unknown. Keep the second; the warehouse picks the real name. - // A `_N` the SQL itself writes (`amount as _1`) is a real alias and stays. - const stripped = stripSql(raw) - const named = new Set(edges.filter((e) => /^_col_\d+$/.test(e.to)).map((e) => `${e.from}|${e.fromCol}|${e.to.slice(5)}`)) + const names = warehouseNames(edges.map((e) => ({ source: `${e.from}|${e.fromCol}`, to: e.to })), stripSql(raw), this.dialect) for (let i = edges.length - 1; i >= 0; i--) { - const e = edges[i]! - if (/^_\d+$/.test(e.to) && engineMade(e.to, stripped) && named.has(`${e.from}|${e.fromCol}|${e.to.slice(1)}`)) edges.splice(i, 1) - } - // Postgres and Redshift name an unaliased cast of a column after the column (`amount::numeric` is `amount`). - if (this.dialect === "postgres" || this.dialect === "redshift") { - const items = selectItems(stripped) - for (const e of edges) { - // A `_col_N` the SQL writes itself (`amount::numeric as _col_1`) is that output's name: keep it. - const n = engineMade(e.to, stripped) ? /^_col_(\d+)$/.exec(e.to)?.[1] : undefined - const name = n === undefined ? null : castColumn(items[Number(n)] ?? "") - if (name && !edges.some((o) => o.from === e.from && o.fromCol === e.fromCol && o.to === name)) e.to = name - } + const name = names[i] + if (name === null) edges.splice(i, 1) + else edges[i]!.to = name! } const errors: unknown[] = Array.isArray(result.errors) ? result.errors : [] const firstError = (): string => { @@ -925,6 +979,26 @@ export class ProjectLineage { } } +/** + * The warehouse's names for edges the engine labels, given each edge's source and target (lower-cased): null drops the + * edge. The engine names an unaliased expression twice: `_N`, as if the value passed through unchanged, and `_col_N`, + * how unknown. The `_N` of a `_col_N` from the same source goes; the warehouse picks the real name. On Postgres and + * Redshift a `_col_N` that is an unaliased cast of a column (`amount::numeric`) takes the column's name, unless that + * source already reaches the name. A `_N` or `_col_N` a SELECT list writes (`amount as _1`) is the output's name. + */ +export function warehouseNames(edges: { source: string; to: string }[], stripped: string, dialect: string): (string | null)[] { + const twins = new Set(edges.filter((e) => /^_col_\d+$/.test(e.to)).map((e) => `${e.source}|${e.to.slice(5)}`)) + const casts = dialect === "postgres" || dialect === "redshift" + const items = casts ? selectItems(stripped) : [] + const out: (string | null)[] = edges.map((e) => (/^_\d+$/.test(e.to) && engineMade(e.to, stripped) && twins.has(`${e.source}|${e.to.slice(1)}`) ? null : e.to)) + for (const [i, e] of edges.entries()) { + const n = casts && out[i] !== null && engineMade(e.to, stripped) ? /^_col_(\d+)$/.exec(e.to)?.[1] : undefined + const name = n === undefined ? null : castColumn(items[Number(n)] ?? "") + if (name && !edges.some((o, j) => o.source === e.source && out[j] === name)) out[i] = name + } + return out +} + function howOfEdge(e: any, fromCol: string, to: string) { return howOf(e?.lens_type, e?.lens_code, fromCol, to) } diff --git a/packages/opencode/test/altimate/column-answer.test.ts b/packages/opencode/test/altimate/column-answer.test.ts index 8cbc27fa1e..9504f79dad 100644 --- a/packages/opencode/test/altimate/column-answer.test.ts +++ b/packages/opencode/test/altimate/column-answer.test.ts @@ -1444,6 +1444,59 @@ describe("both tools: names at the edges", () => { expect(Object.keys((folded.raw_lineage as any).column_dict ?? {}).sort()).toEqual(["id", "val", "val_1"]) }) + test("a _N written outside the SELECT lists is no alias: a table alias _1 adds no fake _1 column", () => { + for (const dialect of ["duckdb", "snowflake", "postgres"]) { + const path = write(nodes(dialect, [ + model("orders", [], "select 1 as order_id, 2.5 as amount", ["order_id", "amount"]), + model("r", ["orders"], `select _1.order_id, _1.amount * 2 from ${T("orders")} _1`), + model("child", ["r"], `select * from ${T("r")}`), + ])) + expect(carried(columnAnswer(path, "orders", "amount"))).not.toEqual(expect.arrayContaining(["r._1"])) + const lineage = dbtLineage({ manifest_path: path, model: "child" }) + expect(Object.keys((lineage.raw_lineage as any).column_dict ?? {})).not.toContain("_1") + } + }) + + test("a _col_N written outside the SELECT lists doesn't stop a cast from taking its column's name", () => { + for (const r of [`select id, amount::numeric from ${T("f")} as _col_1`, `select id, amount::numeric from ${T("f")} where _col_1 > 0`]) { + const path = write(nodes("postgres", [ + model("f", [], "select 1 as id, 2.5 as amount, 3 as _col_1", ["id", "amount", "_col_1"]), + model("r", ["f"], r), + ])) + expect(carried(columnAnswer(path, "f", "amount"))).toEqual(["r.amount"]) + } + }) + + test("a repeat beside a qualified or CTE-wrapped star doesn't settle, and a join that repeats nothing still does", () => { + for (const r of [`select f.*, val as id from ${T("f")} f`, `with q as (select *, val as id from ${T("f")}) select * from q`]) { + const path = write(nodes("duckdb", [ + model("f", [], "select 1 as id, 2 as val", ["id", "val"]), + model("r", ["f"], r), + model("child", ["r"], `select id_1 as x from ${T("r")}`), + ])) + expect(() => columnReach(path, "r", "id_1")).not.toThrow() + expect(() => columnAnswer(path, "r", "id_1")).not.toThrow() + } + // `o.*` brings no `name`, so `c.name` repeats nothing and the model's columns stay settled. + const join = write(nodes("duckdb", [ + model("orders", [], "select 1 as id, 2 as customer_id", ["id", "customer_id"]), + model("customers", [], "select 2 as customer_id, 'x' as name", ["customer_id", "name"]), + model("r", ["orders", "customers"], `select o.*, c.name from ${T("orders")} o join ${T("customers")} c on o.customer_id = c.customer_id`), + ])) + expect(() => columnReach(join, "r", "nope")).toThrow(/has no column nope/) + }) + + test("dbt_lineage names a model's own unaliased cast after its column on Postgres and Redshift, as column_answer does", () => { + for (const dialect of ["postgres", "redshift"]) { + const path = write(nodes(dialect, [ + model("orders", [], "select 1 as order_id, 2.5 as amount", ["order_id", "amount"]), + model("r", ["orders"], `select order_id, amount::numeric from ${T("orders")}`), + ])) + const lineage = dbtLineage({ manifest_path: path, model: "r" }) + expect(Object.keys((lineage.raw_lineage as any).column_dict ?? {}).sort()).toEqual(["amount", "order_id"]) + } + }) + test("the text line says how many may-carry models are only not traced, without suggesting no effect", () => { const path = write(nodes("duckdb", [ model("f", [], "select 1 as id, 2 as val", ["id", "val"]), From 41ddf14f131afba9776648e8493eaba16d699dd1 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 28 Nov 2026 19:58:52 +0800 Subject: [PATCH 2/9] fix: one SELECT-list reader; stars resolve to the parent they read - Upper-case keywords end a list; later UNION branches name nothing - A qualified star brings its parent's columns (quoted qualifiers too), so `o.*, o.id` and two stars sharing a column unsettle - dbt_lineage keeps a written `_1` beside a renamed cast, and `__proto__` Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvqLZuTJdDJ1Ku2ZMDY --- .../src/altimate/native/dbt/lineage.ts | 12 +- .../altimate/native/dbt/project-lineage.ts | 167 +++++++++++------- .../test/altimate/column-answer.test.ts | 64 ++++++- 3 files changed, 172 insertions(+), 71 deletions(-) diff --git a/packages/opencode/src/altimate/native/dbt/lineage.ts b/packages/opencode/src/altimate/native/dbt/lineage.ts index 3c7a250485..2ec34a6d60 100644 --- a/packages/opencode/src/altimate/native/dbt/lineage.ts +++ b/packages/opencode/src/altimate/native/dbt/lineage.ts @@ -23,13 +23,19 @@ function withWarehouseNames(lineage: Record, sql: string, dialect: const renamed = new Map() for (const [i, e] of edges.entries()) if (names[i] && names[i] !== e.to) renamed.set(e.to, names[i]!) if (!renamed.size) return lineage - // The `_N` twin of a renamed `_col_N` goes with it. - const dropped = new Set([...renamed.keys()].map((label) => `_${label.slice(5)}`)) + // The `_N` twin of a renamed `_col_N` goes with it, where `warehouseNames` drops every edge into it; a `_N` the SQL + // writes (`amount as _1`) keeps its edges there, and so stays. + const dropped = new Set( + [...renamed.keys()] + .map((label) => `_${label.slice(5)}`) + .filter((label) => edges.some((e) => e.to === label) && edges.every((e, i) => e.to !== label || names[i] === null)), + ) const target = (text: unknown) => (dropped.has(lower(text)) ? null : (renamed.get(lower(text)) ?? String(text))) const out: Record = { ...lineage } out.column_lineage = lineage.column_lineage.flatMap((e: any) => (target(e?.target) === null ? [] : [{ ...e, target: target(e?.target) }])) if (lineage.column_dict && typeof lineage.column_dict === "object") { - const dict: Record = {} + // No prototype, so an output named `__proto__` is an entry like any other. + const dict: Record = Object.create(null) for (const [key, sources] of Object.entries(lineage.column_dict)) { const name = target(key) if (name === null) continue diff --git a/packages/opencode/src/altimate/native/dbt/project-lineage.ts b/packages/opencode/src/altimate/native/dbt/project-lineage.ts index ab1a10be95..7b2c3a0f60 100644 --- a/packages/opencode/src/altimate/native/dbt/project-lineage.ts +++ b/packages/opencode/src/altimate/native/dbt/project-lineage.ts @@ -126,84 +126,94 @@ function namesItsOutputs(outputs: string[]): boolean { const QUOTED = '"(?:[^"]|"")*"|`[^`]*`|\\[[^\\]]*\\]' const unquoteName = (name: string) => name.replace(/^["`[]|["`\]]$/g, "").toLowerCase() +/** Literal- and comment-stripped SQL with each quoted name blanked whole, so `"from"` or `"a,b"` ends no item. */ +const blankQuoted = (stripped: string) => stripped.replace(new RegExp(QUOTED, "g"), (q) => " ".repeat(q.length)) + /** - * The items of the SQL's outermost SELECT list (the first one outside parentheses, so after any WITH), split at - * top-level commas, from literal- and comment-stripped SQL; [] when there is none. + * Where each `select` keyword starts in quote-blanked text, how deep in parentheses it sits, and whether it starts a + * later branch of a set operation (`… union all select …`), whose names the result doesn't take. */ -export function selectItems(stripped: string): string[] { - // A quoted name is blanked whole, so `"from"` or `"a,b"` ends no item. - const text = stripped.replace(new RegExp(QUOTED, "g"), (q) => " ".repeat(q.length)) +function selectKeywords(text: string): { at: number; depth: number; later: boolean }[] { + const found: { at: number; depth: number; later: boolean }[] = [] let depth = 0 - let start = -1 - const items: string[] = [] - let from = 0 for (let i = 0; i < text.length; i++) { const ch = text[i]! if (ch === "(") depth++ else if (ch === ")") depth-- - if (depth !== 0) continue - const word = /^[a-z_]+/i.exec(text.slice(i))?.[0]?.toLowerCase() - const boundary = i === 0 || !/[\w$]/.test(text[i - 1]!) - if (start < 0) { - if (boundary && word === "select") { - start = i + 6 - start += modifierLength(text, start) - from = start - i = start - 1 - } - continue + else if (/^select(?![\w$])/i.test(text.slice(i, i + 7)) && !/[\w$]/.test(text[i - 1] ?? " ")) { + const later = /(? one !== "") - } + } else if (!/[\w$]/.test(text[i - 1] ?? " ") && LIST_ENDS.test(/^[a-z_]+/i.exec(text.slice(i))?.[0] ?? "")) break } - if (start >= 0) items.push(stripped.slice(from).trim()) + items.push(stripped.slice(from, i).trim()) return items.filter((one) => one !== "") } +/** + * The items of the SQL's outermost SELECT list (the first one outside parentheses, so after any WITH), split at + * top-level commas, from literal- and comment-stripped SQL; [] when there is none. + */ +export function selectItems(stripped: string): string[] { + const text = blankQuoted(stripped) + const outer = selectKeywords(text).find((k) => k.depth === 0) + return outer ? listAt(text, stripped, outer.at) : [] +} + /** A SELECT item that is a bare column reference (`id`, `t.id`, `"T"."Id"`). */ const BARE_REF = new RegExp(`^(?:(?:${QUOTED}|[\\w$]+)\\.)*(?:${QUOTED}|[\\w$]+)$`) /** Words that end a SELECT list. */ -const LIST_ENDS = /^(?:from|into|where|union|intersect|except|group|order|limit|qualify|having|window)$/ +const LIST_ENDS = /^(?:from|into|where|union|intersect|except|group|order|limit|qualify|having|window)$/i /** - * The items of every SELECT list in literal- and comment-stripped SQL, in text order (so CTEs and subqueries before - * the outer list that reads them), each split at its own top-level commas. A list ends at a word that ends a SELECT - * list, or at the `)` that closes the parentheses it sits in. + * The items of every SELECT list that names outputs in literal- and comment-stripped SQL, in text order (so CTEs and + * subqueries before the outer list that reads them), each read as `selectItems` reads the outer one. A later branch of + * a set operation names nothing (the result takes the first branch's names), so it is left out. */ export function everySelectItems(stripped: string): string[][] { - const text = stripped.replace(new RegExp(QUOTED, "g"), (q) => " ".repeat(q.length)) - const lists: string[][] = [] - for (const m of text.matchAll(/(? one !== "")) - } - return lists + const text = blankQuoted(stripped) + return selectKeywords(text) + .filter((k) => !k.later) + .map((k) => listAt(text, stripped, k.at)) +} + +/** The relation a star's qualifier names, lower-cased (`f` for `f.*` or `"F".*`, `t` for `s.t.*`); "" for a bare `*`; null for no star. */ +export function starQualifier(item: string): string | null { + const m = new RegExp(`^((?:(?:${QUOTED}|[\\w$]+)\\.)*)\\*(?:\\s|$)`).exec(item) + if (!m) return null + const parts = [...m[1]!.matchAll(new RegExp(`(${QUOTED}|[\\w$]+)\\.`, "g"))].map((part) => unquoteName(part[1]!)) + return parts.at(-1) ?? "" } +/** Words that follow a relation in FROM or JOIN without being its alias. */ +const NOT_ALIAS = /^(?:join|left|right|inner|outer|full|cross|natural|lateral|on|using|where|group|order|limit|union|intersect|except|minus|qualify|having|window|sample|tablesample|pivot|unpivot)$/i + /** Words that end an expression (`x is null`, `case … end`) rather than alias it. */ const ENDS_EXPRESSION = /^(?:null|true|false|end)$/i /** Words after which the next word is an operand (`a and b`, `sum(x) over w`), not an alias. */ @@ -214,7 +224,7 @@ const TAKES_OPERAND = /^(?:and|or|not|is|in|like|ilike|rlike|regexp|similar|to|b * else null. */ export function itemName(item: string): string | null { - if (/^(?:[\w$]+\.)*\*(?:\s|$)/.test(item)) return "*" + if (starQualifier(item) !== null) return "*" const as = new RegExp(`\\s+as\\s+(${QUOTED}|[\\w$]+)$`, "i").exec(item) if (as) return unquoteName(as[1]!) const bare = new RegExp(`^(?:(?:${QUOTED}|[\\w$]+)\\.)*(${QUOTED}|[\\w$]+)$`).exec(item) @@ -856,10 +866,12 @@ export class ProjectLineage { } /** - * Whether a SELECT list with a star, the outer one or one in a CTE or subquery, names an output twice or gives an - * output a name the star brings in (`select *, val as id`, `select f.*, val as id`): the warehouse renames the - * repeat. A bare `*` brings every parent's columns. A qualified `t.*` brings a name when the model passes a column - * of that name on unchanged from more sources than the list's own bare references to it. + * Whether a SELECT list with a star, the outer one or one in a CTE or subquery, names an output twice or gives two + * outputs one name (`select *, val as id`, `select f.*, f.id`, `select o.*, c.*` over a shared column): the warehouse + * renames the repeat. A bare `*` brings every parent's columns; a qualified `t.*` brings the columns of the parent + * `t` names (the parent itself, or the relation an alias names in FROM or JOIN). A qualifier that names no parent (a + * CTE, a subquery) brings a name when the model passes a column of that name on unchanged from more sources than the + * list's own bare references to it. */ private renamesBesideStar(id: string, stripped: string): boolean { const parentColumns = new Set(this.parents(id).flatMap((p) => [...(this.settledColumns(p) ?? [])])) @@ -867,19 +879,46 @@ export class ProjectLineage { for (const e of this.lineage(id).edges) if (e.how === "=" && e.fromCol === e.to) unchanged.set(e.to, (unchanged.get(e.to) ?? new Set()).add(`${e.from}|${e.fromCol}`)) for (const items of everySelectItems(stripped)) { + const stars = items.map(starQualifier) + if (stars.every((star) => star === null)) continue const names = items.map(itemName) - if (!names.includes("*")) continue const explicit = names.filter((name): name is string => !!name && name !== "*") if (new Set(explicit).size !== explicit.length) return true - const bareStar = items.some((item) => /^\*(?:\s|$)/.test(item)) - for (const name of explicit) { - if (bareStar ? parentColumns.has(name) : (unchanged.get(name)?.size ?? 0) > items.filter((item, i) => names[i] === name && BARE_REF.test(item)).length) - return true - } + // What each star brings: every parent's columns, one parent's, or unknown. + const brought = stars.flatMap((star): (Set | undefined)[] => { + if (star === null) return [] + if (star === "") return [parentColumns] + const parent = this.qualifiedParent(id, star, stripped) + return [parent ? this.settledColumns(parent) : undefined] + }) + const known = brought.filter((set): set is Set => !!set) + if (explicit.some((name) => known.some((set) => set.has(name)))) return true + for (const [i, a] of known.entries()) for (const b of known.slice(i + 1)) for (const name of a) if (b.has(name)) return true + if (known.length < brought.length) + for (const name of explicit) + if ((unchanged.get(name)?.size ?? 0) > items.filter((item, i) => names[i] === name && BARE_REF.test(item)).length) return true } return false } + /** + * The parent a star's qualifier names, if one: a parent called that (its alias or name), or the relation that an + * alias names in FROM or JOIN (`from shop.main.orders o`). A qualifier that names no parent, or names two, gives none. + */ + private qualifiedParent(id: string, qualifier: string, stripped: string): string | undefined { + const byName = new Map(this.parents(id).map((p) => [String(this.node(p)?.alias || this.node(p)?.name || "").toLowerCase(), p])) + if (byName.has(qualifier)) return byName.get(qualifier) + const part = `(?:${QUOTED}|[\\w$]+)` + const relation = new RegExp(`(?() + for (const m of stripped.matchAll(relation)) { + if (NOT_ALIAS.test(m[2]!) || unquoteName(m[2]!) !== qualifier) continue + const last = [...m[1]!.matchAll(new RegExp(part, "g"))].at(-1)?.[0] ?? "" + named.add(unquoteName(last)) + } + return named.size === 1 ? byName.get([...named][0]!) : undefined + } + lineage(id: string): ModelLineage { const memo = this.lineageMemo.get(id) if (memo) return memo diff --git a/packages/opencode/test/altimate/column-answer.test.ts b/packages/opencode/test/altimate/column-answer.test.ts index 9504f79dad..fc5d9c4c2f 100644 --- a/packages/opencode/test/altimate/column-answer.test.ts +++ b/packages/opencode/test/altimate/column-answer.test.ts @@ -1445,10 +1445,11 @@ describe("both tools: names at the edges", () => { }) test("a _N written outside the SELECT lists is no alias: a table alias _1 adds no fake _1 column", () => { - for (const dialect of ["duckdb", "snowflake", "postgres"]) { - const path = write(nodes(dialect, [ + for (const [dialect, sql] of [["duckdb", "select _1.order_id, _1.amount * 2 from"], ["snowflake", "select _1.order_id, _1.amount * 2 from"], + ["postgres", "select _1.order_id, _1.amount * 2 from"], ["duckdb", "SELECT _1.order_id, _1.amount * 2 FROM"]]) { + const path = write(nodes(dialect!, [ model("orders", [], "select 1 as order_id, 2.5 as amount", ["order_id", "amount"]), - model("r", ["orders"], `select _1.order_id, _1.amount * 2 from ${T("orders")} _1`), + model("r", ["orders"], `${sql} ${T("orders")} _1`), model("child", ["r"], `select * from ${T("r")}`), ])) expect(carried(columnAnswer(path, "orders", "amount"))).not.toEqual(expect.arrayContaining(["r._1"])) @@ -1468,7 +1469,8 @@ describe("both tools: names at the edges", () => { }) test("a repeat beside a qualified or CTE-wrapped star doesn't settle, and a join that repeats nothing still does", () => { - for (const r of [`select f.*, val as id from ${T("f")} f`, `with q as (select *, val as id from ${T("f")}) select * from q`]) { + for (const r of [`select f.*, val as id from ${T("f")} f`, `with q as (select *, val as id from ${T("f")}) select * from q`, + `SELECT f.*, val AS id FROM ${T("f")} f`]) { const path = write(nodes("duckdb", [ model("f", [], "select 1 as id, 2 as val", ["id", "val"]), model("r", ["f"], r), @@ -1477,6 +1479,26 @@ describe("both tools: names at the edges", () => { expect(() => columnReach(path, "r", "id_1")).not.toThrow() expect(() => columnAnswer(path, "r", "id_1")).not.toThrow() } + // A star over one parent that resolves through its alias: a repeat of its own column, two stars that share a + // column, a quoted qualifier. + const two = (r: string, col: string) => { + const path = write(nodes("duckdb", [ + model("orders", [], "select 1 as id, 2 as customer_id", ["id", "customer_id"]), + model("customers", [], "select 2 as customer_id, 'x' as name", ["customer_id", "name"]), + model("r", ["orders", "customers"], r), + ])) + expect(() => columnReach(path, "r", col)).not.toThrow() + } + two(`select o.*, o.id from ${T("orders")} o`, "id_1") + two(`select o.*, c.* from ${T("orders")} o join ${T("customers")} c on o.customer_id = c.customer_id`, "customer_id_1") + two(`select "o".*, o.customer_id as id from ${T("orders")} "o"`, "id_1") + // A UNION's branches each name their own list: two stars in two branches repeat nothing. + const union = write(nodes("duckdb", [ + model("a", [], "select 1 as id", ["id"]), + model("b", [], "select 2 as id", ["id"]), + model("r", ["a", "b"], `select a.* from ${T("a")} a union all select b.* from ${T("b")} b`), + ])) + expect(() => columnReach(union, "r", "nope")).toThrow(/has no column nope/) // `o.*` brings no `name`, so `c.name` repeats nothing and the model's columns stay settled. const join = write(nodes("duckdb", [ model("orders", [], "select 1 as id, 2 as customer_id", ["id", "customer_id"]), @@ -1486,6 +1508,40 @@ describe("both tools: names at the edges", () => { expect(() => columnReach(join, "r", "nope")).toThrow(/has no column nope/) }) + test("an alias in a later UNION branch names no output, so the engine's _col_0 there stays an engine name", () => { + const path = write(nodes("duckdb", [ + model("a", [], "select 1 as id, 2.5 as amount", ["id", "amount"]), + model("b", [], "select 2 as id, 3.5 as amount", ["id", "amount"]), + model("r", ["a", "b"], `select amount * 2 from ${T("a")} union all select amount as _col_0 from ${T("b")}`), + model("child", ["r"], `select * from ${T("r")}`), + ])) + const lineage = dbtLineage({ manifest_path: path, model: "child" }) + expect(Object.keys((lineage.raw_lineage as any).column_dict ?? {})).not.toContain("_col_0") + }) + + test("a _N written in upper-case SQL is still a real alias", () => { + const path = write(nodes("duckdb", [ + model("f", [], "select 1 as id, 2.5 as amount", ["id", "amount"]), + model("r", ["f"], `SELECT id, amount AS _1 FROM ${T("f")}`), + model("child", ["r"], `select * from ${T("r")}`), + ])) + const lineage = dbtLineage({ manifest_path: path, model: "child" }) + expect(Object.keys((lineage.raw_lineage as any).column_dict ?? {}).sort()).toEqual(["_1", "id"]) + }) + + test("dbt_lineage keeps a written _1 beside a renamed cast, and an output named __proto__", () => { + const written = write(nodes("postgres", [ + model("orders", [], "select 1 as order_id, 2.5 as amount", ["order_id", "amount"]), + model("r", ["orders"], `select amount as _1, amount::numeric from ${T("orders")}`), + ])) + expect(Object.keys((dbtLineage({ manifest_path: written, model: "r" }).raw_lineage as any).column_dict ?? {}).sort()).toEqual(["_1", "amount"]) + const proto = write(nodes("postgres", [ + model("f", [], `select 1 as id, 2 as "__proto__"`, ["id", "__proto__"]), + model("r", ["f"], `select id, "__proto__"::numeric from ${T("f")}`), + ])) + expect(Object.keys((dbtLineage({ manifest_path: proto, model: "r" }).raw_lineage as any).column_dict ?? {}).sort()).toEqual(["__proto__", "id"]) + }) + test("dbt_lineage names a model's own unaliased cast after its column on Postgres and Redshift, as column_answer does", () => { for (const dialect of ["postgres", "redshift"]) { const path = write(nodes(dialect, [ From 6dd5e89d088a3fce81c947c3e7d6a5f31bbbc540 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 28 Nov 2026 20:22:17 +0800 Subject: [PATCH 3/9] fix: an alias hides a parent of the same name when a star is resolved `from customers orders` makes `orders.*` read customers, as in SQL. The select-keyword scan no longer copies text per character. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvqLZuTJdDJ1Ku2ZMDY --- .../src/altimate/native/dbt/project-lineage.ts | 14 ++++++++------ .../opencode/test/altimate/column-answer.test.ts | 2 ++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/opencode/src/altimate/native/dbt/project-lineage.ts b/packages/opencode/src/altimate/native/dbt/project-lineage.ts index 7b2c3a0f60..9f75521a93 100644 --- a/packages/opencode/src/altimate/native/dbt/project-lineage.ts +++ b/packages/opencode/src/altimate/native/dbt/project-lineage.ts @@ -140,8 +140,9 @@ function selectKeywords(text: string): { at: number; depth: number; later: boole const ch = text[i]! if (ch === "(") depth++ else if (ch === ")") depth-- - else if (/^select(?![\w$])/i.test(text.slice(i, i + 7)) && !/[\w$]/.test(text[i - 1] ?? " ")) { - const later = /(? [String(this.node(p)?.alias || this.node(p)?.name || "").toLowerCase(), p])) - if (byName.has(qualifier)) return byName.get(qualifier) const part = `(?:${QUOTED}|[\\w$]+)` const relation = new RegExp(`(?() @@ -916,7 +917,8 @@ export class ProjectLineage { const last = [...m[1]!.matchAll(new RegExp(part, "g"))].at(-1)?.[0] ?? "" named.add(unquoteName(last)) } - return named.size === 1 ? byName.get([...named][0]!) : undefined + if (named.size) return named.size === 1 ? byName.get([...named][0]!) : undefined + return byName.get(qualifier) } lineage(id: string): ModelLineage { diff --git a/packages/opencode/test/altimate/column-answer.test.ts b/packages/opencode/test/altimate/column-answer.test.ts index fc5d9c4c2f..16a5697b8f 100644 --- a/packages/opencode/test/altimate/column-answer.test.ts +++ b/packages/opencode/test/altimate/column-answer.test.ts @@ -1492,6 +1492,8 @@ describe("both tools: names at the edges", () => { two(`select o.*, o.id from ${T("orders")} o`, "id_1") two(`select o.*, c.* from ${T("orders")} o join ${T("customers")} c on o.customer_id = c.customer_id`, "customer_id_1") two(`select "o".*, o.customer_id as id from ${T("orders")} "o"`, "id_1") + // An alias hides a parent of the same name: `customers` is aliased `orders` here, so `orders.*` reads customers. + two(`select orders.*, 1 as name from ${T("customers")} orders join ${T("orders")} o2 on orders.customer_id = o2.customer_id`, "name_1") // A UNION's branches each name their own list: two stars in two branches repeat nothing. const union = write(nodes("duckdb", [ model("a", [], "select 1 as id", ["id"]), From a363aa0fc0705d8e779602218eee43fb866738e5 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 28 Nov 2026 20:29:26 +0800 Subject: [PATCH 4/9] fix: a star names one parent by schema; any indent before a UNION branch - Two parents of one name in different schemas stay apart: the relation's schema and database pick the one a star reads - The set operator before a branch is found however far indentation puts it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvqLZuTJdDJ1Ku2ZMDY --- .../altimate/native/dbt/project-lineage.ts | 37 +++++++++++++++---- .../test/altimate/column-answer.test.ts | 17 +++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/packages/opencode/src/altimate/native/dbt/project-lineage.ts b/packages/opencode/src/altimate/native/dbt/project-lineage.ts index 9f75521a93..0d8663853d 100644 --- a/packages/opencode/src/altimate/native/dbt/project-lineage.ts +++ b/packages/opencode/src/altimate/native/dbt/project-lineage.ts @@ -129,6 +129,15 @@ const unquoteName = (name: string) => name.replace(/^["`[]|["`\]]$/g, "").toLowe /** Literal- and comment-stripped SQL with each quoted name blanked whole, so `"from"` or `"a,b"` ends no item. */ const blankQuoted = (stripped: string) => stripped.replace(new RegExp(QUOTED, "g"), (q) => " ".repeat(q.length)) +/** The word that ends before `end` in quote-blanked text, past whitespace and `(`, and where it starts. */ +function wordBefore(text: string, end: number): { word: string; start: number } { + let j = end - 1 + while (j >= 0 && /[\s(]/.test(text[j]!)) j-- + let k = j + while (k >= 0 && /[\w$]/.test(text[k]!)) k-- + return { word: text.slice(k + 1, j + 1), start: k + 1 } +} + /** * Where each `select` keyword starts in quote-blanked text, how deep in parentheses it sits, and whether it starts a * later branch of a set operation (`… union all select …`), whose names the result doesn't take. @@ -141,8 +150,10 @@ function selectKeywords(text: string): { at: number; depth: number; later: boole if (ch === "(") depth++ else if (ch === ")") depth-- else if ((ch === "s" || ch === "S") && /^select(?![\w$])/i.test(text.slice(i, i + 7)) && !/[\w$]/.test(text[i - 1] ?? " ")) { - // The set operator sits just before: `union all (select …`, so a short look back is enough. - const later = /(? [String(this.node(p)?.alias || this.node(p)?.name || "").toLowerCase(), p])) const part = `(?:${QUOTED}|[\\w$]+)` + // The one parent a relation's parts name: its own name last, then its schema and database where written; two + // parents of one name in different schemas stay apart. + const parentOf = (parts: string[]): string | undefined => { + const [name, schema, database] = [...parts].reverse() + const lower = (value: unknown) => String(value ?? "").toLowerCase() + const found = this.parents(id).filter((p) => { + const n = this.node(p) + return lower(n?.alias || n?.name) === name && (!schema || lower(n?.schema) === schema) && (!database || lower(n?.database) === database) + }) + return found.length === 1 ? found[0] : undefined + } const relation = new RegExp(`(?() + const aliased = new Map() for (const m of stripped.matchAll(relation)) { if (NOT_ALIAS.test(m[2]!) || unquoteName(m[2]!) !== qualifier) continue - const last = [...m[1]!.matchAll(new RegExp(part, "g"))].at(-1)?.[0] ?? "" - named.add(unquoteName(last)) + const parts = [...m[1]!.matchAll(new RegExp(part, "g"))].map((p) => unquoteName(p[0])) + aliased.set(parts.join("\0"), parts) } - if (named.size) return named.size === 1 ? byName.get([...named][0]!) : undefined - return byName.get(qualifier) + if (aliased.size) return aliased.size === 1 ? parentOf([...aliased.values()][0]!) : undefined + return parentOf([qualifier]) } lineage(id: string): ModelLineage { diff --git a/packages/opencode/test/altimate/column-answer.test.ts b/packages/opencode/test/altimate/column-answer.test.ts index 16a5697b8f..b3737c00dc 100644 --- a/packages/opencode/test/altimate/column-answer.test.ts +++ b/packages/opencode/test/altimate/column-answer.test.ts @@ -1494,6 +1494,15 @@ describe("both tools: names at the edges", () => { two(`select "o".*, o.customer_id as id from ${T("orders")} "o"`, "id_1") // An alias hides a parent of the same name: `customers` is aliased `orders` here, so `orders.*` reads customers. two(`select orders.*, 1 as name from ${T("customers")} orders join ${T("orders")} o2 on orders.customer_id = o2.customer_id`, "name_1") + // Two parents of one name in different schemas: the relation's schema says which one the star reads, in either order. + for (const order of [["one_shared", "two_shared"], ["two_shared", "one_shared"]]) { + const path = write(nodes("duckdb", [ + model("one_shared", [], "select 1 as id", ["id"], { alias: "shared", schema: "one" }), + model("two_shared", [], "select 2 as other", ["other"], { alias: "shared", schema: "two" }), + model("r", order, `select f.*, f.id from "shop"."one"."shared" f cross join "shop"."two"."shared" g`), + ])) + expect(() => columnReach(path, "r", "id_1")).not.toThrow() + } // A UNION's branches each name their own list: two stars in two branches repeat nothing. const union = write(nodes("duckdb", [ model("a", [], "select 1 as id", ["id"]), @@ -1519,6 +1528,14 @@ describe("both tools: names at the edges", () => { ])) const lineage = dbtLineage({ manifest_path: path, model: "child" }) expect(Object.keys((lineage.raw_lineage as any).column_dict ?? {})).not.toContain("_col_0") + // However far indentation puts the operator from the branch's SELECT. + const indented = write(nodes("duckdb", [ + model("a", [], "select 1 as id, 2.5 as amount", ["id", "amount"]), + model("b", [], "select 2 as id, 3.5 as amount", ["id", "amount"]), + model("r", ["a", "b"], `select amount * 2 from ${T("a")} union all\n${" ".repeat(60)}(\n${" ".repeat(60)}select amount as _col_0 from ${T("b")})`), + model("child", ["r"], `select * from ${T("r")}`), + ])) + expect(Object.keys((dbtLineage({ manifest_path: indented, model: "child" }).raw_lineage as any).column_dict ?? {})).not.toContain("_col_0") }) test("a _N written in upper-case SQL is still a real alias", () => { From b34413cdb622472385e0704ac0e0e7ec5b3afec1 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 28 Nov 2026 20:34:27 +0800 Subject: [PATCH 5/9] fix: a star's qualifier resolves in its own SELECT's FROM clause An alias inside a CTE or subquery no longer reaches an outer `t.*`, so a model that repeats nothing stays settled. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvqLZuTJdDJ1Ku2ZMDY --- .../altimate/native/dbt/project-lineage.ts | 54 +++++++++++++++---- .../test/altimate/column-answer.test.ts | 7 +++ 2 files changed, 50 insertions(+), 11 deletions(-) diff --git a/packages/opencode/src/altimate/native/dbt/project-lineage.ts b/packages/opencode/src/altimate/native/dbt/project-lineage.ts index 0d8663853d..da77482276 100644 --- a/packages/opencode/src/altimate/native/dbt/project-lineage.ts +++ b/packages/opencode/src/altimate/native/dbt/project-lineage.ts @@ -164,7 +164,7 @@ function selectKeywords(text: string): { at: number; depth: number; later: boole * The items of the SELECT list whose `select` starts at `at` in quote-blanked text, split at its own top-level commas. * The list ends at a word that ends a SELECT list, in any case, or at the `)` that closes the parentheses around it. */ -function listAt(text: string, stripped: string, at: number): string[] { +function listAt(text: string, stripped: string, at: number): { items: string[]; end: number } { const start = at + 6 + modifierLength(text, at + 6) const items: string[] = [] let from = start @@ -184,7 +184,30 @@ function listAt(text: string, stripped: string, at: number): string[] { } else if (!/[\w$]/.test(text[i - 1] ?? " ") && LIST_ENDS.test(/^[a-z_]+/i.exec(text.slice(i))?.[0] ?? "")) break } items.push(stripped.slice(from, i).trim()) - return items.filter((one) => one !== "") + return { items: items.filter((one) => one !== ""), end: i } +} + +/** Words that end a FROM clause. */ +const FROM_ENDS = /^(?:where|group|order|limit|qualify|having|window|union|intersect|except|minus)$/i + +/** + * The FROM clause that follows a SELECT list ending at `end`, from literal- and comment-stripped SQL, with anything + * inside its parentheses (a subquery, a function's arguments) blanked, so only this SELECT's own relations and + * aliases show; "" when none follows. + */ +function fromClauseAt(text: string, stripped: string, end: number): string { + if (!/^from(?![\w$])/i.test(text.slice(end, end + 5))) return "" + let out = "" + let depth = 0 + for (let i = end; i < text.length; i++) { + const ch = text[i]! + if (ch === ")" && depth === 0) break + if (depth === 0 && !/[\w$]/.test(text[i - 1] ?? " ") && FROM_ENDS.test(/^[a-z_]+/i.exec(text.slice(i))?.[0] ?? "")) break + if (ch === "(") depth++ + out += depth > 0 ? " " : stripped[i] + if (ch === ")") depth-- + } + return out } /** @@ -194,7 +217,7 @@ function listAt(text: string, stripped: string, at: number): string[] { export function selectItems(stripped: string): string[] { const text = blankQuoted(stripped) const outer = selectKeywords(text).find((k) => k.depth === 0) - return outer ? listAt(text, stripped, outer.at) : [] + return outer ? listAt(text, stripped, outer.at).items : [] } /** A SELECT item that is a bare column reference (`id`, `t.id`, `"T"."Id"`). */ @@ -209,10 +232,18 @@ const LIST_ENDS = /^(?:from|into|where|union|intersect|except|group|order|limit| * a set operation names nothing (the result takes the first branch's names), so it is left out. */ export function everySelectItems(stripped: string): string[][] { + return everySelectList(stripped).map((list) => list.items) +} + +/** Each SELECT list `everySelectItems` reads, with the FROM clause of its own SELECT (`fromClauseAt`). */ +function everySelectList(stripped: string): { items: string[]; from: string }[] { const text = blankQuoted(stripped) return selectKeywords(text) .filter((k) => !k.later) - .map((k) => listAt(text, stripped, k.at)) + .map((k) => { + const list = listAt(text, stripped, k.at) + return { items: list.items, from: fromClauseAt(text, stripped, list.end) } + }) } /** The relation a star's qualifier names, lower-cased (`f` for `f.*` or `"F".*`, `t` for `s.t.*`); "" for a bare `*`; null for no star. */ @@ -890,7 +921,7 @@ export class ProjectLineage { const unchanged = new Map>() for (const e of this.lineage(id).edges) if (e.how === "=" && e.fromCol === e.to) unchanged.set(e.to, (unchanged.get(e.to) ?? new Set()).add(`${e.from}|${e.fromCol}`)) - for (const items of everySelectItems(stripped)) { + for (const { items, from } of everySelectList(stripped)) { const stars = items.map(starQualifier) if (stars.every((star) => star === null)) continue const names = items.map(itemName) @@ -900,7 +931,7 @@ export class ProjectLineage { const brought = stars.flatMap((star): (Set | undefined)[] => { if (star === null) return [] if (star === "") return [parentColumns] - const parent = this.qualifiedParent(id, star, stripped) + const parent = this.qualifiedParent(id, star, from) return [parent ? this.settledColumns(parent) : undefined] }) const known = brought.filter((set): set is Set => !!set) @@ -914,11 +945,12 @@ export class ProjectLineage { } /** - * The parent a star's qualifier names, if one. An alias in FROM or JOIN names its relation (`from shop.main.orders o`) - * and hides a table of the same name, as in SQL; with no such alias, a parent called that (its alias or name). A - * qualifier whose alias names two relations, or names no parent, gives none. + * The parent a star's qualifier names, if one, read in the FROM clause of the star's own SELECT. An alias there in + * FROM or JOIN names its relation (`from shop.main.orders o`) and hides a table of the same name, as in SQL; with no + * such alias, a parent called that (its alias or name). A qualifier whose alias names two relations, or names no + * parent, gives none. */ - private qualifiedParent(id: string, qualifier: string, stripped: string): string | undefined { + private qualifiedParent(id: string, qualifier: string, scope: string): string | undefined { const part = `(?:${QUOTED}|[\\w$]+)` // The one parent a relation's parts name: its own name last, then its schema and database where written; two // parents of one name in different schemas stay apart. @@ -933,7 +965,7 @@ export class ProjectLineage { } const relation = new RegExp(`(?() - for (const m of stripped.matchAll(relation)) { + for (const m of scope.matchAll(relation)) { if (NOT_ALIAS.test(m[2]!) || unquoteName(m[2]!) !== qualifier) continue const parts = [...m[1]!.matchAll(new RegExp(part, "g"))].map((p) => unquoteName(p[0])) aliased.set(parts.join("\0"), parts) diff --git a/packages/opencode/test/altimate/column-answer.test.ts b/packages/opencode/test/altimate/column-answer.test.ts index b3737c00dc..738cf3d663 100644 --- a/packages/opencode/test/altimate/column-answer.test.ts +++ b/packages/opencode/test/altimate/column-answer.test.ts @@ -1503,6 +1503,13 @@ describe("both tools: names at the edges", () => { ])) expect(() => columnReach(path, "r", "id_1")).not.toThrow() } + // An alias resolves in the star's own SELECT: a CTE's alias `orders` for customers doesn't reach the outer `orders.*`. + const scoped = write(nodes("duckdb", [ + model("orders", [], "select 1 as id, 2 as customer_id", ["id", "customer_id"]), + model("customers", [], "select 2 as customer_id, 'x' as name", ["customer_id", "name"]), + model("r", ["orders", "customers"], `with x as (select orders.customer_id from ${T("customers")} orders) select orders.*, 1 as name from ${T("orders")} cross join x`), + ])) + expect(() => columnReach(scoped, "r", "nope")).toThrow(/has no column nope/) // A UNION's branches each name their own list: two stars in two branches repeat nothing. const union = write(nodes("duckdb", [ model("a", [], "select 1 as id", ["id"]), From 60e917b77a2edf805d6377b591f0bea7431f8128 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 28 Nov 2026 20:38:36 +0800 Subject: [PATCH 6/9] test: the UNION branch tests prove the lineage worked Each asserts no engine error and a listed `id` before checking that the later branch's `_col_1` is absent. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvqLZuTJdDJ1Ku2ZMDY --- .../test/altimate/column-answer.test.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/packages/opencode/test/altimate/column-answer.test.ts b/packages/opencode/test/altimate/column-answer.test.ts index 738cf3d663..4704bd7f59 100644 --- a/packages/opencode/test/altimate/column-answer.test.ts +++ b/packages/opencode/test/altimate/column-answer.test.ts @@ -1526,23 +1526,30 @@ describe("both tools: names at the edges", () => { expect(() => columnReach(join, "r", "nope")).toThrow(/has no column nope/) }) - test("an alias in a later UNION branch names no output, so the engine's _col_0 there stays an engine name", () => { + test("an alias in a later UNION branch names no output, so the engine's _col_1 there stays an engine name", () => { const path = write(nodes("duckdb", [ model("a", [], "select 1 as id, 2.5 as amount", ["id", "amount"]), model("b", [], "select 2 as id, 3.5 as amount", ["id", "amount"]), - model("r", ["a", "b"], `select amount * 2 from ${T("a")} union all select amount as _col_0 from ${T("b")}`), + model("r", ["a", "b"], `select id, amount * 2 from ${T("a")} union all select id, amount as _col_1 from ${T("b")}`), model("child", ["r"], `select * from ${T("r")}`), ])) - const lineage = dbtLineage({ manifest_path: path, model: "child" }) - expect(Object.keys((lineage.raw_lineage as any).column_dict ?? {})).not.toContain("_col_0") + // The lineage must have worked: the child lists `id`, and no engine error stands in for an empty answer. + const listed = (manifest: string) => { + const raw = dbtLineage({ manifest_path: manifest, model: "child" }).raw_lineage as any + expect(raw.error).toBeUndefined() + return Object.keys(raw.column_dict ?? {}) + } + expect(listed(path)).toContain("id") + expect(listed(path)).not.toContain("_col_1") // However far indentation puts the operator from the branch's SELECT. const indented = write(nodes("duckdb", [ model("a", [], "select 1 as id, 2.5 as amount", ["id", "amount"]), model("b", [], "select 2 as id, 3.5 as amount", ["id", "amount"]), - model("r", ["a", "b"], `select amount * 2 from ${T("a")} union all\n${" ".repeat(60)}(\n${" ".repeat(60)}select amount as _col_0 from ${T("b")})`), + model("r", ["a", "b"], `select id, amount * 2 from ${T("a")} union all\n${" ".repeat(60)}(\n${" ".repeat(60)}select id, amount as _col_1 from ${T("b")})`), model("child", ["r"], `select * from ${T("r")}`), ])) - expect(Object.keys((dbtLineage({ manifest_path: indented, model: "child" }).raw_lineage as any).column_dict ?? {})).not.toContain("_col_0") + expect(listed(indented)).toContain("id") + expect(listed(indented)).not.toContain("_col_1") }) test("a _N written in upper-case SQL is still a real alias", () => { From e4bf03fed8463f249668b7078aadd9b32737d068 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 28 Nov 2026 20:49:03 +0800 Subject: [PATCH 7/9] fix: end words are whole names, read in place - `order1` and `group1` end no SELECT list or FROM clause - Words are read with a sticky regex, so a long FROM clause isn't copied per character - `offset`, `fetch`, `connect` and `start` end a FROM clause Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvqLZuTJdDJ1Ku2ZMDY --- .../altimate/native/dbt/project-lineage.ts | 20 +++++++++++++++---- .../test/altimate/column-answer.test.ts | 17 ++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/packages/opencode/src/altimate/native/dbt/project-lineage.ts b/packages/opencode/src/altimate/native/dbt/project-lineage.ts index da77482276..a914ceaf6f 100644 --- a/packages/opencode/src/altimate/native/dbt/project-lineage.ts +++ b/packages/opencode/src/altimate/native/dbt/project-lineage.ts @@ -181,14 +181,26 @@ function listAt(text: string, stripped: string, at: number): { items: string[]; if (ch === ",") { items.push(stripped.slice(from, i).trim()) from = i + 1 - } else if (!/[\w$]/.test(text[i - 1] ?? " ") && LIST_ENDS.test(/^[a-z_]+/i.exec(text.slice(i))?.[0] ?? "")) break + } else if (LIST_ENDS.test(wordAt(text, i))) break } items.push(stripped.slice(from, i).trim()) return { items: items.filter((one) => one !== ""), end: i } } -/** Words that end a FROM clause. */ -const FROM_ENDS = /^(?:where|group|order|limit|qualify|having|window|union|intersect|except|minus)$/i +/** + * Words that end a FROM clause. (`relationUse`'s list is another set: words that aren't a relation's name, such as + * `join` and `on`, which sit inside a FROM clause.) + */ +const FROM_ENDS = /^(?:where|group|order|limit|offset|fetch|qualify|having|window|connect|start|union|intersect|except|minus)$/i + +const WORD = /[\w$]+/y + +/** The whole name that starts at `i` in quote-blanked text, read in place (no copy of the rest); "" when none starts there. */ +function wordAt(text: string, i: number): string { + if (/[\w$]/.test(text[i - 1] ?? " ")) return "" + WORD.lastIndex = i + return WORD.exec(text)?.[0] ?? "" +} /** * The FROM clause that follows a SELECT list ending at `end`, from literal- and comment-stripped SQL, with anything @@ -202,7 +214,7 @@ function fromClauseAt(text: string, stripped: string, end: number): string { for (let i = end; i < text.length; i++) { const ch = text[i]! if (ch === ")" && depth === 0) break - if (depth === 0 && !/[\w$]/.test(text[i - 1] ?? " ") && FROM_ENDS.test(/^[a-z_]+/i.exec(text.slice(i))?.[0] ?? "")) break + if (depth === 0 && FROM_ENDS.test(wordAt(text, i))) break if (ch === "(") depth++ out += depth > 0 ? " " : stripped[i] if (ch === ")") depth-- diff --git a/packages/opencode/test/altimate/column-answer.test.ts b/packages/opencode/test/altimate/column-answer.test.ts index 4704bd7f59..22aedb96bb 100644 --- a/packages/opencode/test/altimate/column-answer.test.ts +++ b/packages/opencode/test/altimate/column-answer.test.ts @@ -1510,6 +1510,13 @@ describe("both tools: names at the edges", () => { model("r", ["orders", "customers"], `with x as (select orders.customer_id from ${T("customers")} orders) select orders.*, 1 as name from ${T("orders")} cross join x`), ])) expect(() => columnReach(scoped, "r", "nope")).toThrow(/has no column nope/) + // A name that starts like an end word (`group1`) is a whole name: it ends no FROM clause, so the alias after it holds. + const words = write(nodes("duckdb", [ + model("orders", [], "select 1 as id", ["id"]), + model("group1", [], "select 2 as id, 'x' as name", ["id", "name"]), + model("r", ["orders", "group1"], `select orders.*, 1 as name from ${T("group1")} orders cross join ${T("orders")} o`), + ])) + expect(() => columnReach(words, "r", "name_1")).not.toThrow() // A UNION's branches each name their own list: two stars in two branches repeat nothing. const union = write(nodes("duckdb", [ model("a", [], "select 1 as id", ["id"]), @@ -1552,6 +1559,16 @@ describe("both tools: names at the edges", () => { expect(listed(indented)).not.toContain("_col_1") }) + test("a column that starts like an end word (order1) doesn't end the SELECT list before a written _1", () => { + const path = write(nodes("duckdb", [ + model("f", [], "select 1 as order1, 2.5 as amount", ["order1", "amount"]), + model("r", ["f"], `select order1, amount as _1 from ${T("f")}`), + model("child", ["r"], `select * from ${T("r")}`), + ])) + const raw = dbtLineage({ manifest_path: path, model: "child" }).raw_lineage as any + expect(Object.keys(raw.column_dict ?? {}).sort()).toEqual(["_1", "order1"]) + }) + test("a _N written in upper-case SQL is still a real alias", () => { const path = write(nodes("duckdb", [ model("f", [], "select 1 as id, 2.5 as amount", ["id", "amount"]), From 2f78bd95910c32a815fee819b2c3f80584a1cc92 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 28 Nov 2026 20:56:20 +0800 Subject: [PATCH 8/9] fix: words that can be an alias don't end a FROM clause Drops `offset`, `fetch`, `connect` and `start` from the FROM end words again: `from orders as start` keeps its alias. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvqLZuTJdDJ1Ku2ZMDY --- .../opencode/src/altimate/native/dbt/project-lineage.ts | 5 +++-- packages/opencode/test/altimate/column-answer.test.ts | 7 +++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/native/dbt/project-lineage.ts b/packages/opencode/src/altimate/native/dbt/project-lineage.ts index a914ceaf6f..971a0b8f41 100644 --- a/packages/opencode/src/altimate/native/dbt/project-lineage.ts +++ b/packages/opencode/src/altimate/native/dbt/project-lineage.ts @@ -189,9 +189,10 @@ function listAt(text: string, stripped: string, at: number): { items: string[]; /** * Words that end a FROM clause. (`relationUse`'s list is another set: words that aren't a relation's name, such as - * `join` and `on`, which sit inside a FROM clause.) + * `join` and `on`, which sit inside a FROM clause.) Words that can also be an alias (`offset`, `start`) are left out: + * running on past `offset 5` reads no alias, and cutting a FROM clause at an alias would lose it. */ -const FROM_ENDS = /^(?:where|group|order|limit|offset|fetch|qualify|having|window|connect|start|union|intersect|except|minus)$/i +const FROM_ENDS = /^(?:where|group|order|limit|qualify|having|window|union|intersect|except|minus)$/i const WORD = /[\w$]+/y diff --git a/packages/opencode/test/altimate/column-answer.test.ts b/packages/opencode/test/altimate/column-answer.test.ts index 22aedb96bb..0c239d8669 100644 --- a/packages/opencode/test/altimate/column-answer.test.ts +++ b/packages/opencode/test/altimate/column-answer.test.ts @@ -1517,6 +1517,13 @@ describe("both tools: names at the edges", () => { model("r", ["orders", "group1"], `select orders.*, 1 as name from ${T("group1")} orders cross join ${T("orders")} o`), ])) expect(() => columnReach(words, "r", "name_1")).not.toThrow() + // An alias that is also a clause word in some dialect (`start`, `offset`) still names its relation. + const aliasWords = write(nodes("duckdb", [ + model("orders", [], "select 1 as id", ["id"]), + model("group1", [], "select 2 as id, 'x' as name", ["id", "name"]), + model("r", ["orders", "group1"], `select start.*, 1 as name from ${T("group1")} as start cross join ${T("orders")} o`), + ])) + expect(() => columnReach(aliasWords, "r", "name_1")).not.toThrow() // A UNION's branches each name their own list: two stars in two branches repeat nothing. const union = write(nodes("duckdb", [ model("a", [], "select 1 as id", ["id"]), From 7226572e6738b1c631f8ec72b6fc8fe89c49d971 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Sat, 28 Nov 2026 20:58:54 +0800 Subject: [PATCH 9/9] test: the alias-word case uses a repeat the edge fallback misses `select start.*, start.name from group1 as start` fails without the revert; the earlier form passed either way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BXxzvqLZuTJdDJ1Ku2ZMDY --- packages/opencode/test/altimate/column-answer.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opencode/test/altimate/column-answer.test.ts b/packages/opencode/test/altimate/column-answer.test.ts index 0c239d8669..e1060ca57f 100644 --- a/packages/opencode/test/altimate/column-answer.test.ts +++ b/packages/opencode/test/altimate/column-answer.test.ts @@ -1521,7 +1521,7 @@ describe("both tools: names at the edges", () => { const aliasWords = write(nodes("duckdb", [ model("orders", [], "select 1 as id", ["id"]), model("group1", [], "select 2 as id, 'x' as name", ["id", "name"]), - model("r", ["orders", "group1"], `select start.*, 1 as name from ${T("group1")} as start cross join ${T("orders")} o`), + model("r", ["orders", "group1"], `select start.*, start.name from ${T("group1")} as start cross join ${T("orders")} o`), ])) expect(() => columnReach(aliasWords, "r", "name_1")).not.toThrow() // A UNION's branches each name their own list: two stars in two branches repeat nothing.