Skip to content

Engines

base

Abstract base class for DataFrame engines.

BaseEngine[DF] is a generic ABC parameterised by DataFrame type. Concrete implementations bind DF to their native frame type (Spark DataFrame or Polars LazyFrame).

Section layout

  • Construction — __init__, platform, set_platform
  • Read — read_parquet, read_delta, read_iceberg, read_csv, read_json, read_jsonl, read_avro, read_excel, read_path, read_database, create_dataframe, execute_sql, read_table
  • Write — write_to_path, write_to_table
  • Merge — merge_to_path, merge_overwrite_to_path, merge_to_table, merge_overwrite_to_table
  • Transform — add_column, drop_columns, select_columns, rename_column, filter_rows, apply_watermark_filter, deduplicate, deduplicate_by_rank, cast_column
  • System columns — add_system_columns, add_file_info_columns, remove_system_columns, convert_timestamp_ntz_to_timestamp
  • Metrics — count_rows, is_empty, get_columns, get_schema, get_max_values, get_count_and_max_values
  • Maintenance — table_exists_by_path, table_exists_by_name, get_history_by_path, get_history_by_name, compact_by_path, compact_by_name, cleanup_by_path, cleanup_by_name
  • Navigation (concrete dispatchers) — read, write, merge, merge_overwrite, replace_window, exists, get_history, compact, cleanup
  • SCD Type 2 — scd2_to_path, scd2_to_table, scd2

DF module-attribute

DF = TypeVar('DF')

BaseEngine

BaseEngine(platform: Optional[BasePlatform] = None)

Bases: ABC, Generic[DF]

Engine abstraction for DataFrame-based read / write / transform.

Type parameter DF is the concrete DataFrame class (e.g. pyspark.sql.DataFrame or polars.LazyFrame).

platform property

platform: Optional[BasePlatform]

The platform attached to this engine, if any.

add_column abstractmethod

add_column(df: DF, column_name: str, expression: str) -> DF

Add (or replace) a column using a SQL expression.

add_file_info_columns abstractmethod

add_file_info_columns(
    df: DF, file_infos: Optional[List[FileInfo]] = None
) -> DF

Add __file_name, __file_path, __file_modification_time.

Engines that embed the source path at scan time (e.g. Polars via include_file_paths) map file_infos onto the already-present __file_path column to inject __file_name and __file_modification_time. Engines with native metadata support (e.g. Spark _metadata) ignore file_infos entirely.

Parameters:

Name Type Description Default
df DF

Input DataFrame — for Polars this must already contain the __file_path column added by the scan reader.

required
file_infos Optional[List[FileInfo]]

Ordered list of :class:~datacoolie.platforms.base.FileInfo objects used to resolve name / modification-time per path, or None when only the path itself is available.

None

add_hash_column

add_hash_column(df: DF, definition: Any) -> DF

Add a stable hash column using an engine-native expression.

add_system_columns abstractmethod

add_system_columns(
    df: DF,
    author: Optional[str] = None,
    dataflow_run_id: Optional[str] = None,
) -> DF

Add framework audit columns and an optional dataflow run ID.

apply_masking_rule

apply_masking_rule(
    df: DF,
    rule: Any,
    *,
    missing_column_policy: str = "error",
) -> DF

Apply one typed masking rule in one engine-native projection.

apply_value_rule

apply_value_rule(
    df: DF,
    rule: Any,
    *,
    missing_column_policy: str = "error",
) -> DF

Apply one typed value rule using engine-native expressions.

Built-in engines preflight all targets and add at most one native projection for the rule, regardless of the number of target columns.

apply_watermark_filter abstractmethod

apply_watermark_filter(
    df: DF,
    watermark_columns: List[str],
    watermark_start: Dict[str, Any],
    *,
    start_operator: str = ">",
    watermark_end: Optional[Dict[str, Any]] = None,
    end_operator: str = "<",
) -> DF

Filter rows by watermark bounds (lower, upper, or both).

Builds an OR condition across watermark columns. When only lower bound is provided: col1 {op} val1 OR col2 {op} val2 ...

When watermark_end is provided, builds per-column windowed conditions OR'd across columns: (col1 > lower1 AND col1 < upper1) OR (col2 > lower2 AND col2 < upper2)

Per-column edge cases when watermark_end is set: - lower has col, upper has col → col > lower AND col < upper - lower has col, upper missing → col > lower (no ceiling) - lower missing, upper has col → col < upper (no floor) - both missing → skip column

Parameters:

Name Type Description Default
df DF

Input DataFrame.

required
watermark_columns List[str]

Column names to compare.

required
watermark_start Dict[str, Any]

{column: threshold_value} lower-bound mapping.

required
start_operator str

Comparison operator for lower bound, ">" (exclusive, default) or ">=" (inclusive, replay).

'>'
watermark_end Optional[Dict[str, Any]]

Optional upper-bound mapping. When provided, builds a [lower, upper) window per column.

None
end_operator str

Comparison operator for upper bound, "<" (exclusive, default) or "<=" (inclusive).

'<'

Returns:

Type Description
DF

Filtered DataFrame.

cast_column abstractmethod

cast_column(
    df: DF,
    column_name: str,
    target_type: str,
    fmt: Optional[str] = None,
    *,
    type_system: Optional[str] = None,
    precision: Optional[int] = None,
    scale: Optional[int] = None,
) -> DF

Cast a column using an authored source datatype declaration.

target_type is retained as the positional parameter name for the public engine contract, but it is interpreted as the source declaration by the concrete adapter. The adapter resolves it once using type_system and then constructs its native datatype.

cleanup

cleanup(
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    retention_hours: int = 168,
    fmt: str = "delta",
    options: Optional[Dict[str, Any]] = None,
) -> None

