imednet_sinks package

Unified Sinks plugin for iMednet.

Submodules

imednet_sinks.document module

MongoDB document-envelope export sink.

This module implements the structure-preserving export path for a MongoDB destination. Records fetched via DataExtractionWorkflow are wrapped in a consistent document envelope that preserves the clinical hierarchy.

Document envelope

Each document stored in MongoDB represents a single iMednet Record and carries the metadata needed to locate and de-duplicate it:

{
    "_id": "<study_key>/<record_id>",
    "study_key":     "MYSTUDY",
    "record_id":     1234,
    "subject_id":    99,
    "subject_key":   "SUBJ-001",
    "visit_id":      42,
    "form_id":       7,
    "form_key":      "BASELINE",
    "record_status": "Complete",
    "deleted":       false,
    "date_created":  "2024-01-01T08:00:00Z",
    "date_modified": "2024-01-15T12:00:00Z",
    "record_data":   { "var1": "value1", "var2": 99 },
    "exported_at":   "2024-01-15T12:00:00Z"
}

The _id field is a composite key <study_key>/<record_id> which guarantees uniqueness within a collection and enables efficient upserts.

Optional dependency

Requires pymongo (install via pip install 'imednet[mongodb]'). The client is imported lazily at connection time.

Idempotency

When SinkConfig.idempotent is True (default) the sink uses bulk_write with UpdateOne(..., upsert=True) operations so that re-running an export for the same batch updates existing documents rather than inserting duplicates.

Usage

import os
from imednet import ImednetSDK
from imednet.spi.sink_base import iter_batches
from imednet_sinks import MongoDbExportSink, MongoDbSinkConfig
from imednet_workflows.data_extraction import DataExtractionWorkflow

sdk = ImednetSDK(
    api_key=os.environ["IMEDNET_API_KEY"],
    security_key=os.environ["IMEDNET_SECURITY_KEY"],
)
records = DataExtractionWorkflow(sdk).extract_records_by_criteria(
    study_key="MYSTUDY",
)

config = MongoDbSinkConfig(
    study_key="MYSTUDY",
    uri=os.environ["MONGODB_URI"],
    database="imednet",
    collection="records",
)
with MongoDbExportSink(config=config) as sink:
    for i, batch in enumerate(iter_batches(records, config.batch_size)):
        sink.write_batch(batch, batch_id=f"MYSTUDY/all/{i}")
class imednet_sinks.document.AsyncMongoDbExportSink[source]

Bases: AsyncExportSink

Asynchronously export iMednet records to MongoDB via native pymongo.AsyncMongoClient.

__init__(config)[source]

Initialize the asynchronous MongoDB export sink.

Parameters:

config (MongoDbSinkConfig) –

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

async close()[source]

Asynchronously close the underlying pymongo.AsyncMongoClient.

Return type:

None

async flush()[source]

No-op: MongoDB writes are committed per bulk operation.

Return type:

None

async reconcile_deleted(records, *, batch_id)[source]

Asynchronously delete newly voided documents from MongoDB 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

async write_batch(records, *, batch_id)[source]

Asynchronously write records to MongoDB using upsert (idempotent) or insert.

Parameters:
  • records (Sequence[Any]) –

  • batch_id (str) –

Return type:

int

class imednet_sinks.document.MongoDbExportSink[source]

Bases: ExportSink

Export iMednet records as MongoDB document envelopes.

Parameters

config:

Mandatory MongoDbSinkConfig.

raises ~imednet.errors.ExportConfigurationError:

When the client cannot connect to the server.

raises ImportError:

When the pymongo package is not installed.

__init__(config)[source]

Initialize the MongoDB export sink.

Parameters:

config (MongoDbSinkConfig) – Mandatory 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 underlying PyMongo client.

Return type:

None

flush()[source]

No-op: MongoDB writes are committed per bulk operation.

Return type:

None

reconcile_deleted(records, *, batch_id)[source]

Delete newly voided documents from MongoDB 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 MongoDB using upsert (idempotent) or insert.

Parameters:
  • records (Sequence[Any]) –

  • batch_id (str) –

Return type:

int

class imednet_sinks.document.MongoDbSinkConfig[source]

Bases: SinkConfig

