← cd ../blog

Oxyde tutorial: setup, models and migrations for a mini blog, part 1

In one sentence

This part shows you how to set up an isolated Python project, describe the tables of a mini blog as classes, and create those tables in a database. At the end you will have a first program that saves data and reads it back.

What it is and what it’s for

Oxyde is an ORM for Python. An ORM is a library that translates Python classes and objects into tables and rows of a database. This way you work with data by writing Python code, without having to write every SQL instruction by hand. What is an ORM for? It keeps the structure of your data in one place, the code, and it lets the program create and update the tables, instead of you doing it by hand. This is the kind of work that almost every application that saves data does, such as a website with articles and authors.

Oxyde is asynchronous: its database operations are written with await, which tells the program to wait for the result. Its core is written in Rust, and it comes already compiled inside the package (a library ready to install), so you do not need to install Rust to use it. The project is still young: it is at version 0.x, and for this reason the tutorial uses version 0.9.0, pinned to its exact number. The reason is that the interface can change from one version to the next.

This series builds a mini blog with two tables, authors and posts. This part sets up the project and creates the tables; part 2 adds more articles and teaches you how to query the blog.

Project card

What we’ll do in this part

The goal is to set up an isolated Python project with Oxyde 0.9.0. We will describe the tables of a mini blog, that is authors and posts, as Python classes. Then we will turn those classes into tables of an SQLite database (a database that lives entirely in a single file, with no separate server), using migrations: files that describe how to change the structure of the database, step by step. Finally we will write the first asynchronous program, which saves and reads back data.

At the end you will have:

What you need

You need a terminal (the window where you type commands, one line at a time) and Python 3.10 or higher: the steps were tested with version 3.11.

Step by step

Step 1.1: Let’s check the Python version

Before installing anything, let’s check which Python we have. Oxyde requires Python 3.10 or higher, so this check tells us right away whether the system’s Python is recent enough. The command python3 --version prints only the version number. The tutorial was tested on Debian 12 with Python 3.11.

python3 --version

Output:

Python 3.11.2

In my test, a line appears that starts with the word Python, followed by the number 3.11.2. To continue, you need a number 3.10 or higher.

Step 1.2: Let’s create the project folder and the virtual environment

Let’s create the folder miniblog and go into it: the whole project will live inside it. Then python3 -m venv .venv creates a virtual environment (venv), that is a folder .venv that contains a link to the system’s Python and its own space for packages. It keeps the packages of this project separate from those of other projects or of the system: if one day another project needs a different version of Oxyde, the two will not interfere with each other. Inside we find bin (the programs, including python and pip, the program that installs packages), lib (where the packages will end up) and pyvenv.cfg (the settings of the environment).

mkdir miniblog
cd miniblog
python3 -m venv .venv
ls -a
ls .venv

Output:

.
..
.venv
bin
include
lib
lib64
pyvenv.cfg

The list shows .venv, together with bin, include, lib, lib64 and pyvenv.cfg. The dot at the start makes the folder hidden: to see it you need the -a option of the ls command.

Step 1.3: Let’s activate the virtual environment and check that it is active

Creating the environment is not enough: you have to activate it. The command . .venv/bin/activate changes the terminal you are using, so that python and pip point to the ones inside .venv (usually (.venv) appears at the start of the line). We check in two ways: with command -v python, which shows which python will be used, and by asking Python whether it is running inside a virtual environment. Then we use deactivate to leave: on Debian 12 the system’s Python is called python3 and is in /usr/bin/python3, so outside the environment the command python no longer exists. Finally we go back in, because the activation only lasts for the terminal that is open.

. .venv/bin/activate
command -v python | sed "s|^$PWD/||"
python -c "import sys; print('ambiente virtuale attivo:', sys.prefix != sys.base_prefix)"
deactivate
echo "--- dopo deactivate ---"
command -v python || echo "nessun comando python"
command -v python3
python3 -c "import sys; print('ambiente virtuale attivo:', sys.prefix != sys.base_prefix)"
. .venv/bin/activate
echo "--- di nuovo attivo ---"
command -v python | sed "s|^$PWD/||"

Output:

.venv/bin/python
ambiente virtuale attivo: True
--- dopo deactivate ---
nessun comando python
/usr/bin/python3
ambiente virtuale attivo: False
--- di nuovo attivo ---
.venv/bin/python

The result first shows .venv/bin/python and then ambiente virtuale attivo: True. After deactivate, you see nessun comando python and ambiente virtuale attivo: False, and at the end the check returns True.

Step 1.4: Let’s install Oxyde at version 0.9.0

