Skip to content

Operations

dve.core_engine.backends.metadata.rules

Metadata classes for rule steps.

Stage = Literal['Pre-sync', 'Sync', 'Post-sync'] module-attribute

The stage that the rule falls under.

Step = Union[AbstractStep, Literal['sync']] module-attribute

A step within a rule. This is either a rule config or the literal string 'sync'.

AbstractConditionalJoin

Bases: AbstractJoin

An abstract table join configuration with a join condition. This joins target into entity.

Source code in src/dve/core_engine/backends/metadata/rules.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
class AbstractConditionalJoin(AbstractJoin, metaclass=ABCMeta):
    """An abstract table join configuration with a join condition.
    This joins `target` into `entity`.

    """

    join_condition: Expression
    """
    A SQL expression representing the join. Columns will be namespaced
    within the source and target dataset names.

    """

    JOIN_TYPE: ClassVar[str]
    """The type of join that the class uses in Spark."""

JOIN_TYPE class-attribute

The type of join that the class uses in Spark.

join_condition instance-attribute

A SQL expression representing the join. Columns will be namespaced within the source and target dataset names.

AbstractJoin

Bases: AbstractStep

An abstract table join configuration. This joins target into entity.

Source code in src/dve/core_engine/backends/metadata/rules.py
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
class AbstractJoin(AbstractStep, metaclass=ABCMeta):
    """An abstract table join configuration. This joins `target` into `entity`."""

    entity_name: EntityName
    """The name of the source entity to join from."""
    target_name: EntityName
    """The target dataset to join to."""
    new_entity_name: Optional[EntityName] = None
    """Optionally, a new entity to create after the operation."""

    def get_required_entities(self) -> set[EntityName]:
        return {self.entity_name, self.target_name}

    def get_created_entities(self) -> set[EntityName]:
        return {self.new_entity_name or self.entity_name}

entity_name instance-attribute

The name of the source entity to join from.

new_entity_name = None class-attribute instance-attribute

Optionally, a new entity to create after the operation.

target_name instance-attribute

The target dataset to join to.

AbstractNewColumnConditionalJoin

Bases: AbstractConditionalJoin

A join type which adds new columns to the finished entity.

Source code in src/dve/core_engine/backends/metadata/rules.py
325
326
327
328
329
330
331
332
333
334
335
336
class AbstractNewColumnConditionalJoin(AbstractConditionalJoin, metaclass=ABCMeta):
    """A join type which adds new columns to the finished entity."""

    new_columns: MultipleExpressions = Field(default_factory=dict)
    """
    A mapping of SQL expressions to the names of the new columns to be added
    to `entity`.

    Expressions can access columns from the source and the target, and
    columns will be namespaced within the source and target dataset names.

    """

new_columns = Field(default_factory=dict) class-attribute instance-attribute

A mapping of SQL expressions to the names of the new columns to be added to entity.

Expressions can access columns from the source and the target, and columns will be namespaced within the source and target dataset names.

AbstractStep

Bases: BaseModel

An abstract transformation step.

Source code in src/dve/core_engine/backends/metadata/rules.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
class AbstractStep(BaseModel, metaclass=ABCMeta):
    """An abstract transformation step."""

    id: Optional[str] = None
    """An ID for the rule step. This will not be templated."""
    description: Optional[str] = None
    """An optional description for the step."""
    parent: Optional[ParentMetadata] = None
    """Data about the parent rule and the step's place within it."""

    UNTEMPLATED_KEYS: ClassVar[set[str]] = {"id", "description", "parent"}
    """A set of aliases which are exempted from templating."""

    class Config:  # pylint: disable=too-few-public-methods
        """`pydantic configuration options`"""

        frozen = True
        extra = Extra.forbid

    def __repr_args__(self) -> Sequence[tuple[Optional[str], Any]]:
        # Exclude nulls from 'repr' for conciseness.
        return [(key, value) for key, value in super().__repr_args__() if value is not None]

    @abstractmethod
    def get_required_entities(self) -> set[EntityName]:
        """Get a set of the required entity names for the transformation."""
        raise NotImplementedError()  # pragma: no cover

    @abstractmethod
    def get_created_entities(self) -> set[EntityName]:
        """Get a set of the entity names created by the transformation."""
        raise NotImplementedError()  # pragma: no cover

    def get_removed_entities(self) -> set[EntityName]:
        """Get a set of the entity names removed by the transformation."""
        return set()

    def with_parent(self: ASSelf, parent: ParentMetadata) -> ASSelf:
        """Return a new step with different parent metadata."""
        return type(self)(**self.dict(exclude={"parent"}), parent=parent)

    def template(
        self: ASSelf,
        local_variables: TemplateVariables,
        *,
        global_variables: Optional[TemplateVariables] = None,
    ) -> ASSelf:
        """Template the rule, given the global and local variables."""
        type_ = type(self)
        if global_variables:
            variables = global_variables.copy()
            variables.update(local_variables)
        else:
            variables = local_variables

        untemplated_data = {key: getattr(self, key) for key in self.UNTEMPLATED_KEYS}
        data_to_template = self.dict(exclude=self.UNTEMPLATED_KEYS)
        templated_data = template_object(data_to_template, variables, "jinja")

        return type_(**templated_data, **untemplated_data)

    def __str__(self):  # pydantic's default __str__ strips the model name.
        return super().__repr__()

    @root_validator(pre=True)
    @classmethod
    def _warn_for_deprecated_aliases(cls, values: dict[str, JSONable]) -> dict[str, JSONable]:
        for deprecated_name, replacement in (
            ("entity", "entity_name"),
            ("target", "target_entity_name"),
        ):
            if deprecated_name in values:
                warnings.warn(
                    f"Using deprecated name {deprecated_name!r}, should be {replacement!r}"
                )
                if replacement in values:
                    raise ValueError(
                        f"{replacement!r} and deprecated name {deprecated_name!r} both "
                        + "provided"
                    )
                values[replacement] = values.pop(deprecated_name)
        return values

