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