Yara ORM
A fast, async Python ORM with a Rust engine — Tortoise-style
models, querysets, relations and migrations for PostgreSQL, MySQL, MariaDB, SQLite,
Oracle and Microsoft SQL Server.
📖 Documentation: vsdudakov.github.io/yara-orm
✍️ Deep dive: How the GIL, PyO3 & asyncio cooperate — how the Rust engine bridges Python's event loop without the GIL collapsing it.
Yara ORM is a high-performance async ORM for Python that pairs the ergonomics
of a Django/Tortoise-style API — models, querysets, relations, aggregation and
migrations — with a hot path (connection pooling, parameter binding, row decoding)
written in compiled Rust (PyO3 + tokio). It is a drop-in-feel alternative to
Tortoise ORM and async SQLAlchemy: 2–9× faster than popular pure-Python ORMs
on common operations, with first-class PostgreSQL, MySQL, MariaDB and
SQLite backends — plus Oracle and Microsoft SQL Server (both beta) —
full type hints, and 100% test coverage.
from yara_orm import Model, YaraOrm, fields
class User(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=120)
await YaraOrm.init("postgres://localhost/app")
await YaraOrm.generate_schemas()
await User.create(name="Ada")
print(await User.filter(name__icontains="ad").count())
Highlights
- ⚡ Rust engine — pooling, binding and decoding in compiled code; the async
bridge (PyO3 + tokio) keeps your event loop free.
- 🧩 Familiar API — Tortoise/Django-style models, lazy chainable querysets,
Q objects, aggregation, prefetch_related, transactions, signals. Coming from
Tortoise? Most code moves across unchanged — see
Migrating from Tortoise ORM.
- 🗄️ Pluggable backends — PostgreSQL, MySQL/MariaDB and SQLite, plus beta
Oracle and Microsoft SQL Server backends, selected by
URL; a new database is one Rust trait + one Python dialect.
- 🚚 Migrations — operation-based, auto-generated, backend-portable
(
makemigrations / upgrade / downgrade).
- 🧪 Quality — fully typed, linted (ruff + ty) and 100% test coverage.
Installation
pip install yara-orm
Prebuilt wheels are published for Linux, macOS and Windows on CPython 3.9–3.14,
so installation needs no Rust toolchain. (Installing the source
distribution on an unsupported platform compiles the engine and requires a Rust
toolchain — see Development.)
Quick start
import asyncio
from yara_orm import Model, YaraOrm, fields
class Tournament(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=100)
created_at = fields.DatetimeField(auto_now_add=True)
class Event(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=100, index=True)
tournament = fields.ForeignKeyField("Tournament", related_name="events")
async def main() -> None:
await YaraOrm.init("postgres://localhost/app") # or "mysql://…", "sqlite:///app.db"
await YaraOrm.generate_schemas()
cup = await Tournament.create(name="World Cup")
await Event.create(name="Final", tournament=cup)
# Lazy, chainable queries
finals = await Event.filter(name__icontains="fin").order_by("-id")
count = await Event.filter(tournament=cup).count()
# Relations
async for event in cup.events:
print(event.name, "→", (await event.tournament).name)
await YaraOrm.close()
asyncio.run(main())
Querying
# Lookups: exact, not, gt/gte/lt/lte, in, isnull, contains/icontains,
# startswith/endswith (+ case-insensitive `i` variants)
await User.filter(age__gte=18, name__icontains="a").order_by("-age").limit(10)
# Complex boolean filters with Q
from yara_orm import Q
await User.filter(Q(name="Ada") | Q(age__lt=30)).exclude(active=False)
# Aggregation + group by
from yara_orm import Count, Sum
await Author.annotate(books=Count("books")).filter(books__gte=1)
await Book.annotate(total=Sum("rating")).group_by("author_id").values("author_id", "total")
# Construction-free projections
await User.all().values("id", "name")
await User.all().values_list("name", flat=True)
Model methods: create, bulk_create, get, get_or_none, filter,
exclude, all, annotate, prefetch_related, raw; instances save,
delete, fetch_related.
Relations
class Author(Model):
name = fields.CharField(max_length=100)
class Book(Model):
title = fields.CharField(max_length=200)
author = fields.ForeignKeyField("Author", related_name="books")
tags = fields.ManyToManyField("Tag", related_name="books")
book = await Book.create(title="Compilers", author=author)
await book.tags.add(tag1, tag2) # m2m add / remove / clear
await book.author # forward FK (awaitable)
async for b in author.books: ... # reverse manager
await Author.all().prefetch_related("books") # no N+1
ForeignKeyField, OneToOneField, ManyToManyField, recursive self-FK,
related_name, Prefetch(rel, queryset=...).
Transactions, signals & more
from yara_orm import in_transaction, atomic, pre_save, connections
async with in_transaction(): # commit on success, rollback on error
await Account.create(name="A")
async with in_transaction(): # nesting opens a savepoint
await Account.create(name="B") # rolls back independently on error
@atomic(isolation="SERIALIZABLE") # isolation levels (PostgreSQL/MySQL)
async def transfer(): ...
@pre_save(User) # lifecycle signals
async def on_save(sender, instance, using_db, update_fields): ...
await connections.get("default").execute("INSERT ...", [..]) # manual SQL
Also: enum fields (IntEnumField/CharEnumField), column/table
comments (description=, Meta.table_description), and multi-database
routing via a Router over multiple named connections.
Backends
Backends are selected by the connection URL; the abstraction is a single Rust
trait (Backend) plus a Python BaseDialect subclass:
await YaraOrm.init("postgres://user@localhost/db") # PostgreSQL (tokio-postgres)
await YaraOrm.init("mysql://user:pass@localhost/db") # MySQL/MariaDB (mysql_async)
await YaraOrm.init("sqlite:///path/to/app.db") # SQLite (rusqlite)
await YaraOrm.init("oracle://user:pass@localhost:1521/FREEPDB1") # Oracle 23ai — beta (oracle-rs)
await YaraOrm.init("mssql://user:pass@localhost:1433/db") # SQL Server 2017+ — beta (tiberius)
The SQLite backend maps rich types (uuid/json/datetime/decimal) onto SQLite's
storage classes and reconstructs them on read from the declared column type, so
the model layer is identical across backends.
Oracle and Microsoft SQL Server (both beta) ride on the same
model/queryset API — both on pure-Rust drivers (oracle-rs TNS and tiberius
TDS, no OCI/ODBC/Instant Client, so the wheels stay self-contained). The shared
cross-backend suite runs against a live SQL Server 2022 and Oracle 23ai in CI.
See the backends guide for their
type maps and the driver caveats that keep them out of the stable tier.
Migrations
A Django/Tortoise-style, operation-based migration system. Migrations are
auto-generated from model changes and backend-portable — the same operations
render to PostgreSQL, MySQL, SQLite, Oracle or SQL Server DDL at apply time. Applied migrations are tracked
in an orm_migrations table.
# autodetect model changes -> migrations/0001_initial.py
python -m yara_orm --models myapp.models makemigrations --name initial
# preview SQL without running it (per the target dialect)
python -m yara_orm --db sqlite:///app.db --models myapp.models sqlmigrate 0001_initial
# apply / revert / inspect
python -m yara_orm --db postgres://localhost/app --models myapp.models upgrade
python -m yara_orm --db postgres://localhost/app --models myapp.models downgrade
python -m yara_orm --db postgres://localhost/app --models myapp.models history
Each migration is a class Migration(m.Migration) whose operations are built
from live field objects: CreateModel, DeleteModel, AddField, RemoveField,
AlterField, AddIndex, RemoveIndex, plus hand-written renames
(RenameModel / RenameField / RenameIndex), constraints (AddConstraint /
RemoveConstraint / RenameConstraint with UniqueConstraint / CheckConstraint)
and RunSQL / RunPython for data migrations. makemigrations emits the
idempotent analogs (CreateModelIfNotExists, AddFieldIfNotExists, …) and detects
AlterField automatically. The same commands are available programmatically via
yara_orm.MigrationManager.
Performance
Median of 5 runs, Python 3.12, 5000 rows, against eight other Python ORMs
(Tortoise, SQLAlchemy, Pony, Django, Peewee, SQLObject, Ormar, Piccolo) — Yara
ORM is fastest or tied on every operation across PostgreSQL, MySQL, MariaDB and
SQLite, losing only to leaner in-process sync ORMs on single-row point reads. Times in
ms, lower is better. Full methodology, speedup tables and per-op notes in
benchmarks/ and the performance docs.
PostgreSQL 18