UNTEMPLATED_KEYS = {'id', 'description', 'parent'} class-attribute

A set of aliases which are exempted from templating.

description = None class-attribute instance-attribute

An optional description for the step.

id = None class-attribute instance-attribute

An ID for the rule step. This will not be templated.

parent = None class-attribute instance-attribute

Data about the parent rule and the step's place within it.

Config

pydantic configuration options

Source code in src/dve/core_engine/backends/metadata/rules.py
101
102
103
104
105
class Config:  # pylint: disable=too-few-public-methods
    """`pydantic configuration options`"""

    frozen = True
    extra = Extra.forbid

get_created_entities() abstractmethod

Get a set of the entity names created by the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
116
117
118
119
@abstractmethod
def get_created_entities(self) -> set[EntityName]:
    """Get a set of the entity names created by the transformation."""
    raise NotImplementedError()  # pragma: no cover

get_removed_entities()

Get a set of the entity names removed by the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
121
122
123
def get_removed_entities(self) -> set[EntityName]:
    """Get a set of the entity names removed by the transformation."""
    return set()

get_required_entities() abstractmethod

Get a set of the required entity names for the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
111
112
113
114
@abstractmethod
def get_required_entities(self) -> set[EntityName]:
    """Get a set of the required entity names for the transformation."""
    raise NotImplementedError()  # pragma: no cover

template(local_variables, *, global_variables=None)

Template the rule, given the global and local variables.

Source code in src/dve/core_engine/backends/metadata/rules.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def template(
    self: ASSelf,
    local_variables: TemplateVariables,
    *,
    global_variables: Optional[TemplateVariables] = None,
) -> ASSelf:
    """Template the rule, given the global and local variables."""
    type_ = type(self)
    if global_variables:
        variables = global_variables.copy()
        variables.update(local_variables)
    else:
        variables = local_variables

    untemplated_data = {key: getattr(self, key) for key in self.UNTEMPLATED_KEYS}
    data_to_template = self.dict(exclude=self.UNTEMPLATED_KEYS)
    templated_data = template_object(data_to_template, variables, "jinja")

    return type_(**templated_data, **untemplated_data)

with_parent(parent)

Return a new step with different parent metadata.

Source code in src/dve/core_engine/backends/metadata/rules.py
125
126
127
def with_parent(self: ASSelf, parent: ParentMetadata) -> ASSelf:
    """Return a new step with different parent metadata."""
    return type(self)(**self.dict(exclude={"parent"}), parent=parent)

Aggregation

Bases: BaseStep

A transformation which performs aggregation.

Source code in src/dve/core_engine/backends/metadata/rules.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
class Aggregation(BaseStep):
    """A transformation which performs aggregation."""

    group_by: MultipleExpressions
    """Multiple expressions to group by."""
    pivot_column: Optional[Alias] = None
    """An optional pivot column for the table."""
    pivot_values: Optional[list[Any]] = None
    """A list of values to translate to columns when pivoting."""
    agg_columns: Optional[MultipleExpressions] = None
    """Multiple aggregate expressions to take from the group by (for spark backend)"""
    agg_function: Optional[Alias] = None
    """The aggregate function to apply to the agg_columns (for duckdb backend)"""

    @validator("pivot_values")
    @classmethod
    def _ensure_column_if_values(
        cls,
        value: Optional[Any],
        values: dict[str, Any],
    ):
        """Ensure that `pivot_column` is not null if pivot values are provided."""
        if value and not values["pivot_column"]:
            raise ValueError("`pivot_values` specified, but no `pivot_column`")
        return value

    @validator("agg_function")
    @classmethod
    def _ensure_column_if_function(
        cls,
        agg_function: Optional[Any],
        values: dict[str, Any],
    ):
        """Ensure that `pivot_column` is not null if pivot values are provided."""
        if agg_function and not values["agg_columns"]:
            raise ValueError("`agg_function` specified, but no `agg_columns`")
        return agg_function

agg_columns = None class-attribute instance-attribute

Multiple aggregate expressions to take from the group by (for spark backend)

agg_function = None class-attribute instance-attribute

The aggregate function to apply to the agg_columns (for duckdb backend)

group_by instance-attribute

