Skip to content

Core

Authored metadata and Python models have separate owners

Authored JSON fields are rendered on the Metadata reference page. Hydrated Python model details and runtime-only properties remain the responsibility of this API reference. Driver session and replay models are rendered on the Runtime configuration page. This page owns core helpers, registries, secrets and exceptions.

The model constructors below use keyword fields. Authored JSON/YAML is a separate input shape: a metadata provider resolves connection references and hydrates nested Connection, Source, Destination, Transform, and DataFlow objects before the Driver executes them. For example, this is a small programmatic model graph and its derived file path:

from datacoolie.core.models.connection import Connection
from datacoolie.core.models.source import Source

connection = Connection(
    name="orders",
    format="csv",
    configure={"base_path": "input"},
)
source = Source(connection=connection, table="orders")

assert connection.connection_type == "file"
assert source.path == "input/orders"

The example uses Python keyword arguments. A provider can start from authored JSON/YAML, resolve a connection_name reference, and then pass the resulting values to these same model constructors. The schema reference remains the authority for authored keys and validation; this page is the authority for the hydrated Python objects.

Registry factories

The package root exposes six registry-backed factories. Each name selects a registered implementation and **kwargs are passed to that implementation. The factories describe runtime construction; entry-point discovery and metadata format validation are separate contracts.

datacoolie

DataCoolie — Metadata-driven, engine-unified, cloud-agnostic ETL framework.

The package root is intentionally lazy. Importing a pure framework utility must not import optional engine/platform SDKs; registries and built-in plugins are initialized the first time a runtime factory or registry is requested.

create_engine

create_engine(name: str, **kwargs: object) -> Any

Create an engine instance by name (e.g. "spark", "polars").

create_platform

create_platform(name: str, **kwargs: object) -> Any

Create a platform instance by name (e.g. "local", "fabric").

create_source

create_source(name: str, **kwargs: object) -> Any

Create a source reader by name (e.g. "delta", "csv").

create_destination

create_destination(name: str, **kwargs: object) -> Any

Create a destination writer by name (e.g. "delta", "parquet").

create_transformer

create_transformer(name: str, **kwargs: object) -> Any

Create a transformer by name (e.g. "schema_converter").

create_resolver

create_resolver(name: str, **kwargs: object) -> Any

Create a secret resolver by name (e.g. "env").

Models and constants

CompatModel supplies the keyword construction, nested mapping coercion, and model_dump* helpers used by the metadata models. Its subclasses use @dataclass(init=False), so their generated dataclass signature is not the runtime constructor contract. The class signatures are hidden here and the declared fields are listed explicitly so the reference does not suggest an empty constructor.

CompatModel

CompatModel

Small compatibility layer for the subset of BaseModel behavior we use.

model_fields

model_fields

model_construct classmethod

model_construct

model_copy

model_copy

model_dump

model_dump

model_dump_json

model_dump_json

Connection dataclass

Connection

Bases: CompatModel

Endpoint configuration for a data source or destination.

The configure JSON field stores type-specific settings (host, port, read_options, write_options, etc.). Frequently-used values are surfaced as computed properties.

name instance-attribute

name: str

connection_id class-attribute instance-attribute

connection_id: Optional[str] = None

workspace_id class-attribute instance-attribute

workspace_id: Optional[str] = None

connection_type class-attribute instance-attribute

connection_type: str = ConnectionType.FILE.value

format class-attribute instance-attribute

format: str = Format.PARQUET.value

catalog class-attribute instance-attribute

catalog: Optional[str] = None

database class-attribute instance-attribute

database: Optional[str] = None

configure class-attribute instance-attribute

configure: Dict[str, Any] = field(default_factory=dict)

secrets_ref class-attribute instance-attribute

secrets_ref: Optional[Dict[str, List[str]]] = None

is_active class-attribute instance-attribute

is_active: bool = True

base_path property

base_path: Optional[str]

