alembic-default-diff
A dialect-normalizing compare_server_default for alembic autogenerate, and a standalone server-default drift checker for SQLAlchemy metadata.
from alembic_default_diff import compare_server_default
# env.py
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_server_default=compare_server_default,
)
Why
Alembic's compare_server_default is False by default, so column-default
drift between your models and the database goes undetected in autogenerate.
Turning it on (compare_server_default=True) hands comparison to a
per-dialect string comparator that has gotten measurably better over recent
alembic releases, but still has real gaps, and on PostgreSQL one case that
outright crashes autogenerate.
Measured: bench/measure_alembic_baseline.py, run against alembic 1.20.0 /
SQLAlchemy 2.1.1, compare_server_default=True (no custom callable), on this
project's own test corpus (tests/test_corpus.py) of real
(metadata-default, database-default) pairs created and reflected through a
live engine:
sqlite: 65 cases
false positives: 22 ['ts_equal_2', 'ts_equal_3', 'numeric_equal_7', 'numeric_equal_8',
'numeric_equal_9', 'numeric_equal_12', 'numeric_equal_14', 'numeric_equal_15',
'numeric_equal_17', 'bool_equal_2', 'bool_equal_3', 'bool_equal_4', 'bool_equal_5',
'bool_equal_6', 'bool_equal_7', 'string_equal_1', 'string_equal_2', 'string_equal_3',
'string_equal_5', 'string_equal_6', 'string_equal_10', 'string_equal_11']
false negatives: 0 []
raised an exception instead of comparing: 0 []
postgresql: 63 cases
false positives: 0 []
false negatives: 2 ['ts_localtimestamp_is_different', 'nextval_drift_different_seq']
raised an exception instead of comparing: 4 [
('string_equal_1', "(psycopg.errors.SyntaxError) unterminated quoted string at or near \"' AS anon_1\""),
('string_equal_2', '(psycopg.errors.SyntaxError) syntax error at or near "\' word\'"'),
('string_equal_5', "(psycopg.errors.SyntaxError) unterminated quoted string at or near \"' AS anon_1\""),
('string_equal_8', '(psycopg.errors.SyntaxError) syntax error at or near "\' quotes\'"'),
]
SQLite's built-in comparator misses function synonyms (CURRENT_TIMESTAMP vs
datetime('now')), several boolean spellings, and doubled-quote string
escaping — 22 of 65 correct pairs get flagged as drift.
PostgreSQL's built-in comparator is the stronger of the two: it delegates to
the live database (SELECT <reflected> = <metadata>) for anything it can't
handle syntactically, which is why casts, now()/CURRENT_TIMESTAMP, and
numeric-vs-quoted forms already compare correctly (those specific examples
from early drafts of this project's own research turned out to be already
fixed upstream — worth saying plainly). But that same live-execution
strategy is also where its remaining problems come from:
- A plain string default containing an apostrophe crashes autogenerate.
server_default="it's" gets spliced back into a SELECT ... = 'it's'
query by naive f"'{x}'" string formatting, producing a real
psycopg.errors.SyntaxError instead of a comparison result — 4 of the 63
cases above never even got to a verdict.
- Comparing two
nextval(...) defaults can execute both sequences as a
side effect, and two freshly-created, unrelated sequences both return
1 on their first call — so comparing against the wrong sequence can
read back as "equal" by coincidence, a false negative that also mutates
state during a read-only comparison.
LOCALTIMESTAMP is not distinguished from now()/CURRENT_TIMESTAMP,
though it is a different type (timestamp without time zone) on
PostgreSQL — another false negative.
alembic_default_diff.compare_server_default classified all 130 of the
sqlite + postgresql pairs above correctly (0 false positives, 0 false
negatives, 0 crashes — see tests/test_corpus.py), by parsing both sides
with a real SQL parser (sqlglot) instead of string-matching or asking the
live database to execute an expression to check it.
Checked for an existing package first: alembic-utils (migrates views and
procedures, not server defaults) and alembic-postgresql-enum (enum type
diffing, not server defaults) are the closest named incumbents on PyPI, and
neither touches server-default comparison. A gh code search for
compare_server_default turns up real projects working around the same
noise with unconditional return True / return None callbacks, or
compare_server_default=False with a comment explaining why it was turned
off — see scratchpad/w41.md in this project's research notes for the
specifics.
Installation
pip install alembic-default-diff
Requires Python >= 3.11, alembic >= 1.13, sqlalchemy >= 2.0. Depends on
sqlglot for actual SQL parsing — normalizing casts, quoting, and function
synonyms correctly needs a real tokenizer per dialect; regexes cannot tell
'x'::character varying from a cast some other value is wrapped in, or
correctly unescape a doubled quote inside a string literal.
Usage
Plug into alembic autogenerate
# env.py
from alembic_default_diff import compare_server_default
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_server_default=compare_server_default,
)
Returns True for real drift, False for defaults that are equivalent once
dialect quirks are normalized away, and None to defer to alembic's own
comparison (unsupported dialect, or either side didn't parse).
Standalone drift check
alembic-default-diff check "postgresql://user:pass@host/db" myapp.models:metadata
Compares every column's server_default in metadata against what is
actually reflected from the live database, without running alembic at all.
Useful as a pre-deploy CI gate: did anyone edit a default with ALTER TABLE
directly, bypassing migrations?
Programmatic drift check
import sqlalchemy as sa
from alembic_default_diff import find_drift
engine = sa.create_engine("postgresql://user:pass@host/db")
for finding in find_drift(engine, my_metadata):
print(finding.table, finding.column, finding.verdict)
Reference
compare_server_default(context, inspected_column, metadata_column, inspected_default, metadata_default, rendered_metadata_default) -> bool | None
Drop-in for alembic's EnvironmentContext.configure(compare_server_default=...)
callable signature. Supports the postgresql, sqlite, mysql, and
mariadb dialects; returns None (defer) for anything else, and for cases
where one side is present and the other is absent (so alembic's own
dialect-specific handling of things like PostgreSQL's SERIAL exclusion
still applies).
find_drift(engine, metadata) -> list[DefaultFinding]
| Field |
Type |
Description |
table |
str |
Table name |
column |
str |
Column name |
verdict |
"drift" | "unknown" |
"unknown" means one side didn't parse; review manually |
metadata_default |
str | None |
Rendered metadata-side default |
reflected_default |
str | None |
Rendered database-side default |
Tables absent from the live database are skipped. Columns whose metadata
default is Computed, Identity, or a raw Sequence object are skipped —
this tool compares literal/expression server defaults only. An
autoincrement primary key column with no explicit metadata server_default
is skipped, matching how those are normally modeled in SQLAlchemy.
defaults_equal(dialect, left, right, affinity="other", *, left_raw_literal=False, right_raw_literal=False) -> bool | None
The normalizer underneath both of the above, for direct use. affinity is
"boolean", "numeric", "string", or "other" — it decides which literal
folding rules apply (e.g. true only folds against 1 for a boolean
column, never for an integer one). *_raw_literal marks a side as a bare
Python value handed to SQLAlchemy directly (server_default="x") rather
than compiled SQL, so it's treated as the literal value verbatim instead of
being parsed as SQL syntax.
CLI: alembic-default-diff check <url> <module:metadata>
| Exit code |
Meaning |
0 |
No confirmed drift (there may be unresolved/unknown defaults; they're printed) |
1 |
At least one confirmed drifted default |
2 |
Could not analyse: bad module:metadata spec, import error, or connection failure |
How it works
Both sides of a server default are parsed with sqlglot into a real syntax
tree (per-dialect: postgres, sqlite, mysql for both mysql and
mariadb). The tree is then rewritten to a fixpoint — parens and casts
unwrapped, in any nesting order or position, including at the root — and:
- documented function synonyms are folded to one canonical node (per
dialect: PostgreSQL folds
now()/CURRENT_TIMESTAMP together but keeps
LOCALTIMESTAMP separate, since it's a different type there; MySQL/MariaDB
fold all four of CURRENT_TIMESTAMP/NOW()/LOCALTIME/LOCALTIMESTAMP
together, since MySQL's own documentation states they are synonyms; SQLite
folds CURRENT_TIMESTAMP with the zero-argument datetime('now') only —
not datetime('now', 'localtime'), which applies a real timezone shift),
- numeric literals are compared as
Decimal values, not text, so 2.50 and
2.5 match,
- boolean literals are folded per dialect's accepted spellings, but only
when the column's type affinity says the value is actually a boolean,
nextval(...) defaults are compared by sequence name, after unwrapping
whatever cast wraps the argument (::regclass or otherwise) — never by
executing the sequence,
- string literal content comes from
sqlglot's own unescaping, so a doubled
quote ('it''s') and a plain Python string ("it's") compare as the same
value without either side needing to be valid SQL syntax.
The two normalized trees are then compared with ordinary structural
equality. A parse failure on either side returns None (defer) rather than
guessing.
Limitations
- Dialects:
postgresql, sqlite, mysql, mariadb only. Anything else
(Oracle, MSSQL, ...) defers to alembic's own comparison via None.
Computed columns, Identity, and raw Sequence-as-default are out of
scope for both the alembic callable (alembic already handles these before
reaching a user callable) and find_drift (skipped).
- Function-call defaults beyond the documented timestamp-function synonyms
and
nextval(...) are compared structurally after unwrapping casts and
parens, not evaluated for semantic equivalence — lower('X') and
LOWER('X') compare equal (case-insensitive keyword), but two
differently-spelled calls that happen to produce the same value will not.
- Collation- and locale-sensitive string comparison is not modeled; this
tool compares literal content only.
- No live database connection is used or required for the alembic callable
or
defaults_equal — which also means it cannot do what PostgreSQL's own
built-in comparator does for genuinely unclassifiable expressions (fall
back to asking the database). Where this tool can't parse an expression,
it returns None and defers rather than guessing.
Compatibility
Tested against Python 3.14.7 (this machine), alembic 1.20.0, SQLAlchemy
2.1.1, sqlglot 30.20.0.
- SQLite: via the standard library
sqlite3, real engine, real
reflection.
- PostgreSQL: via
@electric-sql/pglite 0.5.8 exposing a real Postgres
wire-protocol server (reports PostgreSQL 18.3 (PGlite 0.5.8)), connected
to from Python with psycopg[binary]. This runs Postgres's actual
parser/planner/executor compiled to WASM, not a system-installed
postgres binary or a reimplementation — but it is not a native server
either, and that distinction is worth being explicit about. Docker was not
used: docker pull could not reach a registry in this environment.
ALEMBIC_DEFAULT_DIFF_TEST_PG_URL (see tests/conftest.py) points the
PostgreSQL test corpus at a connection URL; the CI workflow in this repo
does not set it, so those 63 tests skip loudly there rather than silently
passing.
- MySQL / MariaDB: not tested against a live server in this
environment — no MySQL-or-MariaDB-compatible engine was available without
a system-wide install.
tests/test_mysql_normalize.py exercises the
normalizer directly (83 cases) using reflected-string forms taken from
MySQL's documented behavior and from alembic's own ddl/mysql.py
comparator source (which the same false-positive/crash classes above were
read from, not measured against a live server) — a normalizer-correctness
corpus, not an integration or drift-detection corpus. Treat MySQL/MariaDB
support as unverified against a real server.
- CI (
.github/workflows/test.yml) runs on Python 3.11–3.14, SQLite only.
Development
python3 -m venv .venv
.venv/bin/pip install -e '.[dev]'
.venv/bin/python -m pytest -q
.venv/bin/python -m mypy --strict src tests
Set ALEMBIC_DEFAULT_DIFF_TEST_PG_URL to a reachable PostgreSQL connection
URL to also run the PostgreSQL corpus; otherwise those tests skip with an
explanation instead of failing.
License
MIT. See LICENSE.