dagster-dlt 0.25.9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 Dagster Labs, Inc".
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ include README.md
2
+ include LICENSE
3
+ include integration.yaml
4
+ include dagster_dlt/py.typed
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.1
2
+ Name: dagster-dlt
3
+ Version: 0.25.9
4
+ Summary: Package for performing ETL/ELT tasks with dlt in Dagster.
5
+ Home-page: https://github.com/dagster-io/dagster/tree/master/python_modules/libraries/dagster-dlt
6
+ Author: Dagster Labs
7
+ Author-email: hello@dagsterlabs.com
8
+ License: Apache-2.0
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Requires-Python: >=3.9,<3.13
16
+ Provides-Extra: test
17
+ License-File: LICENSE
@@ -0,0 +1,4 @@
1
+ # dagster-dlt
2
+
3
+ The docs for `dagster-dlt` can be found
4
+ [here](https://docs.dagster.io/_apidocs/libraries/dagster-dlt).
@@ -0,0 +1,11 @@
1
+ from dagster._core.libraries import DagsterLibraryRegistry
2
+
3
+ from dagster_dlt.asset_decorator import build_dlt_asset_specs, dlt_assets
4
+ from dagster_dlt.resource import DagsterDltResource
5
+ from dagster_dlt.translator import DagsterDltTranslator
6
+ from dagster_dlt.version import __version__
7
+
8
+ __all__ = ["DagsterDltResource", "DagsterDltTranslator", "build_dlt_asset_specs", "dlt_assets"]
9
+
10
+
11
+ DagsterLibraryRegistry.register("dagster-dlt", __version__)
@@ -0,0 +1,151 @@
1
+ from collections.abc import Mapping, Sequence
2
+ from typing import Any, Callable, Optional
3
+
4
+ from dagster import (
5
+ AssetsDefinition,
6
+ AssetSpec,
7
+ PartitionsDefinition,
8
+ _check as check,
9
+ multi_asset,
10
+ )
11
+ from dlt.extract.source import DltSource
12
+ from dlt.pipeline.pipeline import Pipeline
13
+
14
+ from dagster_dlt.constants import META_KEY_PIPELINE, META_KEY_SOURCE, META_KEY_TRANSLATOR
15
+ from dagster_dlt.translator import DagsterDltTranslator
16
+
17
+
18
+ def build_dlt_asset_specs(
19
+ dlt_source: DltSource,
20
+ dlt_pipeline: Pipeline,
21
+ dagster_dlt_translator: Optional[DagsterDltTranslator] = None,
22
+ ) -> Sequence[AssetSpec]:
23
+ """Build a list of asset specs from a dlt source and pipeline.
24
+
25
+ Args:
26
+ dlt_source (DltSource): dlt source object
27
+ dlt_pipeline (Pipeline): dlt pipeline object
28
+ dagster_dlt_translator (Optional[DagsterDltTranslator]): Allows customizing how to
29
+ map dlt project to asset keys and asset metadata.
30
+
31
+ Returns:
32
+ List[AssetSpec] list of asset specs from dlt source and pipeline
33
+
34
+ """
35
+ dagster_dlt_translator = dagster_dlt_translator or DagsterDltTranslator()
36
+ return [
37
+ AssetSpec(
38
+ key=dagster_dlt_translator.get_asset_key(dlt_source_resource),
39
+ automation_condition=dagster_dlt_translator.get_automation_condition(
40
+ dlt_source_resource
41
+ ),
42
+ deps=dagster_dlt_translator.get_deps_asset_keys(dlt_source_resource),
43
+ description=dagster_dlt_translator.get_description(dlt_source_resource),
44
+ group_name=dagster_dlt_translator.get_group_name(dlt_source_resource),
45
+ metadata={
46
+ **dagster_dlt_translator.get_metadata(dlt_source_resource),
47
+ META_KEY_SOURCE: dlt_source,
48
+ META_KEY_PIPELINE: dlt_pipeline,
49
+ META_KEY_TRANSLATOR: dagster_dlt_translator,
50
+ },
51
+ owners=dagster_dlt_translator.get_owners(dlt_source_resource),
52
+ tags=dagster_dlt_translator.get_tags(dlt_source_resource),
53
+ kinds=dagster_dlt_translator.get_kinds(dlt_source_resource, dlt_pipeline.destination),
54
+ )
55
+ for dlt_source_resource in dlt_source.selected_resources.values()
56
+ ]
57
+
58
+
59
+ def dlt_assets(
60
+ *,
61
+ dlt_source: DltSource,
62
+ dlt_pipeline: Pipeline,
63
+ name: Optional[str] = None,
64
+ group_name: Optional[str] = None,
65
+ dagster_dlt_translator: Optional[DagsterDltTranslator] = None,
66
+ partitions_def: Optional[PartitionsDefinition] = None,
67
+ op_tags: Optional[Mapping[str, Any]] = None,
68
+ ) -> Callable[[Callable[..., Any]], AssetsDefinition]:
69
+ """Asset Factory for using data load tool (dlt).
70
+
71
+ Args:
72
+ dlt_source (DltSource): The DltSource to be ingested.
73
+ dlt_pipeline (Pipeline): The dlt Pipeline defining the destination parameters.
74
+ name (Optional[str], optional): The name of the op.
75
+ group_name (Optional[str], optional): The name of the asset group.
76
+ dagster_dlt_translator (DagsterDltTranslator, optional): Customization object for defining asset parameters from dlt resources.
77
+ partitions_def (Optional[PartitionsDefinition]): Optional partitions definition.
78
+ op_tags (Optional[Mapping[str, Any]]): The tags for the underlying op.
79
+
80
+ Examples:
81
+ Loading Hubspot data to Snowflake with an auto materialize policy using the dlt verified source:
82
+
83
+ .. code-block:: python
84
+
85
+ from dagster_dlt import DagsterDltResource, DagsterDltTranslator, dlt_assets
86
+
87
+
88
+ class HubspotDagsterDltTranslator(DagsterDltTranslator):
89
+ @public
90
+ def get_auto_materialize_policy(self, resource: DltResource) -> Optional[AutoMaterializePolicy]:
91
+ return AutoMaterializePolicy.eager().with_rules(
92
+ AutoMaterializeRule.materialize_on_cron("0 0 * * *")
93
+ )
94
+
95
+
96
+ @dlt_assets(
97
+ dlt_source=hubspot(include_history=True),
98
+ dlt_pipeline=pipeline(
99
+ pipeline_name="hubspot",
100
+ dataset_name="hubspot",
101
+ destination="snowflake",
102
+ progress="log",
103
+ ),
104
+ name="hubspot",
105
+ group_name="hubspot",
106
+ dagster_dlt_translator=HubspotDagsterDltTranslator(),
107
+ )
108
+ def hubspot_assets(context: AssetExecutionContext, dlt: DagsterDltResource):
109
+ yield from dlt.run(context=context)
110
+
111
+ Loading Github issues to snowflake:
112
+
113
+ .. code-block:: python
114
+
115
+ from dagster_dlt import DagsterDltResource, dlt_assets
116
+
117
+
118
+ @dlt_assets(
119
+ dlt_source=github_reactions(
120
+ "dagster-io", "dagster", items_per_page=100, max_items=250
121
+ ),
122
+ dlt_pipeline=pipeline(
123
+ pipeline_name="github_issues",
124
+ dataset_name="github",
125
+ destination="snowflake",
126
+ progress="log",
127
+ ),
128
+ name="github",
129
+ group_name="github",
130
+ )
131
+ def github_reactions_dagster_assets(context: AssetExecutionContext, dlt: DagsterDltResource):
132
+ yield from dlt.run(context=context)
133
+
134
+ """
135
+ dagster_dlt_translator = check.inst_param(
136
+ dagster_dlt_translator or DagsterDltTranslator(),
137
+ "dagster_dlt_translator",
138
+ DagsterDltTranslator,
139
+ )
140
+ return multi_asset(
141
+ name=name,
142
+ group_name=group_name,
143
+ can_subset=True,
144
+ partitions_def=partitions_def,
145
+ op_tags=op_tags,
146
+ specs=build_dlt_asset_specs(
147
+ dlt_source=dlt_source,
148
+ dlt_pipeline=dlt_pipeline,
149
+ dagster_dlt_translator=dagster_dlt_translator,
150
+ ),
151
+ )
@@ -0,0 +1,3 @@
1
+ META_KEY_SOURCE = "dagster_dlt/source"
2
+ META_KEY_PIPELINE = "dagster_dlt/pipeline"
3
+ META_KEY_TRANSLATOR = "dagster_dlt/translator"
@@ -0,0 +1,108 @@
1
+ from collections.abc import Iterator
2
+ from typing import Optional, Union
3
+
4
+ from dagster import AssetMaterialization, MaterializeResult
5
+ from dagster._annotations import experimental, public
6
+ from dagster._core.definitions.metadata.metadata_set import TableMetadataSet
7
+ from dagster._core.execution.context.asset_execution_context import AssetExecutionContext
8
+ from dagster._core.execution.context.op_execution_context import OpExecutionContext
9
+ from dlt import Pipeline
10
+ from typing_extensions import TypeVar
11
+
12
+ DltEventType = Union[AssetMaterialization, MaterializeResult]
13
+ T = TypeVar("T", bound=DltEventType)
14
+
15
+
16
+ def _fetch_row_count(
17
+ dlt_pipeline: Pipeline,
18
+ table_name: str,
19
+ ) -> Optional[int]:
20
+ """Exists mostly for ease of testing."""
21
+ with dlt_pipeline.sql_client() as client:
22
+ with client.execute_query(
23
+ f"select count(*) as row_count from {table_name}",
24
+ ) as cursor:
25
+ result = cursor.fetchone()
26
+ if result is not None and isinstance(result[0], int):
27
+ return result[0]
28
+ else:
29
+ return None
30
+
31
+
32
+ def fetch_row_count_metadata(
33
+ materialization: DltEventType,
34
+ context: Union[OpExecutionContext, AssetExecutionContext],
35
+ dlt_pipeline: Pipeline,
36
+ ) -> TableMetadataSet:
37
+ if not materialization.metadata:
38
+ raise Exception("Missing required metadata to retrieve row count.")
39
+ if context.has_partition_key:
40
+ rows_loaded = materialization.metadata.get("rows_loaded")
41
+ return TableMetadataSet(
42
+ partition_row_count=rows_loaded.value if rows_loaded else 0 # type: ignore
43
+ )
44
+
45
+ jobs_metadata = materialization.metadata.get("jobs")
46
+ if not jobs_metadata or not isinstance(jobs_metadata, list):
47
+ raise Exception("Missing jobs metadata to retrieve row count.")
48
+ table_name = jobs_metadata[0].get("table_name")
49
+ try:
50
+ return TableMetadataSet(row_count=_fetch_row_count(dlt_pipeline, table_name))
51
+ # Filesystem does not have a SQL client and table might not be found
52
+ except Exception as e:
53
+ context.log.error(
54
+ f"An error occurred while fetching row count for {table_name}. Row count metadata"
55
+ " will not be included in the event.\n\n"
56
+ f"Exception: {e}"
57
+ )
58
+ return TableMetadataSet(row_count=None)
59
+
60
+
61
+ class DltEventIterator(Iterator[T]):
62
+ """A wrapper around an iterator of Dlt events which contains additional methods for
63
+ post-processing the events, such as fetching column metadata.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ events: Iterator[T],
69
+ context: Union[OpExecutionContext, AssetExecutionContext],
70
+ dlt_pipeline: Pipeline,
71
+ ) -> None:
72
+ self._inner_iterator = events
73
+ self._context = context
74
+ self._dlt_pipeline = dlt_pipeline
75
+
76
+ def __next__(self) -> T:
77
+ return next(self._inner_iterator)
78
+
79
+ def __iter__(self) -> "DltEventIterator[T]":
80
+ return self
81
+
82
+ @public
83
+ @experimental
84
+ def fetch_row_count(self) -> "DltEventIterator":
85
+ """Fetches row count metadata for each resource loaded by dlt.
86
+
87
+ Retrieves the row count for each resource.
88
+
89
+ Returns:
90
+ DltEventIterator: An iterator of Dagster events with row count metadata attached.
91
+ """
92
+
93
+ def _fetch_row_count() -> Iterator[T]:
94
+ for event in self:
95
+ row_count_metadata = fetch_row_count_metadata(
96
+ event,
97
+ context=self._context,
98
+ # table_name=str(self._resource.table_name),
99
+ dlt_pipeline=self._dlt_pipeline,
100
+ )
101
+ if event.metadata:
102
+ yield event._replace(metadata={**row_count_metadata, **event.metadata})
103
+
104
+ return DltEventIterator[T](
105
+ _fetch_row_count(),
106
+ self._context,
107
+ self._dlt_pipeline,
108
+ )
@@ -0,0 +1 @@
1
+ partial
@@ -0,0 +1,301 @@
1
+ from collections.abc import Iterator, Mapping
2
+ from datetime import datetime, timezone
3
+ from typing import Any, Optional, Union
4
+
5
+ from dagster import (
6
+ AssetExecutionContext,
7
+ AssetMaterialization,
8
+ ConfigurableResource,
9
+ MaterializeResult,
10
+ MetadataValue,
11
+ OpExecutionContext,
12
+ TableColumnConstraints,
13
+ _check as check,
14
+ )
15
+ from dagster._annotations import experimental, public
16
+ from dagster._core.definitions.metadata.metadata_set import TableMetadataSet
17
+ from dagster._core.definitions.metadata.table import TableColumn, TableSchema
18
+ from dlt.common.pipeline import LoadInfo
19
+ from dlt.common.schema import Schema
20
+ from dlt.extract.resource import DltResource
21
+ from dlt.extract.source import DltSource
22
+ from dlt.pipeline.pipeline import Pipeline
23
+
24
+ from dagster_dlt.constants import META_KEY_PIPELINE, META_KEY_SOURCE, META_KEY_TRANSLATOR
25
+ from dagster_dlt.dlt_event_iterator import DltEventIterator, DltEventType
26
+ from dagster_dlt.translator import DagsterDltTranslator
27
+
28
+
29
+ @experimental
30
+ class DagsterDltResource(ConfigurableResource):
31
+ @classmethod
32
+ def _is_dagster_maintained(cls) -> bool:
33
+ return True
34
+
35
+ def _cast_load_info_metadata(self, mapping: Mapping[Any, Any]) -> Mapping[Any, Any]:
36
+ """Converts datetime and timezone values in a mapping to strings.
37
+
38
+ Workaround for dagster._core.errors.DagsterInvalidMetadata: Could not resolve the metadata
39
+ value for "jobs" to a known type. Value is not JSON serializable.
40
+
41
+ Args:
42
+ mapping (Mapping): Dictionary possibly containing datetime/timezone values
43
+
44
+ Returns:
45
+ Mapping[Any, Any]: Metadata with datetime and timezone values casted to strings
46
+
47
+ """
48
+ try:
49
+ # zoneinfo is python >= 3.9
50
+ from zoneinfo import ZoneInfo
51
+
52
+ casted_instance_types = (datetime, timezone, ZoneInfo)
53
+ except:
54
+ from dateutil.tz import tzfile
55
+
56
+ casted_instance_types = (datetime, timezone, tzfile)
57
+
58
+ def _recursive_cast(value: Any):
59
+ if isinstance(value, dict):
60
+ return {k: _recursive_cast(v) for k, v in value.items()}
61
+ elif isinstance(value, list):
62
+ return [_recursive_cast(item) for item in value]
63
+ elif isinstance(value, casted_instance_types):
64
+ return str(value)
65
+ else:
66
+ return value
67
+
68
+ return {k: _recursive_cast(v) for k, v in mapping.items()}
69
+
70
+ def _extract_table_schema_metadata(self, table_name: str, schema: Schema) -> TableSchema:
71
+ # Pyright does not detect the default value from 'pop' and 'get'
72
+ try:
73
+ table_schema = TableSchema(
74
+ columns=[
75
+ TableColumn(
76
+ name=column.pop("name", ""), # type: ignore
77
+ type=column.pop("data_type", "string"), # type: ignore
78
+ constraints=TableColumnConstraints(
79
+ nullable=column.pop("nullable", True), # type: ignore
80
+ unique=column.pop("unique", False), # type: ignore
81
+ other=[*column.keys()], # e.g. "primary_key" or "foreign_key"
82
+ ),
83
+ )
84
+ for column in schema.get_table_columns(table_name).values()
85
+ ]
86
+ )
87
+ except KeyError:
88
+ # We want the asset to materialize even if we failed to extract the table schema.
89
+ table_schema = TableSchema(columns=[])
90
+ return table_schema
91
+
92
+ def extract_resource_metadata(
93
+ self,
94
+ context: Union[OpExecutionContext, AssetExecutionContext],
95
+ resource: DltResource,
96
+ load_info: LoadInfo,
97
+ dlt_pipeline: Pipeline,
98
+ ) -> Mapping[str, Any]:
99
+ """Helper method to extract dlt resource metadata from load info dict.
100
+
101
+ Args:
102
+ context (Union[OpExecutionContext, AssetExecutionContext]): Asset or op execution context
103
+ resource (DltResource): The dlt resource being materialized
104
+ load_info (LoadInfo): Run metadata from dlt `pipeline.run(...)`
105
+ dlt_pipeline (Pipeline): The dlt pipeline used by `resource`
106
+
107
+ Returns:
108
+ Mapping[str, Any]: Asset-specific metadata dictionary
109
+
110
+ """
111
+ dlt_base_metadata_types = {
112
+ "first_run",
113
+ "started_at",
114
+ "finished_at",
115
+ "dataset_name",
116
+ "destination_name",
117
+ "destination_type",
118
+ }
119
+
120
+ load_info_dict = self._cast_load_info_metadata(load_info.asdict())
121
+
122
+ # shared metadata that is displayed for all assets
123
+ base_metadata = {k: v for k, v in load_info_dict.items() if k in dlt_base_metadata_types}
124
+ default_schema = dlt_pipeline.default_schema
125
+ normalized_table_name = default_schema.naming.normalize_table_identifier(
126
+ str(resource.table_name)
127
+ )
128
+ # job metadata for specific target `normalized_table_name`
129
+ base_metadata["jobs"] = [
130
+ job
131
+ for load_package in load_info_dict.get("load_packages", [])
132
+ for job in load_package.get("jobs", [])
133
+ if job.get("table_name") == normalized_table_name
134
+ ]
135
+ rows_loaded = dlt_pipeline.last_trace.last_normalize_info.row_counts.get(
136
+ normalized_table_name
137
+ )
138
+ if rows_loaded:
139
+ base_metadata["rows_loaded"] = MetadataValue.int(rows_loaded)
140
+
141
+ schema: Optional[str] = None
142
+ for load_package in load_info_dict.get("load_packages", []):
143
+ for table in load_package.get("tables", []):
144
+ if table.get("name") == normalized_table_name:
145
+ schema = table.get("schema_name")
146
+ break
147
+ if schema:
148
+ break
149
+
150
+ destination_name: Optional[str] = base_metadata.get("destination_name")
151
+ table_name = None
152
+ if destination_name and schema:
153
+ table_name = ".".join([destination_name, schema, normalized_table_name])
154
+
155
+ child_table_names = [
156
+ name
157
+ for name in default_schema.data_table_names()
158
+ if name.startswith(f"{normalized_table_name}__")
159
+ ]
160
+ child_table_schemas = {
161
+ table_name: self._extract_table_schema_metadata(table_name, default_schema)
162
+ for table_name in child_table_names
163
+ }
164
+ table_schema = self._extract_table_schema_metadata(normalized_table_name, default_schema)
165
+
166
+ base_metadata = {
167
+ **child_table_schemas,
168
+ **base_metadata,
169
+ **TableMetadataSet(
170
+ column_schema=table_schema,
171
+ table_name=table_name,
172
+ ),
173
+ }
174
+
175
+ return base_metadata
176
+
177
+ @public
178
+ def run(
179
+ self,
180
+ context: Union[OpExecutionContext, AssetExecutionContext],
181
+ dlt_source: Optional[DltSource] = None,
182
+ dlt_pipeline: Optional[Pipeline] = None,
183
+ dagster_dlt_translator: Optional[DagsterDltTranslator] = None,
184
+ **kwargs,
185
+ ) -> DltEventIterator[DltEventType]:
186
+ """Runs the dlt pipeline with subset support.
187
+
188
+ Args:
189
+ context (Union[OpExecutionContext, AssetExecutionContext]): Asset or op execution context
190
+ dlt_source (Optional[DltSource]): optional dlt source if resource is used from an `@op`
191
+ dlt_pipeline (Optional[Pipeline]): optional dlt pipeline if resource is used from an `@op`
192
+ dagster_dlt_translator (Optional[DagsterDltTranslator]): optional dlt translator if resource is used from an `@op`
193
+ **kwargs (dict[str, Any]): Keyword args passed to pipeline `run` method
194
+
195
+ Returns:
196
+ DltEventIterator[DltEventType]: An iterator of MaterializeResult or AssetMaterialization
197
+
198
+ """
199
+ # This resource can be used in both `asset` and `op` definitions. In the context of an asset
200
+ # execution, we retrieve the dlt source, pipeline, and translator from the asset metadata
201
+ # as a fallback mechanism. We give preference to explicit parameters to make it easy to
202
+ # customize execution, e.g., when using partitions.
203
+ if isinstance(context, AssetExecutionContext):
204
+ metadata_by_key = context.assets_def.metadata_by_key
205
+ first_asset_metadata = next(iter(metadata_by_key.values()))
206
+
207
+ dlt_source = check.inst(
208
+ dlt_source or first_asset_metadata.get(META_KEY_SOURCE), DltSource
209
+ )
210
+ dlt_pipeline = check.inst(
211
+ dlt_pipeline or first_asset_metadata.get(META_KEY_PIPELINE), Pipeline
212
+ )
213
+ dagster_dlt_translator = check.inst(
214
+ dagster_dlt_translator or first_asset_metadata.get(META_KEY_TRANSLATOR),
215
+ DagsterDltTranslator,
216
+ )
217
+
218
+ dlt_source = check.not_none(
219
+ dlt_source, "dlt_source is a required parameter in an op context"
220
+ )
221
+ dlt_pipeline = check.not_none(
222
+ dlt_pipeline, "dlt_pipeline is a required parameter in an op context"
223
+ )
224
+
225
+ # Default to base translator if undefined
226
+ dagster_dlt_translator = dagster_dlt_translator or DagsterDltTranslator()
227
+ return DltEventIterator(
228
+ self._run(
229
+ context=context,
230
+ dlt_source=dlt_source,
231
+ dlt_pipeline=dlt_pipeline,
232
+ dagster_dlt_translator=dagster_dlt_translator,
233
+ **kwargs,
234
+ ),
235
+ context=context,
236
+ dlt_pipeline=dlt_pipeline,
237
+ )
238
+
239
+ def _run(
240
+ self,
241
+ context: Union[OpExecutionContext, AssetExecutionContext],
242
+ dlt_source: DltSource,
243
+ dlt_pipeline: Pipeline,
244
+ dagster_dlt_translator: DagsterDltTranslator,
245
+ **kwargs,
246
+ ) -> Iterator[DltEventType]:
247
+ """Runs the dlt pipeline with subset support.
248
+
249
+ Args:
250
+ context (Union[OpExecutionContext, AssetExecutionContext]): Asset or op execution context
251
+ dlt_source (Optional[DltSource]): optional dlt source if resource is used from an `@op`
252
+ dlt_pipeline (Optional[Pipeline]): optional dlt pipeline if resource is used from an `@op`
253
+ dagster_dlt_translator (Optional[DagsterDltTranslator]): optional dlt translator if resource is used from an `@op`
254
+ **kwargs (dict[str, Any]): Keyword args passed to pipeline `run` method
255
+
256
+ Returns:
257
+ DltEventIterator[DltEventType]: An iterator of MaterializeResult or AssetMaterialization
258
+
259
+ """
260
+ asset_key_dlt_source_resource_mapping = {
261
+ dagster_dlt_translator.get_asset_key(dlt_source_resource): dlt_source_resource
262
+ for dlt_source_resource in dlt_source.selected_resources.values()
263
+ }
264
+
265
+ # Filter sources by asset key sub-selection
266
+ if context.is_subset:
267
+ asset_key_dlt_source_resource_mapping = {
268
+ asset_key: asset_dlt_source_resource
269
+ for (
270
+ asset_key,
271
+ asset_dlt_source_resource,
272
+ ) in asset_key_dlt_source_resource_mapping.items()
273
+ if asset_key in context.selected_asset_keys
274
+ }
275
+ dlt_source = dlt_source.with_resources(
276
+ *[
277
+ dlt_source_resource.name
278
+ for dlt_source_resource in asset_key_dlt_source_resource_mapping.values()
279
+ if dlt_source_resource
280
+ ]
281
+ )
282
+
283
+ load_info = dlt_pipeline.run(dlt_source, **kwargs)
284
+
285
+ load_info.raise_on_failed_jobs()
286
+
287
+ has_asset_def: bool = bool(context and context.has_assets_def)
288
+
289
+ for (
290
+ asset_key,
291
+ dlt_source_resource,
292
+ ) in asset_key_dlt_source_resource_mapping.items():
293
+ metadata = self.extract_resource_metadata(
294
+ context, dlt_source_resource, load_info, dlt_pipeline
295
+ )
296
+
297
+ if has_asset_def:
298
+ yield MaterializeResult(asset_key=asset_key, metadata=metadata)
299
+
300
+ else:
301
+ yield AssetMaterialization(asset_key=asset_key, metadata=metadata)
@@ -0,0 +1,168 @@
1
+ from collections.abc import Iterable, Mapping, Sequence
2
+ from dataclasses import dataclass
3
+ from typing import Any, Optional
4
+
5
+ from dagster import AssetKey, AutoMaterializePolicy, AutomationCondition
6
+ from dagster._annotations import public
7
+ from dlt.common.destination import Destination
8
+ from dlt.extract.resource import DltResource
9
+
10
+
11
+ @dataclass
12
+ class DagsterDltTranslator:
13
+ @public
14
+ def get_asset_key(self, resource: DltResource) -> AssetKey:
15
+ """Defines asset key for a given dlt resource key and dataset name.
16
+
17
+ This method can be overriden to provide custom asset key for a dlt resource.
18
+
19
+ Args:
20
+ resource (DltResource): dlt resource
21
+
22
+ Returns:
23
+ AssetKey of Dagster asset derived from dlt resource
24
+
25
+ """
26
+ return AssetKey(f"dlt_{resource.source_name}_{resource.name}")
27
+
28
+ @public
29
+ def get_auto_materialize_policy(self, resource: DltResource) -> Optional[AutoMaterializePolicy]:
30
+ """Defines resource specific auto materialize policy.
31
+
32
+ This method can be overriden to provide custom auto materialize policy for a dlt resource.
33
+
34
+ Args:
35
+ resource (DltResource): dlt resource
36
+
37
+ Returns:
38
+ Optional[AutoMaterializePolicy]: The automaterialize policy for a resource
39
+
40
+ """
41
+ return None
42
+
43
+ @public
44
+ def get_automation_condition(self, resource: DltResource) -> Optional[AutomationCondition]:
45
+ """Defines resource specific automation condition.
46
+
47
+ This method can be overridden to provide custom automation condition for a dlt resource.
48
+
49
+ Args:
50
+ resource (DltResource): dlt resource
51
+
52
+ Returns:
53
+ Optional[AutomationCondition]: The automation condition for a resource
54
+
55
+ """
56
+ auto_materialize_policy = self.get_auto_materialize_policy(resource)
57
+ return (
58
+ auto_materialize_policy.to_automation_condition() if auto_materialize_policy else None
59
+ )
60
+
61
+ @public
62
+ def get_deps_asset_keys(self, resource: DltResource) -> Iterable[AssetKey]:
63
+ """Defines upstream asset dependencies given a dlt resource.
64
+
65
+ Defaults to a concatenation of `resource.source_name` and `resource.name`.
66
+
67
+ Args:
68
+ resource (DltResource): dlt resource
69
+
70
+ Returns:
71
+ Iterable[AssetKey]: The Dagster asset keys upstream of `dlt_resource_key`.
72
+
73
+ """
74
+ if resource.is_transformer:
75
+ pipe = resource._pipe # noqa: SLF001
76
+ while pipe.has_parent:
77
+ pipe = pipe.parent
78
+ return [AssetKey(f"{resource.source_name}_{pipe.name}")]
79
+ return [AssetKey(f"{resource.source_name}_{resource.name}")]
80
+
81
+ @public
82
+ def get_description(self, resource: DltResource) -> Optional[str]:
83
+ """A method that takes in a dlt resource returns the Dagster description of the resource.
84
+
85
+ This method can be overriden to provide a custom description for a dlt resource.
86
+
87
+ Args:
88
+ resource (DltResource): dlt resource
89
+
90
+ Returns:
91
+ Optional[str]: The Dagster description for the dlt resource.
92
+ """
93
+ pipe = resource._pipe # noqa: SLF001
94
+ # If the function underlying the resource is a single callable,
95
+ # return the docstring of the callable.
96
+ if len(pipe.steps) == 1 and callable(pipe.steps[0]):
97
+ return pipe.steps[0].__doc__
98
+ return None
99
+
100
+ @public
101
+ def get_group_name(self, resource: DltResource) -> Optional[str]:
102
+ """A method that takes in a dlt resource and returns the Dagster group name of the resource.
103
+
104
+ This method can be overriden to provide a custom group name for a dlt resource.
105
+
106
+ Args:
107
+ resource (DltResource): dlt resource
108
+
109
+ Returns:
110
+ Optional[str]: A Dagster group name for the dlt resource.
111
+ """
112
+ return None
113
+
114
+ @public
115
+ def get_metadata(self, resource: DltResource) -> Mapping[str, Any]:
116
+ """Defines resource specific metadata.
117
+
118
+ Args:
119
+ resource (DltResource): dlt resource
120
+
121
+ Returns:
122
+ Mapping[str, Any]: The custom metadata entries for this resource.
123
+ """
124
+ return {}
125
+
126
+ @public
127
+ def get_owners(self, resource: DltResource) -> Optional[Sequence[str]]:
128
+ """A method that takes in a dlt resource and returns the Dagster owners of the resource.
129
+
130
+ This method can be overriden to provide custom owners for a dlt resource.
131
+
132
+ Args:
133
+ resource (DltResource): dlt resource
134
+
135
+ Returns:
136
+ Optional[Sequence[str]]: A sequence of Dagster owners for the dlt resource.
137
+ """
138
+ return None
139
+
140
+ @public
141
+ def get_tags(self, resource: DltResource) -> Mapping[str, str]:
142
+ """A method that takes in a dlt resource and returns the Dagster tags of the structure.
143
+
144
+ This method can be overriden to provide custom tags for a dlt resource.
145
+
146
+ Args:
147
+ resource (DltResource): dlt resource
148
+
149
+ Returns:
150
+ Optional[Mapping[str, str]]: A dictionary representing the Dagster tags for the
151
+ dlt resource.
152
+ """
153
+ return {}
154
+
155
+ @public
156
+ def get_kinds(self, resource: DltResource, destination: Destination) -> set[str]:
157
+ """A method that takes in a dlt resource and returns the kinds which should be
158
+ attached. Defaults to the destination type and "dlt".
159
+
160
+ This method can be overriden to provide custom kinds for a dlt resource.
161
+
162
+ Args:
163
+ resource (DltResource): dlt resource
164
+
165
+ Returns:
166
+ Set[str]: The kinds of the asset.
167
+ """
168
+ return {"dlt", destination.destination_name}
@@ -0,0 +1 @@
1
+ __version__ = "0.25.9"
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.1
2
+ Name: dagster-dlt
3
+ Version: 0.25.9
4
+ Summary: Package for performing ETL/ELT tasks with dlt in Dagster.
5
+ Home-page: https://github.com/dagster-io/dagster/tree/master/python_modules/libraries/dagster-dlt
6
+ Author: Dagster Labs
7
+ Author-email: hello@dagsterlabs.com
8
+ License: Apache-2.0
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Requires-Python: >=3.9,<3.13
16
+ Provides-Extra: test
17
+ License-File: LICENSE
@@ -0,0 +1,20 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ integration.yaml
5
+ setup.cfg
6
+ setup.py
7
+ dagster_dlt/__init__.py
8
+ dagster_dlt/asset_decorator.py
9
+ dagster_dlt/constants.py
10
+ dagster_dlt/dlt_event_iterator.py
11
+ dagster_dlt/py.typed
12
+ dagster_dlt/resource.py
13
+ dagster_dlt/translator.py
14
+ dagster_dlt/version.py
15
+ dagster_dlt.egg-info/PKG-INFO
16
+ dagster_dlt.egg-info/SOURCES.txt
17
+ dagster_dlt.egg-info/dependency_links.txt
18
+ dagster_dlt.egg-info/not-zip-safe
19
+ dagster_dlt.egg-info/requires.txt
20
+ dagster_dlt.egg-info/top_level.txt
@@ -0,0 +1,5 @@
1
+ dagster==1.9.9
2
+ dlt>=0.4
3
+
4
+ [test]
5
+ duckdb
@@ -0,0 +1 @@
1
+ dagster_dlt
@@ -0,0 +1,5 @@
1
+ name: Dagster dlt
2
+ suspended: false
3
+ owner: Dagster
4
+ maintainer_type: dagster
5
+ maintainer_email: hello@dagsterlabs.com
@@ -0,0 +1,14 @@
1
+ [metadata]
2
+ license_files = LICENSE
3
+
4
+ [check-manifest]
5
+ ignore =
6
+ .coveragerc
7
+ tox.ini
8
+ pytest.ini
9
+ dagster_dlt_tests/**
10
+
11
+ [egg_info]
12
+ tag_build =
13
+ tag_date = 0
14
+
@@ -0,0 +1,43 @@
1
+ from pathlib import Path
2
+
3
+ from setuptools import find_packages, setup
4
+
5
+
6
+ def get_version() -> str:
7
+ version: dict[str, str] = {}
8
+ with open(Path(__file__).parent / "dagster_dlt/version.py", encoding="utf8") as fp:
9
+ exec(fp.read(), version)
10
+
11
+ return version["__version__"]
12
+
13
+
14
+ ver = get_version()
15
+ # dont pin dev installs to avoid pip dep resolver issues
16
+ pin = "" if ver == "1!0+dev" else f"=={ver}"
17
+ setup(
18
+ name="dagster-dlt",
19
+ version=ver,
20
+ author="Dagster Labs",
21
+ author_email="hello@dagsterlabs.com",
22
+ license="Apache-2.0",
23
+ description="Package for performing ETL/ELT tasks with dlt in Dagster.",
24
+ url="https://github.com/dagster-io/dagster/tree/master/python_modules/libraries/dagster-dlt",
25
+ classifiers=[
26
+ "Programming Language :: Python :: 3.9",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "License :: OSI Approved :: Apache Software License",
31
+ "Operating System :: OS Independent",
32
+ ],
33
+ packages=find_packages(exclude=["dagster_dlt_tests*"]),
34
+ include_package_data=True,
35
+ python_requires=">=3.9,<3.13",
36
+ install_requires=["dagster==1.9.9", "dlt>=0.4"],
37
+ zip_safe=False,
38
+ extras_require={
39
+ "test": [
40
+ "duckdb",
41
+ ]
42
+ },
43
+ )