-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathdbt-cli.test.ts
More file actions
404 lines (330 loc) · 14.5 KB
/
Copy pathdbt-cli.test.ts
File metadata and controls
404 lines (330 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import { describe, test, expect, mock, beforeEach } from "bun:test"
import * as realChildProcess from "child_process"
// We test the parsing logic by mocking execFile.
// Spread the real module so other exports (execFileSync, etc.)
// remain available — mock.module leaks across test files in Bun.
const mockExecFile = mock((cmd: string, args: string[], opts: any, cb: Function) => {
cb(null, "", "")
})
mock.module("child_process", () => ({
...realChildProcess,
execFile: mockExecFile,
}))
// Import after mocking
const { execDbtShow, execDbtCompile, execDbtCompileInline, execDbtLs } = await import("../src/dbt-cli")
// ---------------------------------------------------------------------------
// execDbtShow
// ---------------------------------------------------------------------------
describe("execDbtShow", () => {
beforeEach(() => {
mockExecFile.mockReset()
})
// --- Tier 1: known field paths ---
test("Tier 1: parses data.preview (dbt 1.7-1.9 format)", async () => {
const jsonLines = [
JSON.stringify({ info: { msg: "Running..." } }),
JSON.stringify({ data: { sql: "SELECT 1 AS n" } }),
JSON.stringify({ data: { preview: '[{"n": 1}]' } }),
].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtShow("SELECT 1 AS n")
expect(result.columnNames).toEqual(["n"])
expect(result.data).toEqual([{ n: 1 }])
expect(result.compiledSql).toBe("SELECT 1 AS n")
})
test("Tier 1: parses data.rows (alternative format)", async () => {
const jsonLines = [JSON.stringify({ data: { rows: [{ name: "Alice" }, { name: "Bob" }] } })].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtShow("SELECT name FROM users")
expect(result.columnNames).toEqual(["name"])
expect(result.data).toEqual([{ name: "Alice" }, { name: "Bob" }])
})
test("Tier 1: parses result.preview (hypothetical future format)", async () => {
const jsonLines = [JSON.stringify({ result: { preview: [{ id: 42 }], sql: "SELECT 42" } })].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtShow("SELECT 42 AS id")
expect(result.columnNames).toEqual(["id"])
expect(result.data).toEqual([{ id: 42 }])
})
test("Tier 1: passes --limit flag when provided", async () => {
mockExecFile.mockImplementation((_cmd: string, args: string[], _opts: any, cb: Function) => {
expect(args).toContain("--limit")
expect(args).toContain("10")
cb(null, JSON.stringify({ data: { preview: '[{"n": 1}]' } }), "")
})
const result = await execDbtShow("SELECT 1", 10)
expect(result.data).toEqual([{ n: 1 }])
})
// --- Tier 2: heuristic deep scan ---
test("Tier 2: finds row data nested in unknown structure", async () => {
// Simulates a future dbt version with a completely different JSON shape
const jsonLines = [
JSON.stringify({
level: "info",
msg: "show done",
payload: {
query_results: [{ amount: 100 }, { amount: 200 }],
},
}),
].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtShow("SELECT amount FROM orders")
expect(result.columnNames).toEqual(["amount"])
expect(result.data).toEqual([{ amount: 100 }, { amount: 200 }])
})
test("Tier 2: finds JSON string of rows nested deeply", async () => {
const jsonLines = [
JSON.stringify({
event: {
output: JSON.stringify([{ x: 1 }, { x: 2 }]),
},
}),
].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtShow("SELECT x FROM t")
expect(result.columnNames).toEqual(["x"])
expect(result.data).toEqual([{ x: 1 }, { x: 2 }])
})
// --- Tier 3: plain text fallback ---
test("Tier 3: parses ASCII table when JSON fails", async () => {
let callCount = 0
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
callCount++
if (callCount === 1) {
// JSON attempt fails (no preview data)
cb(null, JSON.stringify({ info: { msg: "done" } }), "")
} else {
// Plain text ASCII table
cb(null, ["| id | name |", "| -- | ----- |", "| 1 | Alice |", "| 2 | Bob |"].join("\n"), "")
}
})
const result = await execDbtShow("SELECT id, name FROM users")
expect(result.columnNames).toEqual(["id", "name"])
expect(result.data).toEqual([
{ id: "1", name: "Alice" },
{ id: "2", name: "Bob" },
])
})
test("Tier 3: throws with helpful message when all tiers fail", async () => {
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, "some unparseable output", "")
})
await expect(execDbtShow("SELECT 1")).rejects.toThrow("Could not parse dbt show output in any format")
})
// --- Bubble real dbt error instead of generic "Could not parse" ---
test("surfaces real dbt stderr when run fails", async () => {
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
const err: any = new Error("Command failed: dbt show --inline ...")
err.code = 1
err.stdout = ""
err.stderr =
"Runtime Error: Failed to read package: No dbt_project.yml found at expected path dbt_packages/dbt_utils/dbt_project.yml"
cb(err, err.stdout, err.stderr)
})
await expect(execDbtShow("SELECT 1")).rejects.toThrow(/Failed to read package/)
await expect(execDbtShow("SELECT 1")).rejects.toThrow(/dbt show failed/)
})
test("prefers structured error event in JSON log over raw stderr", async () => {
const errorLog = JSON.stringify({
info: {
level: "error",
msg: "Compilation Error: Model 'foo' depends on a node named 'bar' which was not found",
},
})
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
const err: any = new Error("Command failed")
err.code = 1
err.stdout = errorLog
err.stderr = "exit status 1"
cb(err, err.stdout, err.stderr)
})
await expect(execDbtShow("SELECT 1")).rejects.toThrow(/Compilation Error.*Model 'foo'/)
})
test("does not surface generic 'Could not parse' when dbt actually crashed", async () => {
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
const err: any = new Error("Command failed")
err.code = 2
err.stdout = ""
err.stderr = "Database Error: connection refused"
cb(err, err.stdout, err.stderr)
})
await expect(execDbtShow("SELECT 1")).rejects.not.toThrow(/Could not parse dbt show output/)
})
test("preserves generic 'Could not parse' when dbt exited 0 but output unparseable", async () => {
// Existing behavior — dbt didn't crash, we just couldn't decode its output.
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, "some unparseable output", "")
})
await expect(execDbtShow("SELECT 1")).rejects.toThrow("Could not parse dbt show output in any format")
})
test("falls back to error message when stderr is empty", async () => {
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
const err: any = new Error("spawn ENOENT")
err.code = "ENOENT"
err.stdout = ""
err.stderr = ""
cb(err, "", "")
})
await expect(execDbtShow("SELECT 1")).rejects.toThrow(/spawn ENOENT|dbt show failed/)
})
})
// ---------------------------------------------------------------------------
// execDbtCompile
// ---------------------------------------------------------------------------
describe("execDbtCompile", () => {
beforeEach(() => {
mockExecFile.mockReset()
})
test("Tier 1: parses data.compiled (dbt 1.7-1.9)", async () => {
const jsonLines = [
JSON.stringify({ info: { msg: "Compiling..." } }),
JSON.stringify({ data: { compiled: "SELECT id FROM raw_orders" } }),
].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtCompile("orders")
expect(result.sql).toBe("SELECT id FROM raw_orders")
})
test("Tier 1: parses data.compiled_code (newer dbt)", async () => {
const jsonLines = [JSON.stringify({ data: { compiled_code: "SELECT * FROM stg_orders" } })].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtCompile("orders")
expect(result.sql).toBe("SELECT * FROM stg_orders")
})
test("Tier 1: parses result.node.compiled_code", async () => {
const jsonLines = [JSON.stringify({ result: { node: { compiled_code: "SELECT 1" } } })].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtCompile("my_model")
expect(result.sql).toBe("SELECT 1")
})
test("Tier 1: parses data.compiled_sql", async () => {
const jsonLines = [JSON.stringify({ data: { compiled_sql: "SELECT 1 FROM foo" } })].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtCompile("foo")
expect(result.sql).toBe("SELECT 1 FROM foo")
})
// --- Tier 2: heuristic ---
test("Tier 2: finds SQL in unknown nested structure", async () => {
const jsonLines = [
JSON.stringify({
event: {
compilation_result: "SELECT id, name FROM public.customers WHERE active = true",
},
}),
].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtCompile("customers")
expect(result.sql).toBe("SELECT id, name FROM public.customers WHERE active = true")
})
// --- Tier 3: plain text ---
test("Tier 3: falls back to plain text output", async () => {
let callCount = 0
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
callCount++
if (callCount === 1) {
cb(null, JSON.stringify({ info: { msg: "done" } }), "")
} else {
cb(null, "SELECT * FROM final_model", "")
}
})
const result = await execDbtCompile("my_model")
expect(result.sql).toBe("SELECT * FROM final_model")
})
})
// ---------------------------------------------------------------------------
// execDbtCompileInline
// ---------------------------------------------------------------------------
describe("execDbtCompileInline", () => {
beforeEach(() => {
mockExecFile.mockReset()
})
test("compiles inline SQL", async () => {
const jsonLines = [JSON.stringify({ data: { compiled: "SELECT id, name FROM raw.customers" } })].join("\n")
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, jsonLines, "")
})
const result = await execDbtCompileInline("SELECT * FROM {{ ref('customers') }}")
expect(result.sql).toBe("SELECT id, name FROM raw.customers")
})
})
// ---------------------------------------------------------------------------
// execDbtLs
// ---------------------------------------------------------------------------
describe("execDbtLs", () => {
beforeEach(() => {
mockExecFile.mockReset()
})
test("JSON format: lists children models", async () => {
const jsonLines = [
JSON.stringify({ name: "orders", unique_id: "model.jaffle.orders" }),
JSON.stringify({ name: "customers", unique_id: "model.jaffle.customers" }),
JSON.stringify({ name: "revenue", unique_id: "model.jaffle.revenue" }),
].join("\n")
mockExecFile.mockImplementation((_cmd: string, args: string[], _opts: any, cb: Function) => {
expect(args).toContain("--select")
expect(args[args.indexOf("--select") + 1]).toBe("orders+")
cb(null, jsonLines, "")
})
const result = await execDbtLs("orders", "children")
expect(result.find((r: any) => r.table === "orders")).toBeUndefined()
expect(result.find((r: any) => r.table === "customers")).toBeTruthy()
expect(result.find((r: any) => r.table === "revenue")).toBeTruthy()
})
test("JSON format: lists parent models", async () => {
const jsonLines = [
JSON.stringify({ name: "stg_orders", unique_id: "model.jaffle.stg_orders" }),
JSON.stringify({ name: "stg_payments", unique_id: "model.jaffle.stg_payments" }),
JSON.stringify({ name: "orders", unique_id: "model.jaffle.orders" }),
].join("\n")
mockExecFile.mockImplementation((_cmd: string, args: string[], _opts: any, cb: Function) => {
expect(args[args.indexOf("--select") + 1]).toBe("+orders")
cb(null, jsonLines, "")
})
const result = await execDbtLs("orders", "parents")
expect(result.find((r: any) => r.table === "orders")).toBeUndefined()
expect(result.find((r: any) => r.table === "stg_orders")).toBeTruthy()
})
test("plain text fallback: parses unique_id lines", async () => {
let callCount = 0
mockExecFile.mockImplementation((_cmd: string, args: string[], _opts: any, cb: Function) => {
callCount++
if (callCount === 1) {
// JSON fails
cb(new Error("--output json not supported"), "", "")
} else {
// Plain text: one unique_id per line
cb(null, "model.jaffle.stg_orders\nmodel.jaffle.stg_payments\nmodel.jaffle.orders\n", "")
}
})
const result = await execDbtLs("orders", "parents")
expect(result.find((r: any) => r.table === "orders")).toBeUndefined()
expect(result.find((r: any) => r.table === "stg_orders")).toBeTruthy()
expect(result.find((r: any) => r.table === "stg_payments")).toBeTruthy()
})
test("handles empty output", async () => {
mockExecFile.mockImplementation((_cmd: string, _args: string[], _opts: any, cb: Function) => {
cb(null, "", "")
})
const result = await execDbtLs("isolated_model", "children")
expect(result).toEqual([])
})
})