Migrations and Input Validation

Migrations and Input Validation in Flask: A municipal water treatment plant never stops. Water is flowing to homes every second of every day, so the two…

The Analogy: The Municipal Water Treatment Plant

A municipal water treatment plant never stops. Water is flowing to homes every second of every day, so the two disciplines that keep it safe both have to happen on a live system. The first is what comes in: raw water arriving from the reservoir is sampled and tested at the intake before it is allowed anywhere near the distribution train. The second is the plant itself changing over time: new filtration stages, wider mains, extra tanks, all added while the town keeps drinking.

The intake test is a boundary check. A sample is drawn, measured against a standard for turbidity, pH, and contaminants, and water that fails is diverted to a holding pond and never pushed into the pipes. The test happens once, at the edge, before anything downstream trusts the water. Everything past the intake is written assuming the water is already clean, exactly the way your models and queries are written assuming the data they hold is already valid.

Upgrading the plant is a different discipline. You cannot demolish and rebuild it, because the town needs water now, so engineers work from a numbered ledger of change orders. Each order is applied in strict sequence, each carries a documented way to reverse it, and each leaves the plant running. You never quietly edit a completed order or reshape a pipe off the books; you issue the next numbered change and record how to undo it. That ledger is the difference between a plant whose real plumbing still matches its master schematic and one where nobody can safely touch anything.

The failure mode is when both disciplines lapse at once. A crew swaps a pipe on the live network during a busy shift without logging a reversible change order, and the same shift waves a batch of untested water straight through the intake. Now two things are wrong together: the plant's real plumbing no longer matches the schematic, so the change cannot be reversed and the next crew is working blind, and contaminated water is already in the mains, past every point that assumed it was clean. This lesson is those two disciplines in Flask: validating input at the boundary so bad data never reaches your models, and evolving the schema through ordered, reversible migrations rather than uncontrolled edits.


Syntax or Core Structure

Validation is ordinary Python that runs at the boundary, before untrusted input reaches a model. The shape is always the same: take the incoming data, check each field against its rule, and return a map of field to error message. An empty map means the input passed. Libraries like WTForms, marshmallow, and pydantic formalize this with declarative schemas, but underneath they are doing exactly what the function below does.

def validate_signup(data):
    errors = {}
    name = data.get("name", "").strip()
    if not name:
        errors["name"] = "required"
    elif len(name) > 20:
        errors["name"] = "too long"
    age = data.get("age")
    if not isinstance(age, int):
        errors["age"] = "must be an integer"
    elif age < 18:
        errors["age"] = "must be at least 18"
    return errors


good = validate_signup({"name": "ada", "age": 21})
bad = validate_signup({"name": "", "age": 15})
print(f"good -> {good}")
print(f"bad  -> {bad}")

Output:

good -> {}
bad  -> {'name': 'required', 'age': 'must be at least 18'}

The valid submission returns an empty dict, so the caller proceeds. The invalid one collects every problem at once -- a missing name and an under-age value -- rather than stopping at the first, which is what lets a form show all its errors in one pass. The rule to internalise is that this check runs before any session.add; nothing downstream re-checks it, so if the validator is wrong or skipped, the bad data flows straight through, exactly like untested water past the intake.


Technical Depth: Why create_all Is Not a Migration

The single most expensive misunderstanding in Flask persistence is treating db.create_all() as a way to keep the schema up to date. It is not. It builds tables that do not yet exist and then stops. It never alters a table that is already there, so the moment you add a column to a model, create_all becomes a no-op and your code and your database drift apart in silence -- the schematic no longer matches the plumbing.

create_all only builds tables that are missing

Here a table already exists with two columns. We then declare a model for the same table with a third column, email, and call create_all again. Nothing happens to the live table.

from sqlalchemy import create_engine, text, inspect, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

engine = create_engine("sqlite://")
with engine.begin() as conn:
    conn.execute(text("CREATE TABLE account (id INTEGER PRIMARY KEY, name TEXT)"))

cols_before = [c["name"] for c in inspect(engine).get_columns("account")]
print(f"before: {cols_before}")


class Base(DeclarativeBase):
    pass


class Account(Base):
    __tablename__ = "account"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(50))
    email: Mapped[str] = mapped_column(String(120))


Base.metadata.create_all(engine)
cols_after = [c["name"] for c in inspect(engine).get_columns("account")]
print(f"after create_all: {cols_after}")

Output:

before: ['id', 'name']
after create_all: ['id', 'name']

The model clearly declares email, yet the table still has only id and name. create_all saw that a table named account already existed and skipped it entirely; it does not compare columns. Any query that now reads Account.email will fail against this database, and it will fail in production, on real data, not in the test that used a fresh empty database where create_all did build the full table.