Run cleanup on a table name (preferred) or a path.

Parameters:

Name Type Description Default
table_name Optional[str]

Fully qualified table name. Takes precedence over path.

None
path Optional[str]

Table file path (used when table_name is not given).

None
retention_hours int

Minimum age in hours of files to retain.

168
fmt str

Table format ("delta" or "iceberg").

'delta'
options Optional[Dict[str, Any]]

Format-specific options for cleanup sub-operations.

None

Raises:

Type Description
EngineError

If neither table_name nor path is provided.

cleanup_by_name abstractmethod

cleanup_by_name(
    table_name: str,
    retention_hours: int = 168,
    *,
    fmt: str = "delta",
    options: Optional[Dict[str, Any]] = None,
) -> None

Run cleanup (VACUUM or equivalent) on a named table.

cleanup_by_path abstractmethod

cleanup_by_path(
    path: str,
    retention_hours: int = 168,
    *,
    fmt: str = "delta",
    options: Optional[Dict[str, Any]] = None,
) -> None

Run cleanup (VACUUM or equivalent) on the table at path.

compact

compact(
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    fmt: str = "delta",
    options: Optional[Dict[str, Any]] = None,
) -> None

Run compaction on a table name (preferred) or a path.

Parameters:

Name Type Description Default
table_name Optional[str]

Fully qualified table name. Takes precedence over path.

None
path Optional[str]

Table file path (used when table_name is not given).

None
fmt str

Table format ("delta" or "iceberg").

'delta'
options Optional[Dict[str, Any]]

Format-specific options for compaction sub-operations.

None

Raises:

Type Description
EngineError

If neither table_name nor path is provided.

compact_by_name abstractmethod

compact_by_name(
    table_name: str,
    *,
    fmt: str = "delta",
    options: Optional[Dict[str, Any]] = None,
) -> None

Run compaction (OPTIMIZE or equivalent) on a named table.

compact_by_path abstractmethod

compact_by_path(
    path: str,
    *,
    fmt: str = "delta",
    options: Optional[Dict[str, Any]] = None,
) -> None

Run compaction (OPTIMIZE or equivalent) on the table at path.

convert_timestamp_ntz_to_timestamp abstractmethod

convert_timestamp_ntz_to_timestamp(
    df: DF, timezone: Optional[str] = None
) -> DF

Convert NTZ columns to UTC using an explicit source timezone.

Implementations must raise when an NTZ column is present but timezone is missing. A wall-clock value must never be silently treated as UTC.

count_rows abstractmethod

count_rows(df: DF) -> int

Return the number of rows in df.

create_dataframe abstractmethod

create_dataframe(records: List[Dict[str, Any]]) -> DF

Create a DataFrame from a list of dicts.

Records may have different keys (heterogeneous schema). Missing fields are filled with null so that the resulting DataFrame has the union of all keys as its columns.

Parameters:

Name Type Description Default
records List[Dict[str, Any]]

List of flat dicts. Values may be None.

required

Returns:

Type Description
DF

A DataFrame with one row per record and one column per

DF

distinct key across all records.

deduplicate abstractmethod

deduplicate(
    df: DF,
    partition_columns: List[str],
    order_columns: Optional[List[str]] = None,
    order: str = "desc",
) -> DF

Remove duplicate rows.

Uses ROW_NUMBER() window partitioned by partition_columns and ordered by order_columns.

deduplicate_by_rank abstractmethod

deduplicate_by_rank(
    df: DF,
    partition_columns: List[str],
    order_columns: List[str],
    order: str = "desc",
) -> DF

Deduplicate using RANK(), keeping ties.

delete_by_window

delete_by_window(
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    window: WindowSpec,
    fmt: str = "delta",
) -> None

Delete all rows within the given column value window.

Used by replace_by_watermark to remove the target scope before re-inserting fresh source data.

Parameters:

Name Type Description Default
table_name Optional[str]

Target table name. Takes precedence over path.

None
path Optional[str]

Target file path (used when table_name is not given).

None
window WindowSpec

Explicit immutable :class:WindowSpec.

required
fmt str

Table / file format.

'delta'

Raises:

Type Description
EngineError

If neither table_name nor path is provided.

delete_by_window_path abstractmethod

delete_by_window_path(
    path: str, window: WindowSpec, fmt: str = "delta"
) -> None

Delete rows in a path-based table within the value window.

delete_by_window_table abstractmethod

delete_by_window_table(
    table_name: str, window: WindowSpec, fmt: str = "delta"
) -> None

Delete rows in a named table within the value window.

drop_columns abstractmethod

drop_columns(df: DF, columns: List[str]) -> DF

Drop one or more columns from a DataFrame.

execute_maintenance_action

execute_maintenance_action(
    prepared, *, action: str, retention_hours: int = 168
)

Explicit native selection requires an engine implementation.

execute_sql abstractmethod

execute_sql(
    sql: str, parameters: Optional[Dict[Any, Any]] = None
) -> DF

Execute a SQL query and return a DataFrame.

exists

exists(
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    fmt: str = "delta",
) -> bool

Return True if the target table or path exists.

Checks by table name first (via :meth:table_exists_by_name), then by path (via :meth:table_exists_by_path). Returns False if neither is provided.

Parameters:

Name Type Description Default
table_name Optional[str]

Fully qualified table name.

None
path Optional[str]

Table file path.

None

file_extensions

file_extensions(fmt: str) -> tuple[str, ...]

Suffixes for framework discovery; subclass overrides are authoritative.

filter_rows abstractmethod

filter_rows(df: DF, condition: str) -> DF

Filter rows using a SQL expression.

generate_symlink_manifest(path: str) -> None

Generate a symlink-format manifest for the Delta table at path.