With pip install oxyde==0.9.0 we install Oxyde inside the virtual environment. The double equals sign fixes the exact version: Oxyde is at version 0.x, and the project itself warns that the interface can change between one minor version (the middle number, here 9) and the next. Pinning the version makes sure that the output shown in this guide matches what you will see too.

pip install --quiet --disable-pip-version-check oxyde==0.9.0

Step 1.5: Let’s check the installation

We check the installation in two ways. pip show oxyde reads the data of the installed package: name, version and the packages it depends on. Among these there are oxyde-core, the Rust core, and Pydantic, the library that Oxyde’s models are built on and that checks their data. Then we ask Python to import Oxyde (that is, to load it into the program) and print its version: if the import works, the package can be used by our programs.

pip show oxyde | grep -E '^(Name|Version|Requires):'
python -c "import oxyde; print('versione di oxyde:', oxyde.__version__)"

Output:

Name: oxyde
Version: 0.9.0
Requires: msgpack, oxyde-core, pydantic, typer
versione di oxyde: 0.9.0

In the result, check that Name is oxyde and that Version is 0.9.0; the last line confirms the same version read by Python. The labels Name, Version and Requires are in English. The Requires line lists the other libraries that Oxyde depends on, including the ones described above.

Step 1.6: Let’s look at the commands that Oxyde adds to the terminal

By installing Oxyde we also got a program that you use from the terminal, and it is called oxyde. With --help we see the list of its commands, each with a line of explanation in English. In this part we will use five of them: init for the configuration, makemigrations to prepare the migrations, sqlmigrate to read them, migrate to apply them and showmigrations to see where we are. The oxyde program exists only as long as the virtual environment is active, because it was installed inside it.

oxyde --help

Output:

                                                                                                    
 Usage: oxyde [OPTIONS] COMMAND [ARGS]...                                                           
                                                                                                    
 Oxyde ORM - Database migration and management tool                                                 
                                                                                                    
╭─ Options ────────────────────────────────────────────────────────────────────────────────────────╮
│ --install-completion        <bool>  Install completion for the current shell.                    │
│ --show-completion           <bool>  Show completion for the current shell, to copy it or         │
│                                     customize the installation.                                  │
│ --help                      <bool>  Show this message and exit.                                  │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Commands ───────────────────────────────────────────────────────────────────────────────────────╮
│ generate-stubs  Generate .pyi stub files for all registered table models.                        │
│ init            Initialize Oxyde configuration.                                                  │
│ makemigrations  Create migration files by comparing current models with replayed migrations.     │
│ migrate         Apply all pending migrations.                                                    │
│ showmigrations  Show list of all migrations with their status (applied/pending).                 │
│ sqlmigrate      Print the SQL for a specific migration.                                          │
│ migrations      Migration maintenance commands                                                   │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯

Step 1.7: Let’s create the configuration file with oxyde init

oxyde init asks four questions and writes the answers into the file oxyde_config.py. The questions are about the Python module that contains the models (models, that is the file models.py), the type of database (sqlite), the address of the database and the migrations folder (migrations). Usually you answer by hand; here we pass the four answers ready-made with printf, one per line, so the command does not wait. As the address we give sqlite:///blog.db, the same as the examples in the official documentation (we will change it shortly). At the end we print the file to see what it contains.

printf 'models\nsqlite\nsqlite:///blog.db\nmigrations\n' | oxyde init > /dev/null
cat oxyde_config.py

Output:

"""Oxyde ORM configuration."""

# List of Python modules containing Model classes
MODELS = ["models"]

# Database dialect: "postgres", "sqlite", or "mysql"
DIALECT = "sqlite"

# Directory for migration files
MIGRATIONS_DIR = "migrations"

# Database connections
# Keys are connection aliases, values are connection URLs
DATABASES = {
    "default": "sqlite:///blog.db",
}

The printed file contains MODELS with models inside it, DIALECT equal to sqlite (that is, the type of database) and MIGRATIONS_DIR equal to migrations. In the DATABASES section, the default key points to the address of the database.

Step 1.8: Let’s correct the database address with an absolute path

The documentation presents sqlite:///blog.db as a relative path, that is an address that depends on the folder you run the program from. However, in our test with Oxyde 0.9.0, the third slash was read as the start of an absolute path, that is a full address that starts from the root of the system: the program was therefore looking for the file /blog.db, where a normal user cannot write, and it failed with unable to open database file. So we use the solution that the documentation itself recommends for portable projects: BASE_DIR is the folder that contains oxyde_config.py. The address becomes sqlite:/// followed by the full path, so with four slashes in a row, and the database always stays next to the project, no matter which folder you run the commands from. To check, we print the address, using the text <cartella del progetto> for the part that changes from computer to computer.