Base storage path (e.g. abfss://container@storage/).

host property

host: Optional[str]

port property

port: Optional[int]

username property

username: Optional[str]

password property

password: Optional[str]

database_type property

database_type: Optional[str]

Database type (mysql, mssql, postgresql, oracle, sqlite).

schema_hint_type_system property

schema_hint_type_system: Optional[str]

Raw source convention used when interpreting transform hints.

The model preserves the authored value. Normalization and validation belong to the transform resolver when a schema hint is actually used.

auth_type property

auth_type: Optional[str]

Database authentication type (password, service_principal, managed_identity, access_token).

tenant_id property

tenant_id: Optional[str]

Azure AD tenant ID for service_principal auth.

token property

token: Optional[str]

Pre-fetched access token for access_token auth.

url property

url: Optional[str]

Explicit URL / connection string from configure.

driver property

driver: Optional[str]

JDBC driver class name.

read_options property

read_options: Dict[str, Any]

write_options property

write_options: Dict[str, Any]

merge_options property

merge_options: Dict[str, Any]

Return options intended for merge/upsert operations.

use_schema_hint property

use_schema_hint: bool

use_hive_partitioning property

use_hive_partitioning: bool

athena_output_location property

athena_output_location: Optional[str]

S3 path for Athena DDL query results.

When set, the writer always registers a native Delta table via Athena DDL (DROP + CREATE EXTERNAL TABLE ... TBLPROPERTIES ('table_type'='DELTA')) after every write and maintenance.

generate_manifest property

generate_manifest: bool

Generate _symlink_format_manifest/ after writes and maintenance.

register_symlink_table: bool

Register a SymlinkTextInputFormat table in Glue after writes.

Implies :attr:generate_manifest.

symlink_database_prefix: str

Prefix for symlink Glue database name. Default "symlink_".

date_folder_partitions property

date_folder_partitions: Optional[str]

date_backward property

date_backward: Optional[Dict[str, Any]]

Backward look-back offset for date-folder partition discovery.

Reads backward_days, backward_months, backward_hours as top-level keys from config, or a nested backward dict.

Strategies:

Fixed offset — subtract days / months / hours from watermark::

config:
  backward_days: 7
  # or
  backward: {days: 7, months: 1}

Closing-day — monthly period boundary based on current date::

config:
  backward: {closing_day: 10}

Source dataclass

Source

Bases: CompatModel

Read-side pipeline configuration.

connection instance-attribute

connection: Connection

schema_name class-attribute instance-attribute

schema_name: Optional[str] = None

table class-attribute instance-attribute

table: Optional[str] = None

query class-attribute instance-attribute

query: Optional[str] = None

python_function class-attribute instance-attribute

python_function: Optional[str] = None

watermark_columns class-attribute instance-attribute

watermark_columns: List[str] = field(default_factory=list)

filter_expression class-attribute instance-attribute

filter_expression: Optional[str] = None

configure class-attribute instance-attribute

configure: Dict[str, Any] = field(default_factory=dict)

full_table_name property

full_table_name: Optional[str]

namespace property

namespace: Optional[str]

Namespace without the table: catalog.database.schema.

path property

path: Optional[str]

read_options property

read_options: Dict[str, Any]

Merged read options: connection defaults + source overrides.

has_watermark_state property

has_watermark_state: bool

Whether ordinary execution needs persisted source state.

A file source with date-folder discovery can emit the internal folder cursor even when the user did not author a row watermark column. That cursor must be loaded on the next run so discovery can prune folders older than the saved frontier.

date_backward property

date_backward: Optional[Dict[str, Any]]

Backward look-back offset, source-level overrides connection-level.

Reads from configure (same keys as :attr:Connection.date_backward). If no source-level config is present, falls back to the connection's value.

Example (YAML / source configure)::

configure:
  backward_days: 7         # overrides connection setting
  # or
  backward: {months: 1}
  # or closing-day strategy
  backward: {closing_day: 10}

PartitionColumn dataclass

PartitionColumn

Bases: CompatModel

Partition column definition.

expression is an optional SQL expression used to derive the partition value (e.g. "year(event_date)").

column instance-attribute

column: str

expression class-attribute instance-attribute

expression: Optional[str] = None

Destination dataclass

Destination

Bases: CompatModel

Write-side pipeline configuration.

connection instance-attribute

connection: Connection

table instance-attribute

table: str

schema_name class-attribute instance-attribute

schema_name: Optional[str] = None

load_type class-attribute instance-attribute

load_type: str = LoadType.APPEND.value

merge_keys class-attribute instance-attribute

merge_keys: List[str] = field(default_factory=list)

partition_columns class-attribute instance-attribute

partition_columns: List[PartitionColumn] = field(
    default_factory=list
)

configure class-attribute instance-attribute

configure: Dict[str, Any] = field(default_factory=dict)

full_table_name property

full_table_name: str

namespace property

namespace: Optional[str]

Namespace without the table: catalog.database.schema.

path property

path: Optional[str]

write_options property

write_options: Dict[str, Any]

Merged write options: connection defaults + destination overrides.

merge_options property

merge_options: Dict[str, Any]

Merged merge options with a compatibility bridge for old aliases.

partition_column_names property

partition_column_names: List[str]

merge_keys_extended property

merge_keys_extended: List[str]

Return merge keys extended with partition columns.

scd2_effective_column property

scd2_effective_column: Optional[str]

SQL expression used as __valid_from for SCD2 loads.

Read from destination.configure["scd2_effective_column"]. Returns None when not set (non-SCD2 destinations).

replace_by_watermark property

replace_by_watermark: bool

Whether merge_overwrite should use range-based window replace.

When True, the strategy deletes all target rows within the watermark window (watermark_effective → new_watermark) instead of doing key-based delete. This handles source-side deletions.

Requires date_backward on the source to ensure the read window covers the delete scope.

SchemaHint dataclass

SchemaHint

Bases: CompatModel

Column-level type hint applied by the transform schema converter.

column_name instance-attribute

column_name: str

data_type instance-attribute

data_type: str

format class-attribute instance-attribute

format: Optional[str] = None

precision class-attribute instance-attribute

precision: Optional[int] = None

scale class-attribute instance-attribute

scale: Optional[int] = None

default_value class-attribute instance-attribute

default_value: Optional[str] = None

ordinal_position class-attribute instance-attribute

ordinal_position: Optional[int] = 0

is_active class-attribute instance-attribute

is_active: bool = True

AdditionalColumn dataclass

AdditionalColumn

Bases: CompatModel

Computed column added during the transform phase.

column instance-attribute

column: str

expression instance-attribute

expression: str

ValueRule dataclass

ValueRule

Bases: CompatModel

Typed, engine-portable value normalization rule.

operation instance-attribute

operation: str

columns class-attribute instance-attribute

columns: List[str] = field(default_factory=list)

order class-attribute instance-attribute

order: int = 100

mode class-attribute instance-attribute

mode: Optional[str] = None

pattern class-attribute instance-attribute

pattern: Optional[str] = None

replacement class-attribute instance-attribute

replacement: str = ''

value class-attribute instance-attribute

value: Any = None

mapping class-attribute instance-attribute

mapping: Dict[str, str] = field(default_factory=dict)

on_unmapped class-attribute instance-attribute

on_unmapped: str = 'keep'

HashColumn dataclass

HashColumn

Bases: CompatModel

Stable hash column generated from an ordered list of scalar columns.

target_column instance-attribute

target_column: str

columns class-attribute instance-attribute

columns: List[str] = field(default_factory=list)

algorithm class-attribute instance-attribute

algorithm: str = 'sha256'

serialization class-attribute instance-attribute

serialization: str = 'dc_hash_v1'

MaskingRule dataclass

MaskingRule

Bases: CompatModel

Typed, irreversible column masking rule.

method instance-attribute

method: str

columns class-attribute instance-attribute

columns: List[str] = field(default_factory=list)

value class-attribute instance-attribute

value: Any = None

keep_start class-attribute instance-attribute

keep_start: int = 0

keep_end class-attribute instance-attribute

keep_end: int = 0

mask_char class-attribute instance-attribute

mask_char: str = '*'

bucket_size class-attribute instance-attribute

bucket_size: Optional[float] = None

unit class-attribute instance-attribute

unit: Optional[str] = None

Transform dataclass

Transform

Bases: CompatModel

Transformation rules applied between source read and destination write.

deduplicate_columns class-attribute instance-attribute

deduplicate_columns: List[str] = field(default_factory=list)

latest_data_columns class-attribute instance-attribute

latest_data_columns: List[str] = field(default_factory=list)

filter_expression class-attribute instance-attribute

filter_expression: Optional[str] = None

additional_columns class-attribute instance-attribute

additional_columns: List[AdditionalColumn] = field(
    default_factory=list
)

schema_hints class-attribute instance-attribute

schema_hints: List[SchemaHint] = field(default_factory=list)

select_columns class-attribute instance-attribute

select_columns: List[str] = field(default_factory=list)

drop_columns class-attribute instance-attribute

drop_columns: List[str] = field(default_factory=list)

rename_columns class-attribute instance-attribute

rename_columns: Dict[str, str] = field(default_factory=dict)

value_rules class-attribute instance-attribute

value_rules: List[ValueRule] = field(default_factory=list)

hash_columns class-attribute instance-attribute

hash_columns: List[HashColumn] = field(default_factory=list)

masking_rules class-attribute instance-attribute

masking_rules: List[MaskingRule] = field(
    default_factory=list
)

configure class-attribute instance-attribute

configure: Dict[str, Any] = field(default_factory=dict)

missing_column_policy property

missing_column_policy: str

convert_timestamp_ntz property

convert_timestamp_ntz: bool

Whether to convert timestamp_ntz columns to timestamp.

Reads convert_timestamp_ntz from :attr:configure. Defaults to False so a naive wall-clock value is not silently interpreted as an instant.

Example (YAML / metadata)::

transform:
  configure:
    convert_timestamp_ntz: false

timestamp_timezone property

timestamp_timezone: Optional[str]

Timezone used when an explicit NTZ-to-instant conversion is requested.

The value is passed to the engine adapter, which validates whether it can implement the conversion without mutating shared session state.

deduplicate_by_rank property

deduplicate_by_rank: bool

Whether to use RANK-based deduplication instead of ROW_NUMBER.

Reads deduplicate_by_rank from :attr:configure. Defaults to False.

Example (YAML / metadata)::

transform:
  configure:
    deduplicate_by_rank: true

schema_hints_dict property

schema_hints_dict: Dict[str, SchemaHint]

deduplicate_column_names

deduplicate_column_names

Return dedup columns, falling back to merge_keys.

DataFlow dataclass

DataFlow

Bases: CompatModel

Complete ETL pipeline configuration.

Composes :class:Source, :class:Destination, and :class:Transform.

source instance-attribute

source: Source

destination instance-attribute

destination: Destination

dataflow_id class-attribute instance-attribute

dataflow_id: Optional[str] = None

workspace_id class-attribute instance-attribute

workspace_id: Optional[str] = None

name class-attribute instance-attribute

name: Optional[str] = None

description class-attribute instance-attribute

description: Optional[str] = None

stage class-attribute instance-attribute

stage: Optional[str] = None

group_number class-attribute instance-attribute

group_number: Optional[int] = None

execution_order class-attribute instance-attribute

execution_order: Optional[int] = None

processing_mode class-attribute instance-attribute

processing_mode: str = ProcessingMode.BATCH.value

is_active class-attribute instance-attribute

is_active: bool = True

transform class-attribute instance-attribute

transform: Transform = field(default_factory=Transform)

configure class-attribute instance-attribute

configure: Dict[str, Any] = field(default_factory=dict)

load_type property

load_type: str

merge_keys property

merge_keys: List[str]

partition_columns property

partition_columns: List[PartitionColumn]

partition_column_names property

partition_column_names: List[str]

deduplicate_columns property

deduplicate_columns: List[str]

order_columns property

order_columns: List[str]

Columns used to order rows during deduplication.

Returns transform.latest_data_columns when set, otherwise falls back to source.watermark_columns.

constants

Framework-wide enums and constants for the DataCoolie framework.

Every enum inherits from str so its .value is a plain string that serialises naturally to JSON/YAML and matches database values.

CONNECTION_TYPE_FORMATS module-attribute

CONNECTION_TYPE_FORMATS: Dict[str, frozenset] = {
    ConnectionType.FILE.value: frozenset(
        {
            Format.PARQUET.value,
            Format.CSV.value,
            Format.JSON.value,
            Format.JSONL.value,
            Format.AVRO.value,
            Format.EXCEL.value,
        }
    ),
    ConnectionType.LAKEHOUSE.value: frozenset(
        {Format.DELTA.value, Format.ICEBERG.value}
    ),
    ConnectionType.DATABASE.value: frozenset(
        {Format.SQL.value}
    ),
    ConnectionType.API.value: frozenset({Format.API.value}),
    ConnectionType.FUNCTION.value: frozenset(
        {Format.FUNCTION.value}
    ),
    ConnectionType.STREAMING.value: frozenset(),
}

TRAILING_COLUMNS module-attribute

TRAILING_COLUMNS: tuple[str, ...] = (
    *((c.value) for c in SCD2Column),
    *((c.value) for c in FileInfoColumn),
    *((c.value) for c in SystemColumn),
)

WATERMARK_FILE_NAME module-attribute

WATERMARK_FILE_NAME: str = 'watermark_value.json'

DEFAULT_MAX_WORKERS module-attribute

DEFAULT_MAX_WORKERS: int = 8

DEFAULT_RETRY_COUNT module-attribute

DEFAULT_RETRY_COUNT: int = 0

DEFAULT_RETRY_DELAY module-attribute

DEFAULT_RETRY_DELAY: float = 5.0

DEFAULT_RETENTION_HOURS module-attribute

DEFAULT_RETENTION_HOURS: int = 168

XXHASH64_SEED module-attribute

XXHASH64_SEED: int = 42

LoadType

Bases: str, Enum

Supported load (write) strategies.

Format

Bases: str, Enum

Supported data formats.

ConnectionType

Bases: str, Enum

Connection endpoint categories.

ProcessingMode

Bases: str, Enum

ETL processing modes.

DataFlowStatus

Bases: str, Enum

Dataflow execution statuses.

ExecutionType

Bases: str, Enum

ETL execution types.

DatabaseType

Bases: str, Enum

Supported database types for connection URL generation.

DatabaseAuthType

Bases: str, Enum

Supported authentication types for database connections.

MaintenanceType

Bases: str, Enum

Maintenance operation types.

ColumnCaseMode

Bases: str, Enum

Column name case-conversion modes used by :class:ColumnNameSanitizer.

SystemColumn

Bases: str, Enum

Column names automatically added to every destination write.

FileInfoColumn

Bases: str, Enum

Column names injected for file-based sources.

SCD2Column

Bases: str, Enum

Column names for Slowly Changing Dimension Type 2.

registry

Thread-safe plugin registry with lazy entry-point discovery.

Registry state transitions are synchronized, while entry-point loading and user constructors run outside the state lock. This keeps plugin imports from deadlocking the registry and makes failed construction visible to callers.

PluginRegistry

PluginRegistry(
    entry_point_group: str, base_class: type[T]
)

Bases: Generic[T]

Registry for manually registered and entry-point plugins.

clear_singletons

clear_singletons() -> None

Evict cached instances and remembered construction failures.

get

get(name: str, **kwargs: object) -> T

Construct a fresh plugin instance outside the registry lock.

get_or_create

get_or_create(name: str, **kwargs: object) -> T

Return one singleton, with deterministic concurrent construction.

get_or_create_optional

get_or_create_optional(
    name: str, **kwargs: object
) -> T | None

Return a singleton or None for proven absence; selected failures raise.

Incomplete discovery cannot prove absence. Unrelated failed entry points do not prevent healthy plugins or genuinely absent names from resolving.

is_available

is_available(name: str) -> bool

Return whether a plugin loaded successfully.

list_plugins

list_plugins() -> list[str]

List registered plugins, triggering one discovery pass.

register

register(name: str, cls: type[T]) -> None

Register or replace a plugin class and invalidate its instance.

unregister

unregister(name: str) -> None

Remove a registered plugin and invalidate its cached state.

exceptions

Exception hierarchy for the DataCoolie framework.

All framework exceptions inherit from :class:DataCoolieError which carries a human-readable message and an optional details dict for structured error context.

ConfigurationError

ConfigurationError(
    message: str, details: dict[str, Any] | None = None
)

Bases: DataCoolieError

Raised for invalid or missing configuration.

DataCoolieError

DataCoolieError(
    message: str, details: dict[str, Any] | None = None
)

Bases: Exception

Base exception for all DataCoolie errors.

Attributes:

Name Type Description
message

Human-readable error description.

details

Optional structured context for logging / debugging.

DataFlowError

DataFlowError(
    message: str,
    dataflow_id: str | None = None,
    stage: str | None = None,
    details: dict[str, Any] | None = None,
)

Bases: DataCoolieError

Raised for dataflow-level execution errors.

Attributes:

Name Type Description
dataflow_id

Identifier of the failed dataflow.

stage

Pipeline stage where the error occurred.

DestinationError

DestinationError(
    message: str,
    details: dict[str, Any] | None = None,
    *,
    runtime_info: DestinationRuntimeInfo | None = None,
)

Bases: DataCoolieError

Raised when writing to a destination fails.

EngineError

EngineError(
    message: str, details: dict[str, Any] | None = None
)

Bases: DataCoolieError

Raised for engine-level failures (Spark, Polars).

MetadataError

MetadataError(
    message: str, details: dict[str, Any] | None = None
)

Bases: DataCoolieError

Raised for metadata loading / parsing failures.

PipelineError

PipelineError(
    message: str,
    attempt: AttemptRuntimeInfo | None = None,
    details: dict[str, Any] | None = None,
)

Bases: DataCoolieError

Raised when a pipeline step fails, carrying partial runtime results.

Attributes:

Name Type Description
attempt

The attempt observation collected before the failure.

PlatformError

PlatformError(
    message: str, details: dict[str, Any] | None = None
)

Bases: DataCoolieError

Raised for platform-specific failures (Fabric, Databricks, AWS).

SourceError

SourceError(
    message: str,
    details: dict[str, Any] | None = None,
    *,
    runtime_info: SourceRuntimeInfo | None = None,
)

Bases: DataCoolieError

Raised when reading from a data source fails.

TransformError

TransformError(
    message: str,
    details: dict[str, Any] | None = None,
    *,
    runtime_info: TransformRuntimeInfo | None = None,
)

Bases: DataCoolieError

Raised when a transformation step fails.

WatermarkError

WatermarkError(
    message: str, details: dict[str, Any] | None = None
)

Bases: DataCoolieError

Raised for watermark read / write / parse failures.

provider

Secret provider abstraction and resolution utilities.

:class:BaseSecretProvider defines the contract for fetching secrets from platform-specific vaults. :func:resolve_secrets wires a provider (or any :class:~datacoolie.core.secrets.resolver.BaseSecretResolver) into a :class:Connection by replacing vault key references with real values.

:class:SecretStr is an opaque wrapper that prevents accidental exposure of secret values through str(), repr(), print(), f-strings, and tracebacks. The raw value is never exposed via a public method. Framework internals use :func:unwrap_secret / :func:unwrap_configure to obtain plain strings at I/O boundaries (HTTP auth, JDBC, etc.).

BaseSecretProvider

BaseSecretProvider(cache_ttl: int = 300, **kwargs: Any)

Bases: ABC

Abstract base class for secret providers.

Implementations fetch secrets from a platform-specific vault (Azure Key Vault, AWS Secrets Manager, Databricks Secrets, env vars).

Supports optional in-memory caching with a configurable TTL.

Parameters:

Name Type Description Default
cache_ttl int

Time-to-live for cached secrets in seconds. 0 disables caching. Default is 300 (5 minutes).

300

clear_cache

clear_cache() -> None

Evict all cached entries.

get_secret

get_secret(key: str, source: str = '') -> str

Fetch a single secret by key from the given source.

Uses the cache when available and not expired, otherwise delegates to :meth:_fetch_secret.

Parameters:

Name Type Description Default
key str

Vault key / secret name. For AWS this is the JSON field name within the secret; for other platforms it is the secret key within the scope / vault.

required
source str

Source identifier whose meaning depends on the platform: scope for Databricks, vault URL for Fabric, env prefix for Local, and secret name/ARN (SecretId) for AWS. Defaults to "".

''

Raises:

Type Description
DataCoolieError

If the secret cannot be retrieved.

get_secrets

get_secrets(
    keys: List[str], source: str = ""
) -> Dict[str, str]

Fetch multiple secrets by keys from the given source.

Parameters:

Name Type Description Default
keys List[str]

Secret key names (JSON field names for AWS).

required
source str

Source identifier (scope, vault URL, env prefix, or secret name/ARN for AWS). Defaults to "".

''

Returns:

Type Description
Dict[str, str]

Mapping of key → secret value.

SecretStr

SecretStr(value: str)

Opaque wrapper that hides secret values from all public access.

str(), repr(), print(), format(), and logging all render *** instead of the real value.

There is no public method to extract the underlying string. Framework internals access the value via :func:unwrap_secret or :func:unwrap_configure.

The wrapper is immutable, unhashable-by-value, and unpicklable to prevent accidental persistence or cache-key leaks.

resolve_secrets

resolve_secrets(
    connection: Connection,
    provider: BaseSecretProvider,
    *,
    resolver_lookup: ResolverLookup | None = None,
) -> None

Resolve secret references in connection.

connection.secrets_ref maps each source (scope / vault URL / prefix / SecretId) to a list of configure field names. Each listed field must already be present in configure with the vault key name as its value; resolve_secrets replaces that value with the real secret. Repeated calls are idempotent: fields already holding :class:SecretStr are left unchanged.

Source keys may contain a <resolver>:<arg> prefix (e.g. "env:APP_"). When resolver_lookup is provided and returns a resolver for that prefix, the plugin resolver is used. Otherwise the platform-native provider handles the request via :class:~datacoolie.core.secrets.resolver.NativeProviderResolver.

Parameters:

Name Type Description Default
connection Connection

A :class:~datacoolie.core.models.connection.Connection instance.

required
provider BaseSecretProvider

The platform-native secret provider.

required
resolver_lookup ResolverLookup | None

Optional callable that maps a prefix string to a :class:~datacoolie.core.secrets.resolver.BaseSecretResolver, or returns None if the prefix is unrecognized.

None

Raises:

Type Description
DataCoolieError

If secrets_ref is invalid, a listed field is absent from configure, or a secret cannot be retrieved.

unwrap_configure

unwrap_configure(
    configure: Dict[str, Any],
) -> Dict[str, Any]

Return a shallow copy with all :class:SecretStr values unwrapped.

Call this once at the I/O boundary (HTTP auth, JDBC connect, etc.) to obtain a plain-string dict for external libraries. The original configure dict retains its SecretStr wrappers.

unwrap_secret

unwrap_secret(value: Any) -> Any

Return the raw string if value is a :class:SecretStr, else pass through.

resolver

Pluggable secret resolver abstraction.

:class:BaseSecretResolver defines the single plugin contract for fetching secrets — whether from environment variables, a cloud vault, HashiCorp Vault, 1Password, or any other backend.

Resolvers are registered via :data:datacoolie.resolver_registry and dispatched by prefix in secrets_ref source keys ("env:APP_").

Sources without a prefix use the platform-native provider via :class:NativeProviderResolver.

BaseSecretResolver

Bases: ABC

Abstract base class for pluggable secret resolvers.

This is the single interface that every secret backend implements. Subclasses must implement :meth:resolve which fetches a single secret value given a key and a source argument.

resolve abstractmethod

resolve(key: str, source: str) -> str

Fetch a single secret.

Parameters:

Name Type Description Default
key str

The secret / field name (value from configure).

required
source str

Backend-specific source identifier. For prefixed sources ("env:APP_"), this is the portion after the :. For native providers, this is the full source key from secrets_ref.

required

Returns:

Type Description
str

The secret value as a string.

Raises:

Type Description
DataCoolieError

If the secret cannot be retrieved.

EnvResolver

Bases: BaseSecretResolver

Resolve secrets from environment variables.

The environment variable name is {source}{key}. For example with source "APP_" and key "DB_PASSWORD" this looks up os.environ["APP_DB_PASSWORD"].

NativeProviderResolver

NativeProviderResolver(
    provider: BaseSecretProvider, **_: object
)

Bases: BaseSecretResolver

Adapter that wraps a :class:BaseSecretProvider as a resolver.

This bridges the existing platform secret providers (Local, Fabric, Databricks, AWS) into the unified :class:BaseSecretResolver interface so that resolve_secrets needs only one code path.

parse_source

parse_source(
    source: str,
    fallback: BaseSecretResolver,
    resolver_lookup: ResolverLookup | None = None,
) -> tuple[BaseSecretResolver, str]

Parse an optional <prefix>:<arg> source key.

Parameters:

Name Type Description Default
source str

The raw source key from secrets_ref (e.g. "env:APP_" or "my-vault-scope").

required
fallback BaseSecretResolver

The resolver to use when source has no recognized prefix (the :class:NativeProviderResolver in practice).

required
resolver_lookup ResolverLookup | None

Optional callable that maps a prefix string to a :class:BaseSecretResolver instance, or None if unrecognized.

None

Returns:

Type Description
BaseSecretResolver

A (resolver, source_arg) tuple ready for

str

resolver.resolve(key, source_arg).