Creates the _symlink_format_manifest/ directory alongside the Delta log, enabling query engines that don't natively support Delta (e.g. Redshift Spectrum) to read the table via SymlinkTextInputFormat.

Parameters:

Name Type Description Default
path str

Root path of the Delta table.

required

get_columns abstractmethod

get_columns(df: DF) -> List[str]

Return the column names of df.

get_count_and_max_values abstractmethod

get_count_and_max_values(
    df: DF, columns: List[str]
) -> Tuple[int, Dict[str, Any]]

Return (row_count, {column: max_value}) in one pass.

get_history

get_history(
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    limit: int = 1,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    fmt: str = "delta",
) -> List[Dict[str, Any]]

Return audit history for a table name (preferred) or a path.

Parameters:

Name Type Description Default
table_name Optional[str]

Fully qualified table name. Takes precedence over path.

None
path Optional[str]

Table file path (used when table_name is not given).

None
limit int

Maximum number of history entries to return.

1
start_time Optional[datetime]

If provided, only return entries whose timestamp is

= start_time.

None
end_time Optional[datetime]

If provided, only return entries whose timestamp is <= end_time.

None
fmt str

Table format ("delta" or "iceberg").

'delta'

Raises:

Type Description
EngineError

If neither table_name nor path is provided.

get_history_by_name abstractmethod

get_history_by_name(
    table_name: str,
    limit: int = 1,
    start_time: Optional[datetime] = None,
    *,
    end_time: Optional[datetime] = None,
    fmt: str = "delta",
) -> List[Dict[str, Any]]

Return audit history entries for a named table.

Parameters:

Name Type Description Default
table_name str

Fully qualified table name.

required
limit int

Maximum number of history entries to return.

1
start_time Optional[datetime]

If provided, only return entries whose timestamp / made_current_at is >= start_time.

None
end_time Optional[datetime]

If provided, only return entries whose timestamp / made_current_at is <= end_time.

None
fmt str

Table format ("delta" or "iceberg").

'delta'

get_history_by_path abstractmethod

get_history_by_path(
    path: str,
    limit: int = 1,
    start_time: Optional[datetime] = None,
    *,
    end_time: Optional[datetime] = None,
    fmt: str = "delta",
) -> List[Dict[str, Any]]

Return audit history entries for the table at path.

Parameters:

Name Type Description Default
path str

Table location.

required
limit int

Maximum number of history entries to return.

1
start_time Optional[datetime]

If provided, only return entries whose timestamp is >= start_time.

None
end_time Optional[datetime]

If provided, only return entries whose timestamp is <= end_time.

None
fmt str

Table format ("delta" or "iceberg").

'delta'

get_hive_schema abstractmethod

get_hive_schema(df: DF) -> Dict[str, str]

Return {column_name: hive_type_string} using native type objects.

Each engine inspects its native DataFrame schema (e.g. pyspark.sql.types, polars.datatypes) to produce Hive/Athena-compatible DDL type strings directly — no string parsing required.

get_max_values abstractmethod

get_max_values(
    df: DF, columns: List[str]
) -> Dict[str, Any]

Return the maximum value for each of columns.

get_schema abstractmethod

get_schema(df: DF) -> Dict[str, str]

Return {column_name: data_type_string}.

is_empty abstractmethod

is_empty(df: DF) -> bool

Return True if the DataFrame has zero rows.

list_format_files

list_format_files(
    path: str, fmt: str, *, recursive: bool = False
) -> list[FileInfo]

Discover one directory, or honor an explicit JSON file with its metadata.

maintenance_preparation

maintenance_preparation()

Return an operation-scoped preparation callable with no shared cache.

merge

merge(
    df: DF,
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
) -> None

Merge (upsert) df into a table name (preferred) or a path.

Parameters:

Name Type Description Default
df DF

Source DataFrame.

required
table_name Optional[str]

Target table name. Takes precedence over path.

None
path Optional[str]

Target file path (used when table_name is not given).

None
merge_keys List[str]

Join columns for the merge condition.

required
fmt str

Table / file format.

'delta'
partition_columns Optional[List[str]]

Optional partition column names.

None
options Optional[Dict[str, str]]

Additional options.

None

Raises:

Type Description
EngineError

If neither table_name nor path is provided.

merge_overwrite

merge_overwrite(
    df: DF,
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
    write_options: Optional[Dict[str, str]] = None,
) -> None

Merge-overwrite (delete + append) into a table name (preferred) or a path.

Parameters:

Name Type Description Default
df DF

Source DataFrame.

required
table_name Optional[str]

Target table name. Takes precedence over path.

None
path Optional[str]

Target file path (used when table_name is not given).

None
merge_keys List[str]

Join columns for the delete condition.

required
fmt str

Table / file format.

'delta'
partition_columns Optional[List[str]]

Optional partition column names.

None
options Optional[Dict[str, str]]

Additional options.

None

Raises:

Type Description
EngineError

If neither table_name nor path is provided.

merge_overwrite_to_path abstractmethod

merge_overwrite_to_path(
    df: DF,
    path: str,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
    write_options: Optional[Dict[str, str]] = None,
) -> None

Merge with full-row overwrite (rolling overwrite / SCD1-style).

Existing rows matching merge keys are deleted and re-inserted from the source DataFrame.

merge_overwrite_to_table abstractmethod

merge_overwrite_to_table(
    df: DF,
    table_name: str,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
    write_options: Optional[Dict[str, str]] = None,
) -> None

Merge-overwrite (delete + append) a named table via SQL MERGE + WriterV2.

Parameters:

Name Type Description Default
df DF

Source DataFrame.

required
table_name str

Fully qualified target table name.

required
merge_keys List[str]

Join columns for the delete condition.

