Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/dbt-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"test:e2e": "bun test test/e2e/ --timeout 300000"
},
"dependencies": {
"@altimateai/dbt-integration": "^0.3.20"
"@altimateai/dbt-integration": "^0.3.21"
},
"devDependencies": {
"@tsconfig/bun": "catalog:",
Expand Down
25 changes: 19 additions & 6 deletions packages/dbt-tools/src/check.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { existsSync } from "fs"
import { execFileSync } from "child_process"
import { join } from "path"
import { isAbsolute, join } from "path"
import type { Config } from "./config"

type Status = { ok: true } | { ok: false; error: string; fix: string }
Expand Down Expand Up @@ -53,21 +53,34 @@ export const fusionBinary = {
find: async (options: FusionLookup) => (await import("@altimateai/dbt-integration")).findDbtV2Binary(options),
}

async function fusion(cfg: Config): Promise<Status> {
/**
* Where dbt-integration's lookup looks for a dbt 2.x binary, as a phrase. Next to the interpreter only
* when `pythonPath` is a path: the lookup's interpreter-adjacent candidate skips a bare command name
* such as `python3`, which carries no directory.
*/
export function fusionPlaces(pythonPath?: string): string {
const adjacent = !!pythonPath && (isAbsolute(pythonPath) || /[\\/]/.test(pythonPath))
return `${adjacent ? `next to ${pythonPath}, ` : ""}in ~/.local/bin or on PATH`
}

/** The dbt Fusion binary for a config, found as the adapter finds the one it runs; undefined when there is none. */
export function findFusion(cfg: { pythonPath?: string; projectRoot?: string }) {
// Judge candidates as the adapter does: it runs any `dbt` whose `--version` reports 2.x,
// script launchers (asdf, nix and company wrappers) included, and allows 15 s for it.
const binary = await fusionBinary.find({
return fusionBinary.find({
pythonPath: cfg.pythonPath || undefined,
cwd: cfg.projectRoot || undefined,
env: process.env,
skipScripts: false,
timeoutMs: 15_000,
})
if (binary) return { ok: true }
const nextTo = cfg.pythonPath ? `next to ${cfg.pythonPath}, ` : ""
}

async function fusion(cfg: Config): Promise<Status> {
if (await findFusion(cfg)) return { ok: true }
return {
ok: false,
error: `dbt Fusion was not found: no dbt 2.x binary ${nextTo}in ~/.local/bin or on PATH`,
error: `dbt Fusion was not found: no dbt 2.x binary ${fusionPlaces(cfg.pythonPath)}`,
fix: "Install dbt Fusion so that `dbt --version` reports 2.x, or set dbtIntegration to core in the altimate-dbt config",
}
}
Expand Down
28 changes: 21 additions & 7 deletions packages/dbt-tools/src/dbt-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export interface DbtCliOptions {
pythonPath?: string
/** dbt project root directory (used as cwd). */
projectRoot?: string
/** The config's dbt-integration mode. In `fusion` the fallbacks run the dbt Fusion binary the adapter runs. */
dbtIntegration?: string
}

/** Module-level options, set once via `configure()`. */
Expand All @@ -44,11 +46,23 @@ export function configure(opts: DbtCliOptions): void {
}

/** Get or resolve the dbt binary path. */
function getDbt(): ResolvedDbt {
if (!resolvedDbt) {
resolvedDbt = resolveDbt(globalOptions.pythonPath, globalOptions.projectRoot)
}
return resolvedDbt
async function getDbt(): Promise<ResolvedDbt> {
if (resolvedDbt) return resolvedDbt
const options = globalOptions
// In dbt Fusion mode, the Fusion binary the prerequisite check and the adapter pick: resolveDbt takes
// the first `dbt` it finds, which can be dbt Core or the dbt Cloud CLI.
const resolved =
options.dbtIntegration === "fusion" ? await fusionDbt(options) : resolveDbt(options.pythonPath, options.projectRoot)
// A configure() while the lookup ran owns the cache now.
if (globalOptions === options) resolvedDbt = resolved
return resolved
}

async function fusionDbt(options: DbtCliOptions): Promise<ResolvedDbt> {
const { findFusion, fusionPlaces } = await import("./check")
const binary = await findFusion(options)
if (!binary) throw new Error(`dbt Fusion was not found: no dbt 2.x binary ${fusionPlaces(options.pythonPath)}`)
return { path: binary.path, source: `dbt Fusion (${binary.location})` }
}

/** Shape of an execFile rejection — carries stdout/stderr alongside message. */
Expand All @@ -65,8 +79,8 @@ function toExecFileError(e: unknown): ExecFileError {
return new Error(String(e)) as ExecFileError
}

function run(args: string[]): Promise<{ stdout: string; stderr: string }> {
const dbt = getDbt()
async function run(args: string[]): Promise<{ stdout: string; stderr: string }> {
const dbt = await getDbt()
const env = buildDbtEnv(dbt)
const cwd = globalOptions.projectRoot ?? process.cwd()

Expand Down
6 changes: 3 additions & 3 deletions packages/dbt-tools/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { failureLines } from "./failure-text"
const USAGE = {
commands: {
init: "Auto-detect dbt project and write config",
doctor: "Check prerequisites (Python, dbt, project)",
doctor: "Check prerequisites: Python, dbt-core and the project, or in Fusion mode the dbt Fusion binary and the project",
info: "Get project info (paths, targets, version)",
compile: "Compile a model (Jinja to SQL) --model <name>",
"compile-query": "Compile a raw query --query <sql> [--model <name>]",
Expand Down Expand Up @@ -138,9 +138,9 @@ async function main() {
const issue = await validate(cfg)
if (issue) return { error: issue }

// Configure CLI fallbacks with the project's Python environment
// Configure CLI fallbacks with the project's Python environment, or its dbt Fusion
const { configure } = await import("./dbt-cli")
configure({ pythonPath: cfg.pythonPath, projectRoot: cfg.projectRoot })
configure({ pythonPath: cfg.pythonPath, projectRoot: cfg.projectRoot, dbtIntegration: cfg.dbtIntegration })

// Lazy import: the adapter loads dbt-integration, which commands above don't need
let adapter
Expand Down
27 changes: 27 additions & 0 deletions packages/dbt-tools/test/adapter-target-path.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { describe, test, expect } from "bun:test"
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"
import { tmpdir } from "os"
import { join } from "path"
import { DBTFusionCommandProjectIntegration } from "@altimateai/dbt-integration"
import { create } from "../src/adapter"
import type { Config } from "../src/config"

/** A stand-in `python` that records the DBT_TARGET_PATH each run sees and fails the bridge run. */
function recordingPython(root: string) {
Expand Down Expand Up @@ -65,3 +67,28 @@ describe.skipIf(process.platform === "win32")("create's target folder", () => {
expect(new Set(runs)).toEqual(new Set(["unset"]))
})
})

// A Fusion config may name no Python at all. dbt-integration types the interpreter as a string and some
// of its code calls string methods on it, so create hands it an empty one rather than undefined.
describe("create's Python for a Fusion config without one", () => {
test("is the empty string", async () => {
const root = mkdtempSync(join(tmpdir(), "dbt-tools-fusion-python-"))
const proto = DBTFusionCommandProjectIntegration.prototype as unknown as { initializeProject: () => Promise<void> }
const initializeProject = proto.initializeProject
const seen: unknown[] = []
// Record the interpreter the Fusion integration was given, and stop before it looks for a binary.
proto.initializeProject = async function (this: { pythonEnvironment: { pythonPath: unknown } }) {
seen.push(this.pythonEnvironment.pythonPath)
throw new Error("stop")
}
try {
writeFileSync(join(root, "dbt_project.yml"), "name: p\nversion: '1.0'\nprofile: p\n")
const cfg = { projectRoot: root, dbtIntegration: "fusion", queryLimit: 500 } as unknown as Config
await expect(create(cfg)).rejects.toThrow("stop")
expect(seen).toEqual([""])
} finally {
proto.initializeProject = initializeProject
rmSync(root, { recursive: true, force: true })
}
})
})
29 changes: 23 additions & 6 deletions packages/dbt-tools/test/check.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,19 @@ describe("prerequisites in dbt Fusion mode", () => {
)
})

test("name no interpreter's folder for a bare command name, which the lookup skips", async () => {
fusionBinary.find = async () => undefined

for (const pythonPath of ["python3", "python"]) {
const issue = await validate(config({ pythonPath }))
expect(issue).toContain("fusion: dbt Fusion was not found: no dbt 2.x binary in ~/.local/bin or on PATH")
}
// A relative path has a folder, which the lookup does search.
expect(await validate(config({ pythonPath: ".venv/bin/python" }))).toContain(
"no dbt 2.x binary next to .venv/bin/python, in ~/.local/bin or on PATH",
)
})

test("still require the project", async () => {
fusionBinary.find = async () => FUSION

Expand All @@ -101,7 +114,8 @@ describe("prerequisites in dbt Fusion mode", () => {
// The real lookup, through the CLI in its own process: another test file here mocks
// `child_process`, and bun's module mocks reach every file of the run. A stand-in `dbt` is the
// only thing on PATH. The lookup always tries ~/.local/bin/dbt first (Bun ignores HOME for that),
// so the rejection test can't run where that is a real Fusion.
// so neither test can run where that is a real Fusion: the lookup would stop there, before the
// stand-in.
function realFusionInLocalBin(): boolean {
const dbt = join(homedir(), ".local", "bin", "dbt")
if (!existsSync(dbt)) return false
Expand All @@ -125,15 +139,18 @@ describe.skipIf(process.platform === "win32")("the Fusion lookup, run by `altima
mode: 0o755,
})
mkdirSync(join(home, ".altimate-code"))
writeFileSync(
join(home, ".altimate-code", "dbt.json"),
JSON.stringify({ projectRoot: project(), dbtIntegration: "fusion", queryLimit: 500 }),
)
// A Fusion-only user's config, which has no pythonPath key at all.
const cfg: Partial<Config> = config({})
delete cfg.pythonPath
writeFileSync(join(home, ".altimate-code", "dbt.json"), JSON.stringify(cfg))
const result = Bun.spawnSync([process.execPath, entry, "doctor"], { env: { HOME: home, PATH: bin } })
// `doctor` exits 0 whether the checks pass or not, so anything else is a crash: say what it printed.
if (result.exitCode !== 0)
throw new Error(`doctor exited ${result.exitCode}:\n${result.stdout.toString()}${result.stderr.toString()}`)
return JSON.parse(result.stdout.toString())
}

test("accepts a Fusion behind a script launcher that reports 2.x", () => {
test.skipIf(realFusionInLocalBin())("accepts a Fusion behind a script launcher that reports 2.x", () => {
const report = doctorWith("dbt 2.0.9")

expect(report.passed).toBe(true)
Expand Down
8 changes: 8 additions & 0 deletions packages/dbt-tools/test/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ describe("cli", () => {
expect(parsed.commands.doctor).toBeDefined()
})

test("usage says what doctor checks in each mode", async () => {
const result = Bun.spawnSync(["bun", entry], { env: { ...process.env, HOME: "/tmp/dbt-tools-test-home" } })
const parsed = JSON.parse(result.stdout.toString())
expect(parsed.commands.doctor).toBe(
"Check prerequisites: Python, dbt-core and the project, or in Fusion mode the dbt Fusion binary and the project",
)
})

test("doctor without config produces init hint", async () => {
const result = Bun.spawnSync(["bun", entry, "doctor"], { env: { ...process.env, HOME: "/tmp/dbt-tools-test-home" } })
const parsed = JSON.parse(result.stdout.toString())
Expand Down
80 changes: 78 additions & 2 deletions packages/dbt-tools/test/dbt-cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { describe, test, expect, mock, beforeEach } from "bun:test"
import { describe, test, expect, mock, beforeEach, afterEach, beforeAll, afterAll } from "bun:test"
import * as realChildProcess from "child_process"
import { mkdtempSync, rmSync, writeFileSync } from "fs"
import { tmpdir } from "os"
import { dirname, join } from "path"

// We test the parsing logic by mocking execFile.
// Spread the real module so other exports (execFileSync, etc.)
Expand All @@ -14,7 +17,8 @@ mock.module("child_process", () => ({
}))

// Import after mocking
const { execDbtShow, execDbtCompile, execDbtCompileInline, execDbtLs } = await import("../src/dbt-cli")
const { configure, execDbtShow, execDbtCompile, execDbtCompileInline, execDbtLs } = await import("../src/dbt-cli")
const { all, fusionBinary } = await import("../src/check")

// ---------------------------------------------------------------------------
// execDbtShow
Expand Down Expand Up @@ -720,3 +724,75 @@ describe("execDbtLs", () => {
expect(result).toEqual([])
})
})

// ---------------------------------------------------------------------------
// Which dbt the fallbacks run
// ---------------------------------------------------------------------------
describe("the fallbacks' dbt", () => {
const realFind = fusionBinary.find
const override = process.env.ALTIMATE_DBT_PATH
const FUSION = { path: "/fusion/bin/dbt", version: [2, 0, 9], location: "installer" as const }
const cfg = { projectRoot: "/p", pythonPath: "/venv/bin/python", dbtIntegration: "fusion", queryLimit: 500 }
// The first dbt resolveDbt would take: in Fusion mode, a dbt Core or a dbt Cloud CLI. It takes only one that exists.
let core: string

beforeAll(() => {
core = join(mkdtempSync(join(tmpdir(), "dbt-cli-core-")), "dbt")
writeFileSync(core, "#!/bin/sh\n", { mode: 0o755 })
})

afterAll(() => rmSync(dirname(core), { recursive: true, force: true }))

beforeEach(() => {
mockExecFile.mockReset()
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, "model.p.orders\n", "")
})
process.env.ALTIMATE_DBT_PATH = core
})

afterEach(() => {
fusionBinary.find = realFind
if (override === undefined) delete process.env.ALTIMATE_DBT_PATH
else process.env.ALTIMATE_DBT_PATH = override
configure({})
})

test("in Fusion mode, are the dbt Fusion binary the prerequisite check finds, looked up as it looks", async () => {
const asked: unknown[] = []
fusionBinary.find = async (options) => {
asked.push(options)
return FUSION
}
configure({ pythonPath: cfg.pythonPath, projectRoot: cfg.projectRoot, dbtIntegration: "fusion" })

await execDbtLs("customers", "children")
await all(cfg)

expect(new Set(mockExecFile.mock.calls.map((c) => c[0]))).toEqual(new Set([FUSION.path]))
expect(asked).toHaveLength(2)
expect(asked[0]).toEqual(asked[1])
})

test("in Fusion mode with no Fusion binary, fail rather than run another dbt", async () => {
fusionBinary.find = async () => undefined
configure({ pythonPath: cfg.pythonPath, projectRoot: cfg.projectRoot, dbtIntegration: "fusion" })

await expect(execDbtLs("customers", "children")).rejects.toThrow(
"dbt Fusion was not found: no dbt 2.x binary next to /venv/bin/python, in ~/.local/bin or on PATH",
)
expect(mockExecFile).not.toHaveBeenCalled()
})

test("in other modes, are resolved as before, with no Fusion lookup", async () => {
fusionBinary.find = async () => {
throw new Error("the Fusion lookup must not run outside Fusion mode")
}
for (const dbtIntegration of ["core", "corecommand", "cloud", undefined]) {
mockExecFile.mockClear()
configure({ pythonPath: cfg.pythonPath, projectRoot: cfg.projectRoot, dbtIntegration })
await execDbtLs("customers", "children")
expect(new Set(mockExecFile.mock.calls.map((c) => c[0]))).toEqual(new Set([core]))
}
})
})
21 changes: 21 additions & 0 deletions packages/dbt-tools/test/e2e/dbt-versions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,27 @@ describe.skipIf(!HAS_DBT)("altimate-dbt e2e", () => {
TEST_TIMEOUT,
)

test(
"on a stale manifest, parents answer from the last successful parse and mark no model external",
() => {
// As for children: the renamed profile fails the project check, and the answer comes from
// the manifest the build left.
const profiles = join(workDir, "profiles.yml")
const original = readFileSync(profiles, "utf-8")
writeFileSync(profiles, original.replace(/^test_jaffle_shop:/m, "test_jaffle_shop_renamed:"))
try {
const out = altDbt(version.pythonPath, workDir, ["parents", "--model", "customers"])
expect(out.stale_manifest).toBeDefined()
const labels = (out.models ?? []).map((m: { label: string }) => m.label)
expect(labels).toContain("stg_customers")
expect(out.models.every((m: { isExternalProject: boolean }) => m.isExternalProject === false)).toBe(true)
} finally {
writeFileSync(profiles, original)
}
},
TEST_TIMEOUT,
)

test(
"dbt ls lists models",
() => {
Expand Down
Loading
Loading