cloe-nessy 0.3.5__py3-none-any.whl → 0.3.8__py3-none-any.whl

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.
Files changed (88) hide show
  1. cloe_nessy/__init__.py +0 -0
  2. cloe_nessy/clients/__init__.py +0 -0
  3. cloe_nessy/clients/api_client/__init__.py +0 -0
  4. cloe_nessy/clients/api_client/api_client.py +0 -0
  5. cloe_nessy/clients/api_client/api_response.py +0 -0
  6. cloe_nessy/clients/api_client/auth.py +0 -0
  7. cloe_nessy/clients/api_client/exceptions.py +0 -0
  8. cloe_nessy/file_utilities/__init__.py +0 -0
  9. cloe_nessy/file_utilities/exceptions.py +0 -0
  10. cloe_nessy/file_utilities/factory.py +0 -0
  11. cloe_nessy/file_utilities/get_file_paths.py +0 -0
  12. cloe_nessy/file_utilities/location_types.py +0 -0
  13. cloe_nessy/file_utilities/strategies/__init__.py +0 -0
  14. cloe_nessy/file_utilities/strategies/base_strategy.py +0 -0
  15. cloe_nessy/file_utilities/strategies/local_strategy.py +0 -0
  16. cloe_nessy/file_utilities/strategies/onelake_strategy.py +0 -0
  17. cloe_nessy/file_utilities/strategies/utils_strategy.py +0 -0
  18. cloe_nessy/integration/__init__.py +0 -0
  19. cloe_nessy/integration/reader/__init__.py +0 -0
  20. cloe_nessy/integration/reader/api_reader.py +0 -0
  21. cloe_nessy/integration/reader/catalog_reader.py +0 -0
  22. cloe_nessy/integration/reader/excel_reader.py +0 -0
  23. cloe_nessy/integration/reader/exceptions.py +0 -0
  24. cloe_nessy/integration/reader/file_reader.py +0 -0
  25. cloe_nessy/integration/reader/reader.py +0 -0
  26. cloe_nessy/integration/writer/__init__.py +0 -0
  27. cloe_nessy/integration/writer/catalog_writer.py +0 -0
  28. cloe_nessy/logging/__init__.py +0 -0
  29. cloe_nessy/logging/logger_mixin.py +0 -0
  30. cloe_nessy/models/__init__.py +4 -0
  31. cloe_nessy/models/adapter/__init__.py +3 -0
  32. cloe_nessy/models/adapter/unity_catalog_adapter.py +292 -0
  33. cloe_nessy/models/catalog.py +10 -0
  34. cloe_nessy/models/column.py +0 -0
  35. cloe_nessy/models/constraint.py +0 -0
  36. cloe_nessy/models/foreign_key.py +0 -0
  37. cloe_nessy/models/mixins/__init__.py +0 -0
  38. cloe_nessy/models/mixins/read_instance_mixin.py +0 -0
  39. cloe_nessy/models/mixins/template_loader_mixin.py +0 -0
  40. cloe_nessy/models/schema.py +19 -0
  41. cloe_nessy/models/table.py +50 -5
  42. cloe_nessy/models/types.py +0 -0
  43. cloe_nessy/models/volume.py +67 -0
  44. cloe_nessy/object_manager/__init__.py +7 -2
  45. cloe_nessy/object_manager/table_manager.py +183 -7
  46. cloe_nessy/object_manager/volume_manager.py +70 -0
  47. cloe_nessy/pipeline/__init__.py +0 -0
  48. cloe_nessy/pipeline/actions/__init__.py +2 -0
  49. cloe_nessy/pipeline/actions/read_api.py +0 -0
  50. cloe_nessy/pipeline/actions/read_catalog_table.py +0 -0
  51. cloe_nessy/pipeline/actions/read_excel.py +0 -0
  52. cloe_nessy/pipeline/actions/read_files.py +0 -0
  53. cloe_nessy/pipeline/actions/read_metadata_yaml.py +0 -0
  54. cloe_nessy/pipeline/actions/transform_change_datatype.py +0 -0
  55. cloe_nessy/pipeline/actions/transform_clean_column_names.py +0 -0
  56. cloe_nessy/pipeline/actions/transform_concat_columns.py +0 -0
  57. cloe_nessy/pipeline/actions/transform_decode.py +0 -0
  58. cloe_nessy/pipeline/actions/transform_deduplication.py +0 -0
  59. cloe_nessy/pipeline/actions/transform_distinct.py +0 -0
  60. cloe_nessy/pipeline/actions/transform_filter.py +0 -0
  61. cloe_nessy/pipeline/actions/transform_generic_sql.py +0 -0
  62. cloe_nessy/pipeline/actions/transform_group_aggregate.py +0 -0
  63. cloe_nessy/pipeline/actions/transform_hash_columns.py +209 -0
  64. cloe_nessy/pipeline/actions/transform_join.py +0 -0
  65. cloe_nessy/pipeline/actions/transform_json_normalize.py +0 -0
  66. cloe_nessy/pipeline/actions/transform_rename_columns.py +0 -0
  67. cloe_nessy/pipeline/actions/transform_replace_values.py +0 -0
  68. cloe_nessy/pipeline/actions/transform_select_columns.py +0 -0
  69. cloe_nessy/pipeline/actions/transform_union.py +0 -0
  70. cloe_nessy/pipeline/actions/write_catalog_table.py +0 -0
  71. cloe_nessy/pipeline/pipeline.py +44 -2
  72. cloe_nessy/pipeline/pipeline_action.py +0 -0
  73. cloe_nessy/pipeline/pipeline_config.py +0 -0
  74. cloe_nessy/pipeline/pipeline_context.py +0 -0
  75. cloe_nessy/pipeline/pipeline_parsing_service.py +0 -0
  76. cloe_nessy/pipeline/pipeline_step.py +0 -0
  77. cloe_nessy/py.typed +0 -0
  78. cloe_nessy/session/__init__.py +0 -0
  79. cloe_nessy/session/session_manager.py +27 -0
  80. cloe_nessy/settings/__init__.py +0 -0
  81. cloe_nessy/settings/settings.py +0 -0
  82. cloe_nessy/utils/__init__.py +0 -0
  83. cloe_nessy/utils/file_and_directory_handler.py +0 -0
  84. cloe_nessy-0.3.8.dist-info/METADATA +46 -0
  85. {cloe_nessy-0.3.5.dist-info → cloe_nessy-0.3.8.dist-info}/RECORD +18 -12
  86. {cloe_nessy-0.3.5.dist-info → cloe_nessy-0.3.8.dist-info}/WHEEL +1 -1
  87. {cloe_nessy-0.3.5.dist-info → cloe_nessy-0.3.8.dist-info}/top_level.txt +0 -0
  88. cloe_nessy-0.3.5.dist-info/METADATA +0 -26