Multiple expressions to group by.

pivot_column = None class-attribute instance-attribute

An optional pivot column for the table.

pivot_values = None class-attribute instance-attribute

A list of values to translate to columns when pivoting.

AntiJoin

Bases: AbstractConditionalJoin

A table join configuration. This keeps the rows in entity where the join condition with target is not true.

The table join will result in all of the columns from entity being retained. No rows can be added from target.

Source code in src/dve/core_engine/backends/metadata/rules.py
502
503
504
505
506
507
508
509
class AntiJoin(AbstractConditionalJoin):
    """A table join configuration. This keeps the rows in `entity` where the join
    condition with `target` is _not_ true.

    The table join will result in all of the columns from `entity` being retained.
    No rows can be added from `target`.

    """

BaseStep

Bases: AbstractStep

A base transformation step which performs a transformation on an entity and provides for a new entity being created instead of modification.

Source code in src/dve/core_engine/backends/metadata/rules.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
class BaseStep(AbstractStep, metaclass=ABCMeta):
    """A base transformation step which performs a transformation on an entity
    and provides for a new entity being created instead of modification.

    """

    entity_name: EntityName
    """The entity to apply the step to."""
    new_entity_name: Optional[EntityName] = None
    """Optionally, a new entity to create after the operation."""

    def get_required_entities(self) -> set[EntityName]:
        """Get a set of the required entity names for the transformation."""
        return {self.entity_name}

    def get_created_entities(self) -> set[EntityName]:
        """Get a set of the entity names created by the transformation."""
        return {self.new_entity_name or self.entity_name}

entity_name instance-attribute

The entity to apply the step to.

new_entity_name = None class-attribute instance-attribute

Optionally, a new entity to create after the operation.

get_created_entities()

Get a set of the entity names created by the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
187
188
189
def get_created_entities(self) -> set[EntityName]:
    """Get a set of the entity names created by the transformation."""
    return {self.new_entity_name or self.entity_name}

get_required_entities()

Get a set of the required entity names for the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
183
184
185
def get_required_entities(self) -> set[EntityName]:
    """Get a set of the required entity names for the transformation."""
    return {self.entity_name}

ColumnAddition

Bases: BaseStep

A transformation step which adds a new column based on an expression.

Source code in src/dve/core_engine/backends/metadata/rules.py
339
340
341
342
343
344
345
class ColumnAddition(BaseStep):
    """A transformation step which adds a new column based on an expression."""

    column_name: Alias
    """The name of the column to be created."""
    expression: Expression
    """The SQL expression for the transformation."""

column_name instance-attribute

The name of the column to be created.

expression instance-attribute

The SQL expression for the transformation.

ColumnRemoval

Bases: BaseStep

A transformation step which removes a column by name.

Source code in src/dve/core_engine/backends/metadata/rules.py
348
349
350
351
352
class ColumnRemoval(BaseStep):
    """A transformation step which removes a column by name."""

    column_name: Alias
    """The name of the column to be dropped."""

column_name instance-attribute

The name of the column to be dropped.

ConfirmJoinHasMatch

Bases: AbstractConditionalJoin

Add a boolean column with name column_name to entity. The new column will indicate whether the entity has a corresponding row in target.

Source code in src/dve/core_engine/backends/metadata/rules.py
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
class ConfirmJoinHasMatch(AbstractConditionalJoin):
    """Add a boolean column with name `column_name` to `entity`. The new column
    will indicate whether the `entity` has a corresponding row in `target`.

    """

    column_name: Alias
    """
    The name of the new column to add to `entity`. This will indicate whether
    there is a corresponding match for each row.

    """
    perform_integrity_check: bool = True
    """
    Whether to perform the integrity check on the number of records. If this is
    disabled, it is not guaranteed that rows in `entity` will not be duplicated.

    """

column_name instance-attribute

The name of the new column to add to entity. This will indicate whether there is a corresponding match for each row.

perform_integrity_check = True class-attribute instance-attribute

Whether to perform the integrity check on the number of records. If this is disabled, it is not guaranteed that rows in entity will not be duplicated.

CopyEntity

Bases: AbstractStep

A transformation which copies an entity.

Source code in src/dve/core_engine/backends/metadata/rules.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
class CopyEntity(AbstractStep):
    """A transformation which copies an entity."""

    entity_name: EntityName
    """The entity to copy."""
    new_entity_name: EntityName
    """The new name for the copied entity."""

    def get_required_entities(self) -> set[EntityName]:
        """Get a set of the required entity names for the transformation."""
        return {self.entity_name}

    def get_created_entities(self) -> set[EntityName]:
        """Get a set of the entity names created by the transformation."""
        return {self.new_entity_name}

    def get_removed_entities(self) -> set[EntityName]:
        """Gets the entity which has been removed"""
        return set()

entity_name instance-attribute

The entity to copy.

new_entity_name instance-attribute

The new name for the copied entity.

get_created_entities()

Get a set of the entity names created by the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
436
437
438
def get_created_entities(self) -> set[EntityName]:
    """Get a set of the entity names created by the transformation."""
    return {self.new_entity_name}

