Many data teams end up with one of two extremes. Either everything lives in a large Python codebase that also does joins and business logic, or everything is pushed into an ETL tool that is hard to test and version. Both become difficult to maintain.
A cleaner approach is to give each tool the job it is best at:
- Python handles input and output: connecting to SQL Server, streaming changed rows, writing compressed Parquet, and uploading files to object storage.
- dbt handles transformation inside Snowflake: de-duplicating, applying changes, and building analytics-ready models as version-controlled, tested SQL.
This article shows a working blueprint for that split, building on the extraction and loading patterns from Extracting Changes from Billion-Row Tables Without Slowing Production and Loading SQL Server Changes into Snowflake the Right Way.
Part 1: The Python extraction script
The script reads the last watermark, fixes a safe upper bound with MIN_ACTIVE_ROWVERSION(), streams changes in chunks, writes each chunk as a Parquet file, uploads it, and only then saves the new watermark.
# extract.py
from datetime import datetime, timezone
import os
import boto3
import pandas as pd
import pyodbc
SQL_CONN_STR = os.environ["SQL_SERVER_CONN_STR"] # injected at runtime, never hard-coded
STAGE_BUCKET = os.environ["LANDING_BUCKET"]
TABLE_NAME = "LargeInventoryTable"
CHUNK_SIZE = 50_000
def get_last_watermark(cursor, table_name: str) -> bytes:
cursor.execute(
"SELECT LastVersion FROM dbo.EtlWatermark WHERE TableName = ?", table_name
)
row = cursor.fetchone()
return row[0] if row else b"\x00" * 8
def update_watermark(cursor, table_name: str, version: bytes) -> None:
cursor.execute(
"UPDATE dbo.EtlWatermark SET LastVersion = ? WHERE TableName = ?",
version, table_name,
)
cursor.commit()
def run_extraction() -> int:
conn = pyodbc.connect(SQL_CONN_STR)
cursor = conn.cursor()
s3 = boto3.client("s3") # credentials come from the runtime IAM role
last_ver = get_last_watermark(cursor, TABLE_NAME)
cursor.execute("SELECT MIN_ACTIVE_ROWVERSION();")
max_safe_ver = cursor.fetchone()[0]
query = f"""
SELECT ItemID, ItemName, Quantity,
CAST(RowVer AS BIGINT) AS RowVerNumeric
FROM dbo.{TABLE_NAME}
WHERE RowVer > ? AND RowVer < ?
ORDER BY RowVer
"""
run_ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
files_written = 0
for idx, chunk in enumerate(
pd.read_sql(query, conn, params=[last_ver, max_safe_ver], chunksize=CHUNK_SIZE)
):
if chunk.empty:
break
filename = f"{TABLE_NAME}_{run_ts}_{idx:05d}.parquet"
local_path = f"/tmp/{filename}"
chunk.to_parquet(local_path, compression="snappy", index=False)
s3.upload_file(local_path, STAGE_BUCKET, f"landing/{TABLE_NAME}/{filename}")
os.remove(local_path)
files_written += 1
# Advance the watermark only after every file is safely in storage
update_watermark(cursor, TABLE_NAME, max_safe_ver)
conn.close()
return files_written
A few choices here are deliberate:
- Parameterised queries. The watermark values are passed as parameters rather than formatted into the SQL string.
- Streaming with
chunksize. Pandas reads the result set in pieces, so memory use stays flat however many rows changed. - Watermark last. If the script fails during an upload, the watermark stays where it was and the next run repeats the same range. Combined with the newer-version guard in Snowflake, a repeated range is harmless.
- Returning the file count. The orchestration layer in From Cron Jobs to Containers: Running Data Pipelines on AWS uses this to skip the dbt run when there is nothing new.
Part 2: Getting files into Snowflake
There are two ways to make the landed files available to dbt.
For small volumes or prototypes, a dbt view can query the external stage directly. It’s quick to set up, but every run reads every file in the stage folder, so performance degrades as files accumulate.
For production, load the files into a raw table with COPY INTO (shown in Loading SQL Server Changes into Snowflake the Right Way), or let Snowpipe load them automatically as they arrive. COPY INTO remembers which files it has already loaded, and its PURGE = TRUE option can remove files from the stage after a successful load if you don’t want to keep them in the landing zone.
The rest of this article assumes a raw table, raw.inventory_raw, declared as a dbt source.
# models/sources.yml
version: 2
sources:
- name: raw
schema: raw
tables:
- name: inventory_raw
Part 3: The dbt incremental model
dbt’s incremental materialisation with the merge strategy generates the MERGE statement for you and runs it on each execution.
-- models/inventory.sql
{{ config(
materialized='incremental',
unique_key='item_id',
incremental_strategy='merge'
) }}
with source_rows as (
select item_id, item_name, quantity, row_version
from {{ source('raw', 'inventory_raw') }}
{% if is_incremental() %}
-- Only consider changes newer than anything already applied
where row_version > (select coalesce(max(row_version), 0) from {{ this }})
{% endif %}
),
latest as (
select *
from source_rows
qualify row_number() over (partition by item_id order by row_version desc) = 1
)
select item_id, item_name, quantity, row_version
from latest
Why this works:
- The incremental filter limits each run to rows newer than the highest version already in the target. Because SQL Server’s
rowversioncomes from a single database-wide counter, any genuinely new change for any key has a higher value than everything loaded before. Older or replayed rows are filtered out before the merge. - The
qualifyclause keeps one row per key, so the merge never sees duplicates. unique_keytells dbt which column to match on in the generatedMERGE.
If the table grows to multiple terabytes, you can add cluster_by=['item_id'] to the config. For smaller tables, leave it out.
Add dbt tests for the guarantees you care about, for example unique and not_null on item_id, so a broken load fails loudly instead of quietly.
Why this split pays off
- Each tool does what it is good at. Python handles networks, drivers and files. Snowflake handles large set-based transformations.
- Business logic is testable and reviewable. dbt models live in Git, go through pull requests, and have automated tests and generated documentation.
- Failures are contained. An extraction problem never leaves the warehouse half-updated, and a transformation problem never loses extracted data, because the files are still in the landing zone.
Next steps
If your transformations are buried in scripts or a legacy ETL tool, moving them into dbt is often the change that makes a data team faster. YenDigital helps teams set up dbt projects, migrate existing logic, and establish testing and deployment practices.
