Git for pipelines
Part of the free LogicWiz Data Engineering course, Module 10: Working like an engineer. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:05 on Monday. Tess opens the revenue dashboard and June is 12% lower than it was on Friday. Nothing failed overnight. On Friday someone edited the revenue query straight on the production server: "only a small filter". Now nobody can say what changed, who changed it, or what it looked like before.
You'll learn to
- Make a change through a branch, a pull request and a review
- Read a diff, and compare what two versions of a query return
- Explain what Git stores, and why big data files hurt it
- Keep secrets and data out of Git
Learn
Friday's edit left no trace
The query on the server was the only copy. When someone typed over it on Friday, the old version was gone.
Git fixes exactly this. It keeps every version of every file in a project. Each saved change is called a commit, and it records who made it, when, and why. Think of a lab notebook: pages are added, never torn out.
With the revenue query in Git, each of Monday's questions is one command:
- What changed?
git diff - Who changed it, and why?
git log - What did it look like before?
git show - Put it back:
git revert
But the notebook only helps if every change goes through it. So teams add one rule: nobody edits production directly.
Friday's filter, made the safe way
The main line of commits, one branch and its pull request in five steps: main holds commit A, a branch adds commit B, a pull request is opened and reviewed, B is merged into main, and on Monday a revert commit C undoes it.
Before.
mainis the line of commits that production runs. Its latest commit, A, holds the revenue query. Nobody may changemaindirectly.A branch and a commit. You create a branch: your own line of work, starting from A. You add the filter and save it as commit B, with a message that says why.
A pull request. You ask to bring B into
main. The pull request shows the change line by line, runs the automated checks, and waits for a teammate to review it.Merged. The checks are green and Nora has approved. B lands on
main, and the next run uses it. Who, when and why are all on record.Monday. Revenue looks wrong. One command,
git revert, adds a commit C that undoes B. Nothing is lost: B stays in the history, and so does the reason it was undone.
Read the left box top to bottom: it is the history of main, oldest commit first. A pull request is called a merge request on GitLab.
Read the change, line by line
What does the reviewer look at? A diff: the old file and the new file, compared line by line. Removed lines start with -, added lines with +, and the unchanged lines around them with a space.
For data code the diff is only the start. A good reviewer asks what it does not show:
- Does the grain change? A new join can multiply rows.
- Which rows do the filters keep now?
status <> 'cancelled'also drops rows where status is NULL. - What about history? Do past days need to be rebuilt?
- What will the numbers do?
Python's difflib builds the same diff a pull request shows. Run it on Friday's change.
The diff a pull request shows
import difflib
old = """SELECT o.order_ts::DATE AS order_date,
SUM(i.qty * i.unit_price) AS revenue
FROM order_items i
JOIN orders o ON o.order_id = i.order_id
GROUP BY o.order_ts::DATE;""".splitlines()
new = """SELECT o.order_ts::DATE AS order_date,
SUM(i.qty * i.unit_price) AS revenue
FROM order_items i
JOIN orders o ON o.order_id = i.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_ts::DATE;""".splitlines()
for line in difflib.unified_diff(old, new, "main/fct_daily_revenue.sql", "branch/fct_daily_revenue.sql", lineterm=""):
print(line)
The two ---/+++ lines name the files, and the @@ line says which lines this block covers. Then come the unchanged, removed and added lines. Only one line was really added: the +++ line is a header. lineterm="" stops difflib adding a second newline to each line.
One line of code, 12% of revenue
A one-line diff can move a lot of money. Friday's filter looked harmless in the code. Its effect only showed in the data, on Monday, on Tess's dashboard.
So for a change to a model, reviewers also want to see what it does to the data. Build the result with the old SQL and with the new SQL, then compare them key by key: rows only in the old result, rows only in the new one, and rows whose values changed. This is a data diff.
The query below runs both versions of the revenue query side by side and keeps only the days that differ.
Data diff: the old query against the new one
WITH old_version AS (
SELECT o.order_ts::DATE AS order_date, SUM(i.qty * i.unit_price) AS revenue
FROM order_items i
JOIN orders o ON o.order_id = i.order_id
GROUP BY o.order_ts::DATE
),
new_version AS (
SELECT o.order_ts::DATE AS order_date, SUM(i.qty * i.unit_price) AS revenue
FROM order_items i
JOIN orders o ON o.order_id = i.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_ts::DATE
)
SELECT COALESCE(o.order_date, n.order_date) AS order_date,
o.revenue AS old_revenue,
n.revenue AS new_revenue,
n.revenue - o.revenue AS change
FROM old_version o
FULL JOIN new_version n ON n.order_date = o.order_date
WHERE o.revenue IS DISTINCT FROM n.revenue
ORDER BY order_date;
Paste this into the pull request: the reviewer sees exactly which days move and by how much. IS DISTINCT FROM is true when the two values differ, and also when exactly one of them is NULL.
Three ways to land a branch
Say your branch has two commits, B1 and B2. Meanwhile a teammate's commit C has landed on main. There are three ways to bring your work in.
- A merge commit joins the two lines. It has two parents, and your commits stay as they were.
- A rebase replays your commits on top of the new
main. They are copies: the same changes, with new ids. - A squash merge turns the whole branch into one new commit on
main.
Data teams often pick squash: one commit per change, and one git revert to undo it.
One rule for rebase: never rebase commits someone else has already pulled. Their copy keeps the old ids, and now the same work exists twice.
One branch, three ways to land it
The main line and a two-commit branch in four pictures: before landing, after a merge commit with two parents, after a rebase that copies the two commits with new ids, and after a squash merge that adds one commit.
Where you start. You branched from A. Since then C has landed on
main, and your branch holds B1 and B2.Merge commit. A new commit M joins the two lines. It has two parents, C and B2. Your commits keep their ids.
Rebase. Your two commits are replayed on top of C. Each copy has a new parent, so it gets a new id. The originals are left behind.
Squash merge. The branch becomes one new commit, S, on top of C. One commit per change, and one
git revertundoes all of it.
Steps 2, 3 and 4 are three different endings of step 1, not one after another. Read main top to bottom each time. To undo a merge commit you must say which side to keep: git revert -m 1 <commit> keeps main's.
Two good changes that break main together
Git merges text. It does not know what the text means.
Pull request A renames the column amount to amount_usd in stg_payments. Pull request B adds a new model, fct_refunds, that reads amount from stg_payments. Different files. Both pass their checks. Both merge without a single conflict. And the next build of main fails: the column amount no longer exists.
Each was tested against the old main, never against the other. Only building the merged result catches it. Two tools do that: a branch rule that makes B rebuild on top of A before it may merge, or a merge queue, which does the same for every pull request in line.
Both green, then main is red
A conversation between two pull requests, main and the automated checks in five steps: A passes, B passes against the old main, both merge with no text conflict, the build of main fails on a missing column, and with a merge queue B is tested on top of A and fails before it merges.
A is checked. It renames
amounttoamount_usd. The checks build it on today'smain: green.B is checked. It adds
fct_refunds, which readsamount. The checks build it on the same oldmain, whereamountstill exists: green.Both merge. They touch different files, so Git sees no conflict.
mainis broken. The next build has both changes at once:fct_refundsasks for a column that A renamed.The same day, with a merge queue. B is rebuilt on top of A before it may land. It fails there, in the pull request, and never reaches
main.
Read it top to bottom; dashed arrows are the results of the checks. SQL has plain text conflicts too: two branches adding a value to the same CASE, or two migrations both numbered 0042.
Under the hood: Git stores three things
Why does a rebase change ids? Open the notebook.
Git stores three kinds of object, and names each one by a fingerprint of its own content: a SHA-1 hash, 40 characters long.
- A blob is the bytes of one version of one file.
- A tree is one folder: a list of names, with the ids of the blobs and trees inside it.
- A commit names one root tree, its parent commit, the author and the message.
A branch is only a pointer: a tiny file holding one commit id.
Since the name comes from the content, an unchanged file is stored once, however many commits include it. And a commit's content includes its parent's id. Give it a new parent, as a rebase does, and its id has to change.
Name a file the way Git does
import hashlib
def blob_id(content):
"""The id Git gives these bytes: SHA-1 of the header 'blob <size>', a zero byte, then the bytes."""
return hashlib.sha1(b'blob %d\x00' % len(content) + content).hexdigest()
stg = b"SELECT order_id, customer_id, order_ts, status\nFROM raw.orders;\n"
print(blob_id(stg)) # git hash-object prints the same
print(blob_id(stg.replace(b'status', b'status '))) # one extra space: a different object
print(blob_id(stg) == blob_id(bytes(stg))) # same bytes, same id, stored once
Before you run it, guess: will one extra space change the id? The first id is the one git hash-object models/staging/stg_orders.sql prints for this file in the repository on the next card. Nothing about the file name or the time goes into it: only the bytes.
Two commits, twelve objects
A graph of a real two-commit repository: the main branch points at the second commit, which points to its parent and its root tree; the trees lead to folder trees and blobs, and the staging folder tree and its blob are shared by both commits.
Start at the branch and follow the arrows: branch, commit, trees, blobs. The green objects are stored once and used by both commits. The second commit changed one file, so Git wrote five new objects (blob, marts tree, models tree, root tree, commit) and reused the rest. Ids are cut to 7 characters, and the models/ tree between each root tree and its folders is left out to fit.
Look inside the object store
Runs on your laptop:
git cat-file -p HEAD
git cat-file -p 'HEAD^{tree}'
git ls-tree -r HEAD
git count-objects -v
$ git cat-file -p HEAD
tree 6e71144777b9e6ce6e5e9ee141bcefab20248c15
parent 11a6c6dfdacfe539816998946d7a2d7ec755329a
author Rosa Lima <[email protected]> 1749546000 +0000
committer Rosa Lima <[email protected]> 1749546000 +0000
Exclude cancelled orders from daily revenue
$ git cat-file -p 'HEAD^{tree}'
040000 tree 966778c66a031494ca98fce0492cd94d87d2766e models
$ git ls-tree -r HEAD
100644 blob eb7c0a890346bfbf506a92e07280181c5670cf50 models/marts/fct_daily_revenue.sql
100644 blob 4024d9fe1a581d2797c0b439ed91c25cbdfd09b2 models/staging/stg_orders.sql
$ git count-objects -v
count: 12
size: 48
in-pack: 0
packs: 0
size-pack: 0
prune-packable: 0
garbage: 0
size-garbage: 0
A commit is a few lines of text naming a tree and a parent. count: 12 says twelve objects, each compressed into its own small file under .git/objects/.
Why data files do not belong in Git
Git keeps every version of every file forever, and a fresh copy of the repository, a clone, downloads all of them.
Text is cheap. When Git tidies up (git gc), it stores most versions of a text file as a small difference from another version.
Compressed files are not cheap. Parquet, gzip, images, model weights: change one row and almost every byte changes. So every version costs its full size, in every clone, even after the file is deleted.
That is why data goes to object storage, and the code that makes it goes to Git.
Five versions of a file, measured
Bars of repository size: five versions of a 20 MiB compressed file take about 100 MiB before and after git gc, while five versions of a 10.6 MiB CSV take 21 MiB loose and 3.7 MiB once packed with deltas.
Compare the red bars with the green one. Measured with Git 2.39 on a laptop: five commits of a 20 MiB file of random bytes (standing in for compressed Parquet), and five commits of a 10.6 MiB CSV with about 0.1% of rows changed and 1,000 rows added each time.
What never goes into Git
| Never commit | Why | Instead |
|---|---|---|
| Passwords, keys, tokens (.env, a config with a password in it) | everyone with the repository can read them, forever | a secret store, read through environment variables (Lesson 10.2) |
| Data files (.csv, .parquet, database dumps) | big, change daily, may hold personal data | object storage (S3, ADLS); commit the code that makes them |
| Generated output (target/, pycache/, logs) | rebuilt on every run; noisy diffs | list them in .gitignore |
| Local environments (.venv/, editor folders) | specific to one laptop | .gitignore, plus a requirements.txt to rebuild them |
A .gitignore file lists patterns Git should ignore: data/ ignores any folder called data, *.parquet every Parquet file, .env every file with that exact name, in any folder.
Is this file ignored?
Runs on your laptop:
cat .gitignore
git check-ignore -v data/orders.csv .env models/marts/fct_daily_revenue.sql
# secrets
.env
*.pem
# data and generated files
data/
*.parquet
target/
__pycache__/
.venv/
.gitignore:5:data/ data/orders.csv
.gitignore:2:.env .env
git check-ignore -v prints the rule that ignores each path. The model file is not printed: it is not ignored, so it will be committed, which is what you want.
Deleting a secret in a new commit does not remove it. The earlier commit still holds it, and everyone who cloned the repository has a copy. If a key reaches Git, treat it as leaked: rotate it first (create a new key, disable the old one), then clean up. Turn on GitHub secret scanning, or a tool such as gitleaks, so most leaks are blocked before the push.
Remember: Git never forgets. That is why it can tell you what changed, who changed it and what it looked like before. It is also why a secret or a data file, once committed, is there for good.
Numbers to remember
| What | Number or command | Notes |
|---|---|---|
| Object id | SHA-1, 40 hex characters | The hash of a short header (blob, the size in bytes, a zero byte) and then the bytes. Git can also use SHA-256: git init --object-format=sha256. |
| A branch | .git/refs/heads/main | A file holding one commit id. HEAD says which branch you are on. |
| Objects on disk | .git/objects/<first 2 hex/<other 38 | Each new object is one zlib-compressed file. git gc later packs them into a packfile and stores similar objects as deltas. |
| GitHub file size | warns over 50 MiB, blocks over 100 MiB | It recommends repositories under 1 GB, and strongly under 5 GB. |
| Remove a big file from history | git filter-repo | Rewrites history, and everyone has to clone again. If a binary must be versioned, Git LFS keeps a small pointer file in Git and the bytes on a separate server. |
| Undo a commit | git revert <commit | For a merge commit: git revert -m 1 <commit keeps main's side. |
| Build the merged result | a branch rule, or a merge queue | The rule is "require branches to be up to date before merging". A merge queue does it for every pull request in line, automatically. |
Most data teams protect main: no direct pushes, at least one approving review, and green checks before the Merge button works. A CODEOWNERS file asks the right people to review changes to their models. dbt Cloud, Databricks Git folders and Airflow deployments all read from Git, so merging to main is how a change reaches production. Commit messages say why ("Exclude cancelled orders from daily revenue"), not "fix".
What changed at SwiftKart
The revenue query now lives in Git, and main is protected: no direct edits, one approving review, green checks.
Friday's filter came back as a pull request, with a data diff pasted in. The reviewer saw which days of revenue would move before anything shipped, and asked the question that mattered: should cancelled orders count? Tess said no. The change merged with that answer on record, and the past days were rebuilt.
Nora's rule from now on: if it runs in production, it came through a pull request.
This time you ran the checks by hand. In the next lesson a machine runs them on every pull request: CI/CD for data.
In one line
Git keeps every version of every file, so every change to a pipeline goes through a branch, a pull request and a review with a data diff; under the hood it stores blobs, trees and commits named by their content, which is why history cannot be quietly changed and why secrets and data files must stay out.
Interview corner
How would you change a SQL model that runs in production?
Create a branch from an up-to-date main, make the change, run it on dev data, and open a pull request. I would attach a data diff of old versus new output, let CI run the tests, and get a review. After the merge the deploy ships it, and if past results change I plan a backfill.
What do you look for when reviewing a SQL pull request?
Whether the grain changes (a new join that can multiply rows), what the filters now keep or drop, including NULLs, whether keys and tie-breakers are deterministic, and whether history needs reprocessing. I also want to see the effect on the data, not just the code: a data diff of the old and new output.
What should never be committed to Git?
Secrets such as passwords, keys and tokens, data files and database dumps, generated output like build folders, and local environments. Secrets go in a secret store and are read from environment variables, data goes to object storage, and the rest goes in .gitignore.
Two pull requests each passed CI, merged without conflicts, and main is now broken. How did that happen, and how do you prevent it?
Git merges text, not meaning: one PR renamed a column in a staging model and the other added a model that reads the old name, in different files, so the merge was clean but the combined code does not build. Each PR was tested against the old main, never against the other. Requiring branches to be up to date before merging, or a merge queue, makes CI build each PR on top of everything ahead of it. For dbt projects, building state:modified+ on the merged result catches it in minutes.