get_removed_entities()

Gets the entity which has been removed

Source code in src/dve/core_engine/backends/metadata/rules.py
440
441
442
def get_removed_entities(self) -> set[EntityName]:
    """Gets the entity which has been removed"""
    return set()

get_required_entities()

Get a set of the required entity names for the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
432
433
434
def get_required_entities(self) -> set[EntityName]:
    """Get a set of the required entity names for the transformation."""
    return {self.entity_name}

DeferredFilter

Bases: AbstractStep

A filter which should be applied in a synchronised step with other filters for the same entity, providing feedback to users.

Messages will be emitted for each record that fails a filter according to the configured reporting, and any record-level errors will be removed from source entities at the end of the stage. This enables multiple issues with the same record to be flagged to a data provider.

Source code in src/dve/core_engine/backends/metadata/rules.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
class DeferredFilter(AbstractStep):
    """A filter which should be applied in a synchronised step with other filters for
    the same entity, providing feedback to users.

    Messages will be  emitted for each record that fails a filter according to the
    configured reporting, and any record-level errors will be removed from source
    entities at the end of the stage. This enables multiple issues with the same record
    to be flagged to a data provider.

    """

    entity_name: EntityName
    """The entity to apply the step to."""
    expression: Expression
    """
    The expression for the filter. Records for which this expression is falsey will be
    removed from the source entity if the reporting level is a record-level error.

    """
    reporting: Union[ReportingConfig, LegacyReportingConfig]
    """The reporting information for the filter."""

    def template(
        self: "DeferredFilter",
        local_variables: dict[Alias, Any],
        *,
        global_variables: Optional[dict[Alias, Any]] = None,
    ) -> "DeferredFilter":
        """Template the rule, given the global and local variables."""
        type_ = type(self)
        if global_variables:
            variables = global_variables.copy()
            variables.update(local_variables)
        else:
            variables = local_variables

        untemplated_data = {key: getattr(self, key) for key in self.UNTEMPLATED_KEYS}
        data_to_template = self.dict(exclude={*self.UNTEMPLATED_KEYS, "reporting"})
        templated_data = template_object(data_to_template, variables, "jinja")
        templated_data["reporting"] = self.reporting.template(
            local_variables, global_variables=global_variables
        )

        return type_(**templated_data, **untemplated_data)

    def get_required_entities(self) -> set[EntityName]:
        """Get a set of the required entity names for the transformation."""
        return {self.entity_name}

    def get_created_entities(self) -> set[EntityName]:
        """Get a set of the required entity names for the transformation."""
        return {self.entity_name}

entity_name instance-attribute

The entity to apply the step to.

expression instance-attribute

The expression for the filter. Records for which this expression is falsey will be removed from the source entity if the reporting level is a record-level error.

reporting instance-attribute

The reporting information for the filter.

get_created_entities()

Get a set of the required entity names for the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
256
257
258
def get_created_entities(self) -> set[EntityName]:
    """Get a set of the required entity names for the transformation."""
    return {self.entity_name}

get_required_entities()

Get a set of the required entity names for the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
252
253
254
def get_required_entities(self) -> set[EntityName]:
    """Get a set of the required entity names for the transformation."""
    return {self.entity_name}

template(local_variables, *, global_variables=None)

Template the rule, given the global and local variables.

Source code in src/dve/core_engine/backends/metadata/rules.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
def template(
    self: "DeferredFilter",
    local_variables: dict[Alias, Any],
    *,
    global_variables: Optional[dict[Alias, Any]] = None,
) -> "DeferredFilter":
    """Template the rule, given the global and local variables."""
    type_ = type(self)
    if global_variables:
        variables = global_variables.copy()
        variables.update(local_variables)
    else:
        variables = local_variables

    untemplated_data = {key: getattr(self, key) for key in self.UNTEMPLATED_KEYS}
    data_to_template = self.dict(exclude={*self.UNTEMPLATED_KEYS, "reporting"})
    templated_data = template_object(data_to_template, variables, "jinja")
    templated_data["reporting"] = self.reporting.template(
        local_variables, global_variables=global_variables
    )

    return type_(**templated_data, **untemplated_data)

EntityRemoval

Bases: AbstractStep

A transformation which drops entities.

Source code in src/dve/core_engine/backends/metadata/rules.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
class EntityRemoval(AbstractStep):
    """A transformation which drops entities."""

    entity_name: Union[EntityName, list[EntityName]]
    """The entity to drop."""

    def get_required_entities(self) -> set[EntityName]:
        """Get a set of the required entity names for the transformation."""
        return set()

    def get_created_entities(self) -> set[EntityName]:
        """Get a set of the entity names created by the transformation."""
        return set()

    def get_removed_entities(self) -> set[EntityName]:
        """Get a set of the entity names created by the transformation."""
        if isinstance(self.entity_name, list):
            return set(self.entity_name)
        return {self.entity_name}

entity_name instance-attribute

The entity to drop.

get_created_entities()

Get a set of the entity names created by the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
413
414
415
def get_created_entities(self) -> set[EntityName]:
    """Get a set of the entity names created by the transformation."""
    return set()

