zyvor-cli 0.1.1

CLI for Zyvor โ€” schema-driven ORM code generator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
<p align="center">
  <img src="https://raw.githubusercontent.com/Fakhir-Israr-200219/zyvor/main/logo.png" alt="Zyvor" width="180">
</p>

<h1 align="center">Zyvor CLI</h1>

<p align="center"><strong>Schema parser, code generator, and migration toolchain for Zyvor ORM.</strong></p>

<p align="center">
  <a href="https://crates.io/crates/zyvor-cli"><img src="https://img.shields.io/crates/v/zyvor-cli.svg" alt="crates.io"></a>
  <a href="https://crates.io/crates/zyvor-cli"><img src="https://img.shields.io/crates/d/zyvor-cli.svg" alt="downloads"></a>
  <a href="https://fakhir-israr-200219.github.io/zyvor-doc/"><img src="https://img.shields.io/badge/docs-book-blue" alt="docs"></a>
  <a href="#license"><img src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue" alt="license"></a>
</p>

<p align="center">
  ๐Ÿ“– <a href="https://fakhir-israr-200219.github.io/zyvor-doc/"><strong>Documentation</strong></a> ยท
  ๐Ÿฆ€ <a href="https://github.com/Fakhir-Israr-200219/zyvor">Runtime</a> ยท
  ๐Ÿš€ <a href="https://github.com/Fakhir-Israr-200219/zyvor-axum-demo">Axum example</a> ยท
  ๐Ÿ“ฆ <a href="https://crates.io/crates/zyvor-cli">crates.io</a>
</p>

---

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`](https://github.com/Fakhir-Israr-200219/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


```bash
# Install

cargo install zyvor-cli

# Scaffold

zyvor init

# Edit .zyvor/schema.zyvor and .zyvor/.env, then generate + watch

zyvor dev

# In a second terminal โ€” creates the database if it doesn't exist

zyvor migrate --apply
```

### โš ๏ธ Order matters


`zyvor dev` **generates** the migration files. Running `migrate --apply` first
gives you:

```text
No migration files found in .zyvor/migrations/. Run 'zyvor dev' first.
```

Leave `dev` running in one terminal, work in another.

### Project structure after init


```text
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
```

๐Ÿ“– [Full quick start](https://fakhir-israr-200219.github.io/zyvor-doc/getting-started/quick-start.html)

---

## 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:

```bash
zyvor validate .zyvor/schema.zyvor
zyvor generate .zyvor/schema.zyvor
```

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:

```bash
zyvor migrate .zyvor/schema.zyvor .zyvor/migrations/0001_initial.sql
```

### Database URL resolution


Highest priority first:

1. `--database <URL>` flag
2. `DATABASE_URL` environment variable
3. `.zyvor/.env`
4. `.zyvor/config.toml` โ†’ `[database] url`

Passwords are masked in all console output.

๐Ÿ“– [CLI reference](https://fakhir-israr-200219.github.io/zyvor-doc/cli/init.html)

---

## Architecture


```text
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


```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")

    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.

๐Ÿ“– [Schema reference](https://fakhir-israr-200219.github.io/zyvor-doc/schema/models.html)

---

## 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


```rust
pub struct UserUpdate {
    pub name: Option<String>,               // non-nullable field
    pub email: Option<String>,
    pub age: Option<i32>,
    pub bio: Option<Option<String>>,        // nullable field โ€” two layers
    pub created_at: Option<zyvor::DateTime>,
}
```

| 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.

๐Ÿ“– [CRUD guide](https://fakhir-israr-200219.github.io/zyvor-doc/api/crud.html)

---

## 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`:

```sql
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()
);
```

- **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


```text
๐Ÿ“ฆ 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`.

๐Ÿ“– [Migrations guide](https://fakhir-israr-200219.github.io/zyvor-doc/schema/migrations.html)

---

## Using generated code


```toml
[dependencies]
zyvor = "0.1"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "chrono"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["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:

```text
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`.

```rust
#[path = "../.zyvor/generated/mod.rs"]

mod generated;

use generated::{Post, User, UserCreate, UserUpdate};
use zyvor::Entity;

// Typed fields โ€” chained where_ calls are AND-ed
let users = User::find()
    .where_(User::name.eq("Ali").and(User::age.gte(18)))
    .order_by(User::id.desc())
    .take(20)
    .all(&db).await?;

// Two-level nested eager loading
let users = User::find()
    .with_nested(User::posts, |q| q.with(Post::comments))
    .all(&db).await?;
```

๐Ÿ“– [Runtime API](https://fakhir-israr-200219.github.io/zyvor-doc/api/queries.html) ยท
[Axum integration](https://fakhir-israr-200219.github.io/zyvor-doc/guides/axum.html)

---

## Verified end-to-end


```text
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`](https://github.com/Fakhir-Israr-200219/zyvor) ยท
`cargo clippy --all-targets --all-features -- -D warnings` clean.

Reproduce it: [zyvor-axum-demo](https://github.com/Fakhir-Israr-200219/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 |

๐Ÿ“– **[Full limitations list](https://fakhir-israr-200219.github.io/zyvor-doc/reference/limitations.html)**

---

## Roadmap


### โœ… Done

- [x] Schema language, lexer, parser, AST, validator
- [x] Modular entity generation (per-model folders)
- [x] All four relation types
- [x] CRUD codegen (`Create` / `Update` / `InsertData` / `UpdateData`)
- [x] Migration generation + execution
- [x] Tracking, checksum skip, drift detection
- [x] Schema diffing + auto-numbering
- [x] Auto database creation
- [x] Watch mode with snapshot change detection
- [x] `.env` / `config.toml` configuration
- [x] Axum integration verified
- [x] [Documentation book](https://fakhir-israr-200219.github.io/zyvor-doc/)

### ๐Ÿ”œ Next

- [ ] Unify default schema paths (`rust.schema` โ†’ `.zyvor/schema.zyvor`)
- [ ] `Default` derive on `Update` structs
- [ ] 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


1. **CLI is a toolchain, not a runtime** โ€” generates code for the `zyvor` crate
2. **Schema is the source of truth** โ€” one definition, everything derived
3. **Generated code is readable Rust** โ€” no hidden macros, fully inspectable
4. **Milestone-tracked features** โ€” parser โ‰  validator โ‰  generator โ‰  runtime verification
5. **Zero manual database setup** โ€” auto-create, auto-migrate, auto-diff
6. **Honest scope** โ€” limitations documented, not buried

---

## Related repositories


| Repo | What |
|---|---|
| [zyvor]https://github.com/Fakhir-Israr-200219/zyvor | Runtime crate โ€” query builder, CRUD, relations |
| [zyvor-cli]https://github.com/Fakhir-Israr-200219/zyvor-cli | This crate โ€” schema toolchain |
| [zyvor-doc]https://github.com/Fakhir-Israr-200219/zyvor-doc | Documentation source ([live book]https://fakhir-israr-200219.github.io/zyvor-doc/) |
| [zyvor-axum-demo]https://github.com/Fakhir-Israr-200219/zyvor-axum-demo | Verified Axum + PostgreSQL example |

---

## License


Licensed under either of

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or
  http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT]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](https://www.prisma.io/), [Drizzle](https://orm.drizzle.team/),
and the frustration of writing repetitive ORM boilerplate in Rust.