@@ -1,22 +1,119 @@
1
+ import functools
2
+ import logging
3
+ from dataclasses import dataclass, field
4
+
5
+ from delta import DeltaTable # type: ignore
6
+
1
7
  from ..logging import LoggerMixin
8
+ from ..models import Table
2
9
  from ..session import SessionManager
3
10
 
4
11
 
12
+ @dataclass
13
+ class TableManagerLogs:
14
+ """Dataclass defining the table manager logs table."""
15
+
16
+ logger_name = "Tabular:TableManager"
17
+ log_type: str = "nessy_simple_logs"
18
+ uc_table_name: str = "nessy_simple_logs"
19
+ uc_table_columns: dict[str, str] = field(
20
+ default_factory=lambda: {
21
+ "message": "STRING",
22
+ }
23
+ )
24
+
25
+
26
+ def table_log_decorator(operation: str):
27
+ """Creates a decorator that logs the start, failure (if any), and completion of a table operation.
28
+
29
+ The created decorator wraps a function that performs an operation on a table. The decorator logs
30
+ the start of the operation, calls the original function, logs if there was an exception, and logs
31
+ the completion of the operation. Functions that are wrapped must support the self._table_logger
32
+ attribute.
33
+
34
+ Args:
35
+ operation: The name of the operation to be logged. This will be included in the log messages.
36
+
37
+ Returns:
38
+ inner_decorator: A decorator that can be used to wrap a function that performs an operation on a table.
39
+
40
+ Example:
41
+ ```python
42
+ @table_log_decorator(operation='delete_physical_data_for_table')
43
+ def _delete_physical_data(self, table_identifier: str):
44
+ self._dbutils.fs.rm(table_location, recurse=True)
45
+ ```
46
+ """
47
+
48
+ def inner_decorator(func):
49
+ @functools.wraps(func)
50
+ def wrapper(self, *args, **kwargs):
51
+ table_identifier = kwargs.get("table_identifier") or kwargs.get("table").identifier or args[0]
52
+ if not isinstance(table_identifier, str):
53
+ # assume its a Table object
54
+ table_identifier = table_identifier.identifier
55
+ self._tabular_logger.info(
56
+ "operation:%s | identifier:%s | status:start | error:''",
57
+ operation,
58
+ table_identifier,
59
+ )
60
+ try:
61
+ func(self, *args, **kwargs)
62
+ except Exception as e:
63
+ self._tabular_logger.error(
64
+ "operation:%s | identifier:%s | status:failed | error:%s",
65
+ operation,
66
+ table_identifier,
67
+ e,
68
+ )
69
+ raise e
70
+ else:
71
+ self._tabular_logger.info(
72
+ "operation:%s | identifier:%s | status:completed | error:''",
73
+ operation,
74
+ table_identifier,
75
+ )
76
+
77
+ return wrapper
78
+
79
+ return inner_decorator
80
+
81
+
5
82
  class TableManager(LoggerMixin):