required
fmt str

Table format.

'delta'
partition_columns Optional[List[str]]

Optional partition column names.

None
options Optional[Dict[str, str]]

Additional options.

None

merge_to_path abstractmethod

merge_to_path(
    df: DF,
    path: str,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
) -> None

Merge (upsert) a DataFrame into a table at path.

merge_to_table abstractmethod

merge_to_table(
    df: DF,
    table_name: str,
    merge_keys: List[str],
    fmt: str,
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
) -> None

Merge (upsert) a DataFrame into a named table via SQL MERGE.

Parameters:

Name Type Description Default
df DF

Source DataFrame.

required
table_name str

Fully qualified target table name.

required
merge_keys List[str]

Join columns for the merge condition.

required
fmt str

Table format.

required
partition_columns Optional[List[str]]

Optional partition column names.

None
options Optional[Dict[str, str]]

Additional options.

None

preferred_target_addressing

preferred_target_addressing(
    *,
    fmt: str,
    table_name: Optional[str],
    path: Optional[str],
) -> Optional[Literal["table", "path"]]

Pure target preference matching this engine's table-first dispatch.

prepare_maintenance_target

prepare_maintenance_target(
    *,
    fmt: str,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
)

Prepare a legacy qualified address; native adapters override binding.

This concrete hook adds no requirements to existing engine subclasses. Destination policy has already selected the operative address.

read

read(
    fmt: str,
    *,
    table_name: Optional[str] = None,
    path: Optional[str | list[str]] = None,
    options: Optional[Dict[str, str]] = None,
) -> DF

Read data by table name (preferred) or by path.

Parameters:

Name Type Description Default
fmt str

Format string — "delta", "parquet", "csv", or "json".

required
table_name Optional[str]

Fully qualified table name. Takes precedence over path.

None
path Optional[str | list[str]]

File or directory path (used when table_name is not given).

None
options Optional[Dict[str, str]]

Additional reader options.

None

Raises:

Type Description
EngineError

If neither table_name nor path is provided, or if the format has no path reader.

read_avro abstractmethod

read_avro(
    path: str | list[str],
    options: Optional[Dict[str, str]] = None,
) -> DF

Read Avro file(s) into a DataFrame.

read_csv abstractmethod

read_csv(
    path: str | list[str],
    options: Optional[Dict[str, str]] = None,
) -> DF

Read CSV file(s) into a DataFrame.

read_database abstractmethod

read_database(
    *,
    table: Optional[str] = None,
    query: Optional[str] = None,
    options: Optional[Dict[str, Any]] = None,
) -> DF

Read from an external database.

Exactly one of table or query must be provided.

Parameters:

Name Type Description Default
table Optional[str]

Plain table or view name (e.g. "schema.orders").

None
query Optional[str]

Full SQL query (e.g. "SELECT * FROM orders WHERE id > 100").

None
options Optional[Dict[str, Any]]

All connection and reader settings in one flat dict. Must include at minimum url and driver. May also carry JDBC tuning keys such as fetchsize, numPartitions, partitionColumn, etc.

None

In Spark this maps to spark.read.format("jdbc").option(...).load(). Use this for reading from external databases. For running queries in the engine's own SQL context, use :meth:execute_sql.

read_delta abstractmethod

read_delta(
    path: str, options: Optional[Dict[str, str]] = None
) -> DF

Read a Delta Lake table into a DataFrame.

read_excel abstractmethod

read_excel(
    path: str | list[str],
    options: Optional[Dict[str, str]] = None,
) -> DF

Read Excel file(s) into a DataFrame.

read_iceberg abstractmethod

read_iceberg(
    path: str, options: Optional[Dict[str, str]] = None
) -> DF

Read an Iceberg table into a DataFrame.

read_json abstractmethod

read_json(
    path: str | list[str],
    options: Optional[Dict[str, str]] = None,
) -> DF

Read JSON file(s) into a DataFrame.

read_jsonl abstractmethod

read_jsonl(
    path: str | list[str],
    options: Optional[Dict[str, str]] = None,
) -> DF

Read JSONL (newline-delimited JSON) file(s) into a DataFrame.

read_parquet abstractmethod

read_parquet(
    path: str | list[str],
    options: Optional[Dict[str, str]] = None,
) -> DF

Read Parquet file(s) into a DataFrame.

read_path abstractmethod

read_path(
    path: str | list[str],
    fmt: str,
    options: Optional[Dict[str, str]] = None,
) -> DF

Read a file or directory at path using the given format.

This is the unified path-based reader. Implementations should dispatch to the appropriate format reader (read_delta, read_parquet, etc.) based on fmt.

Parameters:

Name Type Description Default
path str | list[str]

File or directory path (scalar or list for multi-path reads).

required
fmt str

Format string — "delta", "iceberg", "parquet", "csv", or "json".

required
options Optional[Dict[str, str]]

Additional reader options.

None

Raises:

Type Description
EngineError

If the format is not supported.

read_table abstractmethod

read_table(
    table_name: str,
    fmt: str = "delta",
    options: Optional[Dict[str, str]] = None,
) -> DF

Read a named table and return a DataFrame.

Parameters:

Name Type Description Default
table_name str

Fully qualified table name (e.g. "`catalog`.`db`.`schema`.`table`").

required
fmt str

Table format ("delta", "iceberg", etc.).

'delta'
options Optional[Dict[str, str]]

Additional read options.

None

release_maintenance_target

release_maintenance_target(prepared) -> None

Default binding owns no session or catalog resources.

remove_system_columns

remove_system_columns(df: DF) -> DF

Drop system columns (__created_at, etc.).

This is a concrete convenience method that delegates to :meth:drop_columns.

rename_column abstractmethod

