Zyvor
Define your database once. Get type-safe Rust for free.
Zyvor is a schema-driven ORM for Rust. You write a .zyvor schema file, and the
CLI generates readable Rust — models, entities, typed fields, relations, and
CRUD input types. No derive macros to learn, no hidden magic.
The workflow
schema.zyvor → zyvor CLI → generated Rust → your app → PostgreSQL
You never hand-write a model struct, a column list, or a CREATE TABLE again.
What you get
- Typed fields —
User::age.gte(18)instead of"age >= ?" - Relations — 1:N, N:1, 1:1, M:M with eager loading, including nested
- Migrations — generated, checksum-tracked, auto-numbered, auto-applied
- Readable output — every generated file is plain Rust you can open and inspect
Two crates, one workflow
| Crate | What it does | How to get it |
|---|---|---|
zyvor | Runtime: query builder, CRUD, relations | cargo add zyvor |
zyvor-cli | Toolchain: parser, generator, migrations | cargo install zyvor-cli |
The CLI generates code for the runtime. It doesn’t reimplement it. Your app
depends on zyvor; the CLI is a build-time tool you install once.
A taste
model User {
id Int @id @default(autoincrement())
name String
email String @unique
posts Post[]
}
#![allow(unused)]
fn main() {
let users = User::find()
.with(User::posts)
.where_(User::name.eq("Ali Khan"))
.all(&pool)
.await?;
for user in &users {
println!("{} has {} posts", user.name, user.posts.len());
}
}
That’s a real join-free eager load: one query for users, one for their posts. No N+1.
Current scope (v0.1)
Being honest about what works is a feature, not a weakness.
Working and tested: PostgreSQL, CRUD + bulk operations, transactions, all four relation shapes, 2-level nested eager loading, migration generation with diffing and tracking, automatic database creation, Axum integration.
Not yet: SQLite/MySQL, rollbacks, comparison operators on Boolean /
DateTime / nullable fields, multi-column ORDER BY, CTE / UNION.
The full list lives in Known Limitations. Read it before you commit — it’s short and it will save you an afternoon.
Where to go next
- Installation — two commands and one version rule that matters
- Quick Start — empty folder to working database in five commands
Source
- Runtime: github.com/Fakhir-Israr-200219/zyvor
- CLI: github.com/Fakhir-Israr-200219/zyvor-cli
- Axum example: github.com/Fakhir-Israr-200219/zyvor-axum-demo
Installation
1. Install the CLI
cargo install zyvor-cli
zyvor --version # Zyvor-CLI 0.1.0
This gives you the zyvor command. It’s a build-time tool — your application
doesn’t depend on it.
2. Add the runtime
cargo add zyvor
cargo add sqlx --features runtime-tokio,postgres,chrono,rust_decimal,json
cargo add tokio --features full
cargo add serde --features derive
Building an API? Add Axum too:
cargo add axum serde_json
⚠️ The one rule that will save you an hour
Your sqlx version must match Zyvor’s. Zyvor 0.1 uses sqlx 0.8.
[dependencies]
zyvor = "0.1"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres"] }
cargo add sqlx grabs the newest release, which may be 0.9 or later. If you end
up on a different major-minor than Zyvor, you’ll see errors like:
the trait bound `UserModel: FromRow<'r, PgRow>` is not satisfied
the trait bound `&Pool<Postgres>: Acquire<'_>` is not satisfied
there are multiple different versions of crate `sqlx_core` in the dependency graph
That is not a Zyvor bug. Two sqlx versions means two distinct FromRow
traits, and your generated model implements the other one. Pin to 0.8 and the
errors disappear.
Check what you actually resolved:
cargo tree -i sqlx
One version in the tree = you’re fine.
3. PostgreSQL
You need a running PostgreSQL server and credentials for it.
You do not need to create the database. zyvor migrate --apply creates it
if it’s missing. Just pick a name and put it in your connection string.
4. What you don’t need
Zyvor re-exports what its generated code uses, so these are optional:
| Crate | Needed? |
|---|---|
chrono | ❌ not to hold a DateTime. ✅ if you want chrono APIs in your own code |
rust_decimal | ❌ not to hold a Decimal |
serde_json | ❌ not to hold a Json. ✅ if you build JSON responses by hand |
serde | ✅ for your own DTO derives (or use zyvor::serde::Serialize) |
For timestamps in your own code, the sqlx re-export is free:
#![allow(unused)]
fn main() {
use sqlx::types::chrono;
let now = chrono::Utc::now().timestamp();
}
Verify
zyvor --version # CLI installed
cargo check # runtime + sqlx versions agree
Next: Quick Start.
Quick Start
Empty folder to a working database in five commands.
1. Scaffold
cargo init my-api && cd my-api
zyvor init
✅ Initialized zyvor project
📁 .zyvor/schema.zyvor ← Edit your schema here
📁 .zyvor/generated/ ← Entities will be generated here
📁 .zyvor/migrations/ ← Migration SQL will be generated here
📁 .zyvor/.env ← Database URL (edit this)
📁 .zyvor/config.toml ← Advanced config
📁 .zyvor/.gitignore ← Protects .env from git
2. Point at your database
Edit .zyvor/.env:
DATABASE_URL=postgres://postgres:yourpassword@localhost/my_app
The database my_app doesn’t exist yet. That’s fine — step 5 creates it.
3. Write your schema
Replace .zyvor/schema.zyvor:
model User {
id Int @id @default(autoincrement())
name String
email String @unique
age Int
bio String? @map("user_bio")
createdAt DateTime @default(now()) @map("created_at")
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
userId Int @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
Two models, one relation, a nullable column, a mapped column name, and a timestamp default. That covers most of what you’ll use daily.
4. Generate
zyvor dev
👀 Watching .zyvor/schema.zyvor for changes...
Press Ctrl+C to stop
✅ Generated 5 modular files in ".zyvor/generated"
✅ Generated: .zyvor/generated/ (modular)
✅ Generated: .zyvor/migrations/0001_initial.sql
💾 Snapshot saved
dev keeps running and regenerates on every save. Leave it open in this
terminal and use a second one for the rest.
Order matters:
devproduces the migration files. Runningmigrate --applyfirst gives youNo migration files found in .zyvor/migrations/. Run 'zyvor dev' first.
5. Apply
In a second terminal:
zyvor migrate --apply
🚀 Applying migrations to database...
Database: postgres://postgres:****@localhost/my_app
📦 Creating database 'my_app'...
✅ Database 'my_app' created!
📋 Found 1 migration file(s)
📝 Applying: 0001_initial.sql
✅ 0001_initial.sql applied successfully!
Tables in database:
📋 _zyvor_migrations
📋 posts
📋 users
Database created, tables ready, migration recorded. Run it again and it skips everything — re-applying is free.
6. Use it in Rust
Add dependencies (see Installation — and pin sqlx to 0.8):
[dependencies]
zyvor = "0.1"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "chrono"] }
tokio = { version = "1", features = ["full"] }
src/main.rs:
#[path = "../.zyvor/generated/mod.rs"]
mod generated;
use generated::{Post, PostCreate, User, UserCreate, UserUpdate};
use zyvor::Entity;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let pool = sqlx::PgPool::connect(&std::env::var("DATABASE_URL")?).await?;
// Create
let user = User::create(&pool, UserCreate {
name: "Ali Khan".into(),
email: "ali@example.com".into(),
age: 28,
bio: Some("Rust developer".into()),
}).await?;
println!("created user {}", user.id);
// Create a related row
let post = Post::create(&pool, PostCreate {
title: "Hello Zyvor".into(),
content: None,
user_id: user.id,
}).await?;
// Query with a typed field
let adults = User::find()
.where_(User::age.gte(18))
.order_by(User::id.desc())
.take(20)
.all(&pool)
.await?;
println!("{} adults", adults.len());
// Eager load the relation
let with_posts = User::find().with(User::posts).all(&pool).await?;
println!("{} posts for {}", with_posts[0].posts.len(), with_posts[0].name);
// Partial update
User::update(&pool, user.id, UserUpdate {
bio: Some(Some("Senior Rust dev".into())),
name: None,
email: None,
age: None,
created_at: None,
}).await?;
// Delete — cascades to posts
let affected = User::delete(&pool, user.id).await?;
println!("deleted {affected} user(s)");
Ok(())
}
Set the env var and run:
$env:DATABASE_URL = "postgres://postgres:yourpassword@localhost/my_app"
cargo run
Three things that trip up every new user
id and createdAt aren’t in UserCreate
Fields with @default(autoincrement()) or @default(now()) are excluded — the
database fills them. But literal defaults are not excluded: if your schema
has viewCount Int @default(0), you still pass view_count in Create.
Nullable update fields have two Option layers
| You write | Meaning |
|---|---|
None | leave the column alone |
Some(Some("x")) | set it to "x" |
Some(None) | set it to NULL |
And every field must be listed — Update structs don’t derive Default, so
..Default::default() won’t compile. Over JSON this is a non-issue: serde fills
absent fields with None.
posts is empty unless you ask for it
#![allow(unused)]
fn main() {
User::find().all(&pool).await?; // posts: []
User::find().with(User::posts).all(&pool)...; // posts: populated
}
Relations never load implicitly. See Eager Loading.
Where to go next
- Models & Fields — understand what your schema becomes
- CRUD Operations — the full operation surface
- Axum Integration — turn this into a REST API
- Known Limitations — read before you commit
Project Structure
After zyvor init and zyvor dev, your project looks like this:
my-api/
├── Cargo.toml
├── src/
│ └── main.rs
└── .zyvor/
├── schema.zyvor ← you edit this
├── .env ← DATABASE_URL (gitignored)
├── config.toml ← structured config
├── .gitignore ← ignores .env
├── generated/ ← CLI writes this, you never edit it
│ ├── mod.rs
│ ├── user/
│ │ ├── mod.rs
│ │ └── types.rs
│ ├── post/
│ │ ├── mod.rs
│ │ └── types.rs
│ └── ...
└── migrations/
├── 0001_initial.sql
├── 0002_schema_update.sql
└── snapshot.json
What each piece is for
| Path | Owner | Commit to git? |
|---|---|---|
schema.zyvor | you | ✅ yes — it’s your source of truth |
.env | you | ❌ no — credentials |
config.toml | you | ⚠️ only if it has no secrets |
generated/ | CLI | ✅ recommended (see below) |
migrations/*.sql | CLI | ✅ yes — this is your schema history |
migrations/snapshot.json | CLI | ✅ yes — needed for diffing |
Why one folder per model
Zyvor doesn’t emit a single giant entities.rs. Each model gets a folder:
| File | Contains |
|---|---|
user/mod.rs | User entity, UserModel, typed fields, relations |
user/types.rs | UserCreate, UserUpdate, and their trait impls |
generated/mod.rs | re-exports everything flat |
Two benefits: a 30-model schema stays navigable, and you can open one file to see exactly what Zyvor generated for one table.
Because generated/mod.rs re-exports, you import flat anyway:
#![allow(unused)]
fn main() {
#[path = "../.zyvor/generated/mod.rs"]
mod generated;
use generated::{User, UserCreate, UserModel, Post, PostModel};
}
Commit generated code or not?
Recommendation: commit it.
- Reviewers can see what your schema change actually produced.
- CI builds without running the CLI first.
- Anyone cloning gets a compiling project immediately.
The tradeoff is diff noise on schema changes. If you’d rather not, add
.zyvor/generated/ to .gitignore and run zyvor generate in CI before building —
but then snapshot.json and migrations/ must still be committed.
Never edit generated/
The next zyvor dev save overwrites it. If you need extra behaviour, write it
in your own module:
#![allow(unused)]
fn main() {
// src/models.rs — your code, safe from regeneration
use crate::generated::UserModel;
impl UserModel {
pub fn display_name(&self) -> String {
format!("{} ({})", self.name, self.email)
}
}
}
Rust lets you add inherent impls to a type from another module in the same crate. That’s your extension point.
Models & Fields
Three Translations
Zyvor’s schema is a thin layer over concepts you already know:
| You write | It means | It becomes |
|---|---|---|
model User { } | A table | CREATE TABLE users + struct UserModel |
name String | A column | "name" TEXT NOT NULL + pub name: String |
@unique | A constraint | UNIQUE |
One file, three outputs: Rust types, SQL migrations, and relation metadata.
Start with One Model
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}
Run zyvor dev:
Rust — .zyvor/generated/user/mod.rs
#![allow(unused)]
fn main() {
pub struct UserModel {
pub id: i32,
pub name: String,
pub email: String,
}
}
SQL — .zyvor/migrations/0001_initial.sql
CREATE TABLE IF NOT EXISTS "users" (
"id" SERIAL PRIMARY KEY,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL UNIQUE
);
A typed field to query with:
#![allow(unused)]
fn main() {
User::find()
.where_(User::email.eq("ali@example.com"))
.all(&pool).await?;
}
That’s the whole idea. Everything else is detail.
Names Are Translated
| Schema | Database |
|---|---|
model User | users |
model UserProfile | user_profiles |
userId | user_id |
createdAt | created_at |
Tables use pluralized snake_case. Columns use snake_case.
The same naming module feeds both generators, so Rust and SQL can’t drift apart.
Override the default names with @map and @@map when needed.
Two Kinds of Fields
This is the one thing worth reading twice:
model Post {
userId Int // A real column
user User @relation(fields: [userId], ...) // NOT a column
tags Tag[] @relation(through: "post_tags", ...) // NOT a column
}
- Scalar fields are data.
userId Intbecomes a database column and a Rust field. - Model fields are navigation. They become Rust fields (
Option<Arc<UserModel>>,Vec<Arc<TagModel>>) but create zero SQL columns.
Model-Level Attributes
Model-level attributes are written at the bottom of a model and prefixed with @@.
model PostTag {
id Int @id @default(autoincrement())
postId Int @map("post_id")
tagId Int @map("tag_id")
@@unique([postId, tagId])
@@map("post_tags")
}
Comments
Line comments are supported:
// Line comments work
model User {
id Int @id @default(autoincrement()) // Trailing comments work too
}
Block comments (/* ... */) are not supported yet.
Your Feedback Loop
zyvor validate # Is my schema legal?
zyvor dev # Generate + watch
validate runs the following stages without writing files:
- Lexer
- Parser
- Semantic validator
Use it while learning your schema language.
Rules the Validator Enforces
- Every model needs exactly one
@id. - Field names must be unique within each model.
- Model names must be unique within the schema file.
@relationis only allowed on model-typed fields.fields: [...]andreferences: [...]must have equal lengths.- A referenced field must be a primary key or have
@unique. - Foreign-key and referenced fields must share the same scalar type.
Next: Scalar Types
Scalar Types
The Eight Scalars
Zyvor supports eight scalar types:
| Schema | Rust | PostgreSQL |
|---|---|---|
Int | i32 | INTEGER |
String | String | TEXT |
Boolean | bool | BOOLEAN |
Float | f64 | DOUBLE PRECISION |
DateTime | zyvor::DateTime | TIMESTAMP |
Decimal | zyvor::Decimal | NUMERIC |
Json | zyvor::JsonValue | JSONB |
Int with @default(autoincrement()) becomes SERIAL instead of INTEGER.
Important: Int maps to i32, not i64. 64-bit integer keys are not supported yet.
Nullable Fields
Append ? to a field’s type to make it nullable.
model User {
bio String? // Optional
age Int // Required
}
| Schema | Rust | PostgreSQL |
|---|---|---|
String | String | TEXT NOT NULL |
String? | Option<String> | TEXT |
Nullability in Three Places
Nullability affects reading, creating, and updating records.
1. Reading — Option<T>
Nullable fields become Option<T> in generated models:
#![allow(unused)]
fn main() {
pub bio: Option<String>
}
2. Creating — Some or None
When creating a record, provide either a value or None:
#![allow(unused)]
fn main() {
UserCreate {
bio: Some("hello".into()),
/* ... */
}
}
3. Updating — Two Layers of Option
Updates use two nested Option values to represent three possible states:
#![allow(unused)]
fn main() {
UserUpdate {
bio: Some(Some("new".into())),
/* ... */
}
}
The two layers have different meanings:
| Value | Meaning |
|---|---|
Some(Some(value)) | Set the column to this value |
Some(None) | Set the column to NULL |
None | Leave the column untouched |
Three update states need two Option layers.
That’s the only genuinely new concept in Zyvor’s type system.
Nullable Fields Cannot Be Compared
Comparison operators such as eq, gt, and lt are currently available only for non-nullable String and Int fields.
A nullable field has a type such as Field<E, Option<String>>, which does not implement these comparison methods.
#![allow(unused)]
fn main() {
User::bio.eq("x") // ✗ Does not compile
User::bio.is_null() // ✓ Works
User::bio.is_not_null() // ✓ Works
}
Null checks work on every field type.
See Query Builder for the complete operator table and workarounds.
Wrapper Types
DateTime, Decimal, and Json map to Zyvor’s own wrapper types rather than raw third-party types.
These wrappers implement:
SerializeDeserialize- SQLx encode/decode traits
This means you don’t need to add chrono, rust_decimal, or serde_json to your Cargo.toml just to hold these values.
DateTime Is Copy
zyvor::DateTime implements Copy, so you can use it from a borrowed model without cloning:
#![allow(unused)]
fn main() {
created_at: user.created_at, // No .clone() needed
}
Check the derives on zyvor::Decimal in your generated output before assuming the same behaviour for it.
Accessing the Underlying Chrono Value
Zyvor does not re-export chrono.
If you need Chrono APIs for generating timestamps, formatting, or date arithmetic, you have two options.
Option 1: Add Chrono Directly
Add it to your Cargo.toml:
chrono = "0.4"
Option 2: Use SQLx’s Chrono Re-export
If your SQLx dependency has the chrono feature enabled, you can use its re-export:
#![allow(unused)]
fn main() {
use sqlx::types::chrono;
let email = format!(
"ali_{}@test.com",
chrono::Utc::now().timestamp()
);
}
This option adds no new dependency. That’s what the Axum example uses.
DateTime Has No Timezone
DateTime maps to PostgreSQL TIMESTAMP, not TIMESTAMPTZ.
Serialized output looks like this:
{
"created_at": "2026-11-30T21:37:57"
}
There is:
- No timezone offset.
- No trailing
Z. - No timezone information in the serialized timestamp.
If your API needs timezone-aware timestamps, store UTC by convention and document it. The database won’t enforce this convention for you.
Arrays: Parsed, Not Usable
Zyvor recognizes scalar arrays during parsing, but the CRUD generator currently rejects them.
model User {
tags String[] // Parses successfully, but CRUD generation rejects it
}
Scalar arrays are recognized by the parser but not supported by the CRUD generator.
Model arrays are different:
model User {
posts Post[] // Relation — supported
}
Model arrays represent relations and are fully supported.
If you need a list of strings today, use a child table or Json.
Next: Attributes
Attributes
Attributes attach constraints and metadata. @ is per-field, @@ is per-model.
@id — primary key
id Int @id @default(autoincrement())
Exactly one per model, required. Effect: PRIMARY KEY in SQL, and the field is
excluded from both Create and Update structs.
⚠️ Two hard constraints in v0.1
- The type must be
Int.updateanddeletetakeid: i32concretely. - The column must be named
id. Those methods emitWHERE id = $1literally.
model Account {
id Int @id @default(autoincrement()) // ✓ works
}
model Legacy {
accountId Int @id @map("account_id") // ✗ update/delete will fail
}
For a legacy table with a differently-named key, use update_many /
delete_many (they take a condition) or raw SQL.
Composite @@id([a, b]) is not supported — use a surrogate id plus
@@unique([...]).
@unique — unique constraint
email String @unique
Effect: UNIQUE in SQL. Violating it raises PostgreSQL 23505, which Zyvor
classifies as Error::UniqueViolation — map that to HTTP 409. See
Errors.
@unique on a foreign key is how you express one-to-one:
userId Int @unique // one profile per user
@default(...) — three flavours
| Written | SQL | In Create struct? |
|---|---|---|
@default(autoincrement()) | SERIAL | ❌ excluded |
@default(now()) | DEFAULT NOW() | ❌ excluded |
@default(0) / @default(false) | DEFAULT 0 / DEFAULT false | ⚠️ still required |
That third row surprises everyone. Given:
published Boolean @default(false)
viewCount Int @default(0)
you still have to write:
#![allow(unused)]
fn main() {
PostCreate {
published: true, // required, despite the default
view_count: 150, // required, despite the default
/* ... */
}
}
Why: Zyvor lists every non-excluded column in the INSERT, so the database
default never gets a chance to apply. Only autoincrement() and now() are
special-cased out. Making literal defaults optional is on the roadmap.
@map("...") — column rename
bio String? @map("user_bio")
createdAt DateTime @default(now()) @map("created_at")
Your Rust field keeps the schema name; the database column gets the mapped one.
| Layer | Name |
|---|---|
| Schema | bio |
| Rust | pub bio: Option<String> |
| Generated attribute | #[sqlx(rename = "user_bio")] |
| SQL column | "user_bio" |
Use it when your Rust naming and your database naming disagree.
⚠️ Keep mapped names lowercase
snake_case. Migrations quote identifiers; the executor does not.@map("userName")creates a case-sensitive column that the executor then can’t find.
@@map("...") — table rename
model PostTag {
// ...
@@map("post_tags")
}
Overrides the automatic pluralized name. Essential for join tables and legacy schemas. Same lowercase rule applies.
@@unique([a, b]) — composite unique
model PostTag {
id Int @id @default(autoincrement())
postId Int @map("post_id")
tagId Int @map("tag_id")
@@unique([postId, tagId])
}
Effect: a unique index across both columns. This is what makes
ON CONFLICT DO NOTHING work when inserting pivot rows — the same (post, tag)
pair can’t be added twice.
@@index([a, b]) — index
@@index([userId, createdAt])
Effect: CREATE INDEX in the migration. No effect on generated Rust.
@relation(...)
Declares how models connect. Covered in its own page: Relations.
Parsed but inert
Recognised by the parser, not implemented downstream. Don’t rely on these:
| Attribute | Status |
|---|---|
@updatedAt | parses; no automatic update behaviour generated |
@default(cuid()) | parses; not translated to a SQL default |
Quick reference
model Example {
id Int @id @default(autoincrement())
email String @unique
status Boolean @default(false)
bio String? @map("user_bio")
createdAt DateTime @default(now()) @map("created_at")
parentId Int @map("parent_id")
parent Example @relation(fields: [parentId], references: [id])
@@map("examples")
@@unique([email, status])
@@index([parentId, createdAt])
}
Next: Relations.
Relations
The one rule that explains everything
The foreign key lives on the “many” side.
A user has many posts. So Post holds userId, not the other way around. Once
that clicks, all four shapes are easy.
One-to-many
model User {
id Int @id @default(autoincrement())
posts Post[] // ← no @relation needed
}
model Post {
id Int @id @default(autoincrement())
userId Int @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
Notice the asymmetry:
Post.userdeclaresfields/referencesbecause it owns the FK.User.postsdeclares nothing — Zyvor infers it from the other side.
Generated:
| Side | Rust field | SQL column |
|---|---|---|
User.posts | Vec<PostModel> | none |
Post.userId | i32 | user_id |
Post.user | Option<Arc<UserModel>> | none |
SQL: user_id INTEGER REFERENCES users(id) ON DELETE CASCADE.
Model-typed fields produce zero columns. They’re navigation, not data.
Many-to-one
Same declaration, read from the other direction. Post.user is the
many-to-one. No separate syntax to learn.
One-to-one
Add @unique to the FK, and ? on the parent side:
model User {
id Int @id @default(autoincrement())
profile UserProfile? // ← optional, singular
}
model UserProfile {
id Int @id @default(autoincrement())
userId Int @unique // ← the whole trick
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
@unique means at most one profile row per user. ? means a user may have none.
Generated: User.profile is Option<Arc<UserProfileModel>>.
Verified output — user 1 has a profile, user 2 doesn’t:
[
{ "id": 1, "profile": { "id": 1, "website": "https://zyvor.dev" } },
{ "id": 2, "profile": null }
]
Many-to-many
Both sides declare through, pivotFrom, pivotTo:
model Post {
id Int @id @default(autoincrement())
tags Tag[] @relation(through: "post_tags", pivotFrom: "post_id", pivotTo: "tag_id")
}
model Tag {
id Int @id @default(autoincrement())
posts Post[] @relation(through: "post_tags", pivotFrom: "tag_id", pivotTo: "post_id")
}
Read it as: “from me, my pivot column is pivotFrom; the other side’s column is
pivotTo.” They mirror each other.
⚠️ camelCase: pivotFrom, pivotTo — not pivot_from.
Generated: Vec<Arc<TagModel>> on both sides.
You must declare the pivot table yourself
Zyvor does not invent a join table from through:. Declare it as a model:
model PostTag {
id Int @id @default(autoincrement())
postId Int @map("post_id")
tagId Int @map("tag_id")
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
@@unique([postId, tagId])
@@map("post_tags")
}
Six extra lines, and you get a real CREATE TABLE, real foreign keys, and a
composite unique constraint that makes ON CONFLICT DO NOTHING work.
Verified: Rust → 2 posts, ORM → 1 post, resolved through post_tags.
onDelete
| Value | Meaning |
|---|---|
Cascade | delete children with the parent |
Restrict | block the delete if children exist |
SetNull | set the FK to NULL (field must be nullable) |
NoAction | defer to the database |
Cascade on Post.userId means deleting a user removes their posts — verified
end-to-end.
Three consequences to know before you query
1. Nothing loads automatically
posts is [] until you call .with(User::posts). There’s no lazy loading
either — touching the field never triggers a query. See
Eager Loading.
2. Back-references don’t serialize
Zyvor marks back-references #[serde(skip)] to prevent infinite recursion
(Post → User → Posts → …). Side effect: a loaded Post.user is invisible in
raw model JSON. Use DTOs — the Axum guide shows the
pattern.
3. with_nested needs a collection
Nested eager loading requires a Vec-shaped relation:
#![allow(unused)]
fn main() {
.with_nested(User::posts, |q| q.with(Post::comments)) // ✓ posts is a Vec
.with_nested(Post::user, |q| q.with(User::posts)) // ✗ won't compile
}
For a single relation, use plain .with(Post::user).
Not supported yet
| Gap | Detail |
|---|---|
| Composite foreign keys | multi-column fields / references parses, but codegen handles single-column only |
| Auto-generated pivot tables | declare the pivot model |
| Full cardinality validation | some invalid shapes slip through the validator |
| Scalar arrays | tags String[] is not a relation and is rejected by CRUD generation |
Next: Migrations.
Migrations
Migrations are generated from your schema, tracked in the database, and applied in order. You never hand-write SQL for a schema change.
Where They Come From
zyvor dev # Generates 0001_initial.sql, then detects changes on every save
zyvor migrate --apply # Applies migrations that haven't run yet
Order matters. Run
zyvor devfirst to generate migration files. Runningzyvor migrate --applybefore that results in:
No migration files found in .zyvor/migrations/
Initial Migration
0001_initial.sql contains the following for every model:
CREATE TABLE IF NOT EXISTS— idempotent table creation- Columns with mapped names and quoted identifiers
NOT NULLconstraints for non-nullable fieldsPRIMARY KEYandSERIALfor autoincrement fieldsUNIQUEconstraints and indexes- Composite unique indexes
- Foreign keys with
ON DELETEactions - Supported default values
Type Mapping
| Schema Type | PostgreSQL Type |
|---|---|
Int | INTEGER |
Int @default(autoincrement()) | SERIAL |
String | TEXT |
Boolean | BOOLEAN |
Float | DOUBLE PRECISION |
DateTime | TIMESTAMP |
Decimal | NUMERIC |
Json | JSONB |
Incremental Migrations
zyvor dev maintains a serialized schema snapshot at:
.zyvor/migrations/snapshot.json
Whenever you save your schema, Zyvor compares it with the previous snapshot and generates a migration file if it detects changes.
Example output:
🔄 Schema change detected! Generated: 0002_schema_update.sql
Migration Numbering
Migration numbering is automatic. Zyvor scans the existing .sql files, finds the highest migration number, and increments it.
Supported Schema Changes
| Schema Change | Generated SQL |
|---|---|
| Field added | ALTER TABLE ... ADD COLUMN |
| Field removed | ALTER TABLE ... DROP COLUMN IF EXISTS |
| Model removed | DROP TABLE IF EXISTS ... CASCADE |
| Model added | Noted in the diff; full CREATE TABLE is included in the regenerated initial migration |
An unchanged schema produces no diff file, avoiding unnecessary migration files.
Migration Tracking
Running zyvor migrate --apply creates and maintains the _zyvor_migrations table:
CREATE TABLE IF NOT EXISTS _zyvor_migrations (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
checksum TEXT NOT NULL,
applied_at TIMESTAMP NOT NULL DEFAULT NOW()
);
For each .sql file, Zyvor processes migrations in filename order:
- Calculates a hash of the SQL contents.
- Looks up the migration filename in
_zyvor_migrations. - Same checksum: skips the migration.
- Different checksum: returns a hard error showing both hashes.
- Not recorded: executes the migration and then records it.
Example output:
⏭️ 0001_initial.sql already applied. Skipping.
📝 Applying: 0002_schema_update.sql
✅ 0002_schema_update.sql applied successfully!
What This Means
- Re-running is safe: If the schema and migration files haven’t changed, Zyvor skips already-applied migrations.
- Applied migration edits are detected: Changing an already-applied migration produces a drift error instead of silently allowing the database history to disagree with the migration file.
Automatic Database Creation
If the target database doesn’t exist, Zyvor connects to the PostgreSQL postgres maintenance database, checks pg_database, and creates the target database.
Example output:
📦 Creating database 'my_app'...
✅ Database 'my_app' created!
You don’t need to run CREATE DATABASE manually.
Not Supported Yet
The following migration capabilities are not currently supported. Use the listed workarounds when needed.
| Missing Capability | Current Workaround |
|---|---|
ALTER COLUMN TYPE | Write a forward migration manually |
| Rename detection | A rename is treated as drop + add, which can cause data loss. Hand-write the migration |
| Index and constraint diffs | Handle them manually |
Rollback, migrate reset, and migrate status | Write a forward migration |
Pivot tables from through: | Declare the pivot table as a model |
Composite @@id | Use a surrogate id with @@unique([...]) |
⚠️ Renaming a field is potentially destructive.
For example, renaming
biotobiographyin your schema generates:
DROP COLUMN bioADD COLUMN biographyThe existing data in
biois lost. Until rename detection is supported, review every generated migration diff before applying it.
zyvor init
Scaffolds a Zyvor project in the current directory.
zyvor init
What it creates
.zyvor/
├── schema.zyvor ← template with a User model
├── .env ← DATABASE_URL=postgres://postgres:admin@localhost/zyvor_gen
├── config.toml ← [database] url = "..."
├── .gitignore ← contains .env
├── generated/ ← empty, CLI fills it
└── migrations/ ← empty, CLI fills it
Safe to re-run
If .zyvor/ already exists:
.zyvor/ already exists. Skipping init.
Nothing is overwritten. Your schema and migrations are never at risk.
Immediately after
- Edit
.zyvor/.env— set your real PostgreSQL credentials and database name. The database doesn’t need to exist yet. - Edit
.zyvor/schema.zyvor. - Run
zyvor dev.
About those credentials
The template ships a placeholder password (admin). Change it. .zyvor/.gitignore
already excludes .env, so your real credentials won’t be committed — but only
if you leave that file alone.
config.toml is not gitignored. If you put a real password there, you’ll
commit it. Prefer .env for secrets.
zyvor dev
Generates once, then watches your schema and regenerates on every save.
zyvor dev
Output
👀 Watching .zyvor/schema.zyvor for changes...
Press Ctrl+C to stop
✅ Generated 13 modular files in ".zyvor/generated"
✅ Generated: .zyvor/generated/ (modular)
✅ Generated: .zyvor/migrations/0001_initial.sql
💾 Snapshot saved
On a schema change:
🔄 Schema change detected! Regenerating...
🔄 Schema change detected! Generated: 0002_schema_update.sql
💾 Snapshot saved
✅ Regeneration complete
What it does each cycle
- read → lex → parse → validate
- compare source against
migrations/snapshot.json - if unchanged:
📋 Schema unchanged. Skipping.— nothing written - if changed: write modular entities, regenerate initial SQL, diff against the old snapshot, write an auto-numbered diff migration, save the new snapshot
A 300 ms debounce absorbs the double-write some editors do on save.
How to use it
Leave it running in one terminal. Work in another:
# terminal 1
zyvor dev
# terminal 2
zyvor migrate --apply
cargo run
dev never touches your database. It only writes files. Applying is a
separate, deliberate step.
Errors don’t kill the watcher
If you save a broken schema mid-edit, you get:
❌ Regeneration failed: <error>
The watcher keeps running. Fix the schema, save again, and it recovers. Your previously generated files stay on disk untouched.
Requires init first
No .zyvor/schema.zyvor found. Run 'zyvor init' first.
zyvor migrate
Two modes: generate a SQL file, or apply migrations to a database.
Generate only
zyvor migrate # .zyvor/schema.zyvor → migrations/0001_initial.sql
zyvor migrate path/to/schema.zyvor # custom schema
zyvor migrate schema.zyvor out/custom.sql # custom output
Output directories are created as needed. Existing output files are overwritten.
Apply
zyvor migrate --apply
zyvor migrate --apply --database postgres://user:pass@localhost/mydb
This is the mode you’ll use daily. It:
- resolves the database URL
- creates the database if it doesn’t exist
- ensures
_zyvor_migrationsexists - scans
migrations/*.sql, sorts by filename - for each file: checksum → skip / drift-error / apply + record
- lists the resulting tables
🚀 Applying migrations to database...
Database: postgres://postgres:****@localhost/my_app
📦 Creating database 'my_app'...
✅ Database 'my_app' created!
📋 Found 2 migration file(s)
⏭️ 0001_initial.sql already applied. Skipping.
📝 Applying: 0002_schema_update.sql
✅ 0002_schema_update.sql applied successfully!
Tables in database:
📋 _zyvor_migrations
📋 posts
📋 users
Passwords are always masked in output.
Where the URL comes from
Highest priority first:
--database <URL>DATABASE_URLenvironment variable.zyvor/.env.zyvor/config.toml→[database] url
If none is found, you get an actionable error telling you exactly what to create.
Two errors you’ll actually see
No migration files
No migration files found in .zyvor/migrations/. Run 'zyvor dev' first.
dev generates the files. Run it before applying.
Schema drift
❌ Schema drift in '0001_initial.sql'! Checksum mismatch.
Old: 4a2f...
New: 9c1b...
You edited a migration that was already applied. Don’t do that — migrations are history. Write a new forward migration instead. If you’re intentionally resetting a dev database, drop it and re-apply from scratch.
Not available yet
migrate status, migrate reset, migrate dev, and rollback. To undo
something today, write a new migration that reverses it.
zyvor validate
Checks your schema without generating anything.
zyvor validate # defaults to rust.schema
zyvor validate .zyvor/schema.zyvor # explicit path
Success:
Schema is valid: .zyvor/schema.zyvor
What it runs
source → lexer → parser → AST → semantic validator
No files written, no database contacted. This is the fastest way to check a schema edit.
What it catches
| Category | Examples |
|---|---|
| Syntax | unterminated string, invalid character, malformed attribute |
| Structure | missing @id, multiple @id, duplicate model or field names |
| References | unknown model in a relation, unknown field in fields / references |
| Relations | @relation on a scalar field, mismatched fields / references counts |
| Keys | referenced column isn’t a PK or @unique |
| Types | FK type doesn’t match the referenced column type |
| M2M | incomplete or contradictory through / pivotFrom / pivotTo metadata |
When to reach for it
- Learning the schema language — tight feedback loop, no side effects.
- In CI, as a cheap gate before generating.
- After a big refactor, before you look at generated output.
Known gaps
Error messages don’t yet carry line/column information, and some edge cases
slip through: relation cardinality/array-shape consistency, default-value
type compatibility, and full @@index / @@unique field validation.
So validate passing means “no known rule violated”, not “provably correct”.
Review your generated diff before applying it.
Entity & Model
The trait
Every generated entity implements zyvor::Entity:
#![allow(unused)]
fn main() {
pub trait Entity {
type Model;
const TABLE: &'static str;
const COLUMNS: &'static [Column];
fn columns() -> &'static [Column] { Self::COLUMNS }
fn find() -> Query<Self> where Self: Sized;
async fn create<'c, D, A>(db: A, data: D) -> Result<Self::Model>
where
D: InsertData<Self>,
A: sqlx::Acquire<'c, Database = sqlx::Postgres>,
for<'r> Self::Model: sqlx::FromRow<'r, PgRow> + Send + Unpin;
async fn update<'c, D, A>(db: A, id: i32, data: D) -> Result<Self::Model>;
async fn delete<'c, A>(db: A, id: i32) -> Result<u64>;
async fn create_many<'c, D, A>(db: A, data: Vec<D>) -> Result<Vec<Self::Model>>;
async fn update_many<'c, D, A>(db: A, condition: Condition<Self>, data: D) -> Result<u64>;
async fn delete_many<'c, A>(db: A, condition: Condition<Self>) -> Result<u64>;
}
}
Signatures abbreviated — update, delete, and the bulk methods carry the same
Acquire bound as create.
Three things to notice:
A: sqlx::Acquire— that’s why one call works with both&PgPooland&mut Transaction. See Transactions.D: InsertData<Self>/UpdateData<Self>— the generatedCreate/Updatestructs implement these. You can hand-write your own input type by implementing the trait.id: i32— hardcoded. See the limitation below.
Two types per model
| Type | Role |
|---|---|
User | zero-sized marker. Holds constants and typed fields. Never instantiated. |
UserModel | the actual row. Debug + Serialize + Deserialize + FromRow. |
#![allow(unused)]
fn main() {
pub struct User; // entity: User::find(), User::id, User::posts
pub struct UserModel { /* ... */ } // data: what you get back
}
User::find() returns Query<User>, and Query::all() returns
Vec<UserModel> — the association is Entity::Model.
Column
#![allow(unused)]
fn main() {
impl Column {
pub const fn new(name: &'static str) -> Self;
pub const fn qualified(table: &'static str, name: &'static str) -> Self;
pub const fn name(&self) -> &'static str;
pub const fn table(&self) -> Option<&'static str>;
}
}
Column is Debug + Clone + Copy. Unqualified columns are what generated
COLUMNS contains; qualified is used internally for joins and subqueries.
You’ll pass Column to group_by:
#![allow(unused)]
fn main() {
.group_by(User::name.column())
}
Relation traits
Generated models implement these so the eager loader can attach children:
#![allow(unused)]
fn main() {
pub trait RelationKey {
fn relation_key(&self, column: Column) -> Option<i64>;
}
pub trait RelationLoader<Related> {
fn load_relation(&mut self, related: Vec<Related>); // collections
}
pub trait SingleRelationLoader<Related> {
fn load_relation(&mut self, related: Option<Related>); // single relations
}
}
RelationKey returning Option<i64> is why keys are normalized to i64
internally even though your id is i32.
You rarely touch these directly — but if you hand-write a model, they’re what
you implement to make .with() work.
⚠️ Primary keys must be Int
update and delete take id: i32 concretely. A String or UUID primary key
will generate a model, but you won’t be able to call User::update / User::delete
on it. update_many / delete_many take a Condition, so they still work.
Use Int @id @default(autoincrement()) for now.
Two error types in the API
| Method | Returns |
|---|---|
create, update, delete, bulk variants | zyvor::error::Result<T> (= Result<T, zyvor::Error>) |
Query::all, count, fetch_all | Result<T, sqlx::Error> |
zyvor::Error is a typed enum that auto-classifies unique and foreign-key
violations. Queries return the raw sqlx error — convert it when you want the
same classification:
#![allow(unused)]
fn main() {
let users = User::find().all(&pool).await
.map_err(zyvor::Error::from)?;
}
See Errors & HTTP Status for matching patterns and the current caveats.
Query Builder
User::find() returns Query<User>. Every builder method takes self by value and returns a new query, so you can chain methods freely.
Filtering
#![allow(unused)]
fn main() {
let users = User::find()
.where_(User::age.gte(18))
.where_(User::name.eq("Ali Khan"))
.all(&pool).await?;
}
Combining Conditions
Condition provides and and or, both taking self and another condition by value.
AND:
#![allow(unused)]
fn main() {
let users = User::find()
.where_(
User::age.gte(18)
.and(User::name.eq("Ali Khan"))
)
.all(&pool).await?;
}
OR:
#![allow(unused)]
fn main() {
let users = User::find()
.where_(
User::name.eq("Ali Khan")
.or(User::name.eq("Fakhir Israr"))
)
.all(&pool).await?;
}
Mixing AND and OR — Mind the Grouping
and and or build a left-nested condition tree. There are no grouping helpers, so the order of chaining determines the grouping:
#![allow(unused)]
fn main() {
a.and(b).or(c) // → (a AND b) OR c
a.or(b).and(c) // → (a OR b) AND c
}
Chain conditions in the order you intend.
Each separate .where_() call is combined with AND at the top level. This provides one level of grouping:
#![allow(unused)]
fn main() {
let users = User::find()
.where_(User::age.gte(18))
.where_(
User::name.eq("Ali")
.or(User::name.eq("Fakhir"))
)
.all(&pool).await?;
}
Generated SQL:
WHERE age >= $1 AND (name = $2 OR name = $3)
Chained where_() calls are AND-ed. Each call merges into the existing condition with AND; it does not replace the previous condition.
For deeper nesting than this, use raw SQL.
Comparison Operators
Important: Comparison operators are currently implemented only for
Stringandi32fields.
| Field Type | eq | not_eq | gt | gte | lt | lte |
|---|---|---|---|---|---|---|
String | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Int (i32) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Boolean | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Float (f64) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
DateTime | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Decimal | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Json | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Nullable fields (Option<T>) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
The following examples do not compile:
#![allow(unused)]
fn main() {
User::find().where_(Post::published.eq(true))
User::find().where_(User::created_at.gt(some_date))
User::find().where_(User::bio.eq("x"))
}
These correspond to:
Field<E, bool>Field<E, DateTime>Field<E, Option<String>>
Null Checks
Null checks work with every field type:
#![allow(unused)]
fn main() {
let users = User::find()
.where_(User::bio.is_null())
.all(&pool).await?;
let users = User::find()
.where_(User::bio.is_not_null())
.all(&pool).await?;
}
Using Raw SQL
For comparisons that are not supported by the query builder, use SQLx directly:
#![allow(unused)]
fn main() {
let rows: Vec<UserModel> = sqlx::query_as(
"SELECT * FROM users WHERE published = $1 AND created_at > $2"
)
.bind(true)
.bind(cutoff)
.fetch_all(&pool)
.await?;
}
Raw SQL serves as an escape hatch when the query builder cannot express a particular query.
Ordering and Pagination
#![allow(unused)]
fn main() {
let page = User::find()
.order_by(User::id.desc())
.take(20) // LIMIT
.skip(40) // OFFSET
.all(&pool).await?;
}
The methods are take() and skip(), not limit() and offset().
Single-Column Ordering
order_by() stores only one ordering value. Calling it again replaces the previous value:
#![allow(unused)]
fn main() {
let users = User::find()
.order_by(User::name.asc())
.order_by(User::id.desc()) // Replaces name ordering
.all(&pool).await?;
}
Multi-column ordering is not currently supported.
For queries such as:
ORDER BY name ASC, id DESC
use raw SQL.
DISTINCT, GROUP BY and Aggregates
#![allow(unused)]
fn main() {
let names = User::find()
.distinct()
.all(&pool).await?;
}
You can also select specific columns and aggregate values:
#![allow(unused)]
fn main() {
let counts: Vec<(String, i64)> = User::find()
.select(User::name.select())
.select(User::id.count())
.group_by(User::name.column())
.fetch_all(&pool).await?;
}
Selection Behaviour
- The first
select()call clears the default column list and adds the selected expression. - Subsequent
select()calls append additional selections. group_by()accumulates columns. Call it once for each grouping column.- Aggregate projections require
fetch_all::<M>()with a matching tuple or struct because the result no longer matchesUserModel.
Available Aggregates
The following aggregate methods are available on any field:
| Method | Description |
|---|---|
count() | Counts values |
sum() | Calculates the sum |
avg() | Calculates the average |
min() | Returns the minimum |
max() | Returns the maximum |
HAVING Limitations
having() accepts a Condition<E>, which is built from field comparisons.
However, aggregate methods such as count() return a SelectItem, not a condition.
Therefore, this does not compile:
#![allow(unused)]
fn main() {
.having(User::id.count().gt(2))
}
HAVING COUNT(*) > 2 cannot currently be expressed through the query builder.
Use raw SQL for grouped filters.
Subqueries
The query builder supports subqueries through in_subquery().
#![allow(unused)]
fn main() {
let active = User::find()
.select(User::id.select())
.where_(User::name.eq("Ali Khan"));
let posts = Post::find()
.where_(Post::user_id.in_subquery(active))
.all(&pool).await?;
}
in_subquery() compiles the inner query and embeds its SQL and bind values into the outer query.
Placeholder numbering is adjusted correctly, keeping $1, $2, and subsequent parameters consistent across both queries.
Joins
The query builder supports inner, left, right, full and cross joins.
#![allow(unused)]
fn main() {
let rows = User::find()
.inner_join(Post::user_id.eq_column(User::id))
.all(&pool).await?;
}
Available Join Methods
| Method | Argument |
|---|---|
inner_join() | T: JoinTarget |
left_join() | T: JoinTarget |
right_join() | T: JoinTarget |
full_join() | T: JoinTarget |
cross_join() | &'static str — raw table name |
Understanding eq_column()
The field on which you call eq_column() determines the joined table.
When querying User and joining posts, call it on the Post field:
#![allow(unused)]
fn main() {
User::find()
.inner_join(Post::user_id.eq_column(User::id))
}
Generated SQL:
INNER JOIN posts ON posts.user_id = users.id
Both fields must have the same Rust type:
#![allow(unused)]
fn main() {
Field<E, T>
Field<E2, T>
}
Join Limitations
Joins change the shape of the returned rows.
When using joins:
- Explicitly define the selected columns with
select(). - Use
fetch_all::<M>()with a matching result type. - Do not rely on
all()to constructUserModelfrom a joined result.
Important: GROUP BY and ORDER BY currently emit unqualified column names.
If joined tables contain columns with the same name, such as id, PostgreSQL may return an ambiguity error.
Use raw SQL for such queries.
Query Execution
| Method | Accepts | Returns |
|---|---|---|
all(db) | impl Acquire — pool or transaction | Result<Vec<E::Model>, sqlx::Error> |
count(db) | &PgPool only | Result<i64, sqlx::Error> |
fetch_all::<M>(db) | &PgPool only | Result<Vec<M>, sqlx::Error> |
Fetching All Records
#![allow(unused)]
fn main() {
let users = User::find()
.where_(User::age.gte(18))
.all(&pool).await?;
}
Counting Records
#![allow(unused)]
fn main() {
let total = User::find()
.where_(User::age.gte(18))
.count(&pool).await?;
}
Custom Result Types
For custom projections and aggregate queries:
#![allow(unused)]
fn main() {
let results: Vec<(String, i64)> = User::find()
.select(User::name.select())
.select(User::id.count())
.group_by(User::name.column())
.fetch_all(&pool).await?;
}
COUNT Limitations
count() currently includes only joins and WHERE conditions.
It ignores:
GROUP BYHAVINGLIMITOFFSET
This means:
- Counting a grouped query returns the ungrouped matching row count, not the number of groups.
- Calling
count()aftertake(10)returns the full matching count, not just 10.
The second behaviour is useful for pagination when you need the total number of matching records rather than the number of records on the current page.
Do not rely on count() for grouped queries.
Method Reference
| Category | Methods | Behaviour |
|---|---|---|
| Filtering | where_() | Combines conditions with AND |
| Relations | with(), with_nested() | Loads relations |
| Ordering | order_by() | Single ordering column |
| Pagination | take(), skip() | LIMIT and OFFSET |
| Shape | distinct(), select() | Controls selected results |
| Grouping | group_by() | Accumulates grouping columns |
| Group filtering | having() | Accepts Condition<E> |
| Joins | inner_join(), left_join(), right_join(), full_join(), cross_join() | Joins tables |
| Execution | all(), count(), fetch_all() | Executes queries |
Not Available in 0.1
The following methods are not currently available:
first()one()limit()offset()like()
For queries requiring unsupported functionality, use SQLx raw SQL.
CRUD Operations
Every generated entity gets create, read, update, delete — plus bulk variants. One import:
#![allow(unused)]
fn main() {
use generated::{User, UserCreate, UserUpdate};
use zyvor::Entity;
}
Create
#![allow(unused)]
fn main() {
let user = User::create(&pool, UserCreate {
name: "Ali Khan".into(),
email: "ali@example.com".into(),
age: 28,
bio: Some("Rust developer".into()),
}).await?;
}
Returns the full UserModel, including database-generated id and created_at
(via RETURNING).
What’s not in UserCreate: fields with @default(autoincrement()) or
@default(now()), the primary key, and all relation fields.
What is still required: literal defaults. @default(0) and @default(false)
do not make a field optional — see Attributes.
Read
#![allow(unused)]
fn main() {
let all = User::find().all(&pool).await?;
let adults = User::find()
.where_(User::age.gte(18))
.all(&pool).await?;
let one = User::find()
.where_(User::id.eq(1))
.all(&pool).await?
.into_iter().next(); // Option<UserModel>
}
all() returns a Vec. An empty result is Ok(vec![]), not an error — so
“not found” is a decision your code makes.
Update
#![allow(unused)]
fn main() {
let updated = User::update(&pool, 1, UserUpdate {
name: Some("Ali Updated".into()),
bio: Some(Some("Senior Rust dev".into())),
email: None,
age: None,
created_at: None,
}).await?;
}
Every field must be listed
UserUpdate does not derive Default, so ..Default::default() won’t compile.
Use None for “leave unchanged”. (Adding Default is planned for 0.1.1.)
Nullable fields: Option<Option<T>>
| Value | Effect |
|---|---|
None | column omitted from SET |
Some(Some(v)) | SET col = v |
Some(None) | SET col = NULL |
Over HTTP it’s simpler
Serde fills absent Option fields with None:
PUT /users/2
{ "name": "Fakhir Updated", "bio": "Senior Rust Developer" }
Verified: email, age, created_at unchanged.
⚠️ created_at is writable through Update. If it should be immutable in your
API, use a DTO that doesn’t expose it.
Delete
#![allow(unused)]
fn main() {
let affected = User::delete(&pool, 1).await?;
if affected == 0 { /* row didn't exist */ }
}
Returns a row count. A missing row is Ok(0), not Err.
What “not found” looks like per operation
The four operations behave differently, and this matters for your handlers:
| Operation | Row doesn’t exist |
|---|---|
create | n/a — always inserts |
update | Err(Error::NotFound) — UPDATE … RETURNING returns no row |
delete | Ok(0) — row count, not an error |
find().all() | Ok(vec![]) — empty vector, not an error |
So update gives you a matchable error, while delete and find make you
decide:
#![allow(unused)]
fn main() {
// update — error path
let user = User::update(&pool, id, patch).await.map_err(to_status)?; // → 404
// delete — count path
if User::delete(&pool, id).await? == 0 {
return Err(StatusCode::NOT_FOUND);
}
// find — option path
let user = User::find().where_(User::id.eq(id)).all(&pool).await?
.into_iter().next()
.ok_or(StatusCode::NOT_FOUND)?;
}
⚠️ An empty update is an error
If every field in your Update struct is None, no columns are produced and
Zyvor returns an error rather than executing a no-op:
#![allow(unused)]
fn main() {
User::update(&pool, 1, UserUpdate {
name: None, email: None, age: None, bio: None, created_at: None,
}).await
// → Err(Error::Generation("UPDATE requires at least one field"))
}
This bites PATCH-style endpoints where a client sends {}. Guard it:
#![allow(unused)]
fn main() {
async fn update_user(
State(state): State<AppState>,
Path(id): Path<i32>,
Json(input): Json<UserUpdate>,
) -> Result<Json<UserModel>, StatusCode> {
// treat an empty patch as a bad request, not a 500
if input.name.is_none()
&& input.email.is_none()
&& input.age.is_none()
&& input.bio.is_none()
{
return Err(StatusCode::BAD_REQUEST);
}
let user = User::update(&state.db, id, input).await.map_err(to_status)?;
Ok(Json(user))
}
}
Note the error variant is Generation, which is meant for code-generation
failures — a semantic mismatch in 0.1. Match on it if you must, but don’t read
meaning into the variant name.
⚠️ Your primary key column must be named id
update and delete build WHERE id = $1 literally. Not “the field marked
@id” — the actual column named id.
model Account {
id Int @id @default(autoincrement()) // ✓ works
}
model Legacy {
accountId Int @id @map("account_id") // ✗ update/delete will fail
}
update_many / delete_many take a Condition, so they’re unaffected. For a
legacy table with a differently-named key, use those, or raw SQL.
Bulk
#![allow(unused)]
fn main() {
let created = User::create_many(&pool, vec![a, b, c]).await?; // Vec<UserModel>
let n = User::update_many(&pool, User::age.lt(18), patch).await?; // u64
let n = User::delete_many(&pool, User::age.lt(18)).await?; // u64
}
create_many with an empty Vec is handled — no malformed SQL. NULL values in
bulk operations, including mixed NULL/non-NULL placeholder ordering, are covered
by the runtime test suite.
Works with pools and transactions
All of these accept either &PgPool or &mut Transaction<'_, Postgres>:
#![allow(unused)]
fn main() {
let mut tx = pool.begin().await?;
let user = User::create(&mut tx, input).await?;
User::update(&mut tx, user.id, patch).await?;
tx.commit().await?;
}
Writing your own input types
The generated Create / Update structs are just implementations of two public
traits. You can write your own.
InsertData
#![allow(unused)]
fn main() {
pub trait InsertData<E: Entity> {
fn columns(&self) -> &'static [&'static str];
fn values(&self) -> Vec<BindValue>;
}
}
Note the static slice — the column list is fixed at compile time.
#![allow(unused)]
fn main() {
use zyvor::executor::InsertData;
use zyvor::value::BindValue;
use crate::generated::User;
struct SignupInput {
name: String,
email: String,
}
impl InsertData<User> for SignupInput {
fn columns(&self) -> &'static [&'static str] {
&["name", "email", "age", "user_bio"]
}
fn values(&self) -> Vec<BindValue> {
vec![
BindValue::String(self.name.clone()),
BindValue::String(self.email.clone()),
BindValue::I64(18), // default age
BindValue::Null, // no bio
]
}
}
// works exactly like the generated type
let user = User::create(&pool, SignupInput { name, email }).await?;
}
UpdateData
#![allow(unused)]
fn main() {
pub trait UpdateData<E: Entity> {
fn columns(&self) -> Vec<&'static str>; // ← dynamic, not static
fn values(&self) -> Vec<BindValue>;
}
}
The Vec is deliberate: it lets you include columns conditionally, which is how
partial updates work.
#![allow(unused)]
fn main() {
use zyvor::executor::UpdateData;
struct Patch {
name: Option<String>,
clear_bio: bool,
}
impl UpdateData<User> for Patch {
fn columns(&self) -> Vec<&'static str> {
let mut cols = Vec::new();
if self.name.is_some() { cols.push("name"); }
if self.clear_bio { cols.push("user_bio"); }
cols
}
fn values(&self) -> Vec<BindValue> {
let mut vals = Vec::new();
if let Some(n) = &self.name { vals.push(BindValue::String(n.clone())); }
if self.clear_bio { vals.push(BindValue::Null); }
vals
}
}
}
Rules you must follow
columns()andvalues()must have the same length and order. Zyvor zips them; a mismatch produces wrong SQL, not an error.- Use database column names, not Rust field names —
user_bio, notbio. BindValue::Nullbecomes a literalNULL, not a placeholder. Zyvor skips it during binding and keeps placeholder numbering correct.- At least one column for updates, or you get an error.
BindValue::I64takesi64even though your model field isi32.
BindValue variants
#![allow(unused)]
fn main() {
BindValue::String(String)
BindValue::I64(i64)
BindValue::Boolean(bool)
BindValue::F64(f64)
BindValue::DateTime(chrono::NaiveDateTime)
BindValue::Decimal(rust_decimal::Decimal)
BindValue::Json(serde_json::Value)
BindValue::Null
}
Why identifiers aren’t quoted
The executor formats table and column names directly into SQL without quoting.
Migrations do quote them. Consequence: stick to lowercase snake_case names.
A @@map("User") creates a case-sensitive "User" table in the migration, but
the executor emits INSERT INTO User, which PostgreSQL folds to user — and
the insert fails.
Automatic snake_case naming and @map("snake_case") overrides are safe.
See Transactions.
Eager Loading
Nothing loads unless you ask
#![allow(unused)]
fn main() {
let users = User::find().all(&pool).await?;
assert!(users[0].posts.is_empty()); // always empty here
}
Relations are not loaded by default, and there is no lazy loading either —
touching .posts will never trigger a query. The field just holds its default.
The rule that makes empty values meaningful
| You called | posts: [] means | profile: None means |
|---|---|---|
.find().all() | nothing — not loaded, unknown | nothing — not loaded, unknown |
.find().with(...).all() | this row really has zero children | this row really has no related row |
So .with() doesn’t just fetch data — it makes the empty case trustworthy.
Here is a real response from .with_nested(User::posts, |q| q.with(Post::comments)):
{
"id": 1, "name": "Ali Khan",
"posts": [
{ "id": 1, "title": "Zyvor Guide",
"comments": [
{ "id": 1, "body": "Great article!" },
{ "id": 2, "body": "Very helpful." }
] },
{ "id": 2, "title": "Axum Integration",
"comments": [ { "id": 3, "body": "Nice integration guide." } ] }
]
}
And in the same payload, another user’s post:
{ "id": 3, "title": "Zyvor v0.1 Released", "comments": [] }
That [] is a real answer: post 3 has no comments. Because .with() ran,
you can trust it. Without .with(), you couldn’t.
Practical takeaway: only expose relation fields on endpoints that actually
call .with(). That’s exactly what the DTO pattern in the Axum guide does.
Transactions
Every CRUD method and Query::all is generic over
sqlx::Acquire<'c, Database = sqlx::Postgres>. Both &PgPool and
&mut Transaction<'_, Postgres> satisfy that bound, so the same call works in
either context.
Basic pattern
#![allow(unused)]
fn main() {
let mut tx = pool.begin().await?;
let user = User::create(&mut tx, UserCreate {
name: "Ali Khan".into(),
email: "ali@example.com".into(),
age: 28,
bio: None,
}).await?;
let post = Post::create(&mut tx, PostCreate {
title: "First post".into(),
content: None,
published: false,
view_count: 0,
user_id: user.id,
}).await?;
User::update(&mut tx, user.id, UserUpdate {
bio: Some(Some("Now with a post".into())),
name: None,
email: None,
age: None,
created_at: None,
}).await?;
tx.commit().await?;
}
Note &mut tx, not &tx.
Rollback
Explicit:
#![allow(unused)]
fn main() {
tx.rollback().await?;
}
Or implicit — dropping a Transaction without committing rolls it back. That
means the ? operator gives you rollback for free:
#![allow(unused)]
fn main() {
async fn seed(pool: &PgPool) -> Result<(), Box<dyn std::error::Error>> {
let mut tx = pool.begin().await?;
User::create(&mut tx, a).await?; // any error → early return → tx dropped → rollback
Post::create(&mut tx, b).await?;
tx.commit().await?;
Ok(())
}
}
This is the idiomatic way to make a multi-step operation atomic.
Reads inside a transaction
#![allow(unused)]
fn main() {
let mut tx = pool.begin().await?;
let users = User::find()
.where_(User::age.gte(18))
.all(&mut tx).await?; // ✅ works
let with_posts = User::find()
.with(User::posts)
.all(&mut tx).await?; // ✅ eager loading works too
tx.commit().await?;
}
Eager loading runs on the same connection as the parent query, so relation reads see your uncommitted writes. No surprise consistency gaps.
⚠️ Two methods that don’t work in a transaction
| Method | Signature | In a tx? |
|---|---|---|
count | count(self, db: &PgPool) | ❌ |
fetch_all::<M> | fetch_all<M>(self, db: &PgPool) | ❌ |
They take a concrete &PgPool rather than impl Acquire. Calling them with
&mut tx won’t compile.
Workarounds:
#![allow(unused)]
fn main() {
// instead of count() inside a tx — read and count in Rust
let n = User::find().where_(cond).all(&mut tx).await?.len();
// instead of fetch_all() inside a tx — use sqlx directly on the transaction
let rows: Vec<(String, i64)> = sqlx::query_as(
"SELECT name, COUNT(*) FROM users GROUP BY name"
)
.fetch_all(&mut *tx).await?;
}
Making these two generic over Acquire is a small change and is on the roadmap.
What’s covered by tests
The runtime test suite exercises, inside transactions: queries, create, update, delete, create_many, update_many, delete_many, and relation loading.
Isolation level
Zyvor doesn’t set one — you get PostgreSQL’s default (READ COMMITTED). If you
need something stronger, configure it on the connection before starting your
work, or execute SET TRANSACTION ISOLATION LEVEL ... as the first statement
in the transaction.
Axum Integration
Zyvor’s generated types derive Serialize / Deserialize, so they work with
Axum’s Json extractor directly. No glue code, no wrapper types.
Dependencies
[dependencies]
zyvor = "0.1"
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "chrono"] }
Two pinning rules:
sqlxmust be 0.8 — matching Zyvor. See Installation.- Axum 0.8 uses
{id}path syntax, not:id. If you’re copying an older tutorial,.route("/users/:id", ...)will not match in 0.8.
Including generated code
#![allow(unused)]
fn main() {
#[path = "../.zyvor/generated/mod.rs"]
mod generated;
use generated::{User, UserCreate, UserModel, UserUpdate};
use zyvor::Entity;
}
State
#![allow(unused)]
fn main() {
#[derive(Clone)]
struct AppState { db: PgPool }
}
PgPool is already Clone, and Zyvor’s types are Send + Sync, so this
composes with Axum without friction.
Why you want DTOs (not optional)
Returning PostModel straight from a handler gives you this:
{ "id": 1, "title": "Zyvor Guide", "user_id": 1, "comments": [], "tags": [] }
Notice what’s missing: user. Even if you called .with(Post::user) and
the data is sitting in memory, Zyvor marks back-references #[serde(skip)] to
prevent infinite recursion (Post → User → Posts → Post → …).
So a loaded many-to-one relation is invisible in raw model JSON. A DTO fixes that and gives you a stable API contract:
#![allow(unused)]
fn main() {
#[derive(Serialize)]
struct PostWithUserResponse {
#[serde(flatten)]
post: PostResponse,
user: Option<UserResponse>,
}
}
#[serde(flatten)] keeps the JSON flat — clients see one object, not a nested
{ post: {...}, user: {...} } envelope.
One handler per relation shape
#![allow(unused)]
fn main() {
// 1:N
let users = User::find().with(User::posts).all(&state.db).await?;
// N:1 — Option<Arc<_>>, use as_deref()
let posts = Post::find().with(Post::user).all(&state.db).await?;
let dto = PostWithUserResponse {
post: PostResponse::from(post),
user: post.user.as_deref().map(UserResponse::from),
};
// 1:1 — same shape as N:1
let users = User::find().with(User::profile).all(&state.db).await?;
// M:M — Vec<Arc<_>>, use as_ref()
let tags = Tag::find().with(Tag::posts).all(&state.db).await?;
let posts: Vec<PostResponse> = tag.posts.iter().map(|p| PostResponse::from(p.as_ref())).collect();
// 2-level nested
let users = User::find()
.with_nested(User::posts, |q| q.with(Post::comments))
.all(&state.db).await?;
}
Partial updates over HTTP
Serde fills absent Option fields with None, so clients send only what
they want to change:
#![allow(unused)]
fn main() {
async fn update_user(
State(state): State<AppState>,
Path(id): Path<i32>,
Json(input): Json<UserUpdate>,
) -> Result<Json<UserModel>, StatusCode> {
let user = User::update(&state.db, id, input)
.await
.map_err(|e| db_err(e, "update_user"))?;
Ok(Json(user))
}
}
PUT /users/2
{ "name": "Fakhir Updated", "bio": "Senior Rust Developer" }
Verified: email, age, created_at untouched.
Idempotent seeding
Tag::create fails with 409 on a second run because name is @unique.
Look it up first:
#![allow(unused)]
fn main() {
async fn find_or_create_tag(db: &PgPool, name: &str) -> Result<TagModel, StatusCode> {
if let Some(tag) = Tag::find()
.where_(Tag::name.eq(name))
.all(db).await
.map_err(|e| db_err(e, "find_tag"))?
.into_iter().next()
{
return Ok(tag);
}
Tag::create(db, TagCreate { name: name.to_string() })
.await
.map_err(|e| db_err(e, "create_tag"))
}
}
For the pivot table, raw SQL is the honest tool — Zyvor doesn’t generate pivot insert helpers yet:
#![allow(unused)]
fn main() {
sqlx::query(
"INSERT INTO post_tags (post_id, tag_id) VALUES ($1,$2),($3,$4) \
ON CONFLICT DO NOTHING"
)
.bind(post1.id).bind(tag1.id)
.bind(post1.id).bind(tag2.id)
.execute(&state.db).await?;
}
This is the escape hatch working as intended: the ORM handles the common path, SQL handles the rest.
Verified endpoints
| Endpoint | Shape | Status |
|---|---|---|
GET /users | plain CRUD | ✅ |
POST /users | create | ✅ 201 |
GET /users/{id} | read one | ✅ |
PUT /users/{id} | partial update | ✅ |
DELETE /users/{id} | delete | ✅ 204 |
GET /users/with-posts | 1:N | ✅ |
GET /users/with-profile | 1:1 | ✅ |
GET /posts/with-user | N:1 | ✅ |
GET /tags/with-posts | M:M | ✅ |
GET /users/with-nested | 2-level nested | ✅ |
GET /users/99999 | not found | ✅ 404 |
POST /users duplicate email | unique violation | ✅ 409 |
Full source: zyvor-axum-demo
Errors & HTTP Status
Zyvor has a typed error enum
#![allow(unused)]
fn main() {
pub enum Error {
Database(sqlx::Error),
NotFound { entity: &'static str, id: i64 },
UniqueViolation { entity: &'static str, field: &'static str, value: String },
ForeignKeyViolation { entity: &'static str, field: &'static str, referenced_entity: &'static str },
Migration(MigrationError),
Generation(String),
}
pub type Result<T> = std::result::Result<T, Error>;
}
Error implements Display and std::error::Error, with source() chaining to
the underlying sqlx::Error where one exists.
Automatic classification
impl From<sqlx::Error> for Error inspects the PostgreSQL SQLSTATE code:
| Code | Becomes |
|---|---|
23505 | Error::UniqueViolation { .. } |
23503 | Error::ForeignKeyViolation { .. } |
RowNotFound | Error::NotFound { .. } |
| anything else | Error::Database(err) |
So you don’t parse error strings yourself. CRUD methods already return
zyvor::error::Result, which means classification has happened by the time you
get the error.
Which method returns which error
| Method | Error type |
|---|---|
create, update, delete, create_many, update_many, delete_many | zyvor::Error |
Query::all, count, fetch_all | sqlx::Error |
Queries return the raw sqlx error. Convert it yourself when you want classification:
#![allow(unused)]
fn main() {
let users = User::find()
.all(&pool).await
.map_err(zyvor::Error::from)?; // ← now it's classified
}
That one .map_err gives you the same typed error on the query path.
Matching instead of string scanning
#![allow(unused)]
fn main() {
use zyvor::Error;
fn to_status(e: Error) -> StatusCode {
match e {
Error::NotFound { .. } => StatusCode::NOT_FOUND, // 404
Error::UniqueViolation { .. } => StatusCode::CONFLICT, // 409
Error::ForeignKeyViolation { .. } => StatusCode::BAD_REQUEST, // 400
Error::Database(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND,
other => {
eprintln!("DB error: {other}");
StatusCode::INTERNAL_SERVER_ERROR // 500
}
}
}
}
Usage in a handler:
#![allow(unused)]
fn main() {
let user = User::create(&state.db, input).await.map_err(to_status)?;
}
This is strictly better than scanning a formatted string for "23505".
⚠️ Don’t trust the payload fields yet
The variants exist and classify correctly, but some fields are placeholders:
| Field | Reality |
|---|---|
NotFound.entity | always "unknown" |
NotFound.id | always -1 |
ForeignKeyViolation.referenced_entity | always "unknown" |
UniqueViolation.value | the full PostgreSQL message, not the duplicate value |
And the parsed entity / field come from splitting the constraint name, which
breaks on multi-word table names:
| Constraint | Parsed field | Correct field |
|---|---|---|
users_email_key | email | ✅ |
user_profiles_user_id_key | id | ❌ should be user_id |
post_tags_post_id_tag_id_key | id | ❌ composite |
Practical guidance for 0.1: match on the variant to pick a status code.
Don’t build user-facing messages from entity / field — write your own
message per endpoint instead:
#![allow(unused)]
fn main() {
Error::UniqueViolation { .. } => (
StatusCode::CONFLICT,
Json(json!({ "error": "That email is already registered." })),
),
}
You know which endpoint you’re in; the error doesn’t need to tell you.
Not-found behaves differently per operation
| Operation | Missing row |
|---|---|
update | Err(Error::NotFound) — matchable |
delete | Ok(0) |
find().all() | Ok(vec![]) |
So update maps cleanly to 404 through your matcher. For delete and find,
404 is your decision:
#![allow(unused)]
fn main() {
if User::delete(&state.db, id).await.map_err(to_status)? == 0 {
return Err(StatusCode::NOT_FOUND);
}
}
Migration errors
#![allow(unused)]
fn main() {
pub enum MigrationError {
FileNotFound(String),
DriftDetected { migration: String, expected_checksum: String, actual_checksum: String },
AlreadyAppliedDifferent(String),
ExecutionFailed { migration: String, source: sqlx::Error },
TrackingTableFailed(sqlx::Error),
}
}
Note: the CLI currently reports migration failures through its own error type with formatted messages, so you’ll see these as text output rather than as matchable variants. Unifying the two error systems is on the roadmap.
Verified behaviour
| Case | Request | Result |
|---|---|---|
| Row doesn’t exist | GET /users/99999 | ✅ 404 |
| Delete missing row | DELETE /users/99999 | ✅ 404 |
| Duplicate unique email | POST /users, existing email | ✅ 409 |
| Malformed body | POST /users, {"invalid":true} | ✅ 422 |
The 422 comes from Axum’s Json extractor failing to deserialize into
UserCreate — Zyvor never sees the request. Required fields are enforced by the
type system at the boundary, which is exactly where you want it.
Known issue: memory leak on classified errors
From<sqlx::Error> uses Box::leak to turn parsed Strings into the
&'static str fields the enum declares. Every UniqueViolation and
ForeignKeyViolation permanently leaks two small allocations.
In a long-running server receiving repeated constraint violations, this is unbounded growth. It’s small per occurrence, but it never gets freed.
If you’re running a high-traffic service on 0.1, be aware of it. The fix
(changing those fields to String) is planned for 0.2.0.
Known issue: Generation used for runtime validation
Two runtime input errors are reported as Error::Generation, which is otherwise
meant for code-generation failures:
"UPDATE requires at least one field"— every update field wasNone"All insert_many items must have the same columns"— mismatched bulk inputs
If you match exhaustively, route these to 400 rather than 500:
#![allow(unused)]
fn main() {
Error::Generation(msg) if msg.contains("at least one field") => StatusCode::BAD_REQUEST,
}
A dedicated InvalidInput variant is planned.
Schema Syntax
Your schema lives at .zyvor/schema.zyvor.
A complete example
model User {
id Int @id @default(autoincrement())
name String
email String @unique
age Int
bio String? @map("user_bio")
createdAt DateTime @default(now()) @map("created_at")
profile UserProfile?
posts Post[]
}
model UserProfile {
id Int @id @default(autoincrement())
avatar String?
website String?
userId Int @unique
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
viewCount Int @default(0) @map("view_count")
userId Int @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
comments Comment[]
tags Tag[] @relation(through: "post_tags", pivotFrom: "post_id", pivotTo: "tag_id")
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
posts Post[] @relation(through: "post_tags", pivotFrom: "tag_id", pivotTo: "post_id")
}
model PostTag {
id Int @id @default(autoincrement())
postId Int @map("post_id")
tagId Int @map("tag_id")
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
@@unique([postId, tagId])
@@map("post_tags")
}
Types
| Schema | Rust | PostgreSQL |
|---|---|---|
Int | i32 | INTEGER |
Int @default(autoincrement()) | i32 | SERIAL |
String | String | TEXT |
Boolean | bool | BOOLEAN |
Float | f64 | DOUBLE PRECISION |
DateTime | zyvor::DateTime | TIMESTAMP |
Decimal | zyvor::Decimal | NUMERIC |
Json | zyvor::JsonValue | JSONB |
T? makes it Option<T> / nullable.
The wrapper types re-export their inner crate, so you don’t need chrono,
rust_decimal, or serde_json as direct dependencies just to hold a value.
zyvor::DateTime and zyvor::Decimal are Copy — you can move them out of a
&Model without cloning.
DateTimemaps toTIMESTAMP, notTIMESTAMPTZ. No timezone is stored. Serialized output looks like"2026-11-30T21:37:57".
Field attributes
| Attribute | Effect |
|---|---|
@id | primary key (exactly one per model, required) |
@unique | unique constraint |
@default(autoincrement()) | SERIAL; excluded from Create |
@default(now()) | DEFAULT NOW(); excluded from Create |
@default(<literal>) | SQL default — still required in Create |
@map("col") | column name override → #[sqlx(rename)] |
@relation(...) | relation metadata |
Model attributes
| Attribute | Effect |
|---|---|
@@map("table") | table name override |
@@unique([a, b]) | composite unique index |
@@index([a, b]) | index |
Relations
| Shape | How you write it |
|---|---|
| one-to-many | posts Post[] on the parent, @relation on the child |
| many-to-one | user User @relation(fields: [userId], references: [id]) |
| one-to-one | many-to-one + @unique on the FK, and UserProfile? on the parent |
| many-to-many | Tag[] @relation(through: "post_tags", pivotFrom: ..., pivotTo: ...) on both sides |
onDelete accepts Cascade, Restrict, SetNull, NoAction.
Note the camelCase: pivotFrom / pivotTo, not pivot_from.
Pivot tables must be explicit
Zyvor does not invent a join table from through:. You declare it as a model
(PostTag above) so it gets a real CREATE TABLE, foreign keys, and a
composite unique constraint. @@id([a, b]) is not supported — use a surrogate
id plus @@unique([...]).
Naming conventions
| Schema | Database |
|---|---|
User | users |
UserProfile | user_profiles |
userId | user_id |
createdAt | created_at |
Table names are pluralized snake_case, columns are snake_case. @map / @@map
always win. The same naming module feeds both the entity generator and the
migration generator, so they can’t drift apart.
Parsed but not fully supported
Being explicit so you don’t lose an afternoon:
- Scalar arrays (
tags String[]) — parsed, but CRUD generation rejects them. - Composite foreign keys — metadata parses; codegen handles single-column only.
@updatedAt— parses; no automatic update behaviour is generated.@@id([...])— not supported.cuid()defaults — parsed; not translated to a SQL default.
CLI Commands
cargo install zyvor-cli
zyvor init
Scaffolds the project:
.zyvor/
├── schema.zyvor ← template schema
├── .env ← DATABASE_URL
├── config.toml
├── .gitignore ← ignores .env
├── generated/
└── migrations/
Skips safely if .zyvor/ already exists.
zyvor dev
Generates once, then watches schema.zyvor and regenerates on save
(300 ms debounce for editor double-writes).
✅ Generated 13 modular files in ".zyvor/generated"
✅ Generated: .zyvor/migrations/0001_initial.sql
💾 Snapshot saved
👀 Watching .zyvor/schema.zyvor for changes...
On a schema change it also diffs against snapshot.json and writes an
auto-numbered incremental migration:
🔄 Schema change detected! Generated: 0002_schema_update.sql
Order matters.
devproduces the migration files. Runningmigrate --applybeforedevgives youNo migration files found in .zyvor/migrations/.
zyvor migrate --apply
Applies every .sql file in order, tracking what’s already run.
📦 Creating database 'my_app'...
✅ Database 'my_app' created!
📋 Found 2 migration file(s)
⏭️ 0001_initial.sql already applied. Skipping.
📝 Applying: 0002_schema_update.sql
✅ 0002_schema_update.sql applied successfully!
Three things happen here worth calling out:
- The database is created if missing. You never run
CREATE DATABASEby hand. Zyvor connects to thepostgresmaintenance database, checkspg_database, and creates your target if needed. - Checksums make re-runs free. Each file’s SQL is hashed and recorded in
_zyvor_migrations. Same name + same checksum → skipped. - Edited an applied migration? You get an error, not silent drift. Same name + different checksum → hard stop with both hashes shown.
Passwords are masked in all console output.
zyvor generate / zyvor validate
| Command | What it does |
|---|---|
zyvor validate [SCHEMA] | lex → parse → validate, no output written |
zyvor generate [SCHEMA] | one-shot entity generation, no watching |
Configuration
Resolution order, highest priority first:
--database <URL>flagDATABASE_URLenvironment variable.zyvor/.env.zyvor/config.toml→[database] url = "..."
Not implemented yet
migrate status, migrate reset, migrate dev, and rollback. If you need to
undo, write a new forward migration — that’s the honest workflow today.
Known Limitations (v0.1.0)
Verified against source. Grouped by how likely you are to hit them.
You’ll hit these on day one
Comparison operators only exist for String and Int
eq, not_eq, gt, gte, lt, lte are implemented only for
Field<E, String> and Field<E, i32>.
Not available on: Boolean, Float, DateTime, Decimal, Json, and
every nullable field (Option<T>).
rust Post::published.eq(true) // ✗ won't compile User::created_at.gt(cutoff) // ✗ User::bio.eq("x") // ✗ nullable User::bio.is_null() // ✓ null checks work on any type
Workaround: raw SQL for that query. See Query Builder.
Update structs have no Default
..Default::default() won’t compile. List every field, None to skip.
Over JSON this is a non-issue — serde fills absent fields.
Literal defaults are still required in Create
@default(0) / @default(false) do not make a field optional. Only
autoincrement() and now() are excluded.
Loaded many-to-one relations don’t serialize
Back-references carry #[serde(skip)] to prevent recursion. A loaded
Post.user is invisible in raw model JSON. Use DTOs.
sqlx must be 0.8
Zyvor 0.1 depends on sqlx 0.8. Using 0.9 puts two sqlx_core versions in your
graph and produces FromRow / Acquire trait-bound errors.
Query builder
| Limitation | Detail |
|---|---|
Single ORDER BY column | second order_by() replaces the first |
HAVING can’t compare aggregates | .count() returns SelectItem, which has no .gt() |
count() ignores GROUP BY / HAVING / LIMIT / OFFSET | counts joins + WHERE only |
count() / fetch_all() are pool-only | take &PgPool, not impl Acquire — no transactions |
| Unqualified GROUP BY / ORDER BY | can be ambiguous when joining tables with shared column names |
No first() / one() / like() | use all() + .into_iter().next(), or raw SQL |
| No CTE, UNION, FOR UPDATE | — |
Relations
| Limitation | Detail |
|---|---|
with_nested needs a collection relation | requires RelationLoader (Vec). .with_nested(Post::user, ..) won’t compile |
| Unloaded vs empty is ambiguous | [] / None means both. Only trust it after .with() |
| Composite foreign keys | parsed, but codegen handles single-column only |
| Pivot tables | must be declared as an explicit model |
Schema
| Limitation | Detail |
|---|---|
Primary key must be Int | update/delete take id: i32 concretely |
Composite @@id | unsupported — surrogate id + @@unique([...]) |
Scalar arrays (String[]) | parsed, rejected by CRUD generation |
@updatedAt | parsed, no behaviour generated |
@default(cuid()) | parsed, no SQL default |
| Block comments | not supported |
| Validator gaps | cardinality/array-shape consistency, default-value type compatibility, full @@index/@@unique field validation |
| Error locations | no line/column in messages yet |
Types
DateTime→TIMESTAMP, notTIMESTAMPTZ. No timezone stored.Int→i32(noti64).
Errors
A typed Error enum exists and auto-classifies PostgreSQL 23505 / 23503 /
RowNotFound. Matching on variants works.
Rough edges in 0.1:
| Issue | Detail |
|---|---|
| Memory leak | From<sqlx::Error> uses Box::leak for &'static str fields. Every classified constraint violation leaks two allocations permanently |
| Placeholder fields | NotFound.entity = "unknown", NotFound.id = -1, ForeignKeyViolation.referenced_entity = "unknown" |
| Fragile parsing | entity/field derived from constraint-name splitting; breaks on multi-word tables (user_profiles_user_id_key → field id) |
UniqueViolation.value | holds the full PG message, not the duplicate value |
| Two error types | CRUD → zyvor::Error; queries → sqlx::Error. Bridge with .map_err(zyvor::Error::from) |
| Two migration error systems | runtime MigrationError enum vs CLI’s formatted-string errors |
Generation misuse | runtime input validation reported as a codegen error variant |
Guidance: match on variants for status codes; write your own user-facing
messages rather than trusting entity / field.
Migrations
| Missing | Workaround |
|---|---|
ALTER COLUMN TYPE | hand-write a forward migration |
| rename detection | ⚠️ a rename becomes DROP + ADD — data loss. Review every diff |
| index / constraint diffs | hand-write |
rollback, migrate status, migrate reset | forward migration |
| auto pivot tables | declare the pivot model |
Database support
PostgreSQL only. SQLite and MySQL are not implemented.
Planned
0.1.1 — additive, non-breaking
Defaultderive onUpdatestructscount/fetch_allgeneric overAcquire(transaction support)- Multi-column
order_by migrate status- Populate
NotFound/referenced_entityproperly; usedb_err.table()/.column()instead of constraint-name parsing
0.2.0 — breaking
- Comparison operators for
bool,f64,DateTime,Decimal,Option<T> - Error enum fields
&'static str→String(removes theBox::leakleak) - Unified error type across queries and CRUD
Primary key must be an Int column literally named id
update and delete emit WHERE id = $1. Both the type (i32) and the column
name (id) are hardcoded. @mapping your PK to another name breaks these two
methods; update_many / delete_many still work.
Identifiers are unquoted in the executor
Migrations quote identifiers; the executor does not. Use lowercase snake_case
table and column names. @@map("User") or any name needing quoting will fail at
runtime.
Empty update is an error
All-None update → Err(Error::Generation(..)), not a no-op. Guard PATCH
endpoints.
Models with only auto-generated fields
If every column is @default(autoincrement()) or @default(now()), the
generated Create struct has no fields and the INSERT has an empty column list.
Keep at least one user-supplied column per model.
Changelog
0.1.0 — 2026-12-01
First public release on crates.io: zyvor
and zyvor-cli.
Schema & CLI
- Schema language, lexer, parser, AST, semantic validator
init,dev(watch + debounce),generate,validate,migrate,migrate --apply.env/config.toml/ env-var / CLI-flag configuration with priority resolution.gitignoregeneration to protect credentials- Shared naming module (pluralized snake_case tables, snake_case columns)
Code generation
- Modular output: one folder per model (
mod.rs+types.rs) - Entity, model, typed fields, relation metadata and loaders
Create/Updatestructs withInsertData/UpdateDataimplsSerialize/Deserialize/FromRowderives@map→#[sqlx(rename)],@@map→ table overrideOption<Option<T>>nullable update semantics#[serde(skip)]on back-references to prevent recursive serialization
Migrations
- Initial
CREATE TABLE IF NOT EXISTSwith keys, indexes, FKs,ON DELETE _zyvor_migrationstracking table with checksums- Idempotent re-apply, schema-drift detection
- Snapshot-based diffing (
ADD COLUMN,DROP COLUMN, dropped tables) - Auto-numbered incremental migrations
- Automatic database creation if the target doesn’t exist
Runtime
- Query builder:
WHERE,ORDER BY,LIMIT/OFFSET,DISTINCT,GROUP BY,HAVING,IN, aggregates, subqueries with bind propagation - Joins:
INNER,LEFT,RIGHT,FULL,CROSS, multiple joins - Relations: 1:N, N:1, 1:1, M:M with
.with()and.with_nested() - CRUD + bulk CRUD, pools and transactions
BindValuelayer with explicit SQL NULL semantics- Wrapper types:
DateTime,Decimal,JsonValue Send + Syncthroughout for async frameworks
Verification
- 115 runtime tests, 64 CLI tests, clippy clean at
-D warnings - Axum E2E verified: CRUD, 1:N, N:1, 1:1, M:M, 2-level nested eager loading, 404 / 409 / 422 handling, cascade delete
Known limitations
PostgreSQL only · sqlx must be 0.8 · no rollback · no typed error enum ·
no composite PK/FK codegen · scalar arrays rejected by CRUD generation ·
literal defaults still required in Create · Update has no Default derive ·
DateTime is TIMESTAMP without timezone
See Known Limitations for the full list.
Planned for 0.1.1
DefaultonUpdatestructs- Typed error enum
migrate status
0.1.1 — 2026-12-02
Metadata and ergonomics patch. No breaking changes.
Fixed
- Corrected
repositoryURLs on crates.io (previous links pointed to a non-existent GitHub account) zyvor validateandzyvor generatenow default to.zyvor/schema.zyvorinstead of the legacyrust.schemazyvor migratenow writes to.zyvor/migrations/somigrate --applyfinds the generated file- Corrected the output path printed by
zyvor generate
Added
keywords,categories,homepage,documentationmetadata on both cratesrust-version = "1.85"(edition 2024 requirement made explicit)- LICENSE-MIT and LICENSE-APACHE files
- Documentation book: https://fakhir-israr-200219.github.io/zyvor-doc/