6
- """TableManager class for managing tables in the catalog."""
83
+ """TableManager class for managing tables."""
7
84
 
8
- def __init__(self):
85
+ def __init__(self, tabular_logger: logging.Logger | None = None):
9
86
  self._spark = SessionManager.get_spark_session()
10
87
  self._utils = SessionManager.get_utils()
11
88
  self._console_logger = self.get_console_logger()
12
89
  self._console_logger.debug("TableManager initialized...")
13
- self._tabular_logger = self.get_tabular_logger(uc_table_name="TableManager")
90
+ self._tabular_logger = tabular_logger or self.get_tabular_logger(**TableManagerLogs().__dict__)
14
91
  self._tabular_logger.debug("message:TableManager initialized.")
15
92
 
16
- @staticmethod
17
- def create_table():
18
- """Create a table in the catalog."""
19
- raise NotImplementedError
93
+ @table_log_decorator(operation="create")
94
+ def create_table(
95
+ self,
96
+ table: Table,
97
+ ignore_if_exists: bool = False,
98
+ replace: bool = False,
99
+ ) -> None:
100
+ """Creates a Table in the catalog.
101
+
102
+ Args:
103
+ table: A Table object representing the Delta table.
104
+ ignore_if_exists: If set to True, the function will return early
105
+ without doing anything if the table already exists.
106
+ replace: If set to True, the function will replace the table if it
107
+ already exists.
108
+ """
109
+ if ignore_if_exists and self.table_exists(table):
110
+ return
111
+ self._console_logger.info(f"Creating table: {table.identifier}")
112
+ self._spark.sql(f"USE CATALOG {table.catalog};")
113
+ self._spark.sql(f"USE SCHEMA {table.schema};")
114
+ for statement in table.get_create_statement(replace=replace).split(";"):
115
+ if statement and statement != "\n":
116
+ self._spark.sql(statement)
20
117
 
