Skip to main content

Snowflake Destination

INSERT (append) or MERGE (upsert) rows into Snowflake tables using snowflake-connector-python.

YAML Example​

destination:
type: snowflake
account_env: SF_ACCOUNT # e.g. "acct.us-east-1.aws"
user_env: SF_USER
password_env: SF_PASSWORD
database: ANALYTICS
schema: PUBLIC # YAML key — model field is schema_
table: USER_SCORES
warehouse: COMPUTE_WH
mode: merge # "insert" (default) | "merge"
upsert_key: [id] # required when mode: merge

Configuration​

FieldTypeDefaultDescription
type"snowflake"—Required
account_envstring—Env var holding the Snowflake account identifier (e.g. acct.us-east-1.aws). Required
user_envstring—Env var holding the username. Required
password_envstring | nullnullEnv var holding the password. One of password_env / private_key_env is required.
private_key_envstring | nullnullEnv var holding the PEM (PKCS#8) private key contents for key-pair auth (#737) — the path for TYPE = SERVICE users. Takes precedence over password_env.
private_key_passphrase_envstring | nullnullEnv var holding the private key passphrase, if the key is encrypted.
databasestring—Database name. Required
schemastring—Schema name (YAML key; model field is schema_ to avoid colliding with BaseModel.schema() under mypy strict). Required
tablestring—Target table name. Required
warehousestring—Warehouse to use for the connection. Required
mode"insert" | "merge""insert"Write strategy on the destination side. insert = append; merge = upsert via staging-table-plus-MERGE (requires upsert_key). Orthogonal to sync.mode.
upsert_keylist[str] | nullnullColumns to match on in the MERGE INTO ... USING ... ON clause. Required when mode: merge.
lookupsdict | nullnullFK resolution against the destination (same shape as Postgres/MySQL/ClickHouse — see Destination Lookup). Added in v0.7.9 (#468).

The YAML key is schema: for ergonomics, but the model field on SnowflakeDestinationConfig is schema_ (alias) — BaseModel.schema() is a built-in pydantic method that would otherwise shadow a plain schema attribute under mypy strict mode.

Authentication​

Key-pair (recommended): new Snowflake accounts enforce MFA on password sign-ins, so programmatic access should use a TYPE = SERVICE user with an RSA key pair. Generate a key, register the public half on the user, and point private_key_env at an env var holding the PEM private key contents:

openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out sf_key.p8 -nocrypt
openssl rsa -in sf_key.p8 -pubout # → RSA_PUBLIC_KEY value (strip the PEM headers)
export SF_PRIVATE_KEY="$(cat sf_key.p8)"
CREATE USER drt_writer TYPE = SERVICE DEFAULT_ROLE = ...;
ALTER USER drt_writer SET RSA_PUBLIC_KEY = 'MII...';
destination:
type: snowflake
account_env: SF_ACCOUNT
user_env: SF_USER
private_key_env: SF_PRIVATE_KEY # wins over password_env when both are set
...

Password (legacy): still supported via password_env for human-type users / older accounts, but Snowflake is deprecating password-only sign-ins — expect it to stop working for non-MFA users.

Both paths apply to the source profile too (private_key_env on the snowflake profile in ~/.drt/profiles.yml). OAuth is not yet supported.

Common Patterns​

Insert mode (append)​

destination:
type: snowflake
mode: insert # default — can omit
...
sync:
mode: full # or "incremental"

Each row is INSERTed individually into <database>.<schema>.<table>. Use this when the destination table tolerates duplicates (e.g. append-only event tables) or when deduplication happens downstream.

Merge mode (upsert)​

destination:
type: snowflake
mode: merge
upsert_key: [id]
...

drt issues MERGE INTO <target> USING (SELECT ... FROM (VALUES ...) AS t(...)) ON <upsert_key> — the batch's rows are inlined directly into the MERGE's source, in chunks sized to stay under a verified-safe bind-parameter budget (no separate staging table since #988; see that issue for the live-account measurements behind the chunk size). A chunk that fails outright falls back to one MERGE per row within it, so a single bad row doesn't take down the rest of its chunk.

Requirements:

  • upsert_key columns identify a logical primary key — drt's ON clause uses them verbatim.
  • The destination user needs INSERT, UPDATE, and MERGE privileges on the target schema — no CREATE TABLE of any kind, unlike before #988.

Mirror mode (differential delete, #340 Step 4 — v0.7.7+)​

destination:
type: snowflake
# config.mode here can be left at the default ("insert") — sync.mode:
# mirror forces the MERGE write path regardless. You only need to set
# the upsert_key.
upsert_key: [employee_id]
...
sync:
mode: mirror

Mirror forces the MERGE write path regardless of config.mode — mirror semantics intrinsically require upsert, so users only need to set destination.upsert_key and sync.mode: mirror. Each batch is MERGEd into the target (same as mode: merge); at end-of-sync finalize_sync issues a single DELETE FROM <database>.<schema>.<table> WHERE key NOT IN (collected) that removes destination rows whose upsert_key was not observed in the source.

finalize_sync also drives the replace_strategy: swap atomic SWAP (#434, see Replace mode); for insert / merge / truncate-replace it returns None and the engine's existing dispatch is unchanged.

The Snowflake connector uses %s placeholders (same family as psycopg2 / pymysql) and does not auto-expand a tuple-of-tuples, so the DELETE placeholder shape is built explicitly, identical to MySQL Step 2:

  • single-column form: DELETE FROM <table_fq> WHERE col NOT IN (%s, %s, ...) with a flat values list
  • composite form: DELETE FROM <table_fq> WHERE (c1, c2) NOT IN ((%s, %s), (%s, %s), ...) with values flattened row-major

Mirror is appropriate when rows disappearing from the source should disappear from the destination — master tables (employees / SKUs / permissions) where deletions need to propagate without the full-table rebuild cost of replace mode (see Replace mode for that path).

Comparison:

ModeNew rowsUpdated rowsRemoved-from-source rowsCost shape
upsert / full + config.mode: mergeMERGEMERGEstay in destinationMERGE per batch
upsert / full + config.mode: insertINSERTINSERT (duplicate)stay in destinationINSERT per row
mirror (forces MERGE)MERGEMERGEDELETEd by upsert_key NOT IN (...)MERGE per batch + 1 DELETE

Safety guards:

  • Empty source short-circuit — if no batch ever delivered records, the DELETE is skipped. A transient empty source (auth failure mid-extract, vendor outage) cannot wipe the destination.
  • Failed rows excluded from the key set — only successfully merged keys count as "observed source state"; a row that failed to merge won't cause its destination counterpart to be deleted.
  • upsert_key required at load time — load() raises ValueError before any INSERT touches Snowflake when mirror mode is requested without a populated upsert_key. Fail-fast.
  • Composite keys supported — upsert_key: [tenant_id, user_id] produces WHERE (tenant_id, user_id) NOT IN (...).
  • Run-time change guards — with sync.guards.max_deletes / max_delete_pct set, the final mirror DELETE runs inside an explicit BEGIN (Snowflake otherwise autocommits), drt judges the driver's actual affected-row count, and ROLLBACKs if a guard trips; otherwise it COMMITs. An unknown row count refuses instead of reading as zero. The tracked-state rewrite starts only after the guard passes. Replace-swap compares live keys absent from the shadow table before SWAP WITH; Snowflake has no table lock, so a concurrent writer to the shadow between the count and the swap is a documented residual. drt run --force-guards proceeds and records the override. No delete guards means no extra SQL.

Memory constraint: the in-process key set is memory-bound to source key cardinality. Mirror as shipped today is appropriate for small/medium reference tables.

Same sync.mode: mirror is supported on Postgres (Step 1), MySQL (Step 2), and ClickHouse (Step 3). BigQuery follows once contributor PR #584 lands.

Tracked mirror (mirror.strategy: tracked, #686/#692) — for tables the application also writes to:

sync:
mode: mirror
mirror:
strategy: tracked # default: "destination" (the NOT IN behaviour above)

Same Census-style semantics as Postgres/MySQL (see the Postgres tracked-mirror section for the full write-up): drt persists the set of upsert_key tuples it has itself synced in a drt-managed <database>.<schema>._drt_synced_keys table, and each run deletes only previously-synced − current-source keys — rows drt never wrote are never deletion candidates. First run baselines (WARN, no deletes); lost/missing state re-baselines the same way.

The state table uses the same sync_name / key_hash / key_json shape as Postgres/MySQL, created lazily via CREATE TABLE IF NOT EXISTS, pre-provisioning-friendly the same way (SHOW TABLES LIKE '_drt_synced_keys' IN SCHEMA <database>.<schema> stands in for to_regclass/information_schema.tables, mirroring the existence check _target_exists already uses for the replace-swap path). No PRIMARY KEY enforcement gotcha to worry about here beyond the usual Snowflake caveat that primary keys are informational, not enforced — drt controls the INSERT/DELETE pairing itself and never relies on a uniqueness constraint to reject a duplicate.

Tracked mirror's state-diff step uses a temporary staging table for a server-side diff when the role has schema-level CREATE TABLE; that privilege is optional there — a role limited to the target and pre-provisioned state tables transparently falls back to a client-side diff for that step, at the cost of reading that sync's tracked-key state into process memory (#987). The write path itself no longer needs CREATE TABLE either (#988, see Merge mode above) — sync.mode: mirror, tracked or not, is now genuinely no-DDL end to end on Snowflake for a role with only INSERT/UPDATE/MERGE/DELETE on the target and pre-provisioned state tables.

Scoped mirror (mirror.scope, #687/#692): scope: [parent_id] restricts the mirror DELETE to rows whose scope values appeared in this run's source — the fit for 1:N regeneration. Composable with strategy: tracked (#694) provided scope is a subset of upsert_key. See the Postgres scoped-mirror section for the full semantics — identical on Snowflake, built on the same explicit-placeholder DELETE shape (single-column IN (%s, %s, ...) / composite (c1, c2) IN ((%s, %s), ...)) already used for the plain mirror DELETE above.

Replace mode (#434)​

sync.mode: replace rebuilds the destination table from the current source snapshot. Two strategies:

replace_strategy: truncate (default) — TRUNCATE TABLE once at the start of the sync, then INSERT every batch.

sync:
mode: replace # replace_strategy defaults to truncate

replace_strategy: swap — zero-downtime via Snowflake's atomic ALTER TABLE … SWAP WITH. drt builds a shadow table <table>__drt_swap with CREATE OR REPLACE TABLE … LIKE <table> (which carries clustering keys), writes every batch into the shadow, then at end-of-sync swaps the shadow over the original in a single atomic step and drops the old table. Readers see either the full old table or the full new table — never an empty or half-written one.

sync:
mode: replace
replace_strategy: swap
  • Grants are preserved — SWAP WITH exchanges the underlying objects, not the names, so role privileges (grants) on the original table name survive the swap. No grant re-application needed.
  • Clustering keys are carried by CREATE … LIKE — but masking / row-access policies and tags are not (the shadow is built fresh via LIKE, which doesn't copy them). If your target table relies on column policies, re-apply them after the swap or front the table with a policy-bearing view.
  • First run (target table doesn't exist yet) falls through to a direct write into the target and skips the swap.
  • Interrupted swaps leave a <table>__drt_swap shadow; drt clean --orphans lists and drops them (only __drt_swap-suffixed tables are eligible).

Swap requires mode: replace (enforced by config validation). The same replace_strategy: swap is supported on Postgres, MySQL, and ClickHouse.

Semi-structured columns (VARIANT / OBJECT / ARRAY)​

dict and list values bound for a Snowflake VARIANT / OBJECT / ARRAY column can't be inserted as plain parameters — Snowflake needs them parsed with PARSE_JSON. By default (introspect_schema: true) drt reads INFORMATION_SCHEMA.COLUMNS for the target table once per sync, detects the semi-structured columns, and rewrites the INSERT to wrap them:

-- a VARIANT column "payload" is loaded as:
INSERT INTO db.schema.t (id, payload) SELECT %s, PARSE_JSON(%s)

so a dict/list lands as proper semi-structured data instead of a stringified repr — with no configuration. When no column needs wrapping, the INSERT is the unchanged VALUES (...) form. Introspection is best-effort: if information_schema isn't readable for the role, drt falls back to binding values directly. Disable with introspect_schema: false.

As a source — retry on transient extract failures (#766)​

When Snowflake is the source of a sync, opening the connection and running the model query are retried automatically (3 attempts, exponential backoff from 1s, capped at 60s). No configuration — it is always on, and separate from the sync.retry knobs that govern the load side.

Retried:

  • OperationalError — the connector's own class for network and service-availability trouble, including RevocationCheckError (a CRL/OCSP endpoint being unreachable) which is its subclass.
  • DatabaseError carrying errno 390114 — Authentication token has expired. Observed during the #654 real-warehouse smoke programme: a long extract outstays its session token, and re-connecting is precisely the fix. Before #766 this failed the entire sync.

Not retried: ProgrammingError — SQL compilation errors, a missing table, insufficient privileges.

Note the 390114 check is gated on the exact DatabaseError class, not an isinstance against it: ProgrammingError is also a DatabaseError subclass in this driver, so a base-class check would retry every SQL typo. This is exactly why drt classifies with a predicate rather than a tuple of exception types — 390114 and a permanent error can be the very same class.

⚠️ Scope: connection + query execution + fetching the result set only. An expired token or an unavailable warehouse on the way in is retried. A failure after the first row has been yielded is not retried and fails the sync — those rows are already loaded into the destination and cannot be un-sent. See API_REFERENCE.

As a source — streaming extraction (#765)​

Rows are read by iterating the cursor in fetch_size batches rather than buffered whole with fetchall(), so peak memory tracks the batch instead of the result set.

# ~/.drt/profiles.yml
sf:
type: snowflake
account: xy12345.us-east-1
user: analyst
private_key_env: SNOWFLAKE_PRIVATE_KEY
database: ANALYTICS
schema: PUBLIC
warehouse: COMPUTE_WH
fetch_size: 10000 # rows per round trip (default: 10000)

Memory scales with fetch_size x row width, not with the number of rows — lower it for very wide rows (large VARIANT/OBJECT columns), not for big tables.

⚠️ The connection is held open for the whole load, not just the extract: the result set lives server-side until consumed. A slow destination therefore keeps a Snowflake session — and its warehouse — busy for the duration, which is worth knowing if you are billing on warehouse uptime. Per #766 a failure after the first row has been yielded is not retried.

As a source — diff-based incremental (#1112)​

Snowflake supports sync.incremental_strategy: diff for models without a reliable cursor column. Each run materializes the full model result in _drt_snapshot_<sync_name>_<digest> under the source profile's managed_schema, then classifies added, changed, and removed rows with server-side joins on destination.upsert_key. Added and changed rows follow the normal upsert path; removed keys are available in SyncResult.diff_removed_keys, power mirror.strategy: diff, and appear in --dry-run --diff deletion previews.

# ~/.drt/profiles.yml
sf:
type: snowflake
account: xy12345.us-east-1
user: analyst
private_key_env: SNOWFLAKE_PRIVATE_KEY
database: ANALYTICS
schema: PUBLIC
warehouse: COMPUTE_WH
managed_schema: _drt # default; drt needs table create/drop here
destination:
type: snowflake
# ... connection fields ...
mode: merge
upsert_key: [id]

sync:
mode: upsert # or mirror
incremental_strategy: diff
diff:
hash_columns: all # or an explicit non-empty column list

hash_columns: all hashes every model output column except the upsert key. An explicit list is validated against the actual output columns and a typo fails loudly. Snowflake's native typed HASH(...) is used directly, so NULL and an empty string are different changes without casting values through session-dependent text formats.

The new snapshot becomes the baseline only after a non-dry-run sync completes with zero row failures. Existing baselines are promoted with Snowflake's atomic ALTER TABLE ... SWAP WITH; scratch is rebuilt with CREATE OR REPLACE, so an interrupted extract or a crash around promotion does not wedge the next run. Cursor incremental remains the read-only-source option: diff requires write/create/drop privileges in managed_schema, or an administrator can pre-create and grant the schema following the same managed-table escape hatch used by warehouse-backed state.

Concurrent runs of the same diff sync are unsupported. Each scratch table is tagged with a per-run token in its Snowflake table comment; every classification stream checks the token before reading (and again after draining), and commit checks it immediately before SWAP/RENAME and on the promoted baseline afterward. If a second run has replaced the fixed-name scratch, the first run fails loudly instead of knowingly streaming or successfully reporting promotion of the second run's snapshot. Detection is deliberately best-effort: Snowflake DDL autocommits, so a narrow TOCTOU window remains between each token check and the following statement. drt does not hold a lock across extraction, destination writes, and commit because a row failure deliberately skips commit and could leak that lock in a long-running process. Use drt serve request coalescing (#854) or scheduler overlap protection. The concurrent-replacement detection is covered by a live dwh-smoke test (test_snowflake_diff_incremental_smoke.py) as well as unit tests.

Notes​

  • Requires pip install drt-core[snowflake] (uses snowflake-connector-python)
  • Query tagging (#768): every write query gets both a QUERY_TAG session parameter (set at connect, JSON payload — Snowflake's native cost-attribution mechanism, visible in QUERY_HISTORY.QUERY_TAG) and a leading /* drt app=drt sync=<name> run_id=<id> ... */ comment, by default — see query_tagging in docs/llm/API_REFERENCE.md.
  • Tables are addressed fully-qualified as <database>.<schema>.<table> (e.g. ANALYTICS.PUBLIC.USER_SCORES)
  • The schema: YAML key maps to schema_ on the model — see the model alias note above
  • upsert_key columns identify a logical primary key for mode: merge and sync.mode: mirror
  • Queryable (v0.7.9, #468): Snowflake is now wired into the query infrastructure used by Postgres/MySQL/ClickHouse, which unlocks three things — drt test validators (row_count, not_null, freshness, unique, accepted_values, query) run real queries against the target table; drt run --dry-run --diff produces a true record-level diff instead of falling back to sample mode; and lookups FK resolution works. Test/diff queries address the table fully-qualified (<database>.<schema>.<table>).
  • --dry-run is honoured — destination.load() is never called when dry_run is on