Skip to content

Migrations

Database Initialization

Note that all examples assume that you already have a database.

If that is not the case and you need to create your tables, that's super easy as ormar is using sqlalchemy for underlying table construction.

All you have to do is call create_all() like in the example below.

Python
1
2
3
4
5
import sqlalchemy
# get your database url in sqlalchemy format - same as used with DatabaseConnection in Model definition
engine = sqlalchemy.create_engine("sqlite:///test.db")
# note that this has to be the same metadata that is used in ormar Models definition
metadata.create_all(engine)

You can also create single tables, sqlalchemy tables are exposed in ormar.ormar_config object.

Python
1
2
3
4
5
import sqlalchemy
# get your database url in sqlalchemy format - same as used with DatabaseConnection in Model definition
engine = sqlalchemy.create_engine("sqlite:///test.db")
# Artist is an ormar model from previous examples
Artist.ormar_config.table.create(engine)

Warning

You need to create the tables only once, so use a python console for that or remove the script from your production code after first use.

Alembic usage

Likewise as with tables, since we base tables on sqlalchemy for migrations please use alembic.

Initialization

Use command line to reproduce this minimalistic example.

Bash
1
2
3
alembic init alembic
alembic revision --autogenerate -m "made some changes"
alembic upgrade head

Where does metadata come from?

Ormar models are built on SQLAlchemy Core. Each model stores its table on a SQLAlchemy MetaData instance that you provide through OrmarConfig. Alembic needs that same MetaData object so it can discover which tables exist and autogenerate migrations.

The usual pattern is to create one shared MetaData object and pass it to every model in its OrmarConfig. You can then expose that metadata from any model:

Python
1
target_metadata = Author.ormar_config.metadata

or export the shared metadata instance from your models module and import it into env.py.

The important part is that every model uses the same sqlalchemy.MetaData() instance. If models live in different files or apps, import them all before Alembic inspects the metadata (see Multiple apps with models below).

Complete project layout

Below is a minimal but complete layout that works with alembic revision --autogenerate.

Text Only
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
my_project/
├── alembic/
│   ├── env.py
│   ├── script.py.mako
│   └── versions/
├── my_project/
│   ├── __init__.py
│   └── models.py
├── alembic.ini
└── db.sqlite

my_project/models.py:

Python
1

alembic.ini:

INI
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
[alembic]
script_location = %(here)s/alembic

sqlalchemy.url = sqlite:///%(here)s/db.sqlite

# Logging configuration (required by fileConfig in env.py)
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

Async vs. sync database drivers

Ormar communicates with the database using an asynchronous driver (sqlite+aiosqlite, asyncpg, asyncmy), whereas Alembic's default env.py runs synchronously. The two connection URLs intentionally point to the same database through different driver protocols:

Database Ormar (DatabaseConnection) Alembic (sqlalchemy.url)
SQLite sqlite+aiosqlite:///db.sqlite sqlite:///%(here)s/db.sqlite
PostgreSQL postgresql+asyncpg://... postgresql+psycopg2://...
MySQL mysql+asyncmy://... mysql+pymysql://...

For SQLite, %(here)s makes Alembic's path relative to alembic.ini, while the relative path in ormar's URL resolves against the directory the application is started from. The two point at the same file only when you run the application from the project root, so use an absolute path in ormar if you start it from anywhere else.

If you prefer to use async drivers throughout, you can initialize Alembic with alembic init -t async.

alembic/env.py:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from logging.config import fileConfig
from pathlib import Path
import sys

from sqlalchemy import engine_from_config, pool
from alembic import context

# Add the project root to sys.path so `my_project` can be imported.
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

config = context.config
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# Import the shared metadata (and models, so the metaclass registers the tables).
from my_project.models import metadata  # noqa: E402

target_metadata = metadata


def run_migrations_offline() -> None:
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
        # Required if you use ormar.UUID(); must match alembic's
        # sqlalchemy_module_prefix option (default "sa.").
        user_module_prefix="sa.",
    )

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    connectable = engine_from_config(
        config.get_section(config.config_ini_section, {}),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            # Required if you use ormar.UUID(); must match alembic's
            # sqlalchemy_module_prefix option (default "sa.").
            user_module_prefix="sa.",
        )

        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

Then generate and run your first migration:

Bash
1
2
alembic revision --autogenerate -m "initial"
alembic upgrade head

Multiple apps with models

If your models are split across several packages, the metadata must still be shared and every model must be imported before Alembic reads the metadata. A common layout:

Text Only
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
my_project/
├── alembic/
│   ├── env.py
│   ├── script.py.mako
│   └── versions/
├── my_project/
│   ├── __init__.py
│   ├── database.py
│   ├── models/
│   │   └── __init__.py
│   ├── authors/
│   │   ├── __init__.py
│   │   └── models.py
│   └── books/
│       ├── __init__.py
│       └── models.py
└── alembic.ini

alembic.ini and alembic/env.py are the same as in the complete project layout above, except for the metadata import shown at the end of this section.

my_project/database.py:

Python
1
2
3
4
5
import sqlalchemy
from ormar import DatabaseConnection

database = DatabaseConnection("sqlite+aiosqlite:///db.sqlite")
metadata = sqlalchemy.MetaData()

my_project/authors/models.py:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import ormar
from my_project.database import database, metadata


class Author(ormar.Model):
    ormar_config = ormar.OrmarConfig(
        database=database,
        metadata=metadata,
        tablename="authors",
    )

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)

my_project/books/models.py:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import ormar
from my_project.authors.models import Author
from my_project.database import database, metadata


class Book(ormar.Model):
    ormar_config = ormar.OrmarConfig(
        database=database,
        metadata=metadata,
        tablename="books",
    )

    id: int = ormar.Integer(primary_key=True)
    title: str = ormar.String(max_length=100)
    author: Author = ormar.ForeignKey(Author)

my_project/models/__init__.py acts as a central import point:

Python
1
2
3
4
5
6
7
8
# Import every model so the metaclass registers its table on the shared metadata.
from my_project.authors.models import Author
from my_project.books.models import Book

# Re-export the shared metadata so env.py can import it from one place.
from my_project.database import metadata

__all__ = ["Author", "Book", "metadata"]

Then in alembic/env.py, replace the metadata import with:

Python
1
2
3
4
5
# Import the models explicitly, not only metadata, so their tables are registered
# even if the import later changes to `from my_project.database import metadata`.
from my_project.models import Author, Book, metadata  # noqa: E402, F401

target_metadata = metadata

Importing the models is required: if a model class is never defined/imported, its table is never attached to metadata and Alembic will not see it.

Warning

Do not import metadata only from my_project.database. Alembic does not raise an error when it gets an empty metadata: on a new database it generates an empty migration, and on an existing database it generates a migration that drops every table.

Detecting column type changes (compare_type)

Alembic's --autogenerate does not compare column types by default — it only notices added/dropped columns and changes to nullability/server defaults. Swapping ormar.DateTime() for ormar.DateTime(timezone=True), widening ormar.String(max_length=...), or changing numeric precision will therefore produce an empty migration unless you opt in.

Pass compare_type=True to context.configure(...) in both run_migrations_offline and run_migrations_online:

Python
1
2
3
4
5
6
context.configure(
    connection=connection,
    target_metadata=target_metadata,
    user_module_prefix="sa.",
    compare_type=True,
)

Ormar already forwards timezone (and other column kwargs) to the underlying SQLAlchemy column, so once compare_type=True is set, type-only changes show up in autogenerated revisions like any other change.

Info

See the Alembic docs on comparing types for the full list of caveats (some dialect-specific type swaps still need a custom compare_type callable).

Excluding tables

You can also include/exclude specific tables with include_object parameter passed to context.configure. That should be a function returning True/False for given objects.

A sample function excluding tables starting with data_ in name unless it's 'data_jobs':

Python
1
2
3
4
5
def include_object(object, name, type_, reflected, compare_to):
    if name and name.startswith('data_') and name not in ['data_jobs']:
        return False

    return True

Note

Function parameters for include_objects (you can change the name) are required and defined in alembic to check what they do check the alembic documentation

And you pass it into context like (both in online and offline):

Python
1
2
3
4
5
6
7
8
context.configure(
    url=config.get_main_option("sqlalchemy.url"),
    target_metadata=target_metadata,
    literal_binds=True,
    dialect_opts={"paramstyle": "named"},
    user_module_prefix="sa.",
    include_object=include_object,
)

Info

You can read more about table creation, altering and migrations in sqlalchemy table creation documentation.

Views

Models declared with OrmarConfig(view=True) (see views) are kept out of ormar_config.metadata, so metadata.create_all() and Alembic's autogenerate never create or drop them. Create views in a migration yourself:

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def upgrade():
    op.execute(
        "CREATE VIEW customer_totals AS "
        "SELECT customer AS customer_id, SUM(amount) AS total "
        "FROM purchases GROUP BY customer"
    )


def downgrade():
    op.execute("DROP VIEW customer_totals")