Snowflake Export

This guide covers the warehouse-native Snowflake export path introduced as the first implementation of the staged warehouse export framework.

For the DuckDB / local-analytical path see DuckDB Integration. For general architecture context see Architecture Overview.

Overview

The Snowflake export path uses a staged-loading and merge approach:

  1. Stage – Study records are flattened via CentralizedMapper into top-level Record metadata columns (study_key, record_id, subject_id, subject_key, form_id, form_key, visit_id, record_status, deleted, timestamps, etc.), flattened clinical variable columns extracted from record_data (with var_ prefixing when a clinical variable collides with a Record metadata name), and a JSON-encoded record_data payload column after clinical PHI masking. Empty record_data dictionaries omit zero-field Arrow structs so draft records serialize cleanly to Parquet.

  2. PUT – Each Parquet file is uploaded to a run-scoped path inside a Snowflake internal stage via PUT file://... AUTO_COMPRESS = FALSE OVERWRITE = TRUE.

  3. Evolve & Merge – The sink inspects INFORMATION_SCHEMA.COLUMNS and executes CREATE TABLE IF NOT EXISTS when the target table is missing or ALTER TABLE ... ADD COLUMN when unseen Form Variable columns appear. When idempotent=True (default), Snowflake bulk-loads the staged Parquet file into a temporary staging table via COPY INTO ... FILE_FORMAT = (TYPE = PARQUET) MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE FORCE = TRUE, deduplicates candidate rows by modification timestamp (date_modified / dateModified / DATE_MODIFIED), and executes MERGE INTO keyed on (study_key, record_id) by default (snake_case), (studyKey, recordId) when naming_convention="camelCase", (STUDYID, RECORD_ID) when naming_convention="sdtm", or (STUDYID, DOMAIN, USUBJID, *SEQ) when as_sdtm=True (falling back to (STUDYID, DOMAIN, USUBJID) for single-row-per-Subject domains without *SEQ such as DM). When idempotent=False, Snowflake loads directly into the target table via COPY INTO ... FORCE = TRUE.

This is intentionally different from export_to_sql(), which uses SQLAlchemy DataFrame.to_sql() and is appropriate for transactional SQL targets (SQLite, PostgreSQL, etc.). Do not mix the two paths.

Important

Staging constraint — local staging only. The first version of this framework supports local intermediate staging only. Parquet files are written to the local filesystem and then uploaded to a Snowflake internal stage via PUT. Object-storage staging (S3, GCS, Azure Blob) is not yet supported. If your Snowflake account restricts PUT to external stages only, you will need to wait for a future release.

Installation

pip install 'imednet[snowflake]'

This installs snowflake-connector-python (≥ 3.0) and pyarrow (included transitively).

Quickstart — export_to_snowflake

The export_to_snowflake() convenience function handles batching, staging, and cleanup automatically:

import os
from imednet import ImednetSDK
from imednet_sinks.warehouse import export_to_snowflake, SnowflakeSinkConfig

sdk = ImednetSDK(
    api_key=os.environ["IMEDNET_API_KEY"],
    security_key=os.environ["IMEDNET_SECURITY_KEY"],
)

snowflake_cfg = SnowflakeSinkConfig(
    study_key="MY_STUDY",
    account="myorg-myaccount",
    user="loader",
    password=os.environ["SNOWFLAKE_PASSWORD"],  # never hardcode
    database="IMEDNET_DB",
    schema="PUBLIC",
    warehouse="COMPUTE_WH",
    stage="MY_STAGE",
    table="RECORDS",
)

rows_loaded = export_to_snowflake(sdk, "MY_STUDY", config=snowflake_cfg)
print(f"Loaded {rows_loaded} rows")

Advanced usage — SnowflakeExportSink directly

Use SnowflakeExportSink directly when you need per-batch control, custom batch_id keys, or integration with a workflow engine:

import os
from imednet import ImednetSDK
from imednet.spi.sink_base import iter_batches
from imednet_sinks.warehouse import SnowflakeExportSink, SnowflakeSinkConfig

sdk = ImednetSDK(
    api_key=os.environ["IMEDNET_API_KEY"],
    security_key=os.environ["IMEDNET_SECURITY_KEY"],
)
records = list(sdk.records.list(study_key="MY_STUDY"))

snowflake_cfg_advanced = SnowflakeSinkConfig(
    study_key="MY_STUDY",
    account="myorg-myaccount",
    user="loader",
    password=os.environ["SNOWFLAKE_PASSWORD"],
    database="IMEDNET_DB",
    schema="PUBLIC",
    warehouse="COMPUTE_WH",
    stage="MY_STAGE",
    table="RECORDS",
    stage_prefix="imednet/MY_STUDY",
    batch_size=1000,
    max_retries=5,
    idempotent=True,
)

