diff --git a/cli/api/commands/prune.ts b/cli/api/commands/prune.ts index 682f227f8..549873f53 100644 --- a/cli/api/commands/prune.ts +++ b/cli/api/commands/prune.ts @@ -1,98 +1,138 @@ -import { targetAsReadableString } from "df/core/targets"; +import { targetAsReadableString, targetStringifier } from "df/core/targets"; import * as utils from "df/core/utils"; import { dataform } from "df/protos/ts"; type CompileAction = dataform.ITable | dataform.IOperation | dataform.IAssertion | dataform.IPropertyGraph; +function targetKey(target?: dataform.ITarget | null): string | undefined { + return target ? targetStringifier.stringify(target) : undefined; +} + +function formatTargetParts(target: dataform.ITarget): string { + const parts = [ + target.database ? `database: "${target.database}"` : undefined, + target.schema ? `schema: "${target.schema}"` : undefined, + target.name ? `name: "${target.name}"` : undefined, + ].filter(Boolean); + return `{ ${parts.join(", ")} }`; +} + export function prune( compiledGraph: dataform.ICompiledGraph, runConfig: dataform.IRunConfig, ): dataform.ICompiledGraph { - compiledGraph.tables.forEach(utils.setOrValidateTableEnumType); - const includedActionNames = computeIncludedActionNames(compiledGraph, runConfig); + (compiledGraph.tables || []).forEach(utils.setOrValidateTableEnumType); + const { includedActionKeys, keyByAction } = computeIncludedActionKeys(compiledGraph, runConfig); + const isActionIncluded = (action: CompileAction) => { + const key = keyByAction.get(action); + return key !== undefined && includedActionKeys.has(key); + }; + const isTargetIncluded = (target?: dataform.ITarget | null) => { + const key = targetKey(target); + return key !== undefined && includedActionKeys.has(key); + }; return { ...compiledGraph, - tables: compiledGraph.tables.filter((action) => - includedActionNames.has(targetAsReadableString(action.target)), - ), - assertions: compiledGraph.assertions.filter((action) => - includedActionNames.has(targetAsReadableString(action.target)), - ), - operations: compiledGraph.operations.filter((action) => - includedActionNames.has(targetAsReadableString(action.target)), - ), - propertyGraphs: compiledGraph.propertyGraphs?.filter((action) => - includedActionNames.has(targetAsReadableString(action.target)), - ), + tables: (compiledGraph.tables || []).filter(isActionIncluded), + assertions: (compiledGraph.assertions || []).filter(isActionIncluded), + operations: (compiledGraph.operations || []).filter(isActionIncluded), + propertyGraphs: compiledGraph.propertyGraphs?.filter(isActionIncluded), // `targets` is declarative output only (nothing downstream reads it), but // `compile` prints it, so it has to agree with the filtered action lists. - targets: compiledGraph.targets?.filter((target) => - includedActionNames.has(targetAsReadableString(target)), - ), + targets: compiledGraph.targets?.filter(isTargetIncluded), }; } -function computeIncludedActionNames( +function computeIncludedActionKeys( compiledGraph: dataform.ICompiledGraph, runConfig: dataform.IRunConfig, -): Set { +): { includedActionKeys: Set; keyByAction: Map } { // Union all tables, operations, assertions, property graphs. const allActions: CompileAction[] = [].concat( - compiledGraph.tables, - compiledGraph.operations, - compiledGraph.assertions, - compiledGraph.propertyGraphs, + compiledGraph.tables || [], + compiledGraph.operations || [], + compiledGraph.assertions || [], + compiledGraph.propertyGraphs || [], ); - const allActionNames = new Set( - allActions.map((action) => targetAsReadableString(action.target)), - ); - const allActionsByName = new Map( - allActions.map((action) => [targetAsReadableString(action.target), action]), - ); + const allActionKeys = new Set(); + const keyByAction = new Map(); + const keyedActions: Array<{ action: CompileAction; key: string }> = []; + allActions.forEach((action) => { + const key = targetKey(action?.target); + if (key !== undefined) { + allActionKeys.add(key); + keyByAction.set(action, key); + keyedActions.push({ action, key }); + } + }); const hasActionSelector = runConfig.actions?.length > 0; const hasTagSelector = runConfig.tags?.length > 0; // If no selectors, return all actions. if (!hasActionSelector && !hasTagSelector) { - return allActionNames; + return { includedActionKeys: allActionKeys, keyByAction }; } - const includedActionNames = new Set(); + const includedActionKeys = new Set(); // Add all actions included by action filters. if (hasActionSelector) { + const candidates: utils.IMatchCandidate[] = keyedActions.map(({ action, key }) => { + const fullName = targetAsReadableString(action.target); + return { + fullName, + shortName: action.target.name, + key, + disambiguatedName: `${fullName} (${formatTargetParts(action.target)})`, + }; + }); utils - .matchPatterns(runConfig.actions, [...allActionNames]) - .forEach((actionName) => includedActionNames.add(actionName)); + .matchCandidatePatterns(runConfig.actions, candidates) + .forEach((actionKey) => includedActionKeys.add(actionKey)); } // Determine actions selected with --tag option and update applicable actions if (hasTagSelector) { - allActions - .filter((action) => action.tags?.some((tag) => runConfig.tags.includes(tag))) - .forEach((action) => includedActionNames.add(targetAsReadableString(action.target))); + keyedActions.forEach(({ action, key }) => { + if (action.tags?.some((tag) => runConfig.tags.includes(tag))) { + includedActionKeys.add(key); + } + }); + } + + const dependencyKeysByActionKey = new Map(); + const dependentKeysByActionKey = new Map(); + if (runConfig.includeDependencies || runConfig.includeDependents) { + keyedActions.forEach(({ action, key }) => { + const dependencyKeys: string[] = []; + (action.dependencyTargets || []).forEach((dependency) => { + const dependencyKey = targetKey(dependency); + if (dependencyKey !== undefined && allActionKeys.has(dependencyKey)) { + dependencyKeys.push(dependencyKey); + let dependents = dependentKeysByActionKey.get(dependencyKey); + if (!dependents) { + dependents = []; + dependentKeysByActionKey.set(dependencyKey, dependents); + } + dependents.push(key); + } + }); + dependencyKeysByActionKey.set(key, dependencyKeys); + }); } // Compute all transitive dependencies. if (runConfig.includeDependencies) { - const queue = [...includedActionNames]; + const queue = [...includedActionKeys]; while (queue.length > 0) { - const actionName = queue.pop(); - const action = allActionsByName.get(actionName); - const matchingDependencyNames = - action.dependencyTargets?.length > 0 - ? utils.matchPatterns( - action.dependencyTargets.map((dependency) => targetAsReadableString(dependency)), - [...allActionNames], - ) - : []; - matchingDependencyNames.forEach((dependencyName) => { - if (!includedActionNames.has(dependencyName)) { - queue.push(dependencyName); - includedActionNames.add(dependencyName); + const actionKey = queue.pop(); + (dependencyKeysByActionKey.get(actionKey) || []).forEach((dependencyKey) => { + if (!includedActionKeys.has(dependencyKey)) { + queue.push(dependencyKey); + includedActionKeys.add(dependencyKey); } }); } @@ -100,28 +140,17 @@ function computeIncludedActionNames( // Compute all transitive dependents. if (runConfig.includeDependents) { - const queue = [...includedActionNames]; + const queue = [...includedActionKeys]; while (queue.length > 0) { - const actionName = queue.pop(); - const matchingDependentNames = allActions - .filter( - (compileAction) => - utils.matchPatterns( - [actionName], - compileAction.dependencyTargets?.map((dependency) => - targetAsReadableString(dependency), - ) || [], - ).length >= 1, - ) - .map((compileAction) => targetAsReadableString(compileAction.target)); - matchingDependentNames.forEach((dependentName) => { - if (!includedActionNames.has(dependentName)) { - queue.push(dependentName); - includedActionNames.add(dependentName); + const actionKey = queue.pop(); + (dependentKeysByActionKey.get(actionKey) || []).forEach((dependentKey) => { + if (!includedActionKeys.has(dependentKey)) { + queue.push(dependentKey); + includedActionKeys.add(dependentKey); } }); } } - return includedActionNames; + return { includedActionKeys, keyByAction }; } diff --git a/cli/api/commands/prune_test.ts b/cli/api/commands/prune_test.ts index 87d9f6e7b..589643e72 100644 --- a/cli/api/commands/prune_test.ts +++ b/cli/api/commands/prune_test.ts @@ -167,4 +167,399 @@ suite("prune", () => { }), ); }); + + test("--actions= matches property graphs and keeps targets in sync", () => { + const compiledGraph: dataform.ICompiledGraph = { + tables: [TABLE_ACTION], + operations: [], + assertions: [], + propertyGraphs: [GRAPH_ACTION, TAGGED_GRAPH_ACTION], + targets: [TABLE_TARGET, GRAPH_TARGET, TAGGED_GRAPH_TARGET], + }; + expect(asPlainObject(prune(compiledGraph, { actions: ["*Graph"] }))).deep.equals( + asPlainObject({ + tables: [], + operations: [], + assertions: [], + propertyGraphs: [GRAPH_ACTION, TAGGED_GRAPH_ACTION], + targets: [GRAPH_TARGET, TAGGED_GRAPH_TARGET], + }), + ); + }); + + suite("targets colliding under targetAsReadableString", () => { + const DEP_TABLE_TARGET: dataform.ITarget = { database: "proj", schema: "b", name: "dep_table" }; + const DEP_ASSERT_TARGET: dataform.ITarget = { + database: "proj", + schema: "b", + name: "dep_assert", + }; + const COLLIDING_TABLE_TARGET: dataform.ITarget = { database: "proj", schema: "b", name: "c" }; + const COLLIDING_ASSERT_TARGET: dataform.ITarget = { schema: "proj", name: "b.c" }; + const AFTER_TABLE_TARGET: dataform.ITarget = { + database: "proj", + schema: "b", + name: "after_table", + }; + const AFTER_ASSERT_TARGET: dataform.ITarget = { + database: "proj", + schema: "b", + name: "after_assert", + }; + + const DEP_TABLE: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: DEP_TABLE_TARGET, + canonicalTarget: DEP_TABLE_TARGET, + query: "select 1", + dependencyTargets: [], + }; + const DEP_ASSERT: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: DEP_ASSERT_TARGET, + canonicalTarget: DEP_ASSERT_TARGET, + query: "select 2", + dependencyTargets: [], + }; + const COLLIDING_TABLE: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: COLLIDING_TABLE_TARGET, + canonicalTarget: COLLIDING_TABLE_TARGET, + query: "select 3", + tags: ["tag_tbl"], + dependencyTargets: [DEP_TABLE_TARGET], + }; + const COLLIDING_ASSERT: dataform.IAssertion = { + target: COLLIDING_ASSERT_TARGET, + canonicalTarget: COLLIDING_ASSERT_TARGET, + query: "select 4", + tags: ["tag_ass"], + dependencyTargets: [DEP_ASSERT_TARGET], + }; + const AFTER_TABLE: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: AFTER_TABLE_TARGET, + canonicalTarget: AFTER_TABLE_TARGET, + query: "select 5", + dependencyTargets: [COLLIDING_TABLE_TARGET], + }; + const AFTER_ASSERT: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: AFTER_ASSERT_TARGET, + canonicalTarget: AFTER_ASSERT_TARGET, + query: "select 6", + dependencyTargets: [COLLIDING_ASSERT_TARGET], + }; + + function makeCollidingGraph(): dataform.ICompiledGraph { + return { + tables: [DEP_TABLE, DEP_ASSERT, COLLIDING_TABLE, AFTER_TABLE, AFTER_ASSERT], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + DEP_TABLE_TARGET, + DEP_ASSERT_TARGET, + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + AFTER_TABLE_TARGET, + AFTER_ASSERT_TARGET, + ], + }; + } + + test("unqualified --actions throws ambiguous error when another action shares its short name", () => { + const otherC: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: { schema: "proj.b", name: "c" }, + canonicalTarget: { schema: "proj.b", name: "c" }, + query: "select 7", + dependencyTargets: [], + }; + const graph: dataform.ICompiledGraph = { + tables: [COLLIDING_TABLE, otherC], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, otherC.target], + }; + expect(() => prune(graph, { actions: ["c"] })).to.throw( + 'Ambiguous Action name: c. Did you mean one of: proj.b.c ({ database: "proj", schema: "b", name: "c" }), proj.b.c ({ schema: "proj.b", name: "c" }).', + ); + }); + + test("unqualified --actions keeps plain readable names when candidates do not collide", () => { + const firstC: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: { database: "proj", schema: "s1", name: "c" }, + canonicalTarget: { database: "proj", schema: "s1", name: "c" }, + query: "select 1", + dependencyTargets: [], + }; + const secondC: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: { database: "proj", schema: "s2", name: "c" }, + canonicalTarget: { database: "proj", schema: "s2", name: "c" }, + query: "select 2", + dependencyTargets: [], + }; + const graph: dataform.ICompiledGraph = { + tables: [firstC, secondC], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [firstC.target, secondC.target], + }; + expect(() => prune(graph, { actions: ["c"] })).to.throw( + "Ambiguous Action name: c. Did you mean one of: proj.s1.c, proj.s2.c.", + ); + }); + + test("dotted --actions selects all matching actions and walks all of their dependencies", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["proj.b.c"], + includeDependencies: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [DEP_TABLE, DEP_ASSERT, COLLIDING_TABLE], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + DEP_TABLE_TARGET, + DEP_ASSERT_TARGET, + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + ], + }), + ); + }); + + test("dotted --actions with includeDependents walks dependents of all matching actions", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["proj.b.c"], + includeDependents: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, AFTER_TABLE, AFTER_ASSERT], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + AFTER_TABLE_TARGET, + AFTER_ASSERT_TARGET, + ], + }), + ); + }); + + test("--tags selects only the tagged colliding action and walks only its dependencies", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + tags: ["tag_tbl"], + includeDependencies: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [DEP_TABLE, COLLIDING_TABLE], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [DEP_TABLE_TARGET, COLLIDING_TABLE_TARGET], + }), + ); + }); + + test("--tags with includeDependents walks only dependents of the tagged colliding action", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + tags: ["tag_tbl"], + includeDependents: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, AFTER_TABLE], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, AFTER_TABLE_TARGET], + }), + ); + }); + + test("unqualified wildcard matches actual target.name without ambiguity and skips dotted names", () => { + const otherC: dataform.ITable = { + type: "view", + enumType: dataform.TableType.VIEW, + target: { schema: "proj.b", name: "c" }, + canonicalTarget: { schema: "proj.b", name: "c" }, + query: "select 7", + dependencyTargets: [], + }; + const graph: dataform.ICompiledGraph = { + tables: [COLLIDING_TABLE, otherC], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, otherC.target, COLLIDING_ASSERT_TARGET], + }; + + // "c*" matches target.name === "c" on both tables without throwing ambiguity, and does not + // match COLLIDING_ASSERT whose target.name is "b.c" (even though its readable string ends in ".c"). + expect(asPlainObject(prune(graph, { actions: ["c*"] }))).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, otherC], + operations: [], + assertions: [], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, otherC.target], + }), + ); + + // "*c" matches all three because "c" and "b.c" both end in "c". + expect(asPlainObject(prune(graph, { actions: ["*c"] }))).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, otherC], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [COLLIDING_TABLE_TARGET, otherC.target, COLLIDING_ASSERT_TARGET], + }), + ); + }); + + test("qualified wildcard selects all colliding targets and walks all of their dependencies and dependents", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["*.b.c"], + includeDependencies: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [DEP_TABLE, DEP_ASSERT, COLLIDING_TABLE], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + DEP_TABLE_TARGET, + DEP_ASSERT_TARGET, + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + ], + }), + ); + + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["proj.**c"], + includeDependents: true, + }), + ), + ).deep.equals( + asPlainObject({ + tables: [COLLIDING_TABLE, AFTER_TABLE, AFTER_ASSERT], + operations: [], + assertions: [COLLIDING_ASSERT], + propertyGraphs: [], + targets: [ + COLLIDING_TABLE_TARGET, + COLLIDING_ASSERT_TARGET, + AFTER_TABLE_TARGET, + AFTER_ASSERT_TARGET, + ], + }), + ); + }); + + test("overlapping wildcard, exact and tag selectors do not duplicate actions or targets", () => { + expect( + asPlainObject( + prune(makeCollidingGraph(), { + actions: ["*", "proj.b.c", "*table"], + tags: ["tag_tbl", "tag_ass"], + }), + ), + ).deep.equals(asPlainObject(makeCollidingGraph())); + }); + + test("literal '*' in a target name does not wildcard-expand during dependency or dependent walks", () => { + const starTarget: dataform.ITarget = { schema: "s", name: "op*" }; + const unrelatedTarget: dataform.ITarget = { schema: "s", name: "op_unrelated" }; + const consumerTarget: dataform.ITarget = { schema: "s", name: "consumer" }; + const starOp: dataform.IOperation = { + target: starTarget, + canonicalTarget: starTarget, + queries: ["select 1"], + dependencyTargets: [], + }; + const unrelatedOp: dataform.IOperation = { + target: unrelatedTarget, + canonicalTarget: unrelatedTarget, + queries: ["select 2"], + dependencyTargets: [], + }; + const consumerOp: dataform.IOperation = { + target: consumerTarget, + canonicalTarget: consumerTarget, + queries: ["select 3"], + dependencyTargets: [starTarget], + }; + const graph: dataform.ICompiledGraph = { + tables: [], + operations: [starOp, unrelatedOp, consumerOp], + assertions: [], + propertyGraphs: [], + targets: [starTarget, unrelatedTarget, consumerTarget], + }; + + expect( + asPlainObject(prune(graph, { actions: ["consumer"], includeDependencies: true })), + ).deep.equals( + asPlainObject({ + tables: [], + operations: [starOp, consumerOp], + assertions: [], + propertyGraphs: [], + targets: [starTarget, consumerTarget], + }), + ); + + expect( + asPlainObject(prune(graph, { actions: ["op_unrelated"], includeDependents: true })), + ).deep.equals( + asPlainObject({ + tables: [], + operations: [unrelatedOp], + assertions: [], + propertyGraphs: [], + targets: [unrelatedTarget], + }), + ); + }); + }); }); diff --git a/cli/commands/run_command.ts b/cli/commands/run_command.ts index bb43921c6..cfef5fb36 100644 --- a/cli/commands/run_command.ts +++ b/cli/commands/run_command.ts @@ -108,6 +108,29 @@ function createLineageEmitter( }); } +export function createExecutedGraphPrinter( + actionsByTarget: ReadonlyMap, + dryRun?: boolean, +): (executedGraph: dataform.IRunResult) => void { + const alreadyPrintedActions = new Set(); + return (executedGraph: dataform.IRunResult) => { + for (const executedAction of executedGraph.actions || []) { + if ( + executedAction.status === dataform.ActionResult.ExecutionStatus.RUNNING || + !executedAction.target + ) { + continue; + } + const targetKey = targetStringifier.stringify(executedAction.target); + if (alreadyPrintedActions.has(targetKey)) { + continue; + } + printExecutedAction(executedAction, actionsByTarget.get(targetKey), dryRun); + alreadyPrintedActions.add(targetKey); + } + }; +} + export const runCommand: ICommand = { format: `run [${projectDirOption.name}]`, description: "Run the dataform project.", @@ -236,12 +259,14 @@ export const runCommand: ICommand = { bigqueryOptions = { ...bigqueryOptions, labels: argv.jobLabels }; } - const actionsByName = new Map(); + const actionsByTarget = new Map(); executionGraph.actions.forEach((action) => { - actionsByName.set(targetAsReadableString(action.target), action); + if (action.target) { + actionsByTarget.set(targetStringifier.stringify(action.target), action); + } }); - if (actionsByName.size === 0) { + if (actionsByTarget.size === 0) { if (argv.json) { print( prettyJsonStringify({ @@ -280,26 +305,7 @@ export const runCommand: ICommand = { // The first Ctrl+C cancels the run gracefully; a second one exits immediately. setSignalHandler("SIGINT", () => runner.cancel()); - const alreadyPrintedActions = new Set(); - - const printExecutedGraph = (executedGraph: dataform.IRunResult) => { - executedGraph.actions - .filter( - (actionResult) => actionResult.status !== dataform.ActionResult.ExecutionStatus.RUNNING, - ) - .filter( - (executedAction) => - !alreadyPrintedActions.has(targetAsReadableString(executedAction.target)), - ) - .forEach((executedAction) => { - printExecutedAction( - executedAction, - actionsByName.get(targetAsReadableString(executedAction.target)), - argv.dryRun, - ); - alreadyPrintedActions.add(targetAsReadableString(executedAction.target)); - }); - }; + const printExecutedGraph = createExecutedGraphPrinter(actionsByTarget, argv.dryRun); if (!argv.json) { runner.onChange(printExecutedGraph); diff --git a/cli/index_compile_test.ts b/cli/index_compile_test.ts index ac145225e..034cd4aa7 100644 --- a/cli/index_compile_test.ts +++ b/cli/index_compile_test.ts @@ -703,6 +703,16 @@ SELECT 1 as id const result = await runCli("compile", [projectDir, "--output-actions", "*stream", "--json"]); expect(result.exitCode, result.stderr).equals(0); expect(tableNames(result.stdout)).deep.equals(["downstream", "midstream", "upstream"]); + + const withDepsResult = await runCli("compile", [ + projectDir, + "--output-actions", + "*.mid*", + "--output-include-deps", + "--json", + ]); + expect(withDepsResult.exitCode, withDepsResult.stderr).equals(0); + expect(tableNames(withDepsResult.stdout)).deep.equals(["midstream", "upstream"]); }); test("--output-actions with --schema-suffix retains suffixed targets", async () => { diff --git a/cli/tests/run_command_test.ts b/cli/tests/run_command_test.ts index 0a1f8c4b1..5515c3600 100644 --- a/cli/tests/run_command_test.ts +++ b/cli/tests/run_command_test.ts @@ -1,6 +1,10 @@ import { expect } from "chai"; -import { warnAboutOverrideProtectedFullRefresh } from "df/cli/commands/run_command"; +import { + createExecutedGraphPrinter, + warnAboutOverrideProtectedFullRefresh, +} from "df/cli/commands/run_command"; +import { targetStringifier } from "df/core/targets"; import { dataform } from "df/protos/ts"; import { suite, test } from "df/testing"; @@ -279,3 +283,83 @@ suite("warnAboutOverrideProtectedFullRefresh", ({ beforeEach, afterEach }) => { expect(stderrOutput).deep.equals([]); }); }); + +function stripAnsi(text: string): string { + return text.replace(/\x1b\[[0-9;]*m/g, ""); +} + +function captureStreams(fn: () => void): { stdout: string; stderr: string } { + const stdoutChunks: string[] = []; + const stderrChunks: string[] = []; + const origStdoutWrite = process.stdout.write.bind(process.stdout); + const origStderrWrite = process.stderr.write.bind(process.stderr); + process.stdout.write = ((chunk: string | Uint8Array) => { + stdoutChunks.push(String(chunk)); + return true; + }) as typeof process.stdout.write; + process.stderr.write = ((chunk: string | Uint8Array) => { + stderrChunks.push(String(chunk)); + return true; + }) as typeof process.stderr.write; + try { + fn(); + } finally { + process.stdout.write = origStdoutWrite; + process.stderr.write = origStderrWrite; + } + return { + stdout: stripAnsi(stdoutChunks.join("")), + stderr: stripAnsi(stderrChunks.join("")), + }; +} + +suite("createExecutedGraphPrinter", () => { + test("prints colliding readable targets with their own action types across separate ticks", () => { + const viewTarget: dataform.ITarget = { database: "proj", schema: "b", name: "c" }; + const assertionTarget: dataform.ITarget = { schema: "proj", name: "b.c" }; + + const viewAction: dataform.IExecutionAction = { + type: "table", + tableType: "view", + target: viewTarget, + tasks: [{ type: "statement", statement: "SELECT 1" }], + }; + const assertionAction: dataform.IExecutionAction = { + type: "assertion", + target: assertionTarget, + tasks: [{ type: "assertion", statement: "SELECT 2" }], + }; + + const actionsByTarget = new Map([ + [targetStringifier.stringify(viewTarget), viewAction], + [targetStringifier.stringify(assertionTarget), assertionAction], + ]); + const printExecutedGraph = createExecutedGraphPrinter(actionsByTarget, true); + + const viewCompleted: dataform.IActionResult = { + target: viewTarget, + status: dataform.ActionResult.ExecutionStatus.SUCCESSFUL, + tasks: [{ status: dataform.TaskResult.ExecutionStatus.SUCCESSFUL }], + }; + const assertionRunning: dataform.IActionResult = { + target: assertionTarget, + status: dataform.ActionResult.ExecutionStatus.RUNNING, + tasks: [], + }; + const assertionCompleted: dataform.IActionResult = { + target: assertionTarget, + status: dataform.ActionResult.ExecutionStatus.SUCCESSFUL, + tasks: [{ status: dataform.TaskResult.ExecutionStatus.SUCCESSFUL }], + }; + + const tick1 = captureStreams(() => { + printExecutedGraph({ actions: [viewCompleted, assertionRunning] }); + }); + expect(tick1.stdout.trim()).to.equal("Table dry run success: b.c [view]"); + + const tick2 = captureStreams(() => { + printExecutedGraph({ actions: [viewCompleted, assertionCompleted] }); + }); + expect(tick2.stdout.trim()).to.equal("Assertion dry run success: proj.b.c"); + }); +}); diff --git a/core/utils.ts b/core/utils.ts index a7b22c1f5..9fb961e89 100644 --- a/core/utils.ts +++ b/core/utils.ts @@ -46,39 +46,69 @@ function globToRegExp(pattern: string): RegExp { return new RegExp(`^${pattern.replace(/\*+/g, "*").split("*").map(escapeLiteral).join(".*")}$`); } -export function matchPatterns(patterns: string[], values: string[]) { - const fullyQualifiedActions: string[] = []; +/** @internal */ +export interface IMatchCandidate { + fullName: string; + shortName?: string; + key: string; + disambiguatedName?: string; +} + +/** @internal */ +export function matchCandidatePatterns( + patterns: string[], + candidates: IMatchCandidate[], +): string[] { + const matchedKeys: string[] = []; patterns.forEach((pattern) => { if (pattern.includes("*")) { - // Wildcard selector. A pattern that contains "." matches against the - // fully-qualified action name; otherwise it matches against the unqualified - // name (last segment), mirroring the exact-match branches below. Wildcards - // are expected to select many actions, so no ambiguity error applies here. + // Wildcard selector: patterns containing "." match the full readable target string; + // otherwise they match the unqualified action name, with no ambiguity error. const regExp = globToRegExp(pattern); - const scope = pattern.includes(".") - ? values - : values.map((value) => value.split(".").slice(-1)[0]); - values.forEach((value, i) => { - if (regExp.test(scope[i])) { - fullyQualifiedActions.push(value); + const matchFullTarget = pattern.includes("."); + candidates.forEach((candidate) => { + const value = matchFullTarget ? candidate.fullName : candidate.shortName; + if (value !== undefined && regExp.test(value)) { + matchedKeys.push(candidate.key); } }); } else if (pattern.includes(".")) { - if (values.includes(pattern)) { - fullyQualifiedActions.push(pattern); - } + // Dotted selectors are already fully qualified in CLI syntax, so when distinct targets + // render to the same dotted string, all matching targets are selected. + candidates.forEach((candidate) => { + if (candidate.fullName === pattern) { + matchedKeys.push(candidate.key); + } + }); } else { - const matchingActions = values.filter((value) => pattern === value.split(".").slice(-1)[0]); - if (matchingActions.length === 0) { + const matching = candidates.filter((candidate) => candidate.shortName === pattern); + if (matching.length === 0) { return; } - if (matchingActions.length > 1) { - throw new Error(ambiguousActionNameMsg(pattern, matchingActions)); + if (matching.length > 1) { + const fullNames = matching.map((candidate) => candidate.fullName); + const displayNames = + new Set(fullNames).size < fullNames.length + ? matching.map((candidate) => candidate.disambiguatedName || candidate.fullName) + : fullNames; + throw new Error(ambiguousActionNameMsg(pattern, displayNames)); } - fullyQualifiedActions.push(matchingActions[0]); + matchedKeys.push(matching[0].key); } }); - return fullyQualifiedActions; + return matchedKeys; +} + +/** @internal */ +export function matchPatterns(patterns: string[], values: string[]) { + return matchCandidatePatterns( + patterns, + values.map((value) => ({ + fullName: value, + shortName: value.split(".").slice(-1)[0], + key: value, + })), + ); } export function getCallerFile(rootDir: string) {