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 | class DagsterDbtFactory:
"""Factory to generate dagster definitions from a dbt project."""
@cache
@staticmethod
def build_definitions(dbt: Callable[[], DbtProject]) -> dg.Definitions:
"""Returns a Definitions object from a dbt project."""
assets = [
DagsterDbtFactory._get_assets(
"dbt_partitioned_models",
dbt=dbt,
select=TIME_PARTITION_SELECTOR,
partitioned=True,
),
DagsterDbtFactory._get_assets(
"dbt_non_partitioned_models",
dbt=dbt,
exclude=TIME_PARTITION_SELECTOR,
partitioned=False,
),
]
freshness_checks = build_freshness_checks_from_dbt_assets(dbt_assets=assets)
freshness_sensor = dg.build_sensor_for_freshness_checks(
freshness_checks=freshness_checks, name="dbt_freshness_checks_sensor"
)
return dg.Definitions(
resources={"dbt": DbtCliResource(project_dir=dbt())},
assets=assets,
asset_checks=freshness_checks,
sensors=[freshness_sensor],
)
@cache
@staticmethod
def _get_assets(
name: str | None,
dbt: Callable[[], DbtProject],
partitioned: bool = False,
select: str = DBT_DEFAULT_SELECT,
exclude: str | None = None,
) -> dg.AssetsDefinition:
"""Returns a AssetsDefinition with different execution for partitioned
and non-partitioned models so that they can be ran on the same job.
"""
dbt_project = dbt()
assert dbt_project
@dbt_assets(
name=name,
manifest=dbt_project.manifest_path,
select=select,
exclude=exclude,
dagster_dbt_translator=CustomDagsterDbtTranslator(
settings=DagsterDbtTranslatorSettings(
enable_duplicate_source_asset_keys=True,
)
),
backfill_policy=dg.BackfillPolicy.single_run(),
project=dbt_project,
pool="dbt",
)
def assets(
context: dg.AssetExecutionContext, dbt: DbtCliResource, config: DbtConfig
) -> Generator[DbtEventIterator, Any, Any]:
args = ["build"]
if config.full_refresh:
args.append("--full-refresh")
if config.defer_to_prod:
args.extend(dbt.get_defer_args())
if config.favor_state:
args.append("--favor-state")
if partitioned:
time_window = context.partition_time_window
format = "%Y-%m-%d %H:%M:%S"
dbt_vars = {
"min_date": time_window.start.strftime(format),
"max_date": time_window.end.strftime(format),
}
args.extend(("--vars", json.dumps(dbt_vars)))
yield from dbt.cli(
args,
context=context
).stream() # .with_insights() # type: ignore
else:
yield from dbt.cli(
args,
context=context
).stream() # .with_insights() # type: ignore
return assets
|