data-validation-engine 0.6.2__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 (105) hide show
  1. data_validation_engine-0.6.2.dist-info/METADATA +104 -0
  2. data_validation_engine-0.6.2.dist-info/RECORD +105 -0
  3. data_validation_engine-0.6.2.dist-info/WHEEL +4 -0
  4. data_validation_engine-0.6.2.dist-info/licenses/LICENSE +21 -0
  5. dve/__init__.py +0 -0
  6. dve/common/__init__.py +0 -0
  7. dve/common/error_utils.py +189 -0
  8. dve/core_engine/__init__.py +0 -0
  9. dve/core_engine/backends/__init__.py +1 -0
  10. dve/core_engine/backends/base/__init__.py +1 -0
  11. dve/core_engine/backends/base/auditing.py +618 -0
  12. dve/core_engine/backends/base/backend.py +240 -0
  13. dve/core_engine/backends/base/contract.py +454 -0
  14. dve/core_engine/backends/base/core.py +124 -0
  15. dve/core_engine/backends/base/reader.py +176 -0
  16. dve/core_engine/backends/base/reference_data.py +217 -0
  17. dve/core_engine/backends/base/rules.py +685 -0
  18. dve/core_engine/backends/base/utilities.py +146 -0
  19. dve/core_engine/backends/exceptions.py +311 -0
  20. dve/core_engine/backends/implementations/__init__.py +1 -0
  21. dve/core_engine/backends/implementations/duckdb/__init__.py +26 -0
  22. dve/core_engine/backends/implementations/duckdb/auditing.py +234 -0
  23. dve/core_engine/backends/implementations/duckdb/contract.py +213 -0
  24. dve/core_engine/backends/implementations/duckdb/duckdb_helpers.py +288 -0
  25. dve/core_engine/backends/implementations/duckdb/readers/__init__.py +13 -0
  26. dve/core_engine/backends/implementations/duckdb/readers/csv.py +222 -0
  27. dve/core_engine/backends/implementations/duckdb/readers/json.py +50 -0
  28. dve/core_engine/backends/implementations/duckdb/readers/xml.py +45 -0
  29. dve/core_engine/backends/implementations/duckdb/reference_data.py +49 -0
  30. dve/core_engine/backends/implementations/duckdb/rules.py +534 -0
  31. dve/core_engine/backends/implementations/duckdb/types.py +47 -0
  32. dve/core_engine/backends/implementations/duckdb/utilities.py +41 -0
  33. dve/core_engine/backends/implementations/spark/__init__.py +22 -0
  34. dve/core_engine/backends/implementations/spark/auditing.py +230 -0
  35. dve/core_engine/backends/implementations/spark/backend.py +78 -0
  36. dve/core_engine/backends/implementations/spark/contract.py +241 -0
  37. dve/core_engine/backends/implementations/spark/readers/__init__.py +15 -0
  38. dve/core_engine/backends/implementations/spark/readers/csv.py +77 -0
  39. dve/core_engine/backends/implementations/spark/readers/json.py +66 -0
  40. dve/core_engine/backends/implementations/spark/readers/xml.py +202 -0
  41. dve/core_engine/backends/implementations/spark/reference_data.py +42 -0
  42. dve/core_engine/backends/implementations/spark/rules.py +430 -0
  43. dve/core_engine/backends/implementations/spark/spark_helpers.py +412 -0
  44. dve/core_engine/backends/implementations/spark/types.py +21 -0
  45. dve/core_engine/backends/implementations/spark/utilities.py +144 -0
  46. dve/core_engine/backends/metadata/__init__.py +47 -0
  47. dve/core_engine/backends/metadata/contract.py +80 -0
  48. dve/core_engine/backends/metadata/reporting.py +374 -0
  49. dve/core_engine/backends/metadata/rules.py +737 -0
  50. dve/core_engine/backends/readers/__init__.py +41 -0
  51. dve/core_engine/backends/readers/csv.py +232 -0
  52. dve/core_engine/backends/readers/utilities.py +21 -0
  53. dve/core_engine/backends/readers/xml.py +432 -0
  54. dve/core_engine/backends/readers/xml_linting.py +142 -0
  55. dve/core_engine/backends/types.py +26 -0
  56. dve/core_engine/backends/utilities.py +177 -0
  57. dve/core_engine/configuration/__init__.py +1 -0
  58. dve/core_engine/configuration/base.py +56 -0
  59. dve/core_engine/configuration/v1/__init__.py +351 -0
  60. dve/core_engine/configuration/v1/filters.py +60 -0
  61. dve/core_engine/configuration/v1/rule_stores/__init__.py +1 -0
  62. dve/core_engine/configuration/v1/rule_stores/models.py +57 -0
  63. dve/core_engine/configuration/v1/steps.py +365 -0
  64. dve/core_engine/constants.py +8 -0
  65. dve/core_engine/engine.py +265 -0
  66. dve/core_engine/exceptions.py +29 -0
  67. dve/core_engine/functions/__init__.py +6 -0
  68. dve/core_engine/functions/implementations.py +200 -0
  69. dve/core_engine/loggers.py +57 -0
  70. dve/core_engine/message.py +512 -0
  71. dve/core_engine/models.py +196 -0
  72. dve/core_engine/templating.py +114 -0
  73. dve/core_engine/type_hints.py +255 -0
  74. dve/core_engine/validation.py +160 -0
  75. dve/metadata_parser/__init__.py +2 -0
  76. dve/metadata_parser/domain_types.py +682 -0
  77. dve/metadata_parser/exc.py +44 -0
  78. dve/metadata_parser/function_library.py +64 -0
  79. dve/metadata_parser/function_wrapper.py +201 -0
  80. dve/metadata_parser/model_generator.py +119 -0
  81. dve/metadata_parser/models.py +410 -0
  82. dve/metadata_parser/utilities.py +54 -0
  83. dve/parser/__init__.py +1 -0
  84. dve/parser/exceptions.py +50 -0
  85. dve/parser/file_handling/__init__.py +31 -0
  86. dve/parser/file_handling/helpers.py +29 -0
  87. dve/parser/file_handling/implementations/__init__.py +7 -0
  88. dve/parser/file_handling/implementations/base.py +97 -0
  89. dve/parser/file_handling/implementations/dbfs.py +81 -0
  90. dve/parser/file_handling/implementations/file.py +203 -0
  91. dve/parser/file_handling/implementations/s3.py +371 -0
  92. dve/parser/file_handling/log_handler.py +215 -0
  93. dve/parser/file_handling/service.py +441 -0
  94. dve/parser/file_handling/utilities.py +53 -0
  95. dve/parser/type_hints.py +46 -0
  96. dve/parser/utilities.py +113 -0
  97. dve/pipeline/__init__.py +0 -0
  98. dve/pipeline/duckdb_pipeline.py +56 -0
  99. dve/pipeline/foundry_ddb_pipeline.py +171 -0
  100. dve/pipeline/pipeline.py +935 -0
  101. dve/pipeline/spark_pipeline.py +69 -0
  102. dve/pipeline/utils.py +96 -0
  103. dve/reporting/__init__.py +1 -0
  104. dve/reporting/error_report.py +153 -0
  105. dve/reporting/excel_report.py +319 -0