Configuration for MongoDB export sink.

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
uri: str = ''
database: str = ''
collection: str = ''
__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, uri='', database='', collection='')
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) –

  • uri (str) –

  • database (str) –

  • collection (str) –

Return type:

None

async imednet_sinks.document.async_export_to_mongodb(sdk, study_key, uri='', database='', collection='', *, config=None, mask_phi=None, **kwargs)[source]

Asynchronously export study records to MongoDB using AsyncMongoDbExportSink.

Parameters:
  • sdk (AsyncImednetFacade) –

  • study_key (str) –

  • uri (str) –

  • database (str) –

  • collection (str) –

  • config (MongoDbSinkConfig | None) –

  • mask_phi (bool | None) –

  • kwargs (Any) –

Return type:

int

imednet_sinks.document.export_to_mongodb(sdk, study_key, uri='', database='', collection='', *, config=None, mask_phi=None, **kwargs)[source]

Export study records to MongoDB using MongoDbExportSink.

Parameters:
  • sdk (ImednetFacade) –

  • study_key (str) –

  • uri (str) –

  • database (str) –

  • collection (str) –

  • config (MongoDbSinkConfig | None) –

  • mask_phi (bool | None) –

  • kwargs (Any) –

Return type:

int

imednet_sinks.graph module

Neo4j graph export sink.

This module implements the structure-preserving export path for a Neo4j property-graph destination. Records fetched via DataExtractionWorkflow are written as graph nodes and relationships that mirror the clinical data hierarchy.

Graph shape

Nodes

  • (:Study   {study_key})

  • (:Subject {subject_key, study_key})

  • (:Visit   {visit_id, subject_key, study_key})

  • (:Record  {record_id, form_id, visit_id, subject_key, study_key, **record_data})

Relationships

  • (:Study)-[:HAS_SUBJECT]->(:Subject)

  • (:Subject)-[:HAS_VISIT]->(:Visit)

  • (:Visit)-[:HAS_RECORD]->(:Record) (scheduled records with visit_id > 0)

  • (:Subject)-[:HAS_RECORD]->(:Record) (unscheduled records with visit_id omitted or <= 0)

Optional dependency

Requires neo4j (install via pip install 'imednet[neo4j]'). The driver is imported lazily at connection time so that importing this module never fails when neo4j is not installed.

Idempotency

When SinkConfig.idempotent is True (default) the sink uses MERGE on the node’s primary key property so that re-running an export for the same batch updates existing nodes rather than creating duplicates.

Usage

import os
from imednet import ImednetSDK
from imednet.spi.sink_base import iter_batches
from imednet_sinks import Neo4jExportSink, Neo4jSinkConfig
from imednet_workflows.data_extraction import DataExtractionWorkflow

sdk = ImednetSDK(
    api_key=os.environ["IMEDNET_API_KEY"],
    security_key=os.environ["IMEDNET_SECURITY_KEY"],
)
records = DataExtractionWorkflow(sdk).extract_records_by_criteria(
    study_key="MYSTUDY",
)

config = Neo4jSinkConfig(
    study_key="MYSTUDY",
    uri=os.environ.get("NEO4J_URI", "bolt://localhost:7687"),
    auth=("neo4j", os.environ["NEO4J_PASSWORD"]),
    batch_size=200,
)
with Neo4jExportSink(config=config) as sink:
    for i, batch in enumerate(iter_batches(records, config.batch_size)):
        sink.write_batch(batch, batch_id=f"MYSTUDY/all/{i}")
class imednet_sinks.graph.AsyncNeo4jExportSink[source]

Bases: AsyncExportSink

Asynchronously export iMednet records to Neo4j via native neo4j.AsyncGraphDatabase.

__init__(config)[source]

Initialize the asynchronous Neo4j export sink.

Parameters:

config (Neo4jSinkConfig) –

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

async close()[source]

Asynchronously close the underlying Neo4j AsyncDriver.

Return type:

None

async flush()[source]

No-op: Neo4j writes are committed per transaction.

Return type:

None

async reconcile_deleted(records, *, batch_id)[source]

Asynchronously delete newly voided Record nodes from Neo4j 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

async write_batch(records, *, batch_id)[source]

Asynchronously write records to Neo4j using MERGE (idempotent) or CREATE.