with SnowflakeExportSink(config=snowflake_cfg_advanced) as sink:
    for i, batch in enumerate(iter_batches(records, snowflake_cfg_advanced.batch_size)):
        rows = sink.write_batch(batch, batch_id=f"MY_STUDY/records/{i}")
        print(f"  batch {i}: {rows} rows")

Manifest output

Pass manifest_path to record every loaded batch in a JSON-lines file for audit purposes or replay:

snowflake_cfg_manifest = SnowflakeSinkConfig(
    study_key="MY_STUDY",
    account="myorg",
    user="user",
    database="db",
    schema="public",
    warehouse="wh",
    stage="stg",
    table="tbl",
    manifest_path="/tmp/imednet_manifest.jsonl",
)

Each entry contains:

{
    "batch_id":   "MY_STUDY/records/0",
    "stage_path": "@MY_STAGE/imednet/MY_STUDY_records_0.parquet",
    "row_count":  500,
    "loaded_at":  "2026-01-15T12:00:00+00:00"
}

Idempotency and delete semantics

When SnowflakeSinkConfig.idempotent is True (default), each batch upload runs PUT ... AUTO_COMPRESS = FALSE OVERWRITE = TRUE so refreshed Parquet files replace stale staged artifacts, ensures target table DDL via INFORMATION_SCHEMA.COLUMNS, bulk-loads the batch into a session-scoped temporary staging table via COPY INTO ... FORCE = TRUE, deduplicates staged rows by modification timestamp (date_modified / dateModified / DATE_MODIFIED), and executes MERGE INTO using schema-aware natural keys: (study_key, record_id) for snake_case (default), (studyKey, recordId) for naming_convention="camelCase", (STUDYID, RECORD_ID) for naming_convention="sdtm", and (STUDYID, DOMAIN, USUBJID, *SEQ) when as_sdtm=True (or (STUDYID, DOMAIN, USUBJID) when a domain such as DM has no *SEQ column). Scheduled re-runs update modified Record rows in place without inserting duplicates.

By default (include_deleted=False), voided (deleted=True) Record items are routed through reconcile_deleted() on both full and incremental idempotent runs, deleting matched target rows and excluding unmatched voided records. Set include_deleted=True with hard_delete=False to retain DELETED = TRUE tombstones on matched or newly loaded rows, or pair include_deleted=True with hard_delete=True on SnowflakeSinkConfig (or export_kwargs={"include_deleted": True, "hard_delete": True} in ImednetExportOperator) to delete matched target rows during MERGE INTO while skipping unmatched voided records. Set idempotent = False (--force-reload in the CLI) on non-incremental runs to bypass staging-table merges and append directly into the target table via COPY INTO ... FORCE = TRUE.

Incremental checkpoints with ExtractionStateLedger and AirflowStateProvider

SnowflakeSinkConfig inherits all eight streaming checkpoint options from SinkConfig (incremental, stream_name, ledger_path, state_provider, modified_since, record_filter, record_data_filter, and include_deleted) while keeping mask_phi=True enabled by default.

  • For local or VM-scheduled loads, pass ledger_path or an explicit ExtractionStateLedger (FileStateProvider) instance so export_to_snowflake() (via run_streaming_export()) commits the new Record watermark only after SnowflakeExportSink.flush() succeeds.

  • Inside Apache Airflow tasks, pass AirflowStateProvider (or resolve get_state_provider(provider_name="airflow")) so watermarks persist in Airflow Variable checkpoints across scheduled DAG runs.

  • When incremental=True, idempotent=True, and include_deleted=False, Record items voided after the previous watermark are routed through SnowflakeExportSink.reconcile_deleted so warehouse tables stay synchronized without scanning unchanged history.

import os
import tempfile
from pathlib import Path
from imednet import ImednetSDK
from imednet_sinks.warehouse import SnowflakeSinkConfig, export_to_snowflake
from imednet_workflows import ExtractionStateLedger