21
118
  def drop_table(self, table_identifier: str, delete_physical_data: bool = False):
22
119
  """Deletes a Table. For security reasons you are forced to pass the table_name.
@@ -56,3 +153,82 @@ class TableManager(LoggerMixin):
56
153
  """
57
154
  self._console_logger.info("... deleting physical data for table [ '' ] from Catalog.")
58
155
  raise NotImplementedError("This can be implemented, once a Table object is available.")
156
+
157
+ def get_delta_table(self, table: Table | None = None, location: str | None = None) -> DeltaTable:
158
+ """Get the DeltaTable object from the Table objects location or a location string.
159
+
160
+ Args:
161
+ table: A Table object representing the Delta table.
162
+ location: A string representing the table location.
163
+
164
+ Returns:
165
+ The DeltaTable object corresponding to the given Table object or location string.
166
+
167
+ Raises:
168
+ ValueError: If neither table nor location is provided, or if both are provided.
169
+ """
170
+ if (table is None and location is None) or (table is not None and location is not None):
171
+ raise ValueError("Either table or location must be provided, but not both.")
172
+
173
+ if table is not None:
174
+ location = str(table.storage_path)
175
+ self._console_logger.info(f"Getting DeltaTable object for location: {location}")
176
+ return DeltaTable.forPath(self._spark, str(location))
177
+
178
+ def table_exists(self, table: Table | None = None, table_identifier: str | None = None) -> bool:
179
+ """Checks if a table exists in the catalog.
180
+
181
+ Args:
182
+ table: A Table object representing the Delta table.
183
+ table_identifier: A string representing the table identifier in the format 'catalog.schema.table'.
184
+
185
+ Returns:
186
+ True if the table exists, else False.
187
+
188
+ Raises:
189
+ ValueError: If neither table nor table_identifier is provided, or if both are provided.
190
+ ValueError: If the table_identifier is not in the format 'catalog.schema.table'.
191
+ """
192
+ if (table is None and table_identifier is None) or (table is not None and table_identifier is not None):
193
+ raise ValueError("Either table or table_identifier must be provided, but not both.")
194
+
195
+ if table is not None:
196
+ catalog = table.catalog
197
+ schema = table.schema
198
+ table_name = table.name
199
+ else:
200
+ assert table_identifier is not None, "table_identifier must be provided."
201
+ catalog, schema, table_name = table_identifier.split(".")
202
+ if not all([catalog, schema, table_name]):
203
+ raise ValueError("Invalid table identifier format. Expected 'catalog.schema.table'.")
204
+
205
+ query_result = self._spark.sql(
206
+ f"""
207
+ SELECT 1 FROM {catalog}.information_schema.tables
208
+ WHERE table_name = '{table_name}'
209
+ AND table_schema = '{schema}'
210
+ LIMIT 1""",
211
+ )
212
+ result = query_result.count() > 0
213
+ self._console_logger.info(f"Table [ '{catalog}.{schema}.{table_name}' ] exists: {result}")
214
+ return result is True
215
+
216
+ @table_log_decorator(operation="refresh")
217
+ def refresh_table(self, table: Table | None = None, table_identifier: str | None = None):
218
+ """Refreshes the metadata of a Delta table.
219
+
220
+ Args:
221
+ table: A Table object representing the Delta table.
222
+ table_identifier: The identifier of the Delta table in the format 'catalog.schema.table'.
223
+
224
+ Raises:
225
+ ValueError: If neither table nor table_identifier is provided, or if both are provided.
226
+ """
227
+ if (table is None and table_identifier is None) or (table is not None and table_identifier is not None):
228
+ raise ValueError("Either table or table_identifier must be provided, but not both.")
229
+
230
+ if table is not None:
231
+ table_identifier = f"{table.catalog}.{table.schema}.{table.name}"
232
+
233
+ self._console_logger.info(f"Refreshing table: {table_identifier}")
234
+ self._spark.sql(f"REFRESH TABLE {table_identifier};")
@@ -0,0 +1,70 @@
1
+ import logging
2
+
3
+ from ..logging import LoggerMixin
4
+ from ..models import Volume
5
+ from ..session import SessionManager
6
+
7
+
8
+ class VolumeManager(LoggerMixin):
9
+ """VolumeManager class for managing volumes."""
10
+
11
+ def __init__(self, console_logger: logging.Logger | None = None):
12
+ self._spark = SessionManager.get_spark_session()
13
+ self._console_logger = console_logger or self.get_console_logger()
14
+
15
+ def create_volume(self, volume: Volume):
16
+ """Creates a Volume in the catalog.
17
+
18
+ Args:
19
+ volume: A Volume object representing the UC object.
20
+ """
21
+ self._console_logger.info(f"Creating volume: {volume.identifier}")
22
+ self._spark.sql(f"USE CATALOG {volume.catalog};")
23
+ self._spark.sql(f"USE SCHEMA {volume.schema_name};")
24
+ for statement in volume.get_create_statement().split(";"):
25
+ if statement and statement != "\n":
26
+ self._spark.sql(statement)
27
+
28
+ def drop_volume(self, volume: Volume, if_exists: bool = True):
29
+ """Delete the volume.
30
+
31
+ Args:
32
+ volume: The volume to be deleted.
33
+ if_exists: If False, an error will be raised if the volume does not exist.
34
+ """
35
+ self._console_logger.info(f"Deleting volume: [' {volume.identifier}' ]")
36
+ self._spark.sql(f"DROP VOLUME {'IF EXISTS' if if_exists else ''} {volume.escaped_identifier};")
37
+ self._console_logger.info(f"Volume [' {volume.identifier}' ] has been deleted.")
38
+
39
+ def volume_exists(self, volume: Volume | None = None, volume_identifier: str | None = None) -> bool:
40
+ """Check if the volume exists.
41
+
42
+ Args:
43
+ volume: The volume to check.
44
+ volume_identifier: The identifier of the volume to check.
45
+
46
+ Raises:
47
+ ValueError: If both volume and volume_identifier are provided.
48
+
49
+ Returns:
50
+ True if the volume exists, False otherwise.
51
+ """
52
+ if volume and volume_identifier:
53
+ raise ValueError("Only one of volume or volume_identifier should be provided.")
54
+ if volume:
55
+ volume_identifier = volume.identifier
56
+
57
+ assert volume_identifier is not None
58
+
59
+ if volume_identifier.count(".") != 2:
60
+ raise ValueError("The identifier must be in the format 'catalog.schema.volume_name'.")
61
+ catalog, volume_schema, table_name = volume_identifier.split(".")
62
+ query_result = self._spark.sql(
63
+ f"""
64
+ SELECT 1 FROM {catalog}.information_schema.volumes
65
+ WHERE volume_name = '{table_name}'
66
+ AND volume_schema = '{volume_schema}'
67
+ LIMIT 1""",
68
+ )
69
+ result = query_result.count() > 0
70
+ return result is True
File without changes
@@ -14,6 +14,7 @@ from .transform_distinct import TransformDistinctAction
14
14
  from .transform_filter import TransformFilterAction
