Tonight the load for 1 October fails halfway, and whoever is on duty runs it once more. The next morning sales still holds 2 rows for that date, not 4, and the log says what happened. That's what you build in this lesson: a data pipeline in Python, one script that runs extract, transform and load for one date, records what happened, and is safe to run again. It's like the shop's cash book, filled in every night by whoever is on the late shift. The method is written on a sheet taped to the wall: take that day's receipts, throw out the doubled ones, write the total on that date's page. If it turns out wrong, that date's page is erased and written again, not added to underneath. The sheet on the wall is the script; the page per date is a partition in the warehouse.
The pipeline's shape
| Step | Function in pipeline.py |
At Bookshop |
|---|---|---|
| Extract | extract(order_date) |
SQL against the app's database, one day of orders |
| Transform | transform(df) |
pandas: drop doubled lines, empty cities, catalogue price, week |
| Load | load(df, order_date) |
the sales table in the DuckDB warehouse warehouse.duckdb |
Bookshop's app database is MySQL. So that it runs on a laptop with no server, the source here is a SQLite file, shop.db, holding exactly the same tables. In production you only change how you connect (through PyMySQL or SQLAlchemy, say); the query stays. The libraries come from pip install pandas duckdb (pandas 3.0.6, DuckDB 1.5.6). The script is one file, covered part by part.
Config from the environment
import argparse
import logging
import os
import sqlite3
import time
from datetime import date, timedelta
import duckdb
import pandas as pd
# Configuration from environment variables, not written in the code
SOURCE_DB = os.environ.get("SOURCE_DB", "shop.db")
WAREHOUSE_DB = os.environ.get("WAREHOUSE_DB", "warehouse.duckdb")
ATTEMPTS = int(os.environ.get("ATTEMPTS", "3"))
log = logging.getLogger("pipeline")
- An environment variable is a value handed to the program from outside, for example
SOURCE_DB=wrong.db python pipeline.py 2026-10-02.os.environ.get("SOURCE_DB", "shop.db")reads it, or falls back to the default when it's absent. - A laptop and a server just differ in their environment; the script is the same. The database password comes in this way too, so it never ends up in git.
logging.getLogger("pipeline")makes a logger. Unlikeprint, every log line has a time and a level:INFOfor ordinary news,WARNINGfor things someone should look at.
Extract with retries
EXTRACT_SQL = """
SELECT oi.id AS item_id, oi.order_id, oi.book_id, o.created_at,
c.city, b.title, oi.qty, oi.price AS paid_price, b.price AS catalog_price
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN customers c ON c.id = o.customer_id
JOIN books b ON b.id = oi.book_id
WHERE o.created_at >= ? AND o.created_at < ?
"""
def extract(order_date: date) -> pd.DataFrame:
tomorrow = order_date + timedelta(days=1)
for attempt in range(1, ATTEMPTS + 1):
try:
con = sqlite3.connect(f"file:{SOURCE_DB}?mode=ro", uri=True)
try:
df = pd.read_sql_query(EXTRACT_SQL, con, params=(order_date.isoformat(), tomorrow.isoformat()))
finally:
con.close()
log.info("extract %s, rows: %d", order_date, len(df))
return df
except sqlite3.OperationalError as e:
if attempt == ATTEMPTS:
raise
wait = 2 ** (attempt - 1)
log.warning("extract failed (%s), attempt %d of %d, retrying in %ds", e, attempt, ATTEMPTS, wait)
time.sleep(wait)
created_at >= order_date AND created_at < tomorrowtakes one whole day. Written this way (notdate(created_at) = ...), the query runs the same on MySQL and can use an index.?is a placeholder: the value travels throughparamsinstead of being pasted into the SQL string, so it's safe from SQL injection and quoting trouble. In PyMySQL the placeholder is%s.mode=roopens the source read-only: the pipeline can't change the app's database.- Retry: when connecting fails, wait 1 second, then 2, then give up. Waits that keep growing like this are called exponential backoff. The last attempt throws its error upward (
raise), so the script stops with exit code 1.
Transform with pandas
def transform(df: pd.DataFrame) -> pd.DataFrame:
for row in df[df["paid_price"] != df["catalog_price"]].itertuples():
log.warning("item %d: paid price %d, catalogue %d", row.item_id, row.paid_price, row.catalog_price)
clean = df.drop_duplicates(subset=["order_id", "book_id"])
if len(clean) < len(df):
log.warning("doubled rows dropped: %d", len(df) - len(clean))
created = pd.to_datetime(clean["created_at"])
return pd.DataFrame({
"order_id": clean["order_id"],
"book_id": clean["book_id"],
"order_date": created.dt.date,
"week": created.dt.to_period("W").dt.start_time.dt.date,
"city": clean["city"].fillna("Unknown"),
"title": clean["title"],
"qty": clean["qty"],
"price": clean["catalog_price"],
})
These are the steps from the pandas lesson, plus two checks that log a WARNING: a paid price that differs from the catalogue (item 16), and doubled lines (item 9). The function only takes a DataFrame and returns one, so it's easy to test without a database.
Checks like these can be made tidier with a validation library: Pydantic checks each record against a schema (types and rules per field), Great Expectations checks a whole table with declarative rules such as "price must be between 1 and 100". The details are in the Data Quality & Validation lesson.
Load: delete that date, then fill it
def load(df: pd.DataFrame, order_date: date) -> None:
con = duckdb.connect(WAREHOUSE_DB)
try:
con.execute("""
CREATE TABLE IF NOT EXISTS sales (
order_id INTEGER, book_id INTEGER, order_date DATE, week DATE,
city VARCHAR, title VARCHAR, qty INTEGER, price INTEGER)
""")
con.register("new_rows", df)
con.begin()
con.execute("DELETE FROM sales WHERE order_date = ?", [order_date])
con.execute("INSERT INTO sales SELECT * FROM new_rows")
con.commit()
total = con.execute("SELECT COUNT(*) FROM sales").fetchone()[0]
log.info("load %s, rows: %d, sales total: %d", order_date, len(df), total)
finally:
con.close()
con.register("new_rows", df)lets DuckDB's SQL read the DataFrame as a table namednew_rows.begin(),DELETEthat date,INSERT,commit(): one transaction. If theINSERTfails, the connection closes without acommit, and DuckDB undoes theDELETE.- This is what makes the pipeline idempotent: however many times it runs, the end result is the same.
A CLI and backfills
def run(order_date: date) -> None:
load(transform(extract(order_date)), order_date)
def main() -> None:
parser = argparse.ArgumentParser(description="Bookshop's daily sales load")
parser.add_argument("order_date", type=date.fromisoformat, help="order date, YYYY-MM-DD")
parser.add_argument("--until", type=date.fromisoformat, help="last date, for a backfill")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", datefmt="%H:%M:%S")
day = args.order_date
while day <= (args.until or args.order_date):
run(day)
day += timedelta(days=1)
if __name__ == "__main__":
main()
- The date is an argument, not "yesterday" worked out from the computer's clock. So any date can be loaded again, including filling many old dates at once: a backfill.
type=date.fromisoformatchecks the date.python pipeline.py 2026-10-32is refused witherror: argument order_date: invalid fromisoformat value: '2026-10-32'.
Running it:
$ python pipeline.py 2026-10-01
21:24:23 INFO extract 2026-10-01, rows: 3
21:24:23 WARNING doubled rows dropped: 1
21:24:23 INFO load 2026-10-01, rows: 2, sales total: 2
$ python pipeline.py 2026-10-01
21:24:24 INFO extract 2026-10-01, rows: 3
21:24:24 WARNING doubled rows dropped: 1
21:24:24 INFO load 2026-10-01, rows: 2, sales total: 2
$ python pipeline.py 2026-09-28 --until 2026-10-09
21:24:25 INFO extract 2026-09-28, rows: 3
21:24:25 INFO load 2026-09-28, rows: 3, sales total: 5
...
21:24:25 INFO extract 2026-10-03, rows: 0
21:24:25 INFO load 2026-10-03, rows: 0, sales total: 9
...
21:24:25 INFO extract 2026-10-07, rows: 1
21:24:25 WARNING item 16: paid price 190, catalogue 19
21:24:25 INFO load 2026-10-07, rows: 1, sales total: 15
...
21:24:26 INFO load 2026-10-09, rows: 1, sales total: 18
The second run still has 2 rows, because the DELETE throws away the first run's rows before the INSERT. The 12-date backfill ends at 18 rows, 21 books, $444, the same as every earlier lesson; 1 October is loaded once more without doubling. 3 October had no orders: 0 rows is normal, not an error. Remove the DELETE from the script and the second run of 1 October logs sales total: 4.
When the source can't be opened:
$ SOURCE_DB=wrong.db python pipeline.py 2026-10-02
21:24:26 WARNING extract failed (unable to open database file), attempt 1 of 3, retrying in 1s
21:24:27 WARNING extract failed (unable to open database file), attempt 2 of 3, retrying in 2s
Traceback (most recent call last):
...
sqlite3.OperationalError: unable to open database file
$ echo $?
1
That exit code 1 matters: cron or Airflow (the next lesson) knows the run failed and can tell someone.
⚠️ Scripts that look fine but cause trouble
- A load that only adds.
df.to_sql("sales", engine, if_exists="append")or anINSERTwith noDELETE: a rerun after an error doubles the numbers. Delete the partition first, or upsert. - Retrying every error. A misspelt column name doesn't heal by trying again. In this script, pandas wraps SQL errors as
pandas.errors.DatabaseError: Execution failed on sql ..., notsqlite3.OperationalError, so it stops at once with no retry. Check which error you are catching. - A date from the computer's clock. A script using
date.today() - 1can only fill yesterday. Take the date as an argument. - Swallowing errors.
except Exception: log.error(...)and carrying on gives exit code 0, and the scheduler thinks all is well. Let the script fail clearly.
TL;DR: Bookshop's Python pipeline is one pipeline.py: extract with parameterised SQL (?) against the app's database for one date, transform with pandas (drop doubles, fill empty cities, catalogue price, week), load into sales in DuckDB with a DELETE of that date then an INSERT in one transaction, so a rerun still leaves 2 rows for 1 October. Config comes from environment variables (SOURCE_DB, WAREHOUSE_DB), each step is recorded by logging with a time and a level, extract is retried with 1 and 2 second backoff and then fails with exit code 1, and the date is a CLI argument so the backfill 2026-09-28 --until 2026-10-09 fills 18 rows. Validation can be tidied up with Pydantic (per record) or Great Expectations (per table).
⚡ Three functions, one date
Meaning: pipeline.py runs extract(order_date), transform(df), then load(df, order_date) for one date. The date is a CLI argument, not "yesterday" from the computer's clock, so any date can be loaded again, backfills included.
⚡ Config from the environment
Write:
SOURCE_DB = os.environ.get("SOURCE_DB", "shop.db")
Meaning: The value comes from an environment variable, or "shop.db" when it's absent. A laptop and a server just differ in their environment; the script is the same.
⚡ Delete that date, then fill it
Write:
con.begin()
con.execute("DELETE FROM sales WHERE order_date = ?", [order_date])
con.execute("INSERT INTO sales SELECT * FROM new_rows")
con.commit()
Guess first: 1 October is loaded twice. How many rows for that date are in sales?
Still 2. The DELETE throws away the first run's rows before the INSERT. Without the DELETE, it's 4.
Meaning: An idempotent pipeline: however many times it runs, the result is the same, with no duplicated data.
⚡ Fail clearly
Meaning: The extract is retried after 1 and then 2 seconds, then the script stops with exit code 1. That way cron or Airflow knows the run failed. Don't swallow errors with except Exception.