Parameters:
  • records (Sequence[Any]) –

  • batch_id (str) –

Return type:

int

class imednet_sinks.graph.Neo4jExportSink[source]

Bases: ExportSink

Export iMednet records as Neo4j graph nodes and relationships.

Parameters

config:

Mandatory Neo4jSinkConfig.

raises ~imednet.errors.ExportConfigurationError:

When the driver cannot connect to the database.

raises ImportError:

When the neo4j package is not installed.

__init__(config)[source]

Initialize the Neo4j export sink.

Parameters:

config (Neo4jSinkConfig) – Mandatory Neo4j-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 underlying Neo4j driver connection.

Return type:

None

flush()[source]

No-op: Neo4j writes are committed per transaction.

Return type:

None

reconcile_deleted(records, *, batch_id)[source]

Delete newly voided Record nodes from Neo4j 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 Neo4j using MERGE (idempotent) or CREATE.

Parameters:
  • records (Sequence[Any]) –

  • batch_id (str) –

Return type:

int

class imednet_sinks.graph.Neo4jSinkConfig[source]

Bases: SinkConfig

Extended SinkConfig for Neo4j.

Parameters

database:

Target Neo4j database name (default "neo4j").

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
uri: str = ''
auth: tuple[str, str] = ('', '')
database: str = 'neo4j'
__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, uri='', auth=('', ''), database='neo4j')
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) –

  • uri (str) –

  • auth (tuple[str, str]) –

  • database (str) –

Return type:

None

async imednet_sinks.graph.async_export_to_neo4j(sdk, study_key, uri='', auth=('', ''), *, config=None, mask_phi=None, **kwargs)[source]

Asynchronously export study records to Neo4j using AsyncNeo4jExportSink.

Parameters:
  • sdk (AsyncImednetFacade) –

  • study_key (str) –

  • uri (str) –

  • auth (tuple[str, str]) –

  • config (Neo4jSinkConfig | None) –

  • mask_phi (bool | None) –

  • kwargs (Any) –

Return type:

int

imednet_sinks.graph.export_to_neo4j(sdk, study_key, uri='', auth=('', ''), *, config=None, mask_phi=None, **kwargs)[source]

Export study records to Neo4j using Neo4jExportSink.

Parameters:
  • sdk (ImednetFacade) –

  • study_key (str) –

  • uri (str) –

  • auth (tuple[str, str]) –

  • config (Neo4jSinkConfig | None) –

  • mask_phi (bool | None) –

  • kwargs (Any) –

Return type:

int

imednet_sinks.plugin module

Entry point for the iMednet sinks plugin.

This module provides SinksNamespace and AsyncSinksNamespace, which aggregate all available data export sinks (MongoDB, Neo4j, Snowflake) under sdk.sinks on ImednetSDK and AsyncImednetSDK respectively.

class imednet_sinks.plugin.AsyncSinksNamespace[source]

Bases: object

Asynchronous namespace for accessing native async export sinks on AsyncImednetSDK.sinks.

property AsyncMongoDbExportSink: type[imednet_sinks.document.AsyncMongoDbExportSink]

Asynchronous sink class for exporting records to MongoDB.

property AsyncNeo4jExportSink: type[imednet_sinks.graph.AsyncNeo4jExportSink]

Asynchronous sink class for exporting records to Neo4j.

property AsyncSnowflakeExportSink: type[imednet_sinks.warehouse.AsyncSnowflakeExportSink]

Asynchronous sink class for exporting records to Snowflake.

property MongoDbExportSink: type[imednet_sinks.document.MongoDbExportSink]

Synchronous sink class for exporting records to MongoDB.

property MongoDbSinkConfig: type[imednet_sinks.document.MongoDbSinkConfig]

Configuration class for MongoDB sinks.

property Neo4jExportSink: type[imednet_sinks.graph.Neo4jExportSink]

Synchronous sink class for exporting records to Neo4j.

property Neo4jSinkConfig: type[imednet_sinks.graph.Neo4jSinkConfig]

Configuration class for Neo4j sinks.

property SnowflakeExportSink: type[imednet_sinks.warehouse.SnowflakeExportSink]

Synchronous sink class for exporting records to Snowflake.

property SnowflakeSinkConfig: type[imednet_sinks.warehouse.SnowflakeSinkConfig]