A migration is a numbered, reversible step

The fix is Flask-Migrate, a thin wrapper over Alembic. It keeps a migrations/ folder of numbered scripts, each with an upgrade step and a matching downgrade step, and a version table in the database recording which scripts have run. That is the change-order ledger: ordered, reversible, and applied to the live schema without rebuilding it.

CommandWhat it does
flask db initCreates the migrations/ folder, once per project
flask db migrateAutogenerates a script by diffing models against the database
flask db upgradeApplies pending migrations forward, in order
flask db downgradeReverts the most recent migration using its recorded down step

A typical change to add the email column looks like this on the command line:

flask db init                      # once: create the migrations/ folder
flask db migrate -m "add email"    # autogenerate a script from model diffs
flask db upgrade                   # apply it forward, in order
flask db downgrade                 # revert the most recent migration

Under the hood, the generated upgrade emits an ALTER TABLE and the downgrade emits its inverse. The program below runs both directly so you can see the column appear and then disappear -- the exact round trip Flask-Migrate manages for you:

from sqlalchemy import create_engine, text, inspect

engine = create_engine("sqlite://")
with engine.begin() as conn:
    conn.execute(text("CREATE TABLE account (id INTEGER PRIMARY KEY, name TEXT)"))


def columns():
    return [c["name"] for c in inspect(engine).get_columns("account")]


with engine.begin() as conn:
    conn.execute(text("ALTER TABLE account ADD COLUMN email TEXT"))
print(f"after upgrade: {columns()}")

with engine.begin() as conn:
    conn.execute(text("ALTER TABLE account DROP COLUMN email"))
print(f"after downgrade: {columns()}")

Output:

after upgrade: ['id', 'name', 'email']
after downgrade: ['id', 'name']

The upgrade adds email to the existing table without touching its rows, and the downgrade removes it, returning the schema to exactly where it began. That the two steps compose back to the starting point is the whole promise of the ledger: a migration you cannot reverse is a change order with no undo, which is how teams end up afraid to touch their own database.


Real World Example: A Signup That Validates Before It Persists

This program puts both disciplines together. A signup function validates each submission at the boundary and only reaches the database when the input is clean; anything that fails is rejected and never staged. Four submissions come in -- two valid, two not -- and we check afterwards exactly which rows made it into the table.

from sqlalchemy import create_engine, select, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session


class Base(DeclarativeBase):
    pass


class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(20))
    age: Mapped[int]


engine = create_engine("sqlite://")
Base.metadata.create_all(engine)


def validate(data):
    errors = {}
    name = str(data.get("name", "")).strip()
    if not (1 <= len(name) <= 20):
        errors["name"] = "length 1..20"
    age = data.get("age")
    if not isinstance(age, int) or age < 18:
        errors["age"] = "integer >= 18"
    return errors


def signup(session, data):
    errors = validate(data)
    if errors:
        return {"ok": False, "errors": errors}
    user = User(name=data["name"].strip(), age=data["age"])
    session.add(user)
    session.commit()
    return {"ok": True, "id": user.id}


submissions = [
    {"name": "ada", "age": 21},
    {"name": "", "age": 40},
    {"name": "bob", "age": 15},
    {"name": "cleo", "age": 30},
]

with Session(engine) as session:
    for s in submissions:
        print(signup(session, s))
    stored = session.scalars(select(User.name).order_by(User.id)).all()
    count = session.scalar(select(func.count()).select_from(User))
print(f"stored names: {stored}")
print(f"row count: {count}")

Output:

{'ok': True, 'id': 1}
{'ok': False, 'errors': {'name': 'length 1..20'}}
{'ok': False, 'errors': {'age': 'integer >= 18'}}
{'ok': True, 'id': 2}
stored names: ['ada', 'cleo']
row count: 2

The first and fourth submissions pass and are committed, receiving ids 1 and 2. The second fails on an empty name and the third on an under-age value; both come back with a structured error map and neither is ever staged. The final query confirms it: only ada and cleo are in the table, a row count of 2. Bad input was diverted at the intake and never reached the model.

Notice that the ids are 1 and 2, not 1 and 4. The rejected submissions never called session.add, so no primary keys were consumed and no gaps appear in the sequence. This is the payoff of validating before persisting rather than inserting and catching a database error afterwards: the database only ever sees rows the application already believes are valid, so its own counters and constraints stay clean.