get_removed_entities()

Get a set of the entity names created by the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
417
418
419
420
421
def get_removed_entities(self) -> set[EntityName]:
    """Get a set of the entity names created by the transformation."""
    if isinstance(self.entity_name, list):
        return set(self.entity_name)
    return {self.entity_name}

get_required_entities()

Get a set of the required entity names for the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
409
410
411
def get_required_entities(self) -> set[EntityName]:
    """Get a set of the required entity names for the transformation."""
    return set()

HeaderJoin

Bases: AbstractJoin

Add a 'header' entity (target) to each row in entity. The header entity must contain only a single row.

Source code in src/dve/core_engine/backends/metadata/rules.py
532
533
534
535
536
537
538
539
class HeaderJoin(AbstractJoin):
    """Add a 'header' entity (`target`) to each row in `entity`. The header entity
    must contain only a single row.

    """

    header_column_name: Alias = "_Header"
    """The name of the column to add to `entity`, which will contain the header."""

header_column_name = '_Header' class-attribute instance-attribute

The name of the column to add to entity, which will contain the header.

ImmediateFilter

Bases: BaseStep

A filter which removes records from an entity (or creates a new entity without those rows) according to a provided expression. Only records for which the provided expression is truthy will be retained.

Source code in src/dve/core_engine/backends/metadata/rules.py
192
193
194
195
196
197
198
199
200
201
202
203
204
class ImmediateFilter(BaseStep):
    """A filter which removes records from an entity (or creates a new entity without
    those rows) according to a provided expression. Only records for which the
    provided expression is truthy will be retained.

    """

    expression: Expression
    """
    The expression for the filter. Records for which this expression is falsey will be
    removed.

    """

expression instance-attribute

The expression for the filter. Records for which this expression is falsey will be removed.

InnerJoin

Bases: AbstractNewColumnConditionalJoin

A table join configuration. This joins target into entity, retaining only rows which match in both tables.

The table join will result in all of the columns from entity being retained, new columns can be added based on data from target by adding SQL expressions in new_columns.

Source code in src/dve/core_engine/backends/metadata/rules.py
463
464
465
466
467
468
469
470
471
class InnerJoin(AbstractNewColumnConditionalJoin):
    """A table join configuration. This joins `target` into `entity`, retaining only
    rows which match in both tables.

    The table join will result in all of the columns from `entity` being retained,
    new columns can be added based on data from `target` by adding SQL expressions
    in `new_columns`.

    """

LeftJoin

Bases: AbstractNewColumnConditionalJoin

A table join configuration. This joins target into entity.

The table join will result in all of the columns from entity being retained, new columns can be added based on data from target by adding SQL expressions in new_columns.

Source code in src/dve/core_engine/backends/metadata/rules.py
453
454
455
456
457
458
459
460
class LeftJoin(AbstractNewColumnConditionalJoin):
    """A table join configuration. This joins `target` into `entity`.

    The table join will result in all of the columns from `entity` being retained,
    new columns can be added based on data from `target` by adding SQL expressions
    in `new_columns`.

    """

Notification

Bases: AbstractStep

An implementation of a notification according to a particular reporting configuration. This will emit notifications for all records that meet the expression, and will not modify the source entity.

NOTE: This is not intended to be used directly, but is used in the implementation of the sync filter stage.

Source code in src/dve/core_engine/backends/metadata/rules.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class Notification(AbstractStep):
    """An implementation of a notification according to a particular reporting configuration.
    This will emit notifications for all records that meet the expression, and will
    not modify the source entity.

    NOTE: This is not intended to be used directly, but is used in the implementation
    of the sync filter stage.

    """

    entity_name: EntityName
    """The entity to apply the step to."""
    expression: Expression
    """
    The expression for the notification. Records for which this expression is truthy will
    emit notifications according to the reporting config.

    """
    excluded_columns: list[Alias] = Field(default_factory=list)
    """Columns to be excluded from the record in the report."""
    reporting: ReportingConfig
    """The reporting information for the filter."""

    def get_required_entities(self) -> set[EntityName]:
        return {self.entity_name}

    def get_created_entities(self) -> set[EntityName]:
        return set()

entity_name instance-attribute

The entity to apply the step to.

excluded_columns = Field(default_factory=list) class-attribute instance-attribute

Columns to be excluded from the record in the report.

expression instance-attribute

The expression for the notification. Records for which this expression is truthy will emit notifications according to the reporting config.

reporting instance-attribute

The reporting information for the filter.

OneToOneJoin

Bases: LeftJoin

A table join configuration. This joins target into entity. This will not alter the number of rows in target.

The table join will result in all of the columns from entity being retained, new columns can be added based on data from target by adding SQL expressions in new_columns.

Source code in src/dve/core_engine/backends/metadata/rules.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
class OneToOneJoin(LeftJoin):
    """A table join configuration. This joins `target` into `entity`. This
    will not alter the number of rows in `target`.

    The table join will result in all of the columns from `entity` being retained,
    new columns can be added based on data from `target` by adding SQL expressions
    in `new_columns`.

    """

    perform_integrity_check: bool = True
    """
    Whether to perform the integrity check on the number of records. If this is
    disabled, it is not guaranteed that joins will be one to one.

    """