with tempfile.TemporaryDirectory() as sf_tmp_dir:
    sf_ledger_path = Path(sf_tmp_dir) / "snowflake_ledger.json"
    sf_ledger = ExtractionStateLedger(str(sf_ledger_path))

    snowflake_incremental_cfg = SnowflakeSinkConfig(
        study_key="STUDY",
        account="myorg-myaccount",
        user="loader",
        password=os.environ["SNOWFLAKE_PASSWORD"],
        database="IMEDNET_DB",
        schema="PUBLIC",
        warehouse="COMPUTE_WH",
        stage="MY_STAGE",
        table="RECORDS",
        mask_phi=True,
        incremental=True,
        stream_name="snowflake_vitals",
        ledger_path=sf_ledger_path,
        state_provider=sf_ledger,
        modified_since="2026-01-01T00:00:00Z",
        record_filter={"form_key": "F_VS"},
        record_data_filter="V_WEIGHT>0",
        include_deleted=False,
    )
    sf_rows = export_to_snowflake(
        ImednetSDK(simulation_mode=True),
        "STUDY",
        config=snowflake_incremental_cfg,
    )
    assert sf_rows >= 0

Error handling and retries

Every write_batch call retries up to SinkConfig.max_retries times (default 3) with exponential back-off (retry_backoff * 2 ** attempt, default base 1 s). After all retries are exhausted, ExportBatchError is raised with the failing batch_id. Connection failures during __init__ raise ExportConfigurationError.

Stage lifecycle and cleanup

  • Temporary staging directory – When local_staging_dir is not set, a tempfile.TemporaryDirectory is created automatically and removed when the context manager exits, regardless of success or failure.

  • Persistent staging directory – When local_staging_dir is set, the directory is not cleaned up automatically; this lets you inspect or re-upload the Parquet files.

  • Snowflake stage cleanup – The SDK does not remove files from the Snowflake internal stage after loading. Use REMOVE @MY_STAGE/imednet/ from a Snowflake session to purge them when they are no longer needed.

CLI reference

imednet export snowflake --help

Minimal example:

imednet export snowflake MY_STUDY \
    myorg-myaccount loader "$SNOWFLAKE_PASSWORD" \
    IMEDNET_DB PUBLIC COMPUTE_WH MY_STAGE RECORDS

With options:

imednet export snowflake MY_STUDY \
    myorg-myaccount loader "$SNOWFLAKE_PASSWORD" \
    IMEDNET_DB PUBLIC COMPUTE_WH MY_STAGE RECORDS \
    --stage-prefix imednet/prod \
    --batch-size 1000 \
    --manifest-path /tmp/manifest.jsonl \
    --force-reload

Configuration reference

class imednet_sinks.warehouse.SnowflakeSinkConfig[source]

Bases: SinkConfig

Configuration for SnowflakeExportSink.

Parameters

account:

Snowflake account identifier (<org>-<account> or legacy format).

user:

Snowflake user name.

password:

Snowflake password. Never logged.

database:

Target database.

schema:

Target schema.

warehouse:

Virtual warehouse used for the COPY INTO command.

stage:

Snowflake internal stage name (e.g. "MY_STAGE").

table:

Destination table name inside database.*schema*.

stage_prefix:

Path prefix inside the stage (default "imednet").

prefix:

Optional alias for stage_prefix.

local_staging_dir:

Local directory used to write Parquet files before PUT. Defaults to a temporary directory created by tempfile.

manifest_path:

Optional path to a JSON-lines file where each loaded batch is recorded.

hard_delete:

When True (with idempotent=True and include_deleted=True), matched records with deleted=True are deleted from the target table during MERGE INTO rather than retained as deleted=True tombstones. When include_deleted=False (default), voided records are routed to SnowflakeExportSink.reconcile_deleted().

study_key: str

Required.

