Transformers¶
runtime
¶
Transformer observation contract.
TransformRuntimeInfo
dataclass
¶
TransformRuntimeInfo(
start_time: datetime = utc_now(),
end_time: Optional[datetime] = None,
status: str = PENDING.value,
message: Optional[str] = None,
transformers_applied: list[str] = list(),
)
Bases: RuntimeInfo
base
¶
Abstract base classes for transformers and the transformer pipeline.
BaseTransformer[DF] defines the contract for individual transformers.
TransformerPipeline orchestrates multiple transformers in priority
order, tracking runtime info.
ColumnMapping
dataclass
¶
Typed mapping from input columns to output columns.
None means a source column was removed. known=False marks a
custom transformer that changed names without declaring a mapping; an
active replacement window must reject that state rather than guess.
compose
¶
Compose this mapping with the next transform's mapping.
from_columns
classmethod
¶
from_columns(
before: list[str],
after: list[str],
renames: Mapping[str, str] | None = None,
) -> "ColumnMapping"
Build a deterministic mapping for a built-in column transform.
match_name
staticmethod
¶
Resolve exact spelling first; reject ambiguous case fallback.
preserve_or_unknown
classmethod
¶
Infer only unchanged names; never infer a rename heuristically.
BaseTransformer
¶
Bases: ABC, Generic[DF]
Abstract base class for a single transformation step.
Each transformer has an :attr:order that determines execution
priority within the pipeline (lower values execute first).
Tracking¶
Call :meth:_mark_applied or :meth:_mark_skipped inside
:meth:transform to control what the pipeline records in
transformers_applied.
_mark_applied()→ recordClassName_mark_applied("detail")→ recordClassName(detail)_mark_skipped()→ do not record anything- (no call) → default: record
ClassName
applied_label
property
¶
Label resolved after :meth:transform returns.
Returns:
| Type | Description |
|---|---|
str | None
|
A string label to record, or |
column_mapping
property
¶
column_mapping: Optional[ColumnMapping]
Mapping reported by the most recent transform invocation.
transform
abstractmethod
¶
TransformerPipeline
¶
TransformerPipeline(engine: BaseEngine[DF])
Bases: Generic[DF]
Ordered pipeline of transformers with runtime tracking.
Transformers are sorted by :attr:BaseTransformer.order and executed
sequentially. Runtime info (timing, status, applied transformer names)
is tracked for observability.
transformers
property
¶
transformers: List[BaseTransformer[DF]]
Return transformers sorted by execution order.
add_transformer
¶
add_transformer(transformer: BaseTransformer[DF]) -> None
Add a transformer to the pipeline.
get_column_mapping
¶
get_column_mapping() -> Optional[ColumnMapping]
Return the mapping from source columns to final output columns.
get_output_columns
¶
Return final output columns from the most recent invocation.
get_runtime_info
¶
get_runtime_info() -> TransformRuntimeInfo
Return runtime information from the most recent transform.
remove_transformer
¶
Remove all transformers of a given class.
Returns:
| Type | Description |
|---|---|
bool
|
|
transform
¶
Run all transformers in order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DF
|
Input DataFrame. |
required |
dataflow
|
DataFlow
|
Full pipeline configuration. |
required |
Returns:
| Type | Description |
|---|---|
DF
|
Transformed DataFrame. |
Raises:
| Type | Description |
|---|---|
TransformError
|
If any transformer fails. |
ColumnMapping carries the declared input-to-output column relationship across transformer
steps. A None output records a removed column, and known=False marks a custom transform whose
rename behavior cannot be inferred safely.
For plugins that rename or drop columns, follow the mapping example. The protected reporting hook is part of that extension contract:
_report_column_mapping
¶
_report_column_mapping(mapping: ColumnMapping) -> None
Report deterministic name/drop behavior for this invocation.
schema_converter
¶
Schema conversion transformer.
Casts DataFrame columns according to schema hints defined in the
:class:Transform configuration. Also handles timestamp_ntz →
timestamp conversion. Datatype interpretation is delegated to the
selected engine's :meth:~BaseEngine.cast_column implementation.
SchemaConverter
¶
SchemaConverter(engine: BaseEngine[DF])
Bases: BaseTransformer[DF]
Cast columns per schema hints (order = 10).
Processing
- If
source.connection.use_schema_hintis truthy and hints exist, pass each authored source type and its dialect context to the engine, which resolves it to a native target. - Convert
timestamp_ntzcolumns totimestamp(engine hook) after hint casts so an explicitly hinted NTZ column follows the same conversion policy.
column_value_transformer
¶
Ordered, typed value normalization before schema conversion.
ColumnValueTransformer
¶
ColumnValueTransformer(engine: BaseEngine[DF])
hash_column_adder
¶
Stable portable business hash columns.
HashColumnAdder
¶
HashColumnAdder(engine: BaseEngine[DF])
deduplicator
¶
Deduplication transformer.
Removes duplicate rows based on partition (dedup) columns and ordering
columns. Uses RANK-based dedup for MERGE_OVERWRITE load type
and ROW_NUMBER-based dedup otherwise.
Deduplicator
¶
Deduplicator(engine: BaseEngine[DF])
Bases: BaseTransformer[DF]
Deduplicate DataFrame rows (order = 20).
Decision logic
order_cols=dataflow.order_columns(latest_data_columnswith fallback tosource.watermark_columns).- If
deduplicate_columnsororder_colsis empty, the transformer is a no-op (returns input unchanged). -
Uses :meth:
engine.deduplicate_by_rank(keeps ties) when: -
load_type == MERGE_OVERWRITEandmerge_keysis non-empty andtransform.deduplicate_columnsisNone(partition resolved implicitly from merge keys). -
or
transform.configure["deduplicate_by_rank"]isTrue. -
Otherwise → :meth:
engine.deduplicate(strict ROW_NUMBER).
column_adder
¶
Column adder transformers.
:class:ColumnAdder removes stale system columns and adds computed
(user-defined) columns. :class:SystemColumnAdder appends the standard
audit columns as the final step in the pipeline.
ColumnAdder
¶
ColumnAdder(engine: BaseEngine[DF])
SystemColumnAdder
¶
SystemColumnAdder(
engine: BaseEngine[DF],
author: str = DEFAULT_AUTHOR,
*,
dataflow_run_id: str | None = None,
)
Bases: BaseTransformer[DF]
Append framework audit columns at order 70.
Adds __created_at, __updated_at, and __updated_by to every
DataFrame. Driver-managed runs also add __dataflow_run_id using the
execution ID supplied when the transformer is created.
SCD2ColumnAdder
¶
SCD2ColumnAdder(engine: BaseEngine[DF])
Bases: BaseTransformer[DF]
Add SCD2 tracking columns for scd2 load type (order = 60).
Adds __valid_from (from the effective column), __valid_to (NULL),
and __is_current (true) so downstream MERGE can close old rows and
insert new versions.
row_filter
¶
Row filter transformer.
Applies a SQL WHERE-style expression to discard unwanted rows
after column addition but before SCD2 processing.
RowFilter
¶
RowFilter(engine: BaseEngine[DF])
Bases: BaseTransformer[DF]
Filter rows by a SQL expression (order = 35).
Reads :attr:~datacoolie.core.models.transform.Transform.filter_expression.
When the expression is absent or empty, the transformer is a no-op.
The expression is passed verbatim to
:meth:engine.filter_rows which delegates to the engine's native
WHERE-clause equivalent (Polars filter, Spark where, etc.).
This transformer complements :attr:~datacoolie.core.models.source.Source.filter_expression
(applied at read time inside each source reader). Use
source.filter_expression for conditions on raw source columns and
transform.filter_expression for conditions on computed or added
columns that only exist after :class:ColumnAdder runs.
Example (YAML metadata)::
transform:
filter_expression: "category_label != 'unknown' AND derived_score > 0.5"
Ordering rationale:
- Runs after
ColumnAdder(slot 30) so expressions may reference computed columns. - Runs before
SCD2ColumnAdder(slot 60) to reduce the row set before the heavier SCD2 logic.
partition_handler
¶
Partition handler transformer.
Generates partition columns from SQL expressions defined in the
destination partition_columns configuration.
PartitionHandler
¶
PartitionHandler(engine: BaseEngine[DF])
Bases: BaseTransformer[DF]
Generate partition columns from expressions (order = 80).
For each :class:PartitionColumn with an expression, adds
a new column (or overwrites an existing one) using
:meth:engine.add_column. Columns without expressions are
assumed to already exist in the DataFrame.
data_masker
¶
Structured scalar column masking.
DataMasker
¶
DataMasker(engine: BaseEngine[DF])
column_projector
¶
Column selection, removal, and atomic rename.
ColumnProjector
¶
ColumnProjector(engine: BaseEngine[DF])
column_name_sanitizer
¶
Column name sanitizer transformer.
Renames DataFrame columns using the chosen case-conversion mode:
lower (default)
Lowercases the name without inserting underscores at word boundaries.
"MyColumn" → "mycolumn", "HTTPStatus" → "httpstatus".
snake
Converts camelCase / PascalCase → snake_case.
"MyColumn" → "my_column", "HTTPStatus" → "http_status".
Both modes apply the same clean-up rules:
- Replaces special characters (spaces, hyphens, dots, etc.) with
_. - Collapses consecutive underscores and strips leading / trailing ones.
- Prefixes names that start with a digit with
_. - Columns whose names already start with
_are left unchanged.
ColumnNameSanitizer
¶
ColumnNameSanitizer(
engine: BaseEngine[DF], *, mode: ColumnCaseMode = LOWER
)
Bases: BaseTransformer[DF]
Rename columns using the chosen case-conversion mode (order = 90).
Runs after :class:SystemColumnAdder so the framework audit columns keep
their canonical names. All prior transformers (schema conversion, dedup,
additional columns, partition columns) still work with the original
business column names. Only columns whose names actually change are
renamed. Columns that already start with _ (e.g. system columns added
in the current or a previous run) are skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine
|
BaseEngine[DF]
|
Data engine instance. |
required |
mode
|
ColumnCaseMode
|
Case-conversion mode — |
LOWER
|
to_lower_case
¶
Convert an arbitrary column name to lowercased form.
Column names that already start with an underscore (e.g. system
columns such as __created_at) are returned unchanged.
Examples::
"MyColumn" → "mycolumn"
"HTTPStatus" → "httpstatus"
"order-date" → "order_date"
"Column Name" → "column_name"
"123" → "_123"
"col@#name" → "col_name"
"__created_at" → "__created_at" # unchanged
to_snake_case
¶
Convert an arbitrary column name to snake_case.
Column names that already start with an underscore (e.g. system
columns such as __created_at) are returned unchanged.
Examples::
"MyColumn" → "my_column"
"order-date" → "order_date"
"Column Name" → "column_name"
"HTTPStatus" → "http_status"
"123" → "_123"
"col@#name" → "col_name"
"__created_at" → "__created_at" # unchanged