| operation |
yara-orm |
tortoise |
sqlalchemy |
pony |
django |
peewee |
sqlobject |
ormar |
piccolo |
| bulk_insert |
15.2 |
25.2 |
80.8 |
223.8 |
40.5 |
51.1 |
513.3 |
227.5 |
100.7 |
| single_insert |
34.4 |
84.1 |
158.7 |
60.8 |
42.9 |
46.6 |
53.3 |
169.1 |
92.3 |
| fetch_all |
3.6 |
17.3 |
31.6 |
34.4 |
9.1 |
11.9 |
27.8 |
56.6 |
4.4 |
| count |
0.3 |
0.5 |
1.0 |
0.4 |
0.5 |
0.3 |
0.3 |
6.0 |
0.4 |
| group_by |
0.8 |
1.1 |
1.6 |
2.3 |
1.0 |
0.8 |
0.6 |
- |
1.0 |
| filter |
2.2 |
9.1 |
8.4 |
17.5 |
5.3 |
6.8 |
9.3 |
21.2 |
2.6 |
| get_by_pk |
64.1 |
205.9 |
310.4 |
86.0 |
121.1 |
115.6 |
23.1 |
336.9 |
201.6 |
| update |
3.5 |
3.9 |
4.1 |
121.1 |
3.5 |
3.4 |
3.3 |
12.8 |
3.6 |
| delete |
0.7 |
0.9 |
1.1 |
95.5 |
0.8 |
0.7 |
0.6 |
2.2 |
0.8 |
MySQL 8.4
Same workload against MySQL (Tortoise over asyncmy, SQLAlchemy/Ormar over
aiomysql, the sync ORMs over pymysql; Piccolo has no MySQL backend):

| operation |
yara-orm |
tortoise |
sqlalchemy |
pony |
django |
peewee |
sqlobject |
ormar |
| bulk_insert |
46.8 |
48.2 |
596.1 |
443.5 |
100.0 |
82.1 |
1076.6 |
212.3 |
| single_insert |
638.7 |
660.6 |
985.1 |
800.6 |
783.4 |
743.5 |
773.8 |
1062.2 |