Destinations¶
base
¶
Abstract base classes for destination writers and load strategies.
BaseDestinationWriter[DF] uses the Template Method pattern for
writes and the Strategy pattern for load-type dispatch.
BaseLoadStrategy defines the contract for individual load strategies
(overwrite, append, merge_upsert, merge_overwrite, scd2).
BaseDestinationWriter
¶
BaseDestinationWriter(engine: BaseEngine[DF])
Bases: ABC, Generic[DF]
Abstract destination writer with Template Method lifecycle.
Subclasses implement :meth:_write_internal. The base class
manages timing, error wrapping, runtime info, and maintenance.
get_runtime_info
¶
get_runtime_info() -> DestinationRuntimeInfo
Return runtime information from the most recent write.
run_maintenance
¶
run_maintenance(
dataflow: DataFlow,
*,
do_compact: bool = True,
do_cleanup: bool = True,
retention_hours: Optional[int] = None,
) -> DestinationRuntimeInfo
Run maintenance operations (compact + cleanup) as a single result.
Sub-operation outcomes are stored in operation_details as a list
of dicts, each with an "operation" key ("compact" / "cleanup"
/ "history"). File/byte metrics are summed across both operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataflow
|
DataFlow
|
Pipeline configuration. |
required |
do_compact
|
bool
|
Whether to run compaction. |
True
|
do_cleanup
|
bool
|
Whether to run cleanup. |
True
|
retention_hours
|
Optional[int]
|
Cleanup retention override (default: 168 h). |
None
|
Returns:
| Type | Description |
|---|---|
DestinationRuntimeInfo
|
A single :class: |
run_selected_maintenance
¶
run_selected_maintenance(
dataflow: DataFlow,
*,
prepared=None,
do_compact=True,
do_cleanup=True,
retention_hours=None,
compact_options=None,
cleanup_options=None,
)
Opt-in extension; legacy writers retain their original kwargs.
write
¶
write(
df: DF,
dataflow: DataFlow,
*,
watermark_window: Optional[WindowSpec] = None,
) -> DestinationRuntimeInfo
Write data to the destination (Template Method).
- Validate destination path.
- Delegate to :meth:
_write_internal. - Populate and return runtime info.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DF
|
DataFrame to write. |
required |
dataflow
|
DataFlow
|
Full pipeline configuration. |
required |
Returns:
| Type | Description |
|---|---|
DestinationRuntimeInfo
|
Runtime metrics for the write operation. |
Raises:
| Type | Description |
|---|---|
DestinationError
|
On any write failure. |
BaseLoadStrategy
¶
Bases: ABC
Abstract load strategy (Strategy pattern).
Each strategy knows how to write a DataFrame to a destination path using a specific load type (overwrite, append, merge, etc.).
load_type
abstractmethod
property
¶
The load type this strategy handles (e.g. "overwrite").
execute
abstractmethod
¶
execute(
df: DF,
table_name: Optional[str],
dataflow: DataFlow,
engine: BaseEngine[DF],
path: Optional[str] = None,
*,
watermark_window: Optional[WindowSpec] = None,
) -> None
Execute the load strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DF
|
DataFrame to write. |
required |
table_name
|
Optional[str]
|
Fully qualified table name (always available). |
required |
dataflow
|
DataFlow
|
Pipeline configuration. |
required |
engine
|
BaseEngine[DF]
|
DataFrame engine. |
required |
path
|
Optional[str]
|
Optional destination path for path-based fallback. |
None
|
runtime
¶
Runtime information produced by destination writers.
DestinationRuntimeInfo
dataclass
¶
DestinationRuntimeInfo(
start_time: datetime = utc_now(),
end_time: Optional[datetime] = None,
status: str = PENDING.value,
message: Optional[str] = None,
operation_type: Optional[str] = None,
rows_written: Optional[int] = None,
rows_inserted: Optional[int] = None,
rows_updated: Optional[int] = None,
rows_deleted: Optional[int] = None,
files_added: Optional[int] = None,
files_removed: Optional[int] = None,
bytes_added: Optional[int] = None,
bytes_removed: Optional[int] = None,
operation_details: list[dict[str, Any]] = list(),
)
Bases: RuntimeInfo
Runtime metrics for one destination write or maintenance phase.
Metrics remain nullable because a successful destination operation may not
expose a measurement. Consumers can distinguish that case from an
explicitly measured zero. bytes_saved follows the same rule and is
therefore unavailable until both byte measurements are known.
bytes_saved
property
¶
Return non-negative byte savings when both measurements exist.
Destination target contract¶
Destination writers and maintenance use the same pure target projection. A
resolve_destination_target(destination, engine=engine) reports the effective
table or path handle, format, and addressing mode. Its storage_path retains an
auxiliary path for catalog registration. It performs no catalog or storage I/O.
An unqualified named backend has identity=None; use require_identity=True
to reject it before maintenance dispatch. Engine-free calls retain the legacy
declared projection for inspection and do not establish physical equality.
target
¶
Pure destination target resolution.
Destination routing is owned by the destination layer. Engines receive the resolved handle, while maintenance and orchestration use the same projection to calculate a physical identity. This module performs no I/O or catalog lookup.
ResolvedDestination
dataclass
¶
ResolvedDestination(
table_name: str | None,
path: str | None,
format: str,
addressing: AddressingMode,
identity: str | None,
storage_path: str | None = None,
)
Effective table/path handles and their deterministic identity.
resolve_destination_target
¶
resolve_destination_target(
destination: _DestinationContract,
*,
engine: _EngineTargetContract | None = None,
require_target: bool = True,
require_identity: bool = False,
) -> ResolvedDestination
Resolve the primary handle used by destination engine operations.
Forced-path destination policy precedes the engine's pure preference. Engine-aware results expose only the operative handle, retaining the auxiliary path in storage_path. Unknown named equality is None, or an error when require_identity is requested. Engine-free calls preserve the legacy declared projection for inspection, not runtime physical equality.
Writer extension hooks¶
Implementations subclass BaseDestinationWriter and provide the two protected
backend hooks below. The public write(...) and run_maintenance(...) methods
own timing, error wrapping, runtime metrics, and WindowSpec validation.
_write_internal
abstractmethod
¶
_write_internal(
df: DF,
dataflow: DataFlow,
*,
watermark_window: Optional[WindowSpec] = None,
) -> None
Execute the write operation (subclass implementation).
_maintain_internal
abstractmethod
¶
_maintain_internal(
dataflow: DataFlow,
*,
do_compact: bool,
do_cleanup: bool,
retention_hours: int,
) -> "tuple[List[Dict[str, Any]], List[str]]"
Execute maintenance operations (subclass implementation).
Subclasses own the engine interaction: resolving the canonical
table handle (path vs. name), invoking exists/compact/
cleanup on the engine, and producing structured sub-results.
Use :meth:_run_op to build uniform sub-result dicts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataflow
|
DataFlow
|
Pipeline configuration. |
required |
do_compact
|
bool
|
Whether to run compaction. |
required |
do_cleanup
|
bool
|
Whether to run cleanup. |
required |
retention_hours
|
int
|
Cleanup retention window in hours. |
required |
Returns:
| Type | Description |
|---|---|
'tuple[List[Dict[str, Any]], List[str]]'
|
Tuple of |
'tuple[List[Dict[str, Any]], List[str]]'
|
list of per-operation dicts (compact, cleanup) and |
'tuple[List[Dict[str, Any]], List[str]]'
|
is a list of error messages to surface in the final status. |
file_writer
¶
File-format destination writer (Parquet, CSV, JSON, JSONL, Avro).
Writes DataFrames to storage paths, supporting date-folder partitioning
via connection.date_folder_partitions resolved with the current UTC
timestamp. Only append, overwrite, and full_load load types
are supported. Maintenance (compact / cleanup) is not applicable.
FileWriter
¶
FileWriter(engine: BaseEngine[DF])
Bases: BaseDestinationWriter[DF]
Destination writer for flat-file formats (Parquet, CSV, JSON, …).
Delegates to :func:get_load_strategy for the actual write logic.
Date-folder partitioning is resolved at write time using utc_now().
Maintenance operations (compact / cleanup) are not supported for
flat files and will raise :class:DestinationError if invoked.
delta_writer
¶
Delta Lake destination writer.
The writer owns Delta load-strategy and maintenance orchestration. Optional
AWS Glue/Athena catalog work lives in :mod:datacoolie.destinations._delta.aws_catalog
so non-AWS Delta writes do not carry catalog-specific branching.
DeltaWriter
¶
DeltaWriter(engine: BaseEngine[DF])
iceberg_writer
¶
Iceberg destination writer.
Writes DataFrames to Iceberg tables, preferring table-name-based operations (DataFrameWriterV2 / SQL MERGE) via catalog. Falls back to path-based operations when no catalog is configured.
IcebergWriter
¶
IcebergWriter(engine: BaseEngine[DF])
Bases: BaseDestinationWriter[DF]
Destination writer for Apache Iceberg tables.
Prefers table-name-based operations (catalog-aware) for Iceberg. Falls back to path-based operations when no catalog is configured.
run_selected_maintenance
¶
run_selected_maintenance(
dataflow,
*,
prepared=None,
do_compact=True,
do_cleanup=True,
retention_hours=None,
compact_options=None,
cleanup_options=None,
)
Execute all preflighted native actions against one retained binding.
load
¶
Load strategies for destination writers.
Each strategy implements a specific write mode (overwrite, append,
merge_upsert, merge_overwrite, scd2) via the :class:BaseLoadStrategy
interface.
The :data:LOAD_STRATEGIES registry and :func:get_load_strategy helper
provide lookup by load-type string.
AppendStrategy
¶
MergeOverwriteStrategy
¶
Bases: BaseLoadStrategy
Merge overwrite — delete + re-insert matching rows.
When destination.replace_by_watermark is enabled and a watermark
window is available on the dataflow, this strategy uses range-based
delete (delete all target rows within the watermark window) instead
of key-based delete. This handles source-side deletions within the
window.
MergeUpsertStrategy
¶
OverwriteStrategy
¶
SCD2Strategy
¶
Bases: BaseLoadStrategy
Slowly Changing Dimension Type 2.
Closes existing current records and inserts new versions using
the staged-updates MERGE pattern. Requires merge_keys and
scd2_effective_column in destination.configure.
get_load_strategy
¶
get_load_strategy(load_type: str) -> BaseLoadStrategy
Look up a load strategy by type string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
load_type
|
str
|
Load type (e.g. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Matching |
BaseLoadStrategy
|
class: |
Raises:
| Type | Description |
|---|---|
DestinationError
|
If the load type is not registered. |