File oxyde_config.py:

"""Oxyde ORM configuration."""

from pathlib import Path

# Folder that contains this file: the database lives next to it
BASE_DIR = Path(__file__).resolve().parent

# List of Python modules containing Model classes
MODELS = ["models"]

# Database dialect: "postgres", "sqlite", or "mysql"
DIALECT = "sqlite"

# Directory for migration files
MIGRATIONS_DIR = "migrations"

# Database connections: an absolute path gives "sqlite:////..." (four slashes)
DATABASES = {
    "default": f"sqlite:///{BASE_DIR}/blog.db",
}
python -c "from oxyde_config import DATABASES, BASE_DIR; url = DATABASES['default']; print(url.replace(str(BASE_DIR), '/<cartella del progetto>')); print('percorso assoluto:', url.startswith('sqlite:////'))"

Output:

sqlite:////<cartella del progetto>/blog.db
percorso assoluto: True

In the result, the address has four slashes and the project folder in place of the part that changes. The line percorso assoluto: True confirms that the address is now complete.

Step 1.9: Let’s describe the blog tables in the models.py file

A model is a class that inherits from Model and describes a table: each attribute with a type becomes a column (str becomes text, int a whole number, bool a true or false value). int | None with db_pk=True marks the primary key: the value is None until the row is saved, then the database gives it a number. db_unique=True stops two authors from having the same email. In the Post model, the field author: Author | None creates a foreign key, that is a column author_id that points to an author, and db_on_delete="CASCADE" means that when you delete an author, their articles are deleted too. The inner class Meta holds the settings of the table: is_table = True is required and table_name chooses the name of the table. Author must be written before Post, because Post names it.

File models.py:

from oxyde import Model, Field


class Author(Model):
    id: int | None = Field(default=None, db_pk=True)
    name: str
    email: str = Field(db_unique=True)

    class Meta:
        is_table = True
        table_name = "authors"


class Post(Model):
    id: int | None = Field(default=None, db_pk=True)
    title: str
    content: str
    published: bool = Field(default=False)
    views: int = Field(default=0)
    author: Author | None = Field(default=None, db_on_delete="CASCADE")

    class Meta:
        is_table = True
        table_name = "posts"
python -c "import models; print('modelli caricati:', models.Author.__name__, models.Post.__name__)"

Output:

modelli caricati: Author Post

In the result, modelli caricati: Author Post appears: Oxyde found both classes.

Step 1.10: Let’s generate the first migration

oxyde makemigrations reads the models listed in oxyde_config.py, compares them with the migrations that already exist (for now, none) and writes a new file in the migrations folder, with the instructions to reach the structure described by the models. This command does not touch the database: it only writes the plan, and the starting number of the name tells the order in which the migrations must be applied. With --name initial we choose the file name, 0001_initial.py; without this option Oxyde 0.9.0 takes the name from the first operation, that is 0001_create_authors_table.py. The command also generates models.pyi, a types file (in English it is called a stub) that is used by type-checking tools. With sed we remove the path of the working folder from the output.

oxyde makemigrations --name initial 2>&1 | sed "s|$PWD/||g"
ls migrations

Output:

📝 Creating migrations...

0️⃣  Loading models...
   ✅ Imported 1 module(s)

1️⃣  Extracting schema from models...
   ✅ Found 2 table(s): authors, posts

2️⃣  Replaying existing migrations...
   📁 Creating migrations directory: migrations
   ✅ Replayed 0 migration(s)

3️⃣  Computing diff...
   ✅ Found 2 operation(s):
      - Create table: authors
      - Create table: posts

4️⃣  Generating migration file...

   ✅ Created: migrations/0001_initial.py

5️⃣  Generating type stubs...
Generated stub: models.pyi
   ✅ Generated 1 stub file(s)
0001_initial.py

The result lists the steps of the command: it finds two tables, authors and posts, and two create operations, one for each. Some lines are in English, such as Creating migrations... and Replaying existing migrations; Replayed 0 migration(s) means there were no earlier migrations. The last line shows the file created, 0001_initial.py.

Step 1.11: Let’s read the migration and the SQL it will produce

A migration is a normal Python file with two functions: upgrade applies the change and downgrade undoes it. The full file is long, so with grep we show only the main lines, with their number: create_table for authors and for posts, the name of each column and the foreign key to authors with the CASCADE rule. The authors table is created first, because posts refers to it, and downgrade deletes the tables in reverse order. The command oxyde sqlmigrate instead shows the SQL, the database language that will run on SQLite: it is a way to check a migration before applying it. You can also see how Python types become database types: for example str becomes VARCHAR(255), while int and bool become INTEGER.