15
15
  from .transform_generic_sql import TransformSqlAction
16
16
  from .transform_group_aggregate import TransformGroupAggregate
17
+ from .transform_hash_columns import TransformHashColumnsAction
17
18
  from .transform_join import TransformJoinAction
18
19
  from .transform_json_normalize import TransformJsonNormalize
19
20
  from .transform_rename_columns import TransformRenameColumnsAction
@@ -51,4 +52,5 @@ __all__ = [
51
52
  "TransformRenameColumnsAction",
52
53
  "TransformReplaceValuesAction",
53
54
  "TransformSelectColumnsAction",
55
+ "TransformHashColumnsAction",
54
56
  ]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -0,0 +1,209 @@
1
+ from typing import Any
2
+
3
+ from pydantic import BaseModel, Field, model_validator
4
+ from pyspark.sql import functions as F
5
+
6
+ from ..pipeline_action import PipelineAction
7
+ from ..pipeline_context import PipelineContext
8
+
9
+ SUPPORTED_ALGORITHMS = {"hash", "md5", "sha1", "sha2", "xxhash64", "crc32"}
10
+ VALID_SHA2_BITS = {224, 256, 384, 512}
11
+
12
+
13
+ class HashSettings(BaseModel):
14
+ """Represents the settings for hashing columns.
15
+
16
+ Attributes:
17
+ columns: List of column names to hash.
18
+ algorithm: Hashing algorithm to use. Must be one of
19
+ "hash", "md5", "sha1", "sha2", "xxhash64", or "crc32".
20
+ bits: Bit length for the 'sha2' algorithm. Optional.
21
+ """
22
+
23
+ columns: list[str]
24
+ algorithm: str = Field(..., description="Hashing algorithm to use")
25
+ bits: int | None = Field(default=None, description="Only required for sha2")
26
+
27
+ @model_validator(mode="before")
28
+ def validate_all(cls, values):
29
+ """Validates the input values for a hashing operation before model instantiation.
30
+
31
+ This method performs the following checks:
32
+
33
+ 1. Ensures the specified hashing algorithm is supported.
34
+ 2. Validates that at least one column is provided and that the columns parameter is a non-empty list.
35
+ 3. Checks that hashing multiple columns is only supported for the 'hash' and 'xxhash64' algorithms.
36
+ 4. For the 'sha2' algorithm, ensures that the 'bits' parameter is one of the valid options.
37
+ 5. Ensures that the 'bits' parameter is not provided for algorithms other than 'sha2'.
38
+
39
+ Raises:
40
+ ValueError: If the algorithm is unsupported, no columns are provided, the columns parameter is invalid,
41
+ or the 'bits' parameter is invalid for the specified algorithm.
42
+ NotImplementedError: If multiple columns are provided and the algorithm does not support hashing multiple columns.
43
+
44
+ Args:
45
+ cls: The class being validated.
46
+ values: A dictionary of input values containing 'algorithm', 'columns', and 'bits'.
47
+
48
+ Returns:
49
+ The validated input values.
50
+ """
51
+ algorithm = values.get("algorithm")
52
+ columns = values.get("columns")
53
+ bits = values.get("bits")
54
+
55
+ if algorithm not in SUPPORTED_ALGORITHMS:
56
+ raise ValueError(
57
+ f"Unsupported hashing algorithm '{algorithm}'. Supported algorithms are: {SUPPORTED_ALGORITHMS}."
58
+ )
59
+
60
+ if not columns or not isinstance(columns, list) or len(columns) == 0:
61
+ raise ValueError("At least one column must be provided.")
62
+
63
+ if len(columns) > 1 and algorithm not in {"hash", "xxhash64"}:
64
+ raise NotImplementedError(
65
+ f"Hashing multiple columns is only supported for 'hash' and 'xxhash64'. Algorithm '{algorithm}' does not support this."
66
+ )
67
+
68
+ if algorithm == "sha2":
69
+ if bits not in VALID_SHA2_BITS:
70
+ raise ValueError(f"'bits' must be one of {VALID_SHA2_BITS} when using 'sha2'.")
71
+ elif bits is not None:
72
+ raise ValueError("'bits' is only allowed when algorithm is 'sha2'.")
73
+
74
+ return values
75
+
76
+
77
+ class HashConfig(BaseModel):
78
+ """A configuration model for defining hash settings for specific columns.
79
+
80
+ Attributes:
81
+ hash_config: A dictionary where the keys are column names
82
+ (as strings) and the values are `HashSettings` objects that define
83
+ the hash settings for each column.
84
+
85
+ Methods:
86
+ validate_config: Validates the hash configuration to ensure it contains
87
+ at least one entry and that all column names are valid strings. Raises a
88
+ `ValueError` if the configuration is invalid.
89
+ """
90
+
91
+ hash_config: dict[str, HashSettings]
92
+
93
+ @model_validator(mode="before")
94
+ def validate_config(cls, values):
95
+ """Validates the hash configuration provided in the model.
96
+
97
+ This method is executed in "before" mode to ensure that the `hash_config`
98
+ field in the input values meets the required criteria:
99
+
100
+ - It must be a dictionary.
101
+ - It must contain at least one entry.
102
+ - Each key in the dictionary must be a non-empty string.
103
+
104
+ Raises:
105
+ ValueError: If `hash_config` is missing, not a dictionary, empty, or
106
+ contains invalid column names.
107
+
108
+ Args:
109
+ cls: The class to which this validator is applied.
110
+ values: The input values to validate.
111
+
112
+ Returns:
113
+ The validated input values.
114
+ """
115
+ config = values.get("hash_config")
116
+ if not config or not isinstance(config, dict) or len(config) == 0:
117
+ raise ValueError("Hash configuration must contain at least one entry.")
118
+ for new_col in config:
119
+ if not new_col or not isinstance(new_col, str):
120
+ raise ValueError(f"Invalid column name '{new_col}' in hash configuration.")
121
+ return values
122
+
123
+
124
+ class TransformHashColumnsAction(PipelineAction):
125
+ """Hashes specified columns in a DataFrame using a chosen algorithm.
126
+
127
+ Given the following `hash_config`:
128
+
129
+ Example:
130
+ ```yaml
131
+ Hash Columns:
132
+ action: TRANSFORM_HASH_COLUMNS
133
+ options:
134
+ hash_config:
135
+ - hashed_column1:
136
+ columns: ["column1", "column2"]
137
+ algorithm: "sha2"
138
+ bits: 224
139
+ - hashed_column2:
140
+ columns: ["column1"]
141
+ algorithm: "crc32"
142
+ ```
143
+
144
+ Given a DataFrame `df` with the following structure:
145
+
146
+ | column1 | column2 | column3 |
147
+ |---------|---------|---------|
148
+ | foo | bar | baz |
149
+
150
+ After running the action, the resulting DataFrame will look like:
151
+
152
+ | column1 | column2 | column3 | hashed_column1 | hashed_column2 |
153
+ |---------|---------|---------|-----------------------------------------------------------|----------------|
154
+ | foo | bar | baz | 17725b837e9c896e7123b142eb980131dcc0baa6160db45d4adfdb21 | 1670361220 |
155
+
156
+
157
+ !!! note "Hash values might vary"
158
+ The actual hash values will depend on the hashing algorithm used and the input data.
159
+ """
160
+
161
+ name: str = "TRANSFORM_HASH_COLUMNS"
162
+
163
+ def run(
164
+ self,
165
+ context: PipelineContext,
166
+ *,
167
+ hash_config: HashConfig | None = None,
168
+ **_: Any,
169
+ ) -> PipelineContext:
170
+ """Hashes the specified columns in the DataFrame.
171
+
172
+ Args:
173
+ context: Context in which this Action is executed.
174
+ hash_config: Dictionary that contains the configuration for executing the hashing.
175
+
176
+ Returns:
177
+ Updated PipelineContext with hashed columns.
178
+
179
+ Raises:
180
+ ValueError: If columns are missing, data is None, or algorithm/bits are invalid.
181
+ ValueError: If the hash configuration is invalid.
182
+ """
183
+ if context.data is None:
184
+ raise ValueError("Context data is required for hashing.")
185
+
186
+ if not hash_config:
187
+ raise ValueError("Hash configuration is required.")
188
+
189
+ df = context.data
190
+
191
+ hash_functions = {
192
+ "hash": lambda cols: F.hash(*[F.col(c) for c in cols]).cast("string"),
193
+ "xxhash64": lambda cols: F.xxhash64(F.concat_ws("||", *[F.col(c) for c in cols])).cast("string"),
194
+ "md5": lambda cols: F.md5(F.concat_ws("||", *[F.col(c) for c in cols])).cast("string"),
195
+ "sha1": lambda cols: F.sha1(F.concat_ws("||", *[F.col(c) for c in cols])).cast("string"),
196
+ "sha2": lambda cols, bits: F.sha2(F.concat_ws("||", *[F.col(c) for c in cols]), bits).cast("string"),
197
+ "crc32": lambda cols: F.crc32(F.concat_ws("||", *[F.col(c) for c in cols])).cast("string"),
198
+ }
199
+ default_sha2_bits = 256
200
+
201
+ config_obj = HashConfig.model_validate({"hash_config": hash_config})
202
+ for new_col, config in config_obj.hash_config.items():
203
+ hash_func = hash_functions[config.algorithm]
204
+ if config.algorithm == "sha2":
205
+ df = df.withColumn(new_col, hash_func(config.columns, config.bits or default_sha2_bits)) # type: ignore
206
+ else:
207
+ df = df.withColumn(new_col, hash_func(config.columns)) # type: ignore
208
+
209
+ return context.from_existing(data=df)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -134,9 +134,51 @@ class Pipeline(LoggerMixin):
134
134
  self._console_logger.debug("No more steps to run")