perform_integrity_check = True class-attribute instance-attribute

Whether to perform the integrity check on the number of records. If this is disabled, it is not guaranteed that joins will be one to one.

OrphanIdentification

Bases: AbstractConditionalJoin

Identify records in entity which don't have at least one corresponding match in target. A new boolean column will be added to entity ('IsOrphaned') indicating whether the condition matched.

If there is already an 'IsOrphaned' column in the entity, this will be set to the logical OR of its current value and the value it would have been set to otherwise.

Source code in src/dve/core_engine/backends/metadata/rules.py
554
555
556
557
558
559
560
561
562
class OrphanIdentification(AbstractConditionalJoin):
    """Identify records in `entity` which don't have at least one corresponding
    match in `target`. A new boolean column will be added to `entity` ('IsOrphaned')
    indicating whether the condition matched.

    If there is already an 'IsOrphaned' column in the entity, this will be set to the
    logical OR of its current value and the value it would have been set to otherwise.

    """

ParentMetadata

Bases: BaseModel

Data about the parent rule for a step.

Source code in src/dve/core_engine/backends/metadata/rules.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class ParentMetadata(BaseModel):
    """Data about the parent rule for a step."""

    rule: Union["Rule", str]
    """The rule the step belongs to, or a string representing the rule."""
    index: int
    """The index of the step within the parent rule."""
    stage: Stage
    """The name of the stage in the rule the step belongs to."""

    def __repr__(self) -> str:
        components: list[str] = []
        if isinstance(self.rule, Rule):
            components.append(f"rule=Rule(name={self.rule.name!r}, ...)")
        else:
            components.append(f"rule=Rule(name={self.rule!r}, ...)")

        for key, value in self.dict(exclude={"rule"}).items():
            components.append(f"{key}={value!r}")

        return f"ParentMetadata({', '.join(components)})"

    class Config:  # pylint: disable=too-few-public-methods
        """`pydantic configuration options`"""

        frozen = True
        extra = Extra.forbid

index instance-attribute

The index of the step within the parent rule.

rule instance-attribute

The rule the step belongs to, or a string representing the rule.

stage instance-attribute

The name of the stage in the rule the step belongs to.

Config

pydantic configuration options

Source code in src/dve/core_engine/backends/metadata/rules.py
80
81
82
83
84
class Config:  # pylint: disable=too-few-public-methods
    """`pydantic configuration options`"""

    frozen = True
    extra = Extra.forbid

RenameEntity

Bases: CopyEntity

A transformation which renames an entity.

Source code in src/dve/core_engine/backends/metadata/rules.py
445
446
447
448
449
450
class RenameEntity(CopyEntity):
    """A transformation which renames an entity."""

    def get_removed_entities(self) -> set[EntityName]:
        """Get a set of the entity names removed by the transformation."""
        return {self.entity_name}

get_removed_entities()

Get a set of the entity names removed by the transformation.

Source code in src/dve/core_engine/backends/metadata/rules.py
448
449
450
def get_removed_entities(self) -> set[EntityName]:
    """Get a set of the entity names removed by the transformation."""
    return {self.entity_name}

Rule

Bases: BaseModel

A rule, made up of multiple steps.