The validator also gathers all of a submission's errors together before returning, so a form with three bad fields reports three problems in one response instead of making the user resubmit three times. That single detail is most of the difference between validation that feels helpful and validation that feels hostile, and it costs nothing but collecting into a dict instead of returning on the first failure.

The genuine flaw is that every one of these rules lives only in the application layer. The database has no NOT NULL on name, no CHECK (age >= 18), no length constraint that it actually enforces -- SQLite ignores the String(20) length entirely, and even on PostgreSQL the column length and the Python check can silently drift apart. So the "rules" hold only for code that goes through signup. A one-off script, an admin action, a second endpoint, or a bulk import that calls session.add directly will write a blank name or a fifteen-year-old without complaint, and the next reader will trust that data because the model said it was valid. The fix is to mirror the invariants as real database constraints, added through a migration, so the guarantee holds no matter which code path does the writing; the application-layer validator then exists for friendly, aggregated error messages, not as the only thing standing between bad input and the table.


Common Mistakes

  1. Using create_all to update the schema. It only builds tables that do not exist and silently skips any that do. Add a column to a model and create_all changes nothing, leaving code and database disagreeing until a query fails on real data.
  1. Validating only on the client. JavaScript checks are user experience, not security; anyone can POST directly to the endpoint. Every rule that matters must be re-checked on the server before the data is used.
  1. Editing a migration that has already run. Other developers and every deployed environment have recorded that version as applied. Change the schema forward with a new migration instead of rewriting history nobody can re-run.
  1. Writing migrations with no working downgrade. An upgrade without a matching downgrade is a change order with no undo. When a release goes wrong you cannot step back, so the whole team becomes afraid to touch the schema.
  1. Not reviewing autogenerated migrations. Alembic autogenerate is a draft: it misses server defaults and some type changes, and it renders a column rename as a drop plus an add, which destroys data. Read and edit every generated script before applying it.
  1. Trusting the application validator as the only guard. If the database has no matching NOT NULL, CHECK, or UNIQUE constraint, any code path that skips your validation -- a script, an admin tool, a second endpoint -- writes invalid data unopposed.
  1. Inserting first and catching the database error. Letting a bad row hit the table and handling the exception consumes primary keys, risks partial writes, and turns a friendly field message into an opaque 500. Validate before session.add.
  1. Returning on the first invalid field. Stopping at the first error forces the user to resubmit repeatedly. Collect every field's problem into one map and return them together.
  1. Validating un-normalised input. A string of spaces passes a naive "required" check until you .strip() it, and case or whitespace differences defeat uniqueness. Normalise the value first, then apply the rule.

Best Practices

  • Change models only through migrations. Whenever a model changes, generate a migration and apply it; never lean on create_all for anything holding data you care about.
  • Give every migration a tested downgrade. Write the reverse step and actually run upgrade then downgrade on a scratch database so you know the round trip works before you need it.
  • Review autogenerated scripts before committing them. Treat autogenerate as a first draft, correct what it missed, and keep the final migration in version control alongside the code that needs it.
  • Validate at the boundary, before persistence. Check untrusted input the moment it arrives and reject it before any session.add, so nothing downstream has to wonder whether the data is trustworthy.
  • Mirror critical invariants as database constraints. Back the rules that must never be violated with NOT NULL, CHECK, UNIQUE, and foreign keys, added via migration, so the guarantee holds regardless of which code path writes.
  • Aggregate errors into a structured response. Return a map of field to message rather than a single string, letting the client show every problem at once and fix the form in one pass.
  • Use a schema library for non-trivial input. WTForms, marshmallow, or pydantic give declarative rules, coercion, and consistent error shapes; reserve hand-written validators for the simplest cases.
  • Apply migrations as an explicit deploy step. Run flask db upgrade as a deliberate, logged part of deployment rather than silently on application start, so schema changes are visible and ordered.

Practice Exercises

  1. Add a UNIQUE constraint on name by issuing an ALTER-style migration on a table that already has rows. Insert a duplicate name directly with session.add, bypassing any application validation, and confirm the database itself rejects it. This shows why constraints, not just validators, protect the data.
  1. Extend validate to also check an email field against a simple regex. Feed it a submission whose name and email are both invalid and prove the returned map contains both errors, not just the first one encountered.
  1. Reproduce the create_all trap end to end. Create a table with two columns, declare a model that adds a third, call create_all, and assert with inspect that the third column is still absent. Then apply an ALTER TABLE ... ADD COLUMN and confirm it appears.
  1. Write a matching upgrade/downgrade pair that adds and then removes a phone column. Run the upgrade, print the columns, run the downgrade, print them again, and confirm the table returns to its original set -- the round trip that makes a migration reversible.