Write a .zyvor schema file, get type-safe Rust and tracked PostgreSQL migrations.
The CLI is a build-time toolchain — your application depends on
zyvor, not on this crate.
⚡ Status: v0.1 — active development. Parsing, validation, modular codegen, migration tracking with diffing, watch mode, and auto database creation are functional and verified end-to-end against PostgreSQL + Axum.
Quick Start
# Install
# Scaffold
# Edit .zyvor/schema.zyvor and .zyvor/.env, then generate + watch
# In a second terminal — creates the database if it doesn't exist
⚠️ Order matters
zyvor dev generates the migration files. Running migrate --apply first
gives you:
No migration files found in .zyvor/migrations/. Run 'zyvor dev' first.
Leave dev running in one terminal, work in another.
Project structure after init
my-api/
├── Cargo.toml
├── src/main.rs
└── .zyvor/
├── schema.zyvor ← you edit this
├── .env ← DATABASE_URL (gitignored)
├── config.toml
├── .gitignore ← protects .env
├── generated/ ← CLI writes this, never edit by hand
│ ├── mod.rs ← flat re-exports
│ ├── user/
│ │ ├── mod.rs ← Entity + Model + fields + relations
│ │ └── types.rs ← Create + Update structs
│ └── post/
│ ├── mod.rs
│ └── types.rs
└── migrations/
├── 0001_initial.sql
├── 0002_schema_update.sql
└── snapshot.json
Commands
| Command | Description |
|---|---|
zyvor init |
Scaffold .zyvor/ — schema template, .env, config, .gitignore |
zyvor dev |
Generate, then watch and regenerate + diff on every save |
zyvor migrate --apply |
Apply pending migrations (creates the database if missing) |
zyvor validate [SCHEMA] |
Lex + parse + validate, nothing written |
zyvor generate [SCHEMA] |
One-shot entity generation |
zyvor migrate [SCHEMA] [OUTPUT] |
Generate migration SQL to a file |
zyvor --help / -h |
Usage |
zyvor --version / -V |
Version |
⚠️ Pass schema paths explicitly
validate and generate still default to the legacy filename rust.schema,
while dev and migrate --apply use .zyvor/schema.zyvor. Until that's
unified, be explicit:
Similarly, plain zyvor migrate writes to migrations/0001_initial.sql at the
project root, not .zyvor/migrations/. For the standard workflow use
zyvor dev — it writes to the right place. Plain migrate is for standalone
SQL generation with an explicit output path:
Database URL resolution
Highest priority first:
--database <URL>flagDATABASE_URLenvironment variable.zyvor/.env.zyvor/config.toml→[database] url
Passwords are masked in all console output.
Architecture
schema.zyvor
↓
Lexer → Parser → AST → Validator
↓
┌──────────────────┬─────────────────┬──────────────────┐
│ Entity Generator │ Migration Gen │ Snapshot Manager │
└────────┬─────────┴────────┬────────┴────────┬─────────┘
↓ ↓ ↓
generated/ migrations/ snapshot.json
(modular) (auto-numbered) (change detection)
Runtime boundary
| Responsibility | CLI | Runtime |
|---|---|---|
| Schema parsing & validation | ✅ | — |
| Rust code generation | ✅ | — |
| Migration SQL generation | ✅ | — |
| Migration tracking & diffing | ✅ | — |
| Auto database creation | ✅ | — |
| Watch-mode regeneration | ✅ | — |
| Query building & execution | — | ✅ |
| Entity CRUD operations | — | ✅ |
| Relation eager loading | — | ✅ |
| Transactions | — | ✅ |
The CLI generates code for the runtime. It never reimplements it.
Schema language
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 Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
userId Int @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
comments Comment[]
tags Tag[] @relation(through: "post_tags", pivotFrom: "post_id", pivotTo: "tag_id")
}
| Category | Supported |
|---|---|
| Scalars | Int String Boolean Float DateTime Decimal Json |
| Modifiers | nullable T? · model arrays Post[] (relations) |
| Field attrs | @id @unique @default(...) @map("col") @relation(...) |
| Model attrs | @@map("table") @@unique([a, b]) @@index([a, b]) |
| Relations | 1:N, N:1, 1:1, M:M (explicit pivot model required) |
| Referential actions | Cascade Restrict SetNull NoAction |
| Defaults | autoincrement(), now(), literals |
⚠️ Scalar arrays (tags String[]) parse but are rejected by CRUD
generation. Model arrays (posts Post[]) are relations and fully supported.
⚠️ Relation args are camelCase: pivotFrom / pivotTo, not pivot_from.
Type mapping
| Schema | Generated Rust | SQL |
|---|---|---|
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 |
Naming is automatic: UserProfile → user_profiles, createdAt → created_at.
@map / @@map override it. The same naming module feeds both generators, so
Rust and SQL can't drift apart.
Modular code generation
One folder per model, so a 30-model schema stays navigable:
| Component | File | Contents |
|---|---|---|
| Entity marker | {model}/mod.rs |
pub struct User; |
| Model struct | {model}/mod.rs |
UserModel — Serialize, Deserialize, FromRow |
| Typed fields | {model}/mod.rs |
User::name, User::id |
| Relations | {model}/mod.rs |
Relation constants + loader impls |
| Create input | {model}/types.rs |
UserCreate + InsertData impl |
| Update input | {model}/types.rs |
UserUpdate + UpdateData impl |
| Re-exports | generated/mod.rs |
pub use user::{User, UserModel, UserCreate, UserUpdate}; |
Create structs
Fields with @default(autoincrement()) or @default(now()) are excluded —
the database fills them. Primary keys and relation fields are excluded too.
⚠️ Literal defaults are not excluded. @default(0) and @default(false)
still require a value in Create, because Zyvor lists every non-excluded column
in the INSERT.
Update structs
| Value | Effect |
|---|---|
None |
column omitted from SET |
Some(Some(v)) |
SET col = v |
Some(None) |
SET col = NULL |
⚠️ No Default derive — ..Default::default() won't compile. List every
field. Over JSON this is a non-issue: serde fills absent fields with None.
⚠️ An all-None update returns an error, not a no-op. Guard PATCH endpoints.
Migration system
Initial migration
CREATE TABLE IF NOT EXISTS with columns, primary keys, SERIAL, NOT NULL,
unique constraints, defaults, foreign keys with ON DELETE, indexes, composite
unique indexes, and mapped identifiers.
Schema diffing
zyvor dev compares against migrations/snapshot.json on every save:
| 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 diff; full CREATE TABLE in regenerated initial |
Auto-numbered sequentially: 0001_initial.sql, 0002_schema_update.sql, …
⚠️ Rename detection is not implemented. Renaming a field generates DROP + ADD, which loses data. Review every generated diff before applying.
Tracking
Every migrate --apply maintains _zyvor_migrations:
(
id SERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
checksum TEXT NOT NULL,
applied_at TIMESTAMP NOT NULL DEFAULT NOW
);
- Checksum skip — same name + same hash → skipped
- Drift detection — same name + different hash → hard error with both hashes
- Idempotent — re-running with unchanged files does nothing
Auto database creation
📦 Creating database 'my_app'...
✅ Database 'my_app' created!
🚀 Applying migrations to database...
Zyvor connects to the postgres maintenance database, checks pg_database, and
creates your target if needed. No manual CREATE DATABASE.
Using generated code
[]
= "0.1"
= { = "0.8", = ["runtime-tokio", "postgres", "chrono"] }
= { = "1", = ["full"] }
= { = "1", = ["derive"] }
⚠️ sqlx must be 0.8
Zyvor 0.1 depends on sqlx 0.8. A different major-minor puts two sqlx_core
versions in your graph and produces confusing errors:
the trait bound `UserModel: FromRow<'r, PgRow>` is not satisfied
there are multiple different versions of crate `sqlx_core` in the dependency graph
Pin to 0.8. Verify with cargo tree -i sqlx.
use ;
use Entity;
// Typed fields — chained where_ calls are AND-ed
let users = find
.where_
.order_by
.take
.all.await?;
// Two-level nested eager loading
let users = find
.with_nested
.all.await?;
📖 Runtime API · Axum integration
Verified end-to-end
zyvor init → schema.zyvor → zyvor dev → generated/ + migrations/
↓
zyvor migrate --apply → database created, tables applied
↓
Axum API → CRUD + all 4 relation types + nested eager loading
↓
✅ verified
| Area | Status |
|---|---|
| Lexer, parser, validator | ✅ |
| Entity + CRUD code generation | ✅ |
| Migration SQL generation | ✅ |
| Migration tracking + drift detection | ✅ |
| Schema diffing + auto-numbering | ✅ |
| Auto database creation | ✅ |
| Axum CRUD endpoints | ✅ |
| Eager loading (1:N, N:1, 1:1, M:M) | ✅ |
| Nested eager loading (2 levels) | ✅ |
| Error handling (404 / 409 / 422) | ✅ |
| Cascade delete | ✅ |
64 CLI tests passing · 115 runtime tests passing in
zyvor ·
cargo clippy --all-targets --all-features -- -D warnings clean.
Reproduce it: zyvor-axum-demo
Known limitations
| Limitation | Detail |
|---|---|
| Scalar arrays | String[] parses, rejected by CRUD generation |
Literal defaults required in Create |
@default(0) doesn't make a field optional |
Update has no Default |
list every field; all-None update errors |
Primary key must be Int named id |
runtime update/delete emit WHERE id = $1 |
| Composite foreign keys | metadata parses, codegen handles single-column only |
Composite @@id |
unsupported — use surrogate id + @@unique([...]) |
| Pivot tables | must be declared as an explicit model |
@updatedAt |
parses, no behaviour generated |
@default(cuid()) |
parses, no SQL default |
| Identifier quoting | migrations quote, executor doesn't — keep names lowercase snake_case |
| Rename detection | missing — a rename becomes DROP + ADD (data loss) |
| Column type changes | not diffed |
Rollback / migrate status / migrate reset |
not implemented |
| Default schema path | validate/generate still default to rust.schema |
| Error locations | no line/column info yet |
| PostgreSQL only | no SQLite / MySQL |
Roadmap
✅ Done
- Schema language, lexer, parser, AST, validator
- Modular entity generation (per-model folders)
- All four relation types
- CRUD codegen (
Create/Update/InsertData/UpdateData) - Migration generation + execution
- Tracking, checksum skip, drift detection
- Schema diffing + auto-numbering
- Auto database creation
- Watch mode with snapshot change detection
-
.env/config.tomlconfiguration - Axum integration verified
- Documentation book
🔜 Next
- Unify default schema paths (
rust.schema→.zyvor/schema.zyvor) -
Defaultderive onUpdatestructs - Make literal defaults optional in
Create -
migrate status - Line/column info in parser and validator errors
🔜 Later
- Column type changes · rename detection · rollback
- Composite foreign-key codegen
- VS Code syntax highlighting for
.zyvor - MySQL / SQLite
Design principles
- CLI is a toolchain, not a runtime — generates code for the
zyvorcrate - Schema is the source of truth — one definition, everything derived
- Generated code is readable Rust — no hidden macros, fully inspectable
- Milestone-tracked features — parser ≠ validator ≠ generator ≠ runtime verification
- Zero manual database setup — auto-create, auto-migrate, auto-diff
- Honest scope — limitations documented, not buried
Related repositories
| Repo | What |
|---|---|
| zyvor | Runtime crate — query builder, CRUD, relations |
| zyvor-cli | This crate — schema toolchain |
| zyvor-doc | Documentation source (live book) |
| zyvor-axum-demo | Verified Axum + PostgreSQL example |
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
Acknowledgements
Inspired by Prisma, Drizzle, and the frustration of writing repetitive ORM boilerplate in Rust.