grep -nE "def |create_table|drop_table|'name'|on_delete|ref_table" migrations/0001_initial.py
echo "----- SQL per SQLite -----"
oxyde sqlmigrate 0001_initial

Output:

9:def upgrade(ctx):
11:    ctx.create_table(
15:                'name': 'id',
30:                'name': 'name',
45:                'name': 'email',
61:    ctx.create_table(
65:                'name': 'id',
80:                'name': 'title',
95:                'name': 'content',
110:                'name': 'published',
125:                'name': 'views',
140:                'name': 'author_id',
157:                'name': 'fk_posts_author_id',
161:                'ref_table': 'authors',
165:                'on_delete': 'CASCADE',
172:def downgrade(ctx):
174:    ctx.drop_table("posts")
175:    ctx.drop_table("authors")
----- SQL per SQLite -----
📝 SQL for migration: 0001_initial

-- Generated SQL (sqlite):

CREATE TABLE "authors" ( "id" INTEGER PRIMARY KEY, "name" VARCHAR(255) NOT NULL, "email" VARCHAR(255) NOT NULL UNIQUE )

CREATE TABLE "posts" ( "id" INTEGER PRIMARY KEY, "title" VARCHAR(255) NOT NULL, "content" VARCHAR(255) NOT NULL, "published" INTEGER NOT NULL DEFAULT 0, "views" INTEGER NOT NULL DEFAULT 0, "author_id" INTEGER, FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON DELETE CASCADE ON UPDATE CASCADE )

In the numbered lines there are two create_table calls, one per table, and at the bottom two drop_table calls in the downgrade function. After the part titled SQL, two CREATE TABLE statements show the SQL code for SQLite: in the posts table the foreign key is written with ON DELETE CASCADE. Some lines, such as Generated SQL (sqlite), are in English.

Step 1.12: Let’s write the first asynchronous program

As I mentioned before, database operations are asynchronous: they are written inside an async def function, and every call to the database is preceded by await. asyncio.run(main()) starts the main function. db.init(**DATABASES) opens the connections listed in oxyde_config.py, so the database address is written in only one place, and the try/finally block makes sure that db.close() closes them even if an error happens. Each model has an objects manager, that is the place from which you call the operations on its table: create inserts a row and returns the object with the id given by the database. To link an article to its author, you pass author_id.

File primo_programma.py:

import asyncio

from oxyde import db

from models import Author, Post
from oxyde_config import DATABASES


async def main():
    await db.init(**DATABASES)
    try:
        # Create two authors: create() inserts the row and returns it with its id
        alice = await Author.objects.create(name="Alice Rossi", email="alice@example.com")
        bruno = await Author.objects.create(name="Bruno Bianchi", email="bruno@example.com")
        print(f"Autore creato: {alice.name} (id={alice.id})")
        print(f"Autore creato: {bruno.name} (id={bruno.id})")

        # Create posts linked to their author through author_id
        await Post.objects.create(
            title="Primi passi con Oxyde",
            content="Installazione e primo modello.",
            published=True,
            views=120,
            author_id=alice.id,
        )
        await Post.objects.create(
            title="Le migrazioni spiegate bene",
            content="makemigrations e migrate.",
            published=True,
            views=45,
            author_id=alice.id,
        )

        # Build an object by hand: it becomes a row only after save()
        bozza = Post(title="Bozza: idee sparse", content="Da finire.", author_id=bruno.id)
        print(f"Prima di save(): id={bozza.id}")
        await bozza.save()
        print(f"Dopo save(): id={bozza.id}")

        # Read everything back
        print("--- Autori ---")
        for author in await Author.objects.order_by("id").all():
            print(f"{author.id}: {author.name} <{author.email}>")

        print("--- Articoli ---")
        for post in await Post.objects.order_by("id").all():
            stato = "pubblicato" if post.published else "bozza"
            print(f"{post.id}: {post.title} | autore {post.author_id} | {stato} | {post.views} letture")

        print(f"Totale articoli: {await Post.objects.count()}")
    finally:
        await db.close()


if __name__ == "__main__":
    asyncio.run(main())
python -c "import ast; ast.parse(open('primo_programma.py').read()); print('sintassi corretta')"

Output:

sintassi corretta

For now we only save the file, without running it: we will run it in steps 1.13 and 1.16. The result says sintassi corretta, that is, the file contains no Python writing errors.

Step 1.13: Common mistake: running the program before applying the migration

Let’s run the program now, before oxyde migrate, to see the most common mistake of beginners. The migration has been written but not applied, so the database does not have the tables yet. The program stops at the first write with a message that contains no such table, that is “the table does not exist”, and the message is in English because it comes directly from SQLite. We show only the last line of the error and the value that the program returns to the system: a value other than zero means that the program stopped with an error. Now we cause the error on purpose.

python primo_programma.py > errore.txt 2>&1
codice=$?
tail -n 1 errore.txt
echo "codice di uscita: $codice"
(exit "$codice")

Output:

oxyde.exceptions.ManagerError: Query execution error: Query failed: error returned from database: (code: 1) no such table: authors
codice di uscita: 1

The message says that the authors table does not exist: no such table: authors. The line starts with oxyde.exceptions.ManagerError, the name of the error reported by Oxyde, and the final line reports the value 1, which indicates an error. This is the same error described at the end of this part, in the section on the most common mistake.

Step 1.14: Let’s apply the migration to the database

oxyde migrate runs on the database all the migrations that have not been applied yet, in order of their number. Now the authors and posts tables really exist in the blog.db file. Oxyde also keeps an internal table where it notes which migrations have been applied: the “pending” migrations are the files that are not yet noted there, and oxyde migrate applies only those.

oxyde migrate

Output:

⏳ Applying migrations...

Found 1 pending migration(s):
  - 0001_initial

Migrating to latest...

✅ Applied 1 migration(s)
   - 0001_initial

The result says Found 1 pending migration(s), that is one pending migration, and then Applied 1 migration(s) with 0001_initial: the migration is now applied. These messages are also in English, like the title Applying migrations....

Step 1.15: Let’s check the migration status and the tables created

oxyde showmigrations lists the migrations with a check mark next to those already applied: it is the first command to run when something does not add up. Then we open the blog.db file with the sqlite3 module, which is part of Python, and ask SQLite for the list of tables. We find authors, posts and the internal table oxyde_migrations, where Oxyde keeps track of the migrations applied.

oxyde showmigrations
python -c "import sqlite3; c = sqlite3.connect('blog.db'); print('tabelle:', [r[0] for r in c.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name\")])"

Output:

📋 Migrations status:

  [✓] 0001_initial

Total: 1 migration(s)
Applied: 1
Pending: 0
tabelle: ['authors', 'oxyde_migrations', 'posts']

The result shows [✓] next to 0001_initial, and the summary says Total: 1 migration(s), Applied: 1 and Pending: 0. The last line lists the tables authors, oxyde_migrations and posts.

Step 1.16: Let’s run the program again, now that the tables are ready

With the tables in place, the program works. We see the id values given by the database (1 and 2 for the authors), then the object created by hand that has id=None before save() and a number after it. Finally we print the full list read from the database with all(), sorted by id with order_by. count() makes the database itself count the rows, with the SQL instruction COUNT(*). The article created without published=True is a draft, because the default value of the field is False.

python primo_programma.py

Output:

Autore creato: Alice Rossi (id=1)
Autore creato: Bruno Bianchi (id=2)
Prima di save(): id=None
Dopo save(): id=3
--- Autori ---
1: Alice Rossi <alice@example.com>
2: Bruno Bianchi <bruno@example.com>
--- Articoli ---
1: Primi passi con Oxyde | autore 1 | pubblicato | 120 letture
2: Le migrazioni spiegate bene | autore 1 | pubblicato | 45 letture
3: Bozza: idee sparse | autore 2 | bozza | 0 letture
Totale articoli: 3

In the result, the authors with id 1 and 2 appear, then the test of save(): first id=None, after it id=3. The articles section lists three rows, and Totale articoli: 3 confirms the count; the last row is marked as a draft.

The most common mistake

The program stops with an error that contains no such table: authors, that is “the table authors does not exist”, even if the Author model is written correctly and the migration was generated. It is the error we caused on purpose in step 1.13.

The cause is that oxyde makemigrations only writes the file with the instructions to create the tables, without touching the database. If you do not also run oxyde migrate, the program finds or creates a blog.db file that is empty, with no tables, and the first write fails.

The fix is to run oxyde migrate after every oxyde makemigrations, and to check with oxyde showmigrations that next to each migration there is the check mark [✓], as in step 1.15.

Summary

In the next part

In part 2 we fill the mini blog with more articles and learn to query it: filters, exclusions, sorting, comparisons on numbers and texts, loading the author together with the article with join(), counts and sums. The project built in this part is the base we will work on.

Glossary

A note on the test

This first part of the Oxyde series was tested on Debian 12 with Python 3.11.2.