135
135
  return False
136
136
 
137
- def run(self) -> None:
138
- """Runs the pipeline by executing each step in the correct order."""
137
+ def _trim_graph(self, graph, until):
138
+ """Trims the pipeline graph to only include steps up to the specified 'until' step (excluding).
139
+
140
+ This method first verifies that the given step exists in the graph. It then finds all ancestors
141
+ (i.e., steps that precede the 'until' step) and creates a subgraph consisting solely of those steps.
142
+
143
+ Args:
144
+ graph: The complete directed acyclic graph representing the pipeline.
145
+ until: The identifier of the step up to which the graph should be trimmed.
146
+
147
+ Returns:
148
+ A subgraph containing only the steps leading to (and including) the 'until' step.
149
+
150
+ Raises:
151
+ ValueError: If the specified 'until' step is not found in the graph.
152
+ """
153
+ if until not in graph.nodes:
154
+ raise ValueError(f"Step '{until}' not found in the pipeline.")
155
+
156
+ predecessors = set(nx.ancestors(graph, until))
157
+ predecessors.add(until)
158
+
159
+ trimmed_graph = graph.subgraph(predecessors).copy()
160
+ return trimmed_graph
161
+
162
+ def run(self, until: str | None = None) -> None:
163
+ """Executes the pipeline steps in the correct order based on dependencies.
164
+
165
+ This method creates a directed acyclic graph (DAG) of the pipeline steps and, if specified, trims
166
+ the graph to only include steps up to the given 'until' step (excluding: the step specified as 'until' will not be executed). It then concurrently executes steps
167
+ with no pending dependencies using a ThreadPoolExecutor, ensuring that all steps are run in order.
168
+ If a cyclic dependency is detected, or if any step fails during execution, the method raises an error.
169
+
170
+ Args:
171
+ until: Optional; the identifier of the step up to which the pipeline should be executed.
172
+
173
+ Raises:
174
+ RuntimeError: If a cyclic dependency is detected.
175
+ Exception: Propagates any error raised during the execution of a step.
176
+ """
139
177
  g = self._create_graph()
178
+
179
+ if until is not None:
180
+ g = self._trim_graph(g, until)
181
+
140
182
  remaining_steps = list(g.nodes())
141
183
  self._console_logger.info(f"Pipeline [' {self.name} '] started with {len(remaining_steps)} steps.")
142
184
 
File without changes
File without changes
File without changes
File without changes
File without changes
cloe_nessy/py.typed CHANGED
File without changes
File without changes