rename_column(df: DF, old_name: str, new_name: str) -> DF

Rename a column.

rename_columns

rename_columns(df: DF, mapping: Dict[str, str]) -> DF

Rename multiple columns.

Engines can override this compatibility fallback with a native batch operation. Keeping the default concrete avoids breaking third-party engines that only implement :meth:rename_column.

replace_window

replace_window(
    df: DF,
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    window: WindowSpec,
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
) -> None

Replace rows in a bounded window with df.

This is the engine-owned replacement boundary. Backends may override it with a native transaction or merge implementation. The default keeps the accepted portable behavior (delete then append) inside the engine rather than exposing two mutating calls to load strategies. The operation is intentionally not advertised as atomic.

resolve_column_name staticmethod

resolve_column_name(
    actual_columns: List[str], column: str
) -> str

Return the actual column name matching column case-insensitively.

If column already matches an element of actual_columns exactly it is returned as-is (fast path). Otherwise a case-insensitive scan is performed using lower() against actual_columns, selecting the first match in supplied order when several spellings match.

Parameters:

Name Type Description Default
actual_columns List[str]

Column names present in the DataFrame schema.

required
column str

User-supplied column name (potentially wrong case).

required

Returns:

Type Description
str

The exact column name from actual_columns.

Raises:

Type Description
EngineError

If no case-insensitive match is found.

resolve_column_names staticmethod

resolve_column_names(
    actual_columns: List[str], columns: List[str]
) -> List[str]

Resolve a list of column names case-insensitively.

Delegates to the concrete :meth:BaseEngine.resolve_column_name for each entry, preserving requested order and duplicates. Subclass overrides of the singular helper do not change this static default dispatch.

Parameters:

Name Type Description Default
actual_columns List[str]

Column names present in the DataFrame schema.

required
columns List[str]

User-supplied column names.

required

Returns:

Type Description
List[str]

List of exact column names from actual_columns.

Raises:

Type Description
EngineError

If any column is not found.

scd2

scd2(
    df: DF,
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
    write_options: Optional[Dict[str, str]] = None,
) -> None

SCD Type 2 write to a table name (preferred) or a path.

scd2_to_path

scd2_to_path(
    df: DF,
    path: str,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
    write_options: Optional[Dict[str, str]] = None,
) -> None

SCD Type 2 write to a path-based table.

Tracks historical changes by closing existing current records (setting scd2_end_date, scd2_is_current = false) and inserting new versions with scd2_start_date, scd2_is_current = true.

scd2_to_table

scd2_to_table(
    df: DF,
    table_name: str,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
    write_options: Optional[Dict[str, str]] = None,
) -> None

SCD Type 2 write to a named table.

select_columns abstractmethod

select_columns(df: DF, columns: List[str]) -> DF

Return df with only the given columns, in the specified order.

set_platform

set_platform(platform: BasePlatform) -> None

Attach a platform once; replacement would split execution state.

table_exists_by_name abstractmethod

table_exists_by_name(
    table_name: str, *, fmt: str = "delta"
) -> bool

Return True if a named table exists in the catalog.

table_exists_by_path abstractmethod

table_exists_by_path(
    path: str, *, fmt: str = "delta"
) -> bool

Return True if a table exists at path.

target_name_identity

target_name_identity(
    *, fmt: str, table_name: str
) -> Optional[Tuple[str, str]]

Return qualified (backend scope, native name), or None if unknown.

This concrete extension hook adds no abstract requirement to plugins. Implementations may inspect borrowed loaded resources, never load them.

write

write(
    df: DF,
    *,
    table_name: Optional[str] = None,
    path: Optional[str] = None,
    mode: str,
    fmt: str,
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
) -> None

Write df to a table name (preferred) or to a path.

Parameters:

Name Type Description Default
df DF

DataFrame to write.

required
table_name Optional[str]

Target table name. Takes precedence over path.

None
path Optional[str]

Target file path (used when table_name is not given).

None
mode str

Write mode ("overwrite", "append", …).

required
fmt str

Table / file format.

required
partition_columns Optional[List[str]]

Optional partition column names.

None
options Optional[Dict[str, str]]

Additional writer options.

None

Raises:

Type Description
EngineError

If neither table_name nor path is provided.

write_to_path abstractmethod

write_to_path(
    df: DF,
    path: str,
    mode: str,
    fmt: str,
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
) -> None

Write a DataFrame to a path.

write_to_table abstractmethod

write_to_table(
    df: DF,
    table_name: str,
    mode: str,
    fmt: str,
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
) -> None

Write a DataFrame to a named table using DataFrameWriterV2.

Parameters:

Name Type Description Default
df DF

DataFrame to write.

required
table_name str

Fully qualified table name (e.g. catalog.db.schema.table).

required
mode str

Write mode — LoadType.OVERWRITE ("overwrite"), LoadType.APPEND ("append"), or LoadType.FULL_LOAD ("full_load").

required
fmt str

Table format ("delta", "iceberg").

required
partition_columns Optional[List[str]]

Optional partition column names.

None
options Optional[Dict[str, str]]

Additional writer options.

None

Destination addressing hooks

BaseEngine.preferred_target_addressing(fmt=..., table_name=..., path=...) returns "table", "path", or None when no handle is usable. Its concrete default matches table-first dispatch. Polars selects paths for Delta/files and names for Iceberg. Destination forced-path policy takes precedence.

target_name_identity(fmt=..., table_name=...) returns a qualified (backend_scope, canonical_native_name) or None. The default is unqualified. Subclasses need no new abstract method; plugins with different addressing must override preference, and named maintenance requires a qualified identity hook. Hooks may inspect attached loaded resources but must not create sessions, load catalogs, or query storage. Direct engine method signatures stay unchanged.