Configuration class for Snowflake sinks.

__init__(sdk)[source]

Initialize the asynchronous sinks namespace.

Parameters:

sdk (AsyncImednetFacade) –

Return type:

None

async export_to_mongodb(study_key: str, uri: str = '', database: str = '', collection: str = '', *, config: MongoDbSinkConfig | None = None, mask_phi: bool | None = None, **kwargs: Any) → int[source]
async export_to_mongodb(sdk: AsyncImednetFacade, study_key: str, uri: str = '', database: str = '', collection: str = '', *, config: MongoDbSinkConfig | None = None, mask_phi: bool | None = None, **kwargs: Any) → int

Asynchronously export study records to MongoDB using the bound AsyncImednetSDK.

async export_to_neo4j(study_key: str, uri: str = '', auth: tuple[str, str] = ('', ''), *, config: Neo4jSinkConfig | None = None, mask_phi: bool | None = None, **kwargs: Any) → int[source]
async export_to_neo4j(sdk: AsyncImednetFacade, study_key: str, uri: str = '', auth: tuple[str, str] = ('', ''), *, config: Neo4jSinkConfig | None = None, mask_phi: bool | None = None, **kwargs: Any) → int

Asynchronously export study records to Neo4j using the bound AsyncImednetSDK.

async export_to_snowflake(study_key: str, *, config: SnowflakeSinkConfig, mask_phi: bool | None = None) → int[source]
async export_to_snowflake(sdk: AsyncImednetFacade, study_key: str, *, config: SnowflakeSinkConfig, mask_phi: bool | None = None) → int

Asynchronously export study records to Snowflake using the bound AsyncImednetSDK.

class imednet_sinks.plugin.SinksNamespace[source]

Bases: object

Synchronous namespace for accessing data export sinks on ImednetSDK.sinks.

property AsyncMongoDbExportSink: type[imednet_sinks.document.AsyncMongoDbExportSink]

Asynchronous sink class for exporting records to MongoDB.

property AsyncNeo4jExportSink: type[imednet_sinks.graph.AsyncNeo4jExportSink]

Asynchronous sink class for exporting records to Neo4j.

property AsyncSnowflakeExportSink: type[imednet_sinks.warehouse.AsyncSnowflakeExportSink]

Asynchronous sink class for exporting records to Snowflake.

property MongoDbExportSink: type[imednet_sinks.document.MongoDbExportSink]

Synchronous sink class for exporting records to MongoDB.

property MongoDbSinkConfig: type[imednet_sinks.document.MongoDbSinkConfig]

Configuration class for MongoDB sinks.

property Neo4jExportSink: type[imednet_sinks.graph.Neo4jExportSink]

Synchronous sink class for exporting records to Neo4j.

property Neo4jSinkConfig: type[imednet_sinks.graph.Neo4jSinkConfig]

Configuration class for Neo4j sinks.

property SnowflakeExportSink: type[imednet_sinks.warehouse.SnowflakeExportSink]

Synchronous sink class for exporting records to Snowflake.

property SnowflakeSinkConfig: type[imednet_sinks.warehouse.SnowflakeSinkConfig]

Configuration class for Snowflake sinks.

__init__(sdk)[source]

Initialize the synchronous sinks namespace.

Parameters:

sdk (ImednetFacade | AsyncImednetFacade) –

Return type:

None

export_to_mongodb(study_key: str, uri: str = '', database: str = '', collection: str = '', *, config: MongoDbSinkConfig | None = None, mask_phi: bool | None = None, **kwargs: Any) → int[source]
export_to_mongodb(sdk: ImednetFacade, study_key: str, uri: str = '', database: str = '', collection: str = '', *, config: MongoDbSinkConfig | None = None, mask_phi: bool | None = None, **kwargs: Any) → int

Export study records to MongoDB using the bound synchronous SDK instance.

export_to_neo4j(study_key: str, uri: str = '', auth: tuple[str, str] = ('', ''), *, config: Neo4jSinkConfig | None = None, mask_phi: bool | None = None, **kwargs: Any) → int[source]
export_to_neo4j(sdk: ImednetFacade, study_key: str, uri: str = '', auth: tuple[str, str] = ('', ''), *, config: Neo4jSinkConfig | None = None, mask_phi: bool | None = None, **kwargs: Any) → int