Source code in src/dve/core_engine/backends/metadata/rules.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
class Rule(BaseModel):
    """A rule, made up of multiple steps."""

    name: str
    """The name of the rule."""
    pre_sync_steps: list[AbstractStep]
    """The pre-sync steps in the rule."""
    sync_filter_steps: list[DeferredFilter]
    """The sync filter steps in the rule."""
    post_sync_steps: list[AbstractStep]
    """The post-sync steps in the rule."""

    def __str__(self):  # pydantic's default __str__ strips the model name.
        return super().__repr__()

    @classmethod
    @validate_arguments
    def from_step_list(cls, name: str, steps: list[Step]):
        """Load the rule from a single step list."""
        pre_sync_steps: list[AbstractStep] = []
        sync_filter_steps: list[DeferredFilter] = []
        post_sync_steps: list[AbstractStep] = []
        self = cls(
            name=name,
            pre_sync_steps=pre_sync_steps,
            sync_filter_steps=sync_filter_steps,
            post_sync_steps=post_sync_steps,
        )

        sync_stage_start: Optional[int] = None
        sync_stage_stop: Optional[int] = None
        for step_index, step in enumerate(steps):
            in_sync_stage = (sync_stage_start is not None) and (sync_stage_stop is None)
            sync_stage_completed = sync_stage_stop is not None

            step_is_sync_filter = isinstance(step, DeferredFilter)
            step_is_sync_keyword = isinstance(step, str) and step == "sync"
            step_is_sync = step_is_sync_filter or step_is_sync_keyword

            if step_is_sync:
                if sync_stage_completed:
                    raise ValueError(
                        "Synchronised steps must be contiguous. The step at index "
                        + f"{step_index} comes after the end of the first continuous "
                        + f"sync stage ([{sync_stage_start}:{sync_stage_stop}])"
                    )

                if sync_stage_start is None:
                    sync_stage_start = step_index

                if step_is_sync_filter:
                    sync_filter_steps.append(step)  # type: ignore

                continue

            if in_sync_stage:
                sync_stage_completed = True
                sync_stage_stop = step_index

            if not sync_stage_completed:
                pre_sync_steps.append(step)  # type: ignore
            else:
                post_sync_steps.append(step)  # type: ignore

        return self

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        global_index = 0
        for stage, step_list in (
            ("Pre-sync", self.pre_sync_steps),
            ("Sync", self.sync_filter_steps),
            ("Post-sync", self.post_sync_steps),
        ):
            for stage_step_index, step in enumerate(step_list):
                step_list[stage_step_index] = step.with_parent(
                    ParentMetadata(rule=self, index=global_index, stage=stage)
                )
                global_index += 1

    def template(
        self: RSelf,
        local_variables: TemplateVariables,
        *,
        global_variables: Optional[TemplateVariables] = None,
    ) -> RSelf:
        """Template the rule, returning the new templated rule. This is only really useful
        for 'upfront' templating, as all stages of the rule will be templated at once.

        """
        rule_lists: dict[str, Union[list[AbstractStep], list[DeferredFilter]]] = {
            "pre_sync_steps": self.pre_sync_steps,
            "sync_filter_steps": self.sync_filter_steps,
            "post_sync_steps": self.post_sync_steps,
        }
        for list_name, step_list in rule_lists.items():
            templated_rule_list = []
            for step in step_list:
                step = step.template(local_variables, global_variables=global_variables)
                templated_rule_list.append(step)
            rule_lists[list_name] = templated_rule_list

        type_ = type(self)
        return type_(name=self.name, **rule_lists)

name instance-attribute

The name of the rule.

post_sync_steps instance-attribute

The post-sync steps in the rule.

pre_sync_steps instance-attribute

The pre-sync steps in the rule.

sync_filter_steps instance-attribute

The sync filter steps in the rule.

from_step_list(name, steps) classmethod

Load the rule from a single step list.

Source code in src/dve/core_engine/backends/metadata/rules.py
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
@classmethod
@validate_arguments
def from_step_list(cls, name: str, steps: list[Step]):
    """Load the rule from a single step list."""
    pre_sync_steps: list[AbstractStep] = []
    sync_filter_steps: list[DeferredFilter] = []
    post_sync_steps: list[AbstractStep] = []
    self = cls(
        name=name,
        pre_sync_steps=pre_sync_steps,
        sync_filter_steps=sync_filter_steps,
        post_sync_steps=post_sync_steps,
    )

    sync_stage_start: Optional[int] = None
    sync_stage_stop: Optional[int] = None
    for step_index, step in enumerate(steps):
        in_sync_stage = (sync_stage_start is not None) and (sync_stage_stop is None)
        sync_stage_completed = sync_stage_stop is not None

        step_is_sync_filter = isinstance(step, DeferredFilter)
        step_is_sync_keyword = isinstance(step, str) and step == "sync"
        step_is_sync = step_is_sync_filter or step_is_sync_keyword

        if step_is_sync:
            if sync_stage_completed:
                raise ValueError(
                    "Synchronised steps must be contiguous. The step at index "
                    + f"{step_index} comes after the end of the first continuous "
                    + f"sync stage ([{sync_stage_start}:{sync_stage_stop}])"
                )

            if sync_stage_start is None:
                sync_stage_start = step_index

            if step_is_sync_filter:
                sync_filter_steps.append(step)  # type: ignore

            continue

        if in_sync_stage:
            sync_stage_completed = True
            sync_stage_stop = step_index

        if not sync_stage_completed:
            pre_sync_steps.append(step)  # type: ignore
        else:
            post_sync_steps.append(step)  # type: ignore

    return self

template(local_variables, *, global_variables=None)

Template the rule, returning the new templated rule. This is only really useful for 'upfront' templating, as all stages of the rule will be templated at once.

Source code in src/dve/core_engine/backends/metadata/rules.py
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def template(
    self: RSelf,
    local_variables: TemplateVariables,
    *,
    global_variables: Optional[TemplateVariables] = None,
) -> RSelf:
    """Template the rule, returning the new templated rule. This is only really useful
    for 'upfront' templating, as all stages of the rule will be templated at once.

    """
    rule_lists: dict[str, Union[list[AbstractStep], list[DeferredFilter]]] = {
        "pre_sync_steps": self.pre_sync_steps,
        "sync_filter_steps": self.sync_filter_steps,
        "post_sync_steps": self.post_sync_steps,
    }
    for list_name, step_list in rule_lists.items():
        templated_rule_list = []
        for step in step_list:
            step = step.template(local_variables, global_variables=global_variables)
            templated_rule_list.append(step)
        rule_lists[list_name] = templated_rule_list

    type_ = type(self)
    return type_(name=self.name, **rule_lists)

RuleMetadata

Bases: BaseModel

Metadata about the rules.