Maintenance preparation hooks

maintenance_preparation() returns an operation-scoped callable with fmt, table_name, path and optional table_address keyword arguments. The structured MaintenanceTableAddress keeps catalog separate from namespace/name; REST adapters reject unsupported catalogs before lookup. The default wrapper passes only the original fmt, table_name and path kwargs to legacy hooks. It returns a PreparedMaintenanceTarget carrying the selected identity, missing state, capabilities and optional borrowed native binding. The concrete default delegates to prepare_maintenance_target() and preserves existing local/plugin addressing. REST adapters qualify deployment routing and load native UUID metadata here; the destination resolver remains pure.

execute_maintenance_action(prepared, action=..., retention_hours=168) executes an explicitly supported action, and maintenance_history(prepared, ...) observes the same prepared incarnation. release_maintenance_target(prepared) is a concrete no-op for borrowed resources. Plugins need no new abstract method. The existing default writer and _maintain_internal signatures remain valid; nonempty action maps require the concrete selected-maintenance extension. Empty mappings and omitted mappings both retain default action intent.

Both built-in engines accept keyword-only maintenance_deployment for the bounded REST profile. Spark additionally accepts maintenance_guard_manifest. See maintenance setup and supported selections.

Column resolution helpers

BaseEngine.resolve_column_name(actual_columns, column) and resolve_column_names(actual_columns, columns) are concrete public helpers. Exact spelling wins, followed by the first lower() match in schema order; missing names raise EngineError. The plural helper preserves order and duplicates and uses the BaseEngine default singular implementation.

Neutral execution windows

WindowSpec is the engine-neutral replacement-window contract. Bounds are combined with OR across columns and with AND within a column; the lower and upper operators are explicit. Engine operations accept this value rather than an untyped mapping.

windows

Pure contracts for resolving physical engine targets.

Destination writers and orchestration must agree on the same primary handle. This module contains no engine instance, platform I/O, catalog client, or run configuration; it only projects a destination model into the addressing information an engine operation will receive.

WindowSpec dataclass

WindowSpec(
    bounds: Mapping[str, tuple[Any, Any]],
    lower_operator: Literal[">", ">="] = ">",
    upper_operator: Literal["<", "<="] = "<=",
    combine_operator: Literal["OR"] = "OR",
)

Execution-only watermark bounds passed to engine replacement calls.

Bounds are combined with OR across columns and with AND within a column. The operators are explicit so rolling and replay semantics do not depend on a hidden engine default.

items

items()

Expose mapping-style iteration for engine adapters.

normalize_window

normalize_window(window: WindowSpec) -> WindowSpec

Validate an explicit execution window.

Window mappings are deliberately not accepted at the engine boundary. A mapping has no way to express replay operators and made equality silently ignore execution semantics.

spark_engine

PySpark engine facade backed by private Spark capability modules.

SparkEngine

SparkEngine(
    spark_session: Optional[SparkSession] = None,
    config: Optional[Dict[str, str]] = None,
    platform: Optional[BasePlatform] = None,
    *,
    maintenance_deployment: Optional[Any] = None,
    maintenance_guard_manifest: Optional[Any] = None,
)

Bases: BaseEngine[DataFrame]

PySpark implementation of :class:BaseEngine.

Parameters:

Name Type Description Default
spark_session Optional[SparkSession]

Existing session for managed or notebook runtimes. A configured session is created when omitted.

None
config Optional[Dict[str, str]]

Explicit Spark configuration overrides. They are applied to a supplied session; framework defaults are applied only when DataCoolie creates the session.

None
platform Optional[BasePlatform]

Optional platform attached to this engine.

None
maintenance_deployment Optional[Any]

Optional operator-attested REST deployment record for qualified REST Iceberg maintenance.

None
maintenance_guard_manifest Optional[Any]

Optional manifest for the prebuilt native helper used by Spark REST Iceberg maintenance. It is required with maintenance_deployment for that profile.

None

Implementation details are delegated to the private _spark capability modules; this class remains the stable public facade and runtime-state owner.

spark property

spark: SparkSession

Return the underlying SparkSession.

spark_major_version property

spark_major_version: int

Return the active Spark runtime's major version.

target_name_identity

target_name_identity(
    *, fmt: str, table_name: str
) -> Optional[Tuple[str, str]]

Pure projection of qualified, already-loaded native catalog state.

polars_engine

Polars + Delta Lake + Iceberg engine implementation.

:class:PolarsEngine binds :class:BaseEngine to polars.LazyFrame and implements every abstract method using the Polars LazyFrame API, the deltalake library, and optional pyiceberg integration.

Reads return lazy frames via scan_* APIs; materialisation (.collect()) happens only at write / merge / metrics boundaries.

Catalog support
  • Iceberg Catalog via iceberg_catalog (a pyiceberg.catalog.Catalog instance).
  • SQLContext for executing SQL queries against registered tables.

PolarsEngine

PolarsEngine(
    platform: Optional[BasePlatform] = None,
    storage_options: Optional[Dict[str, str]] = None,
    *,
    iceberg_catalog: Optional[Any] = None,
    sql_context: Optional[SQLContext] = None,
    sql_dialect: Optional[str] = None,
    maintenance_deployment: Optional[Any] = None,
)

Bases: BaseEngine['pl.LazyFrame']

Polars implementation of :class:BaseEngine bound to pl.LazyFrame.

All reads return lazy frames via scan_* APIs. Materialisation (.collect()) happens only at write boundaries, merge operations, and metric computations.

Parameters:

Name Type Description Default
storage_options Optional[Dict[str, str]]

Cloud storage credentials forwarded to Polars readers and deltalake operations.

None
iceberg_catalog Optional[Any]

