Skip to content

Your first database code

You will build the database of a small blog: authors and their posts. You create the tables with a migration, then insert, read, change and delete rows, and finish with a second migration. You need basic Python and nothing else. Linked words, like migration, are explained in the glossary.

1. Install and start Postgres

korbase talks to Postgres, so you need one running. A throwaway container is the quickest way. It needs Docker; any Postgres you can write to works too.

docker run -d --name blog-pg -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=blog -p 5432:5432 postgres:18

A virtual environment keeps this project's packages apart from the others. Create one, then install korbase with the asyncpg driver, and msgspec (the library the models use). Without the asyncpg extra, korbase has no driver to talk to Postgres.

mkdir blog && cd blog
python -m venv .venv && source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install --pre "korbase[asyncpg]" msgspec

The database address (the DSN) goes in an environment variable, so the password is not in your code, and not in ps:

export KORBASE_DSN="postgresql://postgres:secret@localhost:5432/blog"

2. Declare the models

A model is a Python class that describes one table. You write the models once, and korbase uses them for the tables, the queries and the rows you get back. Create blog.py:

from __future__ import annotations

import asyncio
import os
from typing import Annotated, Optional

import msgspec

from korbase import FK, PK, Database, KorbaseError, Rel, cols, delete, insert, select, table, update


@table("authors")
class Author(msgspec.Struct):
    id: Annotated[int, PK()]
    name: str
    posts: Annotated[list[Post], Rel("author_id")] = msgspec.field(default_factory=list)


@table("posts")
class Post(msgspec.Struct):
    id: Annotated[int, PK()]
    author_id: Annotated[int, FK("authors.id")]
    title: str
    author: Annotated[Optional[Author], Rel("author_id")] = None
  • @table("authors") names the table.
  • PK() marks the primary key, the column that tells rows apart. An integer key is filled in by the database.
  • FK("authors.id") marks author_id as a foreign key: each post must point to a real author.
  • Rel("author_id") marks a relation. It is not a column. A list means one author has many posts. A single model means one post has one author.

3. First migration

The tables do not exist yet. A migration is a SQL file that creates or changes them. korbase writes it for you by comparing your models with the database. You read it, then you apply it. Run this next to blog.py; --models blog is the module name, without .py:

python -m korbase.migrate make --models blog --dir migrations -m "create tables"

It prints the new file, migrations/0001_create_tables.sql. Open it before you go on. This is the step where you check what will happen to your data:

-- Generated by korbase on 2026-11-20.
SET standard_conforming_strings = on;
CREATE TABLE "authors" (
    "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
    "name" text NOT NULL,
    CONSTRAINT "authors_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "posts" (
    "id" bigint GENERATED BY DEFAULT AS IDENTITY NOT NULL,
    "author_id" bigint NOT NULL,
    "title" text NOT NULL,
    CONSTRAINT "posts_pkey" PRIMARY KEY ("id")
);
ALTER TABLE "posts" ADD CONSTRAINT "posts_author_id_fkey" FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON DELETE NO ACTION;

make did not change the database. Now apply the file, and list the files to check:

python -m korbase.migrate apply --dir migrations
python -m korbase.migrate status --dir migrations
applied 0001_create_tables.sql
applied 0001_create_tables.sql

The first line comes from apply, the second from status. korbase remembers each applied file and its checksum, so a file never runs twice.

4. Insert rows

Now the tables exist. Every query goes through a Database, which keeps a pool of connections. Add main() at the end of blog.py. The code of the next steps goes inside its async with block.

async def main() -> None:
    async with await Database.connect(os.environ["KORBASE_DSN"]) as db:
        a, p = cols(Author), cols(Post)

        [ada] = await db.run(insert(Author).values(name="Ada"))
        [bob] = await db.run(insert(Author).values(name="Bob"))
        await db.run(insert(Post).values(author_id=ada.id, title="Hello"))
        await db.run(insert(Post).values(author_id=ada.id, title="Second thoughts"))
        await db.run(insert(Post).values(author_id=bob.id, title="Bob's first"))


if __name__ == "__main__":
    asyncio.run(main())

cols(Author) gives you the columns of a model, to use in filters. The database chooses each id, so an insert always hands the new row back, as a list with one Author. [ada] = takes that row out of the list, and you can use ada.id right away.

5. Query and filter