Source code in src/dve/core_engine/backends/metadata/rules.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
class RuleMetadata(BaseModel):
    """Metadata about the rules."""

    rules: list[Rule]
    """A list of rules to be applied to to the entities."""
    local_variables: Optional[list[TemplateVariables]] = None
    """
    An optional list of local, rule-level template variables.

    If provided, this must be the same length as `rules`.

    """
    global_variables: TemplateVariables = Field(default_factory=dict)
    """An optional mapping of global template variables."""
    templating_strategy: Literal["upfront", "runtime"] = "upfront"
    """
    The templating strategy for the rules.

    If 'upfront', template all rules at the beginning of the rule stage
    execution.

    If 'runtime', template rules immediately before evaluating them.

    Runtime templating doesn't currently add any value, but will provide
    the ability to set variables from data items in the future. With runtime
    rules, it is not possible to check that all entities are present before
    performing work.

    """
    reference_data_config: dict[EntityName, ReferenceConfigUnion]
    """
    Per-entity configuration options for the reference data.

    Options are likely to vary by backend (e.g. some backends will have
    a database and table name, some might have a remote URI).

    """

    @root_validator()
    @classmethod
    def _ensure_locals_same_length_as_rules(cls, values: dict[str, list[Any]]):
        """Ensure that if 'local_variables' is provided, it's the same length as 'rules'."""
        local_vars = values["local_variables"]
        if local_vars is not None:
            n_local_vars = len(local_vars)
            n_rules = len(values["rules"])
            if n_local_vars != n_rules:
                raise ValueError(
                    f"Mismatch between number of local variables {n_local_vars} and number of "
                    + f"rules {n_rules}"
                )
        return values

    def __iter__(self) -> Iterator[tuple[Rule, TemplateVariables]]:  # type: ignore
        """Iterate over the rules and local variables."""
        if self.local_variables is None:
            yield from ((rule, {}) for rule in self.rules)  # type: ignore
        else:
            yield from zip(self.rules, self.local_variables)

global_variables = Field(default_factory=dict) class-attribute instance-attribute

An optional mapping of global template variables.

local_variables = None class-attribute instance-attribute

An optional list of local, rule-level template variables.

If provided, this must be the same length as rules.

reference_data_config instance-attribute

Per-entity configuration options for the reference data.

Options are likely to vary by backend (e.g. some backends will have a database and table name, some might have a remote URI).

rules instance-attribute

A list of rules to be applied to to the entities.

templating_strategy = 'upfront' class-attribute instance-attribute

The templating strategy for the rules.

If 'upfront', template all rules at the beginning of the rule stage execution.

If 'runtime', template rules immediately before evaluating them.

Runtime templating doesn't currently add any value, but will provide the ability to set variables from data items in the future. With runtime rules, it is not possible to check that all entities are present before performing work.

__iter__()

Iterate over the rules and local variables.

Source code in src/dve/core_engine/backends/metadata/rules.py
729
730
731
732
733
734
def __iter__(self) -> Iterator[tuple[Rule, TemplateVariables]]:  # type: ignore
    """Iterate over the rules and local variables."""
    if self.local_variables is None:
        yield from ((rule, {}) for rule in self.rules)  # type: ignore
    else:
        yield from zip(self.rules, self.local_variables)

SelectColumns

Bases: BaseStep

A transformation step which selects columns from an entity.

Source code in src/dve/core_engine/backends/metadata/rules.py
355
356
357
358
359
360
361
class SelectColumns(BaseStep):
    """A transformation step which selects columns from an entity."""

    columns: MultipleExpressions
    """Multiple expressions to select from the specified entity."""
    distinct: bool = False
    """Whether to keep only distinct columns from the select statement."""

columns instance-attribute

Multiple expressions to select from the specified entity.

distinct = False class-attribute instance-attribute

Whether to keep only distinct columns from the select statement.

SemiJoin

Bases: AbstractConditionalJoin

A table join configuration. This keeps the rows in entity where the join condition with target is true.

The table join will result in all of the columns from entity being retained. No rows can be added from target.

Source code in src/dve/core_engine/backends/metadata/rules.py
492
493
494
495
496
497
498
499
class SemiJoin(AbstractConditionalJoin):
    """A table join configuration. This keeps the rows in `entity` where the join
    condition with `target` is true.

    The table join will result in all of the columns from `entity` being retained.
    No rows can be added from `target`.

    """

TableUnion

Bases: AbstractJoin

Union two tables together, taking the columns from each by name.

Where columns have the same name, they must be the same type or coerceable. Where column casing differs, the casing from the source entity will be kept.

Column order will be preserved, with columns from source taken first and extra columns in target added in order afterwards.

Source code in src/dve/core_engine/backends/metadata/rules.py
542
543
544
545
546
547
548
549
550
551
class TableUnion(AbstractJoin):
    """Union two tables together, taking the columns from each by name.

    Where columns have the same name, they must be the same type or coerceable.
    Where column casing differs, the casing from the `source` entity will be kept.

    Column order will be preserved, with columns from `source` taken first and extra
    columns in `target` added in order afterwards.

    """