A pyiceberg.catalog.Catalog instance for Iceberg table discovery and management.

None
sql_context Optional[SQLContext]

An existing polars.SQLContext to reuse. A new context is created when None (the default).

None
sql_dialect Optional[str]

Optional SQL dialect passed to the Polars SQL resolver.

None
maintenance_deployment Optional[Any]

Optional operator-attested REST deployment record for qualified REST Iceberg maintenance.

None
platform Optional[BasePlatform]

Optional platform to attach to this engine immediately.

None

delta property

delta: type

Lazily imported DeltaTable class from the deltalake package.

last_registration_report property

last_registration_report: RegistrationReport

Return the observable result of the latest discovery call.

sql_context property

sql_context: SQLContext

Return the engine's :class:polars.SQLContext.

add_file_info_columns

add_file_info_columns(
    df: LazyFrame,
    file_infos: Optional[List[FileInfo]] = None,
) -> LazyFrame

Map file metadata onto rows using the embedded __file_path column.

The scan readers (read_parquet, read_csv, read_json) embed the source path via include_file_paths / manual injection, so __file_path is already present in df.

When file_infos is provided a small mapping LazyFrame is joined on __file_path to resolve __file_name and __file_modification_time. When file_infos is None the name is derived from the path and modification-time is set to null.

add_hash_column

add_hash_column(
    df: LazyFrame, definition: HashColumn
) -> LazyFrame

Add a stable hash over DataCoolie's canonical scalar payload.

create_dataframe

create_dataframe(
    records: List[Dict[str, Any]],
) -> LazyFrame

Create a Polars LazyFrame from a list of heterogeneous dicts.

pl.from_dicts with infer_schema_length=None scans all records to compute the union schema and fills missing fields with null.

delete_by_window_path

delete_by_window_path(
    path: str, window: WindowSpec, fmt: str = "delta"
) -> None

Delete rows in a Delta path where columns fall within the window bounds.

delete_by_window_table

delete_by_window_table(
    table_name: str, window: WindowSpec, fmt: str = "delta"
) -> None

Delete rows in a named table within the value window.

execute_sql

execute_sql(
    sql: str, parameters: Optional[Dict[Any, Any]] = None
) -> LazyFrame

Execute a SQL query against the engine's :class:polars.SQLContext.

Register tables first via :meth:register_table, :meth:register_delta_tables, or :meth:register_iceberg_tables.

generate_symlink_manifest(path: str) -> None

Generate a symlink manifest using delta-rs DeltaTable.generate().

get_hive_schema

get_hive_schema(df: LazyFrame) -> Dict[str, str]

Return {column_name: hive_type} using native Polars dtype objects.

merge_overwrite_to_path

merge_overwrite_to_path(
    df: LazyFrame,
    path: str,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
    write_options: Optional[Dict[str, str]] = None,
) -> None

Rolling overwrite via MERGE DELETE + APPEND (mirrors SparkEngine).

preferred_target_addressing

preferred_target_addressing(
    *,
    fmt: str,
    table_name: Optional[str],
    path: Optional[str],
) -> Optional[Literal["table", "path"]]

Match native Delta/file path routing and Iceberg catalog routing.

read_iceberg

read_iceberg(
    path: str, options: Optional[Dict[str, str]] = None
) -> LazyFrame

Read an Iceberg table directly from path.

For catalog-based lookup by table name use :meth:read_table with fmt="iceberg" and an iceberg_catalog configured.

register_delta_tables

register_delta_tables(
    base_path: str,
    *,
    logical_prefix: NameInput | None = (),
    recursive: bool = False,
    max_depth: Optional[int] = None,
    include: PatternInput = None,
    exclude: PatternInput = None,
    max_tables: Optional[int] = None,
    preload: bool = False,
    on_error: Literal["raise", "skip"] = "raise",
) -> List[str]

Index Delta tables below base_path for lazy SQL registration.

Relative table-directory components are appended to logical_prefix. Unique trailing suffixes of the resulting 1-4 part name can be used in :meth:execute_sql. With the default preload=False, table scans are created only when a query first references them.

Parameters:

Name Type Description Default
base_path str

Physical folder root to enumerate.

required
logical_prefix NameInput | None

Structured SQL components prepended to relative paths.

()
recursive bool

Descend into non-table directories.

False
max_depth Optional[int]

Optional traversal depth relative to base_path.

None
include PatternInput

Component glob or globs selecting logical names.

None
exclude PatternInput

Component glob or globs removed after include matching.

None
max_tables Optional[int]

Safety ceiling; exceeding it aborts without indexing.

None
preload bool

Create and bind every discovered frame immediately.

False
on_error Literal['raise', 'skip']

"raise" or observable best-effort "skip".

'raise'

register_iceberg_tables

register_iceberg_tables(
    namespace: NameInput | None = None,
    base_path: Optional[str] = None,
    *,
    logical_prefix: NameInput | None = None,
    recursive: bool = False,
    max_depth: Optional[int] = None,
    include: PatternInput = None,
    exclude: PatternInput = None,
    max_tables: Optional[int] = None,
    preload: bool = False,
    on_error: Literal["raise", "skip"] = "raise",
) -> List[str]

Index Iceberg catalog identifiers or table paths for lazy SQL use.

Catalog mode is used when base_path is absent and an Iceberg catalog is attached. namespace=None starts at the catalog root. A supplied logical_prefix replaces the catalog/root-namespace mapping; relative child namespaces and the table name are appended.

Parameters:

Name Type Description Default
namespace NameInput | None

Physical Iceberg namespace root in catalog mode.

None
base_path Optional[str]

Compatibility path-discovery root; mutually exclusive with namespace.

None
logical_prefix NameInput | None