@@ -0,0 +1,737 @@
1
+ """Metadata classes for rule steps."""
2
+
3
+ import warnings
4
+ from abc import ABCMeta, abstractmethod
5
+ from collections.abc import Iterator, Sequence
6
+ from typing import Any, ClassVar, Optional, TypeVar, Union
7
+
8
+ from pydantic import BaseModel, Extra, Field, root_validator, validate_arguments, validator
9
+ from typing_extensions import Literal
10
+
11
+ from dve.core_engine.backends.base.reference_data import ReferenceConfigUnion
12
+ from dve.core_engine.backends.metadata.reporting import LegacyReportingConfig, ReportingConfig
13
+ from dve.core_engine.templating import template_object
14
+ from dve.core_engine.type_hints import (
15
+ Alias,
16
+ EntityName,
17
+ Expression,
18
+ JSONable,
19
+ MultipleExpressions,
20
+ TemplateVariables,
21
+ )
22
+
23
+ __all__ = [
24
+ "AbstractStep",
25
+ "Aggregation",
26
+ "AntiJoin",
27
+ "BaseStep",
28
+ "ColumnAddition",
29
+ "ColumnRemoval",
30
+ "ConfirmJoinHasMatch",
31
+ "CopyEntity",
32
+ "DeferredFilter",
33
+ "EntityRemoval",
34
+ "HeaderJoin",
35
+ "ImmediateFilter",
36
+ "InnerJoin",
37
+ "LeftJoin",
38
+ "OneToOneJoin",
39
+ "OneToOneJoin",
40
+ "OrphanIdentification",
41
+ "ParentMetadata",
42
+ "RenameEntity",
43
+ "Rule",
44
+ "RuleMetadata",
45
+ "SelectColumns",
46
+ "SemiJoin",
47
+ "TableUnion",
48
+ ]
49
+
50
+ ASSelf = TypeVar("ASSelf", bound="AbstractStep")
51
+ RSelf = TypeVar("RSelf", bound="Rule")
52
+
53
+ Stage = Literal["Pre-sync", "Sync", "Post-sync"]
54
+ """The stage that the rule falls under."""
55
+
56
+
57
+ # pylint: disable=too-few-public-methods
58
+ class ParentMetadata(BaseModel):
59
+ """Data about the parent rule for a step."""
60
+
61
+ rule: Union["Rule", str]
62
+ """The rule the step belongs to, or a string representing the rule."""
63
+ index: int
64
+ """The index of the step within the parent rule."""
65
+ stage: Stage
66
+ """The name of the stage in the rule the step belongs to."""
67
+
68
+ def __repr__(self) -> str:
69
+ components: list[str] = []
70
+ if isinstance(self.rule, Rule):
71
+ components.append(f"rule=Rule(name={self.rule.name!r}, ...)")
72
+ else:
73
+ components.append(f"rule=Rule(name={self.rule!r}, ...)")
74
+
75
+ for key, value in self.dict(exclude={"rule"}).items():
76
+ components.append(f"{key}={value!r}")
77
+
78
+ return f"ParentMetadata({', '.join(components)})"
79
+
80
+ class Config: # pylint: disable=too-few-public-methods
81
+ """`pydantic configuration options`"""
82
+
83
+ frozen = True
84
+ extra = Extra.forbid
85
+
86
+
87
+ # pylint: disable=too-few-public-methods
88
+ class AbstractStep(BaseModel, metaclass=ABCMeta):
89
+ """An abstract transformation step."""
90
+
91
+ id: Optional[str] = None
92
+ """An ID for the rule step. This will not be templated."""
93
+ description: Optional[str] = None
94
+ """An optional description for the step."""
95
+ parent: Optional[ParentMetadata] = None
96
+ """Data about the parent rule and the step's place within it."""
97
+
98
+ UNTEMPLATED_KEYS: ClassVar[set[str]] = {"id", "description", "parent"}
99
+ """A set of aliases which are exempted from templating."""
100
+
101
+ class Config: # pylint: disable=too-few-public-methods
102
+ """`pydantic configuration options`"""
103
+
104
+ frozen = True
105
+ extra = Extra.forbid
106
+
107
+ def __repr_args__(self) -> Sequence[tuple[Optional[str], Any]]:
108
+ # Exclude nulls from 'repr' for conciseness.
109
+ return [(key, value) for key, value in super().__repr_args__() if value is not None]
110
+
111
+ @abstractmethod
112
+ def get_required_entities(self) -> set[EntityName]:
113
+ """Get a set of the required entity names for the transformation."""
114
+ raise NotImplementedError() # pragma: no cover
115
+
116
+ @abstractmethod
117
+ def get_created_entities(self) -> set[EntityName]:
118
+ """Get a set of the entity names created by the transformation."""
119
+ raise NotImplementedError() # pragma: no cover
120
+
121
+ def get_removed_entities(self) -> set[EntityName]:
122
+ """Get a set of the entity names removed by the transformation."""
123
+ return set()
124
+
125
+ def with_parent(self: ASSelf, parent: ParentMetadata) -> ASSelf:
126
+ """Return a new step with different parent metadata."""
127
+ return type(self)(**self.dict(exclude={"parent"}), parent=parent)
128
+
129
+ def template(
130
+ self: ASSelf,
131
+ local_variables: TemplateVariables,
132
+ *,
133
+ global_variables: Optional[TemplateVariables] = None,
134
+ ) -> ASSelf:
135
+ """Template the rule, given the global and local variables."""
136
+ type_ = type(self)
137
+ if global_variables:
138
+ variables = global_variables.copy()
139
+ variables.update(local_variables)
140
+ else:
141
+ variables = local_variables
142
+
143
+ untemplated_data = {key: getattr(self, key) for key in self.UNTEMPLATED_KEYS}
144
+ data_to_template = self.dict(exclude=self.UNTEMPLATED_KEYS)
145
+ templated_data = template_object(data_to_template, variables, "jinja")
146
+
147
+ return type_(**templated_data, **untemplated_data)
148
+
149
+ def __str__(self): # pydantic's default __str__ strips the model name.
150
+ return super().__repr__()
151
+
152
+ @root_validator(pre=True)
153
+ @classmethod
154
+ def _warn_for_deprecated_aliases(cls, values: dict[str, JSONable]) -> dict[str, JSONable]:
155
+ for deprecated_name, replacement in (
156
+ ("entity", "entity_name"),
157
+ ("target", "target_entity_name"),
158
+ ):
159
+ if deprecated_name in values:
160
+ warnings.warn(
161
+ f"Using deprecated name {deprecated_name!r}, should be {replacement!r}"
162
+ )
163
+ if replacement in values:
164
+ raise ValueError(
165
+ f"{replacement!r} and deprecated name {deprecated_name!r} both "
166
+ + "provided"
167
+ )
168
+ values[replacement] = values.pop(deprecated_name)
169
+ return values
170
+
171
+
172
+ class BaseStep(AbstractStep, metaclass=ABCMeta):
173
+ """A base transformation step which performs a transformation on an entity
174
+ and provides for a new entity being created instead of modification.
175
+
176
+ """
177
+
178
+ entity_name: EntityName
179
+ """The entity to apply the step to."""
180
+ new_entity_name: Optional[EntityName] = None
181
+ """Optionally, a new entity to create after the operation."""
182
+
183
+ def get_required_entities(self) -> set[EntityName]:
184
+ """Get a set of the required entity names for the transformation."""
185
+ return {self.entity_name}
186
+
187
+ def get_created_entities(self) -> set[EntityName]:
188
+ """Get a set of the entity names created by the transformation."""
189
+ return {self.new_entity_name or self.entity_name}
190
+
191
+
192
+ class ImmediateFilter(BaseStep):
193
+ """A filter which removes records from an entity (or creates a new entity without
194
+ those rows) according to a provided expression. Only records for which the
195
+ provided expression is truthy will be retained.
196
+
197
+ """
198
+
199
+ expression: Expression
200
+ """
201
+ The expression for the filter. Records for which this expression is falsey will be
202
+ removed.
203
+
204
+ """
205
+
206
+
207
+ class DeferredFilter(AbstractStep):
208
+ """A filter which should be applied in a synchronised step with other filters for
209
+ the same entity, providing feedback to users.
210
+
211
+ Messages will be emitted for each record that fails a filter according to the
212
+ configured reporting, and any record-level errors will be removed from source
213
+ entities at the end of the stage. This enables multiple issues with the same record
214
+ to be flagged to a data provider.
215
+
216
+ """
217
+
218
+ entity_name: EntityName
219
+ """The entity to apply the step to."""
220
+ expression: Expression
221
+ """
222
+ The expression for the filter. Records for which this expression is falsey will be
223
+ removed from the source entity if the reporting level is a record-level error.
224
+
225
+ """
226
+ reporting: Union[ReportingConfig, LegacyReportingConfig]
227
+ """The reporting information for the filter."""
228
+
229
+ def template(
230
+ self: "DeferredFilter",
231
+ local_variables: dict[Alias, Any],
232
+ *,
233
+ global_variables: Optional[dict[Alias, Any]] = None,
234
+ ) -> "DeferredFilter":
235
+ """Template the rule, given the global and local variables."""
236
+ type_ = type(self)
237
+ if global_variables:
238
+ variables = global_variables.copy()
239
+ variables.update(local_variables)
240
+ else:
241
+ variables = local_variables
242
+
243
+ untemplated_data = {key: getattr(self, key) for key in self.UNTEMPLATED_KEYS}
244
+ data_to_template = self.dict(exclude={*self.UNTEMPLATED_KEYS, "reporting"})
245
+ templated_data = template_object(data_to_template, variables, "jinja")
246
+ templated_data["reporting"] = self.reporting.template(
247
+ local_variables, global_variables=global_variables
248
+ )
249
+
250
+ return type_(**templated_data, **untemplated_data)
251
+
252
+ def get_required_entities(self) -> set[EntityName]:
253
+ """Get a set of the required entity names for the transformation."""
254
+ return {self.entity_name}
255
+
256
+ def get_created_entities(self) -> set[EntityName]:
257
+ """Get a set of the required entity names for the transformation."""
258
+ return {self.entity_name}
259
+
260
+
261
+ class Notification(AbstractStep):
262
+ """An implementation of a notification according to a particular reporting configuration.
263
+ This will emit notifications for all records that meet the expression, and will
264
+ not modify the source entity.
265
+
266
+ NOTE: This is not intended to be used directly, but is used in the implementation
267
+ of the sync filter stage.
268
+
269
+ """
270
+
271
+ entity_name: EntityName
272
+ """The entity to apply the step to."""
273
+ expression: Expression
274
+ """
275
+ The expression for the notification. Records for which this expression is truthy will
276
+ emit notifications according to the reporting config.
277
+
278
+ """
279
+ excluded_columns: list[Alias] = Field(default_factory=list)
280
+ """Columns to be excluded from the record in the report."""
281
+ reporting: ReportingConfig
282
+ """The reporting information for the filter."""
283
+
284
+ def get_required_entities(self) -> set[EntityName]:
285
+ return {self.entity_name}
286
+
287
+ def get_created_entities(self) -> set[EntityName]:
288
+ return set()
289
+
290
+
291
+ class AbstractJoin(AbstractStep, metaclass=ABCMeta):
292
+ """An abstract table join configuration. This joins `target` into `entity`."""
293
+
294
+ entity_name: EntityName
295
+ """The name of the source entity to join from."""
296
+ target_name: EntityName
297
+ """The target dataset to join to."""
298
+ new_entity_name: Optional[EntityName] = None
299
+ """Optionally, a new entity to create after the operation."""
300
+
301
+ def get_required_entities(self) -> set[EntityName]:
302
+ return {self.entity_name, self.target_name}
303
+
304
+ def get_created_entities(self) -> set[EntityName]:
305
+ return {self.new_entity_name or self.entity_name}
306
+
307
+
308
+ class AbstractConditionalJoin(AbstractJoin, metaclass=ABCMeta):
309
+ """An abstract table join configuration with a join condition.
310
+ This joins `target` into `entity`.
311
+
312
+ """
313
+
314
+ join_condition: Expression
315
+ """
316
+ A SQL expression representing the join. Columns will be namespaced
317
+ within the source and target dataset names.
318
+
319
+ """
320
+
321
+ JOIN_TYPE: ClassVar[str]
322
+ """The type of join that the class uses in Spark."""
323
+
324
+
325
+ class AbstractNewColumnConditionalJoin(AbstractConditionalJoin, metaclass=ABCMeta):
326
+ """A join type which adds new columns to the finished entity."""
327
+
328
+ new_columns: MultipleExpressions = Field(default_factory=dict)
329
+ """
330
+ A mapping of SQL expressions to the names of the new columns to be added
331
+ to `entity`.
332
+
333
+ Expressions can access columns from the source and the target, and
334
+ columns will be namespaced within the source and target dataset names.
335
+
336
+ """
337
+
338
+
339
+ class ColumnAddition(BaseStep):
340
+ """A transformation step which adds a new column based on an expression."""
341
+
342
+ column_name: Alias
343
+ """The name of the column to be created."""
344
+ expression: Expression
345
+ """The SQL expression for the transformation."""
346
+
347
+
348
+ class ColumnRemoval(BaseStep):
349
+ """A transformation step which removes a column by name."""
350
+
351
+ column_name: Alias
352
+ """The name of the column to be dropped."""
353
+
354
+
355
+ class SelectColumns(BaseStep):
356
+ """A transformation step which selects columns from an entity."""
357
+
358
+ columns: MultipleExpressions
359
+ """Multiple expressions to select from the specified entity."""
360
+ distinct: bool = False
361
+ """Whether to keep only distinct columns from the select statement."""
362
+
363
+
364
+ class Aggregation(BaseStep):
365
+ """A transformation which performs aggregation."""
366
+
367
+ group_by: MultipleExpressions
368
+ """Multiple expressions to group by."""
369
+ pivot_column: Optional[Alias] = None
370
+ """An optional pivot column for the table."""
371
+ pivot_values: Optional[list[Any]] = None
372
+ """A list of values to translate to columns when pivoting."""
373
+ agg_columns: Optional[MultipleExpressions] = None
374
+ """Multiple aggregate expressions to take from the group by (for spark backend)"""
375
+ agg_function: Optional[Alias] = None
376
+ """The aggregate function to apply to the agg_columns (for duckdb backend)"""
377
+
378
+ @validator("pivot_values")
379
+ @classmethod
380
+ def _ensure_column_if_values(
381
+ cls,
382
+ value: Optional[Any],
383
+ values: dict[str, Any],
384
+ ):
385
+ """Ensure that `pivot_column` is not null if pivot values are provided."""
386
+ if value and not values["pivot_column"]:
387
+ raise ValueError("`pivot_values` specified, but no `pivot_column`")
388
+ return value
389
+
390
+ @validator("agg_function")
391
+ @classmethod
392
+ def _ensure_column_if_function(
393
+ cls,
394
+ agg_function: Optional[Any],
395
+ values: dict[str, Any],
396
+ ):
397
+ """Ensure that `pivot_column` is not null if pivot values are provided."""
398
+ if agg_function and not values["agg_columns"]:
399
+ raise ValueError("`agg_function` specified, but no `agg_columns`")
400
+ return agg_function
401
+
402
+
403
+ class EntityRemoval(AbstractStep):
404
+ """A transformation which drops entities."""
405
+
406
+ entity_name: Union[EntityName, list[EntityName]]
407
+ """The entity to drop."""
408
+
409
+ def get_required_entities(self) -> set[EntityName]:
410
+ """Get a set of the required entity names for the transformation."""
411
+ return set()
412
+
413
+ def get_created_entities(self) -> set[EntityName]:
414
+ """Get a set of the entity names created by the transformation."""
415
+ return set()
416
+
417
+ def get_removed_entities(self) -> set[EntityName]:
418
+ """Get a set of the entity names created by the transformation."""
419
+ if isinstance(self.entity_name, list):
420
+ return set(self.entity_name)
421
+ return {self.entity_name}
422
+
423
+
424
+ class CopyEntity(AbstractStep):
425
+ """A transformation which copies an entity."""
426
+
427
+ entity_name: EntityName
428
+ """The entity to copy."""
429
+ new_entity_name: EntityName
430
+ """The new name for the copied entity."""
431
+
432
+ def get_required_entities(self) -> set[EntityName]:
433
+ """Get a set of the required entity names for the transformation."""
434
+ return {self.entity_name}
435
+
436
+ def get_created_entities(self) -> set[EntityName]:
437
+ """Get a set of the entity names created by the transformation."""
438
+ return {self.new_entity_name}
439
+
440
+ def get_removed_entities(self) -> set[EntityName]:
441
+ """Gets the entity which has been removed"""
442
+ return set()
443
+
444
+
445
+ class RenameEntity(CopyEntity):
446
+ """A transformation which renames an entity."""
447
+
448
+ def get_removed_entities(self) -> set[EntityName]:
449
+ """Get a set of the entity names removed by the transformation."""
450
+ return {self.entity_name}
451
+
452
+
453
+ class LeftJoin(AbstractNewColumnConditionalJoin):
454
+ """A table join configuration. This joins `target` into `entity`.
455
+
456
+ The table join will result in all of the columns from `entity` being retained,
457
+ new columns can be added based on data from `target` by adding SQL expressions
458
+ in `new_columns`.
459
+
460
+ """
461
+
462
+
463
+ class InnerJoin(AbstractNewColumnConditionalJoin):
464
+ """A table join configuration. This joins `target` into `entity`, retaining only
465
+ rows which match in both tables.
466
+
467
+ The table join will result in all of the columns from `entity` being retained,
468
+ new columns can be added based on data from `target` by adding SQL expressions
469
+ in `new_columns`.
470
+
471
+ """
472
+
473
+
474
+ class OneToOneJoin(LeftJoin):
475
+ """A table join configuration. This joins `target` into `entity`. This
476
+ will not alter the number of rows in `target`.
477
+
478
+ The table join will result in all of the columns from `entity` being retained,
479
+ new columns can be added based on data from `target` by adding SQL expressions
480
+ in `new_columns`.
481
+
482
+ """
483
+
484
+ perform_integrity_check: bool = True
485
+ """
486
+ Whether to perform the integrity check on the number of records. If this is
487
+ disabled, it is not guaranteed that joins will be one to one.
488
+
489
+ """
490
+
491
+
492
+ class SemiJoin(AbstractConditionalJoin):
493
+ """A table join configuration. This keeps the rows in `entity` where the join
494
+ condition with `target` is true.
495
+
496
+ The table join will result in all of the columns from `entity` being retained.
497
+ No rows can be added from `target`.
498
+
499
+ """
500
+
501
+
502
+ class AntiJoin(AbstractConditionalJoin):
503
+ """A table join configuration. This keeps the rows in `entity` where the join
504
+ condition with `target` is _not_ true.
505
+
506
+ The table join will result in all of the columns from `entity` being retained.
507
+ No rows can be added from `target`.
508
+
509
+ """
510
+
511
+
512
+ class ConfirmJoinHasMatch(AbstractConditionalJoin):
513
+ """Add a boolean column with name `column_name` to `entity`. The new column
514
+ will indicate whether the `entity` has a corresponding row in `target`.
515
+
516
+ """
517
+
518
+ column_name: Alias
519
+ """
520
+ The name of the new column to add to `entity`. This will indicate whether
521
+ there is a corresponding match for each row.
522
+
523
+ """
524
+ perform_integrity_check: bool = True
525
+ """
526
+ Whether to perform the integrity check on the number of records. If this is
527
+ disabled, it is not guaranteed that rows in `entity` will not be duplicated.
528
+
529
+ """
530
+
531
+
532
+ class HeaderJoin(AbstractJoin):
533
+ """Add a 'header' entity (`target`) to each row in `entity`. The header entity
534
+ must contain only a single row.
535
+
536
+ """
537
+
538
+ header_column_name: Alias = "_Header"
539
+ """The name of the column to add to `entity`, which will contain the header."""
540
+
541
+
542
+ class TableUnion(AbstractJoin):
543
+ """Union two tables together, taking the columns from each by name.
544
+
545
+ Where columns have the same name, they must be the same type or coerceable.
546
+ Where column casing differs, the casing from the `source` entity will be kept.
547
+
548
+ Column order will be preserved, with columns from `source` taken first and extra
549
+ columns in `target` added in order afterwards.
550
+
551
+ """
552
+
553
+
554
+ class OrphanIdentification(AbstractConditionalJoin):
555
+ """Identify records in `entity` which don't have at least one corresponding
556
+ match in `target`. A new boolean column will be added to `entity` ('IsOrphaned')
557
+ indicating whether the condition matched.
558
+
559
+ If there is already an 'IsOrphaned' column in the entity, this will be set to the
560
+ logical OR of its current value and the value it would have been set to otherwise.
561
+
562
+ """
563
+
564
+
565
+ Step = Union[AbstractStep, Literal["sync"]]
566
+ """A step within a rule. This is either a rule config or the literal string 'sync'."""
567
+
568
+
569
+ class Rule(BaseModel):
570
+ """A rule, made up of multiple steps."""
571
+
572
+ name: str
573
+ """The name of the rule."""
574
+ pre_sync_steps: list[AbstractStep]
575
+ """The pre-sync steps in the rule."""
576
+ sync_filter_steps: list[DeferredFilter]
577
+ """The sync filter steps in the rule."""
578
+ post_sync_steps: list[AbstractStep]
579
+ """The post-sync steps in the rule."""
580
+
581
+ def __str__(self): # pydantic's default __str__ strips the model name.
582
+ return super().__repr__()
583
+
584
+ @classmethod
585
+ @validate_arguments
586
+ def from_step_list(cls, name: str, steps: list[Step]):
587
+ """Load the rule from a single step list."""
588
+ pre_sync_steps: list[AbstractStep] = []
589
+ sync_filter_steps: list[DeferredFilter] = []
590
+ post_sync_steps: list[AbstractStep] = []
591
+ self = cls(
592
+ name=name,
593
+ pre_sync_steps=pre_sync_steps,
594
+ sync_filter_steps=sync_filter_steps,
595
+ post_sync_steps=post_sync_steps,
596
+ )
597
+
598
+ sync_stage_start: Optional[int] = None
599
+ sync_stage_stop: Optional[int] = None
600
+ for step_index, step in enumerate(steps):
601
+ in_sync_stage = (sync_stage_start is not None) and (sync_stage_stop is None)
602
+ sync_stage_completed = sync_stage_stop is not None
603
+
604
+ step_is_sync_filter = isinstance(step, DeferredFilter)
605
+ step_is_sync_keyword = isinstance(step, str) and step == "sync"
606
+ step_is_sync = step_is_sync_filter or step_is_sync_keyword
607
+
608
+ if step_is_sync:
609
+ if sync_stage_completed:
610
+ raise ValueError(
611
+ "Synchronised steps must be contiguous. The step at index "
612
+ + f"{step_index} comes after the end of the first continuous "
613
+ + f"sync stage ([{sync_stage_start}:{sync_stage_stop}])"
614
+ )
615
+
616
+ if sync_stage_start is None:
617
+ sync_stage_start = step_index
618
+
619
+ if step_is_sync_filter:
620
+ sync_filter_steps.append(step) # type: ignore
621
+
622
+ continue
623
+
624
+ if in_sync_stage:
625
+ sync_stage_completed = True
626
+ sync_stage_stop = step_index
627
+
628
+ if not sync_stage_completed:
629
+ pre_sync_steps.append(step) # type: ignore
630
+ else:
631
+ post_sync_steps.append(step) # type: ignore
632
+
633
+ return self
634
+
635
+ def __init__(self, *args, **kwargs):
636
+ super().__init__(*args, **kwargs)
637
+
638
+ global_index = 0
639
+ for stage, step_list in (
640
+ ("Pre-sync", self.pre_sync_steps),
641
+ ("Sync", self.sync_filter_steps),
642
+ ("Post-sync", self.post_sync_steps),
643
+ ):
644
+ for stage_step_index, step in enumerate(step_list):
645
+ step_list[stage_step_index] = step.with_parent(
646
+ ParentMetadata(rule=self, index=global_index, stage=stage)
647
+ )
648
+ global_index += 1
649
+
650
+ def template(
651
+ self: RSelf,
652
+ local_variables: TemplateVariables,
653
+ *,
654
+ global_variables: Optional[TemplateVariables] = None,
655
+ ) -> RSelf:
656
+ """Template the rule, returning the new templated rule. This is only really useful
657
+ for 'upfront' templating, as all stages of the rule will be templated at once.
658
+
659
+ """
660
+ rule_lists: dict[str, Union[list[AbstractStep], list[DeferredFilter]]] = {
661
+ "pre_sync_steps": self.pre_sync_steps,
662
+ "sync_filter_steps": self.sync_filter_steps,
663
+ "post_sync_steps": self.post_sync_steps,
664
+ }
665
+ for list_name, step_list in rule_lists.items():
666
+ templated_rule_list = []
667
+ for step in step_list:
668
+ step = step.template(local_variables, global_variables=global_variables)
669
+ templated_rule_list.append(step)
670
+ rule_lists[list_name] = templated_rule_list
671
+
672
+ type_ = type(self)
673
+ return type_(name=self.name, **rule_lists)
674
+
675
+
676
+ class RuleMetadata(BaseModel):
677
+ """Metadata about the rules."""
678
+
679
+ rules: list[Rule]
680
+ """A list of rules to be applied to to the entities."""
681
+ local_variables: Optional[list[TemplateVariables]] = None
682
+ """
683
+ An optional list of local, rule-level template variables.
684
+
685
+ If provided, this must be the same length as `rules`.
686
+
687
+ """
688
+ global_variables: TemplateVariables = Field(default_factory=dict)
689
+ """An optional mapping of global template variables."""
690
+ templating_strategy: Literal["upfront", "runtime"] = "upfront"
691
+ """
692
+ The templating strategy for the rules.
693
+
694
+ If 'upfront', template all rules at the beginning of the rule stage
695
+ execution.
696
+
697
+ If 'runtime', template rules immediately before evaluating them.
698
+
699
+ Runtime templating doesn't currently add any value, but will provide
700
+ the ability to set variables from data items in the future. With runtime
701
+ rules, it is not possible to check that all entities are present before
702
+ performing work.
703
+
704
+ """
705
+ reference_data_config: dict[EntityName, ReferenceConfigUnion]
706
+ """
707
+ Per-entity configuration options for the reference data.
708
+
709
+ Options are likely to vary by backend (e.g. some backends will have
710
+ a database and table name, some might have a remote URI).
711
+
712
+ """
713
+
714
+ @root_validator()
715
+ @classmethod
716
+ def _ensure_locals_same_length_as_rules(cls, values: dict[str, list[Any]]):
717
+ """Ensure that if 'local_variables' is provided, it's the same length as 'rules'."""
718
+ local_vars = values["local_variables"]
719
+ if local_vars is not None:
720
+ n_local_vars = len(local_vars)
721
+ n_rules = len(values["rules"])
722
+ if n_local_vars != n_rules:
723
+ raise ValueError(
724
+ f"Mismatch between number of local variables {n_local_vars} and number of "
725
+ + f"rules {n_rules}"
726
+ )
727
+ return values
728
+
729
+ def __iter__(self) -> Iterator[tuple[Rule, TemplateVariables]]: # type: ignore
730
+ """Iterate over the rules and local variables."""
731
+ if self.local_variables is None:
732
+ yield from ((rule, {}) for rule in self.rules) # type: ignore
733
+ else:
734
+ yield from zip(self.rules, self.local_variables)
735
+
736
+
737
+ ParentMetadata.update_forward_refs()