batch_size: int = 500
max_retries: int = 3
retry_backoff: float = 1.0
idempotent: bool = True
mask_phi: bool = True
extra: dict[str, Any] = dict()
quality_gate_enabled: bool = False
min_schema_readiness_score: float = 100.0
tracer: Any | None = ...
modified_since: datetime | str | None = None
record_filter: dict[str, Any] | str | None = None
record_data_filter: str | None = None
include_deleted: bool = False
incremental: bool = False
stream_name: str | None = None
ledger_path: str | Path | None = None
state_provider: Any | None = ...
max_buffered_records: int | None = None
as_sdtm: bool = None
sdtm_domain: str | None = None
standards_profile: str | Any | None = None
min_standards_score: float | None = None
naming_convention: str | None = None
preserve_record_id: bool | None = None
account: str = ''
user: str = ''
password: str = ...
database: str = ''
schema: str = 'PUBLIC'
warehouse: str = ''
stage: str = ''
table: str = ''
stage_prefix: str = 'imednet'
prefix: str | None = None
local_staging_dir: str | PathLike[str] | None = None
manifest_path: str | PathLike[str] | None = None
hard_delete: bool = False
__init__(study_key, batch_size=500, max_retries=3, retry_backoff=1.0, idempotent=True, mask_phi=True, extra=dict(), quality_gate_enabled=False, min_schema_readiness_score=100.0, tracer=..., modified_since=None, record_filter=None, record_data_filter=None, include_deleted=False, incremental=False, stream_name=None, ledger_path=None, state_provider=..., max_buffered_records=None, as_sdtm=None, sdtm_domain=None, standards_profile=None, min_standards_score=None, naming_convention=None, preserve_record_id=None, account='', user='', password=..., database='', schema='PUBLIC', warehouse='', stage='', table='', stage_prefix='imednet', prefix=None, local_staging_dir=None, manifest_path=None, hard_delete=False)
Parameters:
  • study_key (str) –

  • batch_size (int) –

  • max_retries (int) –

  • retry_backoff (float) –

  • idempotent (bool) –

  • mask_phi (bool) –

  • extra (dict[str, Any]) –

  • quality_gate_enabled (bool) –

  • min_schema_readiness_score (float) –

  • tracer (Any | None) –

  • modified_since (datetime | str | None) –

  • record_filter (dict[str, Any] | str | None) –

  • record_data_filter (str | None) –

  • include_deleted (bool) –

  • incremental (bool) –

  • stream_name (str | None) –

  • ledger_path (str | Path | None) –

  • state_provider (Any | None) –

  • max_buffered_records (int | None) –

  • as_sdtm (bool) –

  • sdtm_domain (str | None) –

  • standards_profile (str | Any | None) –

  • min_standards_score (float | None) –

  • naming_convention (str | None) –

  • preserve_record_id (bool | None) –

  • account (str) –

  • user (str) –

  • password (str) –

  • database (str) –

  • schema (str) –

  • warehouse (str) –

  • stage (str) –

  • table (str) –

  • stage_prefix (str) –

  • prefix (str | None) –

  • local_staging_dir (str | PathLike[str] | None) –

  • manifest_path (str | PathLike[str] | None) –

  • hard_delete (bool) –

Return type:

None

validate_identifiers(*, require_coordinates=False)[source]

Validate Snowflake database coordinates and stage prefix against strict patterns.

Parameters:

require_coordinates (bool) –

Return type:

None

imednet_sinks.warehouse.export_to_snowflake(sdk, study_key, *, config, mask_phi=None)[source]

Export study records to Snowflake using SnowflakeExportSink.

Parameters:
Return type:

int

class imednet_sinks.warehouse.SnowflakeExportSink[source]

Bases: ExportSink

Stage Parquet files and bulk-load them into Snowflake.

Parameters

config:

SnowflakeSinkConfig containing all connection details and staging paths.

raises ~imednet.errors.ExportConfigurationError:

When the Snowflake connector cannot be initialised or the required configuration values are missing.

raises ImportError:

When snowflake-connector-python or pyarrow are not installed.

__init__(config)[source]

Initialize the Snowflake export sink.

Parameters:

config (SnowflakeSinkConfig) – Mandatory Snowflake-specific sink configuration.

Return type:

None

bind_stream_metadata(metadata)

Hydrate and bind SDTM sequence counters into transactional stream metadata.

Parameters:

metadata (dict[str, Any]) –

Return type:

None

close()[source]

Close the Snowflake connection and clean up temporary staging files.

Return type:

None

flush()[source]

No-op: each batch is committed individually.

Return type:

None

reconcile_deleted(records, *, batch_id)[source]

Delete newly voided rows from Snowflake when running idempotently.

Parameters:
  • records (Sequence[Any]) –

  • batch_id (str) –

Return type:

int

redact_batch(records, *, study_key=None, config=None, phi_keys=None)

Redact sensitive clinical PHI across records when config.mask_phi is enabled.

Parameters:
  • records (Sequence[Any]) –

  • study_key (str | None) –

  • config (SinkConfig | None) –

  • phi_keys (Collection[str] | None) –

Return type:

Any

write_batch(records, *, batch_id)[source]

Write records to Snowflake via Parquet staging, DDL evolution, and MERGE INTO (or COPY INTO).

Parameters:
  • records (Sequence[Any]) –

  • batch_id (str) –

Return type:

int

Out of scope

  • Object-storage (S3/GCS/Azure) staging — planned for a future release.

  • Snowpark / Python connector Pandas integration — not used; Parquet staging is the preferred path for throughput.

  • Row-wise insert via SQLAlchemy — use export_to_sql() for transactional SQL targets instead.