You almost never want every row. where filters, order_by sorts and limit caps the count. Write the values you filter on as plain Python values. korbase sends them to the database apart from the SQL text, so user input cannot change the meaning of a query. Add, inside the block:

        found = await db.run(select(Post).where(author_id=ada.id).order_by(p.title.asc()).limit(10))
        print([x.title for x in found])  # ['Hello', 'Second thoughts']

        hello = await db.run(select(Post).where(p.title.like("H%"), author_id=ada.id))
        print([x.title for x in hello])  # ['Hello']

        one = await db.first(select(Author).where(name="Bob"))
        if one:
            print(one.name)  # Bob

where(author_id=ada.id) means "the posts whose author_id equals this". For anything else than equal, write a condition with the columns: p.title.like("H%"). Give where several, and they must all hold.

db.run returns a list of Post objects, the same class you declared, and your editor knows it: type x. and it offers title, author_id and the other fields. db.first returns one model or None, so the editor asks you to check, which is why the code says if one:. select(...) only describes a query. Nothing reaches the database until you give it to db.run or db.first.

A query that runs many times with different values can be built once, with a named blank, param("n"), that you fill in at each run. That is a speed-up for later, in Queries. You do not need it here.

6. Update, delete, and the where() guard

Changing the wrong rows is a classic database mistake: an UPDATE or DELETE with no filter hits the whole table. korbase refuses to run one unless you write .where(...), or say .all_rows() on purpose. Add:

        print("updated", await db.run(update(Post).set(title="Hello, world").where(title="Hello")))
        print("deleted", await db.run(delete(Post).where(title="Second thoughts")))
        # updated 1
        # deleted 1

        try:
            await db.run(delete(Post))  # no where()
        except KorbaseError as exc:
            print(exc)  # delete without where; call .all_rows() to confirm

An update or delete gives back the number of rows it changed, as an int: here 1 each time. Add .returning() to get the rows themselves instead, as a list of models.

7. Load relations

A post has an author_id, but you often want the author's name. .load(...) fills a relation after the main query. Nothing is loaded unless you ask:

        posts = await db.run(select(Post).order_by(p.id.asc()).load(p.author))
        print([(x.title, x.author.name) for x in posts if x.author])
        # [('Hello, world', 'Ada'), ("Bob's first", 'Bob')]

        authors = await db.run(select(Author).order_by(a.id.asc()).load(a.posts))
        print([(x.name, [y.title for y in x.posts]) for x in authors])
        # [('Ada', ['Hello, world']), ('Bob', ["Bob's first"])]

Each .load runs one extra query for all the rows, not one per row. That avoids the N+1 queries trap, where a loop asks the database a new question for every row.

8. A transaction

Some changes only make sense together, such as an author and their first post. A transaction groups queries so that they all succeed, or none does. The block commits when it ends, and rolls back if it raises:

        async with db.transaction() as tx:
            [cy] = await tx.run(insert(Author).values(name="Cy"))
            await tx.run(insert(Post).values(author_id=cy.id, title="Draft"))

        try:
            async with db.transaction() as tx:
                await tx.run(insert(Author).values(name="Dee"))
                raise RuntimeError("changed my mind")
        except RuntimeError:
            pass

        print(len(await db.run(select(Author))))  # 3: Ada, Bob and Cy; Dee was rolled back

Inside the block, use tx instead of db. It holds the one connection that the transaction runs on.

9. Change a model, make a second migration

Models change. Say a post can be a draft or published. Add one field to Post, with a default so the existing rows get a value. Add Default to the from korbase import ... line, then edit the class:

@table("posts")
class Post(msgspec.Struct):
    id: Annotated[int, PK()]
    author_id: Annotated[int, FK("authors.id")]
    title: str
    published: Annotated[bool, Default(False)] = False
    author: Annotated[Optional[Author], Rel("author_id")] = None

Run make again. It compares the models with the database and writes only the difference, as the next file:

python -m korbase.migrate make --models blog --dir migrations -m "add published"
-- Generated by korbase on 2026-11-20.
SET standard_conforming_strings = on;
ALTER TABLE "posts" ADD COLUMN "published" boolean NOT NULL DEFAULT false;

This change is safe, so the file has no warning. A change that can lose data, such as dropping a column, gets a review marker line above it, and apply refuses to run until you read the statement and remove the marker. Never edit a file that was already applied: apply notices and stops. To change the schema again, run make again.

python -m korbase.migrate apply --dir migrations
python -m korbase.migrate make --models blog --dir migrations
applied 0002_add_published.sql
no changes

The second command finds no difference, so it writes nothing. Now use the column, inside main():

        await db.run(update(Post).set(published=True).where(title="Hello, world"))
        live = await db.run(select(Post).where(published=True))
        print([x.title for x in live])  # ['Hello, world']

