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:
Stage – Study records are flattened via
CentralizedMapperinto top-levelRecordmetadata 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 fromrecord_data(withvar_prefixing when a clinical variable collides with aRecordmetadata name), and a JSON-encodedrecord_datapayload column after clinical PHI masking. Emptyrecord_datadictionaries omit zero-field Arrow structs so draft records serialize cleanly to Parquet.PUT – Each Parquet file is uploaded to a run-scoped path inside a Snowflake internal stage via
PUT file://... AUTO_COMPRESS = FALSE OVERWRITE = TRUE.Evolve & Merge – The sink inspects
INFORMATION_SCHEMA.COLUMNSand executesCREATE TABLE IF NOT EXISTSwhen the target table is missing orALTER TABLE ... ADD COLUMNwhen unseenFormVariablecolumns appear. Whenidempotent=True(default), Snowflake bulk-loads the staged Parquet file into a temporary staging table viaCOPY 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 executesMERGE INTOkeyed on(study_key, record_id)by default (snake_case),(studyKey, recordId)whennaming_convention="camelCase",(STUDYID, RECORD_ID)whennaming_convention="sdtm", or(STUDYID, DOMAIN, USUBJID, *SEQ)whenas_sdtm=True(falling back to(STUDYID, DOMAIN, USUBJID)for single-row-per-Subjectdomains without*SEQsuch asDM). Whenidempotent=False, Snowflake loads directly into the target table viaCOPY 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_pathor an explicitExtractionStateLedger(FileStateProvider) instance soexport_to_snowflake()(viarun_streaming_export()) commits the newRecordwatermark only afterSnowflakeExportSink.flush()succeeds.Inside Apache Airflow tasks, pass
AirflowStateProvider(or resolveget_state_provider(provider_name="airflow")) so watermarks persist in AirflowVariablecheckpoints across scheduled DAG runs.When
incremental=True,idempotent=True, andinclude_deleted=False,Recorditems voided after the previous watermark are routed throughSnowflakeExportSink.reconcile_deletedso 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_diris not set, atempfile.TemporaryDirectoryis created automatically and removed when the context manager exits, regardless of success or failure.Persistent staging directory – When
local_staging_diris 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:
SinkConfigConfiguration 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 INTOcommand.- 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 bytempfile.- manifest_path:
Optional path to a JSON-lines file where each loaded batch is recorded.
- hard_delete:
When
True(withidempotent=Trueandinclude_deleted=True), matched records withdeleted=Trueare deleted from the target table duringMERGE INTOrather than retained asdeleted=Truetombstones. Wheninclude_deleted=False(default), voided records are routed toSnowflakeExportSink.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:
sdk (ImednetFacade) –
study_key (str) –
config (SnowflakeSinkConfig) –
mask_phi (bool | None) –
- Return type:
int
- class imednet_sinks.warehouse.SnowflakeExportSink[source]
Bases:
ExportSinkStage Parquet files and bulk-load them into Snowflake.
Parameters¶
- config:
SnowflakeSinkConfigcontaining 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-pythonorpyarroware 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
recordswhenconfig.mask_phiis 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.