Replacement logical root, or None to preserve catalog name and root namespace.

None
recursive bool

Enumerate child namespaces/directories.

False
max_depth Optional[int]

Optional traversal depth relative to the source root.

None
include PatternInput

Component glob or globs selecting logical names.

None
exclude PatternInput

Component glob or globs removed after include matching.

None
max_tables Optional[int]

Safety ceiling; exceeding it aborts without indexing.

None
preload bool

Load metadata and bind all discovered frames immediately.

False
on_error Literal['raise', 'skip']

"raise" or observable best-effort "skip".

'raise'

register_table

register_table(
    name: str, data: Union["pl.LazyFrame", "pl.DataFrame"]
) -> None

Register a frame as a named table in the SQLContext.

registered_tables

registered_tables() -> List[str]

Return sorted logical names indexed by discovery registration.

scd2_to_path

scd2_to_path(
    df: LazyFrame,
    path: str,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
    write_options: Optional[Dict[str, str]] = None,
) -> None

SCD2 via two-step MERGE + APPEND on a Delta table.

MERGE to close current rows (set __valid_to,

__is_current = false) where source is strictly newer.

Step 2: APPEND all source rows as new versions.

This avoids the staged-UNION pattern (2× data duplication) by splitting close and insert into separate operations — same approach as :meth:merge_overwrite_to_path.

scd2_to_table

scd2_to_table(
    df: LazyFrame,
    table_name: str,
    merge_keys: List[str],
    fmt: str = "delta",
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
    write_options: Optional[Dict[str, str]] = None,
) -> None

SCD2 for named tables (Iceberg two-step, non-atomic).

  1. Upsert to close current matched rows (__valid_to, __is_current = false).
  2. Append all source rows as new versions.

set_iceberg_catalog

set_iceberg_catalog(catalog: Any) -> None

Replace the Iceberg catalog used for Iceberg table operations.

target_name_identity

target_name_identity(
    *, fmt: str, table_name: str
) -> Optional[Tuple[str, str]]

Qualify only the attached local PyIceberg SQLite file catalog.

write_to_path

write_to_path(
    df: LazyFrame,
    path: str,
    mode: str,
    fmt: str,
    partition_columns: Optional[List[str]] = None,
    options: Optional[Dict[str, str]] = None,
) -> None

Write a LazyFrame to path (always treated as a folder).

Behaviour by format:

  • Delta — uses sink_delta (streaming); partition_columns forwarded via delta_write_options.
  • Parquet / CSV / JSONL — uses streaming sink_*. When partition_columns are provided the target is a :class:polars.PartitionBy so data is split by those columns.
  • JSON / Avro — no sink_ available; falls back to eager write_* to a single file (partition_columns not supported).

Iceberg writes use catalog-backed write_to_table; a generic path-based Iceberg write is not implemented by this engine.

Write modes:

  • overwrite / full_load — existing files in the folder are removed before writing. File name: {folder_name}.{ext}.
  • append — a new file is added. File name includes a timestamp: {folder_name}_{yyyyMMdd_HHmmss}.{ext}.

Datatype interpretation

data_types

Pure source-datatype interpretation shared by engine adapters.

This package has no optional dataframe imports, sessions, connectors, or I/O. It turns an authored source declaration into an immutable logical description; Spark and Polars adapters consume that description using native APIs.

TypeSystem

Bases: str, Enum

Named source conventions understood by the resolver.

LogicalKind

Bases: str, Enum

Portable logical categories used by engine adapters.

TimestampKind

Bases: str, Enum

Whether a timestamp represents an instant or a wall-clock value.

ResolvedDataType dataclass

ResolvedDataType(
    kind: LogicalKind,
    source_type: str,
    source_type_system: str,
    bit_width: int | None = None,
    precision: int | None = None,
    scale: int | None = None,
    timestamp_kind: TimestampKind | None = None,
)

Resolved logical type plus source provenance.

source_type and source_type_system are retained for diagnostics. Native adapters decide how this logical description is represented; no engine-specific target string is part of this contract.

unsigned property

unsigned: bool

Whether this logical kind represents an unsigned integer.

infer_type_system

infer_type_system(
    database_type: str | None = None,
    explicit_type_system: str | TypeSystem | None = None,
) -> str

Choose the authored hint dialect from explicit source metadata.

The execution engine is intentionally not an input. A lakehouse/file, API, function, or database without a declared vendor has no reliable dialect signal, so Spark SQL is the documented neutral convention.

normalize_type_system

normalize_type_system(
    value: str | TypeSystem | None,
) -> str

Normalize a documented dialect name or fail explicitly.

resolve_schema_hint

resolve_schema_hint(
    data_type: str,
    *,
    type_system: str | TypeSystem | None = None,
    precision: int | None = None,
    scale: int | None = None,
) -> ResolvedDataType

Resolve one authored datatype string to the shared logical contract.

The resolver is dependency-free and only describes source datatype semantics. Native engines construct their own Spark or Polars datatype objects from the resolved description; metadata models and readers do not import it.

Datatype model migration

ResolvedDataType now derives signedness from kind. Its unsigned property remains available for reads, but unsigned= and the unused length= constructor arguments are no longer accepted. Resolve a source declaration with resolve_schema_hint(...) or construct the model with its declared logical fields instead of maintaining a second signedness flag.

Polars SQL registration contract

register_delta_tables and register_iceberg_tables return sorted logical names immediately, but with the default preload=False they only index source descriptors. execute_sql resolves and binds referenced tables once per engine lifetime. Inspect registered_tables() for indexed logical names and last_registration_report for indexed, materialized, skipped, and failed entries.

Qualified/indexed execution requires the polars-sql extra. Plain register_table and direct Polars DataFrame/LazyFrame APIs do not.