Skip to content

Models

Use this when you want to describe your database tables as Python classes.

The idea

A database keeps data in tables. A table is a grid: each row is one thing (one user), and each column is one fact about it (the name, the email). A model is a Python class that describes one table. Each field of the class is a column.

Two kinds of column matter most. The primary key is the column whose value is different in every row, such as id. It is how you point at one row. A foreign key is a column that holds the primary key of a row in another table. A post stores its author's id, and that is how the database knows who wrote it.

You mark these facts with small markers inside Annotated[...]. Korbase reads the class when it is decorated, and raises KorbaseError at import time if the model is not valid.

import dataclasses
import datetime
from typing import Annotated, Optional

from korbase import FK, PK, Default, Index, Unique, table


@table("users")
@dataclasses.dataclass
class User:
    id: Annotated[int, PK()]
    email: Annotated[str, Unique()]
    bio: Optional[str] = None


@table("posts", indexes=(Index("author_id", "created_at"),))
@dataclasses.dataclass
class Post:
    id: Annotated[int, PK()]
    author_id: Annotated[int, FK("users.id", on_delete="cascade")]
    title: Annotated[str, Default("untitled")]
    created_at: Annotated[datetime.datetime, Default(sql="now()")]

A model can be a msgspec Struct, a @dataclass, or a TypedDict. For a dataclass, put @table above @dataclass. Any other class raises KorbaseError.

Markers

Marker Goes on Meaning
PK() a field Part of the primary key. A table needs at least one.
FK("table.column", on_delete=...) a field Foreign key to a column of another table.
Unique() a field A unique constraint on this column.
Default(value) or Default(sql=...) a field The column default.
SqlType("...") a field Overrides the SQL type.
Rel("field") a field A relation, not a column. See Relations.
Index(*columns, unique=False, name=None, where=None) table(..., indexes=(...)) An index over one or more columns. It makes lookups on them faster. where makes it a partial index.

Primary keys

  • A single int key is an identity column (GENERATED BY DEFAULT AS IDENTITY): the database numbers new rows for you. PK(identity=False) turns this off. PK(identity=True) forces it, and is only valid on a single integer key.
  • A field with a SqlType is not an identity column unless you set identity=True. That still needs a Python int field.
  • A composite key (several PK() fields) has no identity column.

Foreign keys

on_delete says what happens to a row when the row it points to is deleted. It is one of "cascade" (delete it too), "restrict", "set null", "set default" and "no action". The default is "no action". "set null" needs an Optional field, and fails at import otherwise. The target must be exactly "table.column", with valid names.

Defaults

  • Default(3), Default("x"), Default(True), Default(None) and finite floats are literal defaults. Strings are written as escape strings (E'...'), with quotes and backslashes doubled.
  • Default(sql="now()") is written into the migration as is. Use it only with SQL from trusted code, never from user input.
  • Give a value or sql, not both. A bare Default() means DEFAULT NULL.

Indexes

An index makes lookups on its columns faster, and costs some space and extra work on each write. Declare indexes in table(..., indexes=(...)).

A partial index covers only the rows that match a condition, given as where. It is smaller than a full index on the same columns, so it costs less to keep. Postgres and SQLite both support it:

import dataclasses
import datetime
from typing import Annotated, Optional

from korbase import PK, Index, table


@table("tasks", indexes=(Index("due", name="tasks_by_due", where="due IS NOT NULL"),))
@dataclasses.dataclass
class Task:
    id: Annotated[int, PK()]
    due: Optional[datetime.date] = None

Here the index holds only the tasks that have a due date. A query needs to repeat the condition, such as WHERE due IS NOT NULL, for the database to use it.

  • where is a SQL predicate written as is after WHERE. It must come from trusted code, never from user input, in the same way as Default(sql=...). Korbase only rejects an empty predicate, or one with a ; or a NUL byte.
  • Changing where is a change of the index: make drops the index and creates it again with the new predicate.
  • The generated name ignores where. Two indexes on the same columns get the same name, and the database rejects the second one. Give one of them name=.

Nullability

A field typed Optional[T] can hold NULL, the database's "no value". Any other field is NOT NULL. Primary key columns are always NOT NULL.

author_id: Annotated[Optional[int], FK("users.id", on_delete="set null")] = None

Going further

Type mapping

Migrations turn each column into a database type with this table. An Optional[T] maps like T. The SQLite column is what sqlite: DSNs use (see SQLite for how values are stored).

Python type Postgres type SQLite type
bool boolean INTEGER
int bigint INTEGER
float double precision REAL
str text TEXT
bytes bytea BLOB
uuid.UUID uuid TEXT
datetime.datetime timestamptz TEXT
datetime.date date TEXT
datetime.time time TEXT
decimal.Decimal numeric TEXT
dict, list (also list[...]) jsonb TEXT
an enum.Enum subclass text INTEGER if every value is an int, else TEXT

Any other type raises KorbaseError, naming the column. Add a SqlType to choose the type yourself:

import dataclasses
import decimal
from typing import Annotated

from korbase import PK, SqlType, table


@table("items")
@dataclasses.dataclass
class Item:
    id: Annotated[int, PK()]
    name: Annotated[str, SqlType("varchar(80)")]
    price: Annotated[decimal.Decimal, SqlType("numeric(10, 2)")]

A SqlType must be lowercase, such as varchar(80), numeric(10, 2), text[] or double precision. Anything else raises KorbaseError.

Names

Table, column and index names are checked, never escaped:

  • A name is 1 to 63 ASCII letters, digits or underscores, and does not start with a digit. 63 is the Postgres limit in bytes, and an ASCII character is one byte. Anything else raises KorbaseError when the model is declared.
  • Field names are the column names. Every name is written in double quotes in the SQL.
  • A generated name longer than 63 characters raises KorbaseError, so a long table name and column name together can fail the model. Shorten one of them.

Constraint names

Constraints get fixed names, so migrations can find and compare them:

Constraint Name
primary key {table}_pkey
foreign key {table}_{column}_fkey
unique {table}_{column}_key
index {table}_{columns}_idx, columns joined by _

Index(name=...) replaces the generated index name, and is checked like any other name. In the first example, the index is posts_author_id_created_at_idx.

How rows are built

When a query returns rows, Korbase makes one model per row, with no validation by default.

  • A TypedDict row is a dict.
  • If the model's __init__ takes the columns first, in column order, Korbase calls Model(*row). This is the fast path.
  • Otherwise it calls Model(**fields) by name. This covers a kw_only struct or dataclass, and a Rel field declared before the columns.
  • A field with init=False cannot go through __init__. Korbase sets it after the object is built, even on a frozen dataclass.
  • With Database.connect(..., validate=True), each row is checked against the model with msgspec.convert, so msgspec must be installed.

Next: Queries