Export study records to Neo4j using the bound synchronous SDK instance.

export_to_snowflake(study_key: str, *, config: SnowflakeSinkConfig, mask_phi: bool | None = None) → int[source]
export_to_snowflake(sdk: ImednetFacade, study_key: str, *, config: SnowflakeSinkConfig, mask_phi: bool | None = None) → int

Export study records to Snowflake using the bound synchronous SDK instance.

imednet_sinks.plugin.create_sinks(sdk: AsyncImednetFacade) → AsyncSinksNamespace[source]
imednet_sinks.plugin.create_sinks(sdk: ImednetFacade) → SinksNamespace
imednet_sinks.plugin.create_sinks(sdk: ImednetFacade | AsyncImednetFacade) → SinksNamespace | AsyncSinksNamespace

Factory function returning AsyncSinksNamespace or SinksNamespace for sdk.

imednet_sinks.warehouse module

Snowflake warehouse export sink.

This module implements the warehouse export path for a Snowflake destination. Study records are:

  1. Written to Parquet files in a local staging directory (one file per batch).

  2. Uploaded to the configured Snowflake internal stage via PUT.

  3. Bulk-loaded into the target table with COPY INTO ... FROM @<stage>.

This two-phase approach decouples data preparation from bulk ingestion, allows the Parquet files to be independently audited or re-uploaded, and leverages Snowflake’s native columnar loader for best throughput.

Manifest

After each successful COPY INTO, a manifest entry is appended to SinkConfig.extra["manifest_path"] (if provided):

{
    "batch_id":   "MYSTUDY/FORM1/0",
    "stage_path": "@MY_STAGE/imednet/MYSTUDY/FORM1/batch_0.parquet",
    "row_count":  500,
    "loaded_at":  "2024-01-15T12:00:00Z"
}

Optional dependencies

  • snowflake-connector-python (pip install 'imednet[snowflake]')

  • pyarrow (included in imednet[snowflake])

Both are imported lazily at connection / write time.

Idempotency

When SinkConfig.idempotent is True (default) the sink overwrites staged Parquet files (PUT ... OVERWRITE = TRUE), bulk-loads each batch into a temporary staging table, and executes MERGE INTO keyed on (study_key, record_id) so that modified Study Records update in place without creating duplicate rows. Set idempotent = False to load batches directly into the target table via COPY INTO ... FORCE = TRUE.

Usage

import os
from imednet import ImednetSDK
from imednet.spi.sink_base import iter_batches
from imednet_sinks 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="MYSTUDY"))

config = SnowflakeSinkConfig(
    study_key="MYSTUDY",
    account="myorg-myaccount",
    user="loader",
    password=os.environ["SNOWFLAKE_PASSWORD"],  # keep credentials out of source code
    database="IMEDNET_DB",
    schema="PUBLIC",
    warehouse="COMPUTE_WH",
    stage="MY_STAGE",
    table="RECORDS",
    stage_prefix="imednet",
    local_staging_dir="/tmp/imednet_stage",
)
with SnowflakeExportSink(config=config) as sink:
    for i, batch in enumerate(iter_batches(records, config.batch_size)):
        sink.write_batch(batch, batch_id=f"MYSTUDY/FORM1/{i}")
class imednet_sinks.warehouse.AsyncSnowflakeExportSink[source]

Bases: AsyncExportSink

Asynchronously stage Parquet files and bulk-load them into Snowflake without blocking the event loop.

__init__(config)[source]

Initialize the asynchronous Snowflake export sink.

Parameters:

config (SnowflakeSinkConfig) –

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

async close()[source]

Asynchronously close the Snowflake connection and clean up temporary staging files.

Return type:

None

async flush()[source]

No-op: each batch is committed individually.

Return type:

None

async reconcile_deleted(records, *, batch_id)[source]

Asynchronously 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

async write_batch(records, *, batch_id)[source]

Asynchronously stage records to Parquet and execute Snowflake PUT + MERGE INTO/COPY INTO.

Parameters:
  • records (Sequence[Any]) –

  • batch_id (str) –

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

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

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

Asynchronously export study records to Snowflake using AsyncSnowflakeExportSink.

Parameters:
Return type:

int

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