Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

ValueEffect
Nonecolumn 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:

OperationRow doesn’t exist
createn/a — always inserts
updateErr(Error::NotFound) — UPDATE … RETURNING returns no row
deleteOk(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

  1. columns() and values() must have the same length and order. Zyvor zips them; a mismatch produces wrong SQL, not an error.
  2. Use database column names, not Rust field names — user_bio, not bio.
  3. BindValue::Null becomes a literal NULL, not a placeholder. Zyvor skips it during binding and keeps placeholder numbering correct.
  4. At least one column for updates, or you get an error.
  5. BindValue::I64 takes i64 even though your model field is i32.

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.