Docs / Guides / Auto database create

Feature 03 · Study guide

Auto database create

Understand migrate: create missing SQL databases, apply ordered migrations, roll back safely.

What you will learn
  • What tpy migrate does step by step
  • How migration files are ordered
  • When to use status and rollback

1. Setup

You need a project with generated migrations and a valid .env (from tpy build or tpy db configure).

$ tpy migrate
$ tpy migrate status
$ tpy migrate rollback

2. How it works

  1. Load database settings from the environment.
  2. For Postgres/MySQL: if the database name is missing, attempt to create it.
  3. Connect to the target database.
  4. Apply pending files in database/migrations/ in numeric order (001_, 002_, …).
  5. Record applied migrations so the next run only applies new ones.

3. Migration files

database/migrations/
  001_user_migration.py
  002_post_migration.py

Each file provides up (apply) and down (undo). Model order in schema.tpy becomes migration order — define referenced models first.

4. After schema changes

  1. tpy crud — regenerate migration + layers.
  2. tpy migrate — apply new pending files.
  3. tpy migrate status — confirm what ran.
SQLite creates the file database automatically on connect. Auto-create of a named server DB is mainly for Postgres/MySQL.

5. Common mistakes

  • Running migrate before tpy build/tpy crud (no migration files yet).
  • Hand-editing applied migrations instead of adding a new ordered file.