The whole script

This is blog.py as it ends up, in one piece. So that one file does everything, it runs the migration from Python, with make and apply from korbase.migrate, instead of the shell commands. On an empty database it writes one file, 0001, that already holds the published column. It starts by emptying both tables, so you can run it again and get the same output. Set KORBASE_DSN as in step 1, then run python blog.py.

from __future__ import annotations

import asyncio
import os
from typing import Annotated, Optional

import msgspec

from korbase import FK, PK, Database, Default, KorbaseError, Rel, cols, delete, insert, select, table, update
from korbase.migrate import apply, make


@table("authors")
class Author(msgspec.Struct):
    id: Annotated[int, PK()]
    name: str
    posts: Annotated[list[Post], Rel("author_id")] = msgspec.field(default_factory=list)


@table("posts")
class Post(msgspec.Struct):
    id: Annotated[int, PK()]
    author_id: Annotated[int, FK("authors.id")]
    title: str
    published: Annotated[bool, Default(False)] = False
    author: Annotated[Optional[Author], Rel("author_id")] = None


async def main() -> None:
    async with await Database.connect(os.environ["KORBASE_DSN"]) as db:
        # Create the tables from the models (steps 3 and 9, from Python).
        await make(db, [Author, Post], "migrations", "create blog tables")
        for name in await apply(db, "migrations"):
            print("applied", name)

        a, p = cols(Author), cols(Post)

        # Start clean, so the script can run again.
        await db.run(delete(Post).all_rows())
        await db.run(delete(Author).all_rows())

        # Step 4: insert.
        [ada] = await db.run(insert(Author).values(name="Ada"))
        [bob] = await db.run(insert(Author).values(name="Bob"))
        await db.run(insert(Post).values(author_id=ada.id, title="Hello"))
        await db.run(insert(Post).values(author_id=ada.id, title="Second thoughts"))
        await db.run(insert(Post).values(author_id=bob.id, title="Bob's first"))

        # Step 5: query and filter.
        found = await db.run(select(Post).where(author_id=ada.id).order_by(p.title.asc()).limit(10))
        print([x.title for x in found])
        hello = await db.run(select(Post).where(p.title.like("H%"), author_id=ada.id))
        print([x.title for x in hello])
        one = await db.first(select(Author).where(name="Bob"))
        if one:
            print(one.name)

        # Step 6: update and delete.
        print("updated", await db.run(update(Post).set(title="Hello, world").where(title="Hello")))
        print("deleted", await db.run(delete(Post).where(title="Second thoughts")))
        try:
            await db.run(delete(Post))
        except KorbaseError as exc:
            print(exc)

        # Step 7: load relations.
        posts = await db.run(select(Post).order_by(p.id.asc()).load(p.author))
        print([(x.title, x.author.name) for x in posts if x.author])
        authors = await db.run(select(Author).order_by(a.id.asc()).load(a.posts))
        print([(x.name, [y.title for y in x.posts]) for x in authors])

        # Step 8: a transaction.
        async with db.transaction() as tx:
            [cy] = await tx.run(insert(Author).values(name="Cy"))
            await tx.run(insert(Post).values(author_id=cy.id, title="Draft"))
        try:
            async with db.transaction() as tx:
                await tx.run(insert(Author).values(name="Dee"))
                raise RuntimeError("changed my mind")
        except RuntimeError:
            pass
        print(len(await db.run(select(Author))))

        # Step 9: use the new column.
        await db.run(update(Post).set(published=True).where(title="Hello, world"))
        live = await db.run(select(Post).where(published=True))
        print([x.title for x in live])


if __name__ == "__main__":
    asyncio.run(main())

The first time, the output is:

applied 0001_create_blog_tables.sql
['Hello', 'Second thoughts']
['Hello']
Bob
updated 1
deleted 1
delete without where; call .all_rows() to confirm
[('Hello, world', 'Ada'), ("Bob's first", 'Bob')]
[('Ada', ['Hello, world']), ('Bob', ["Bob's first"])]
3
['Hello, world']

On later runs the first line is missing: there is nothing new to migrate. When you are done, docker rm -f blog-pg removes the database.

  • Models: all the markers and the three model kinds.
  • Queries: filters, sorting, paging, upsert and parameters.
  • Relations: how loading works, and its limits.
  • Transactions: savepoints and raw SQL.
  • Migrations: review markers, renames and the Python API.
  • Korvex: using the database in a web app.

Next: Models