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

ruprizzle

Crates.io docs.rs MSRV License CI

A schema-first ORM for Rust that combines the best parts of Prisma and Drizzle:

  • Prisma's declarative schema as the single source of truth, with a generated typed client, automatic migration diffing, and nested relation loading.
  • Drizzle's SQL transparency — no hidden query engine, no sidecar binary, and .to_sql() on every builder so you always know what is being sent to the database.

PostgreSQL, MySQL/MariaDB, and SQLite 3+ are supported behind a dialect trait, so more backends are additive. Built on sqlx for the wire protocol and pooling; we do not write a driver. Native driver features are also available: sqlite-rusqlite for synchronous SQLite and an experimental postgres-tokio-postgres for PostgreSQL.

Status

The current published version is 1.5.1 — the first stable release, live on crates.io since 2026-09-13 for every crate in the workspace, including ruprizzle-turso and ruprizzle-d1. Run scripts/check-release-state.sh to confirm this against the registry rather than taking this page's word for it.

1.0.0, 1.0.1 and 1.5.0 are git tags, not releases: their publish runs failed before uploading, so the tags are kept as evidence of the attempts rather than moved. 1.0.0-rc.1 remains on crates.io as the previous published version.

Upgrading from 1.0.0-rc.1? Most applications need no code changes. See Upgrading from 1.0.0-rc.1 to 1.5.1, and pin "=1.0.0-rc.1" until you are ready, because "1.0.0-rc.1" also matches 1.6.0.

The core P0–P8 implementation is complete and MySQL/MariaDB support is shipped. The public API is covered by semantic versioning from 1.5.1 onward.

The v1.1–v1.5 feature line shipped as 1.5.1 — array filters, full-text search, soft deletes, offline query checking, nested writes, tree hierarchies, OpenTelemetry, read-replica routing, query caching, PostGIS and Ruprizzle Studio. See What's new in v1.1–v1.5. The current release is 1.6.0: Studio authentication, with_deleted() on hierarchies, background replica health checks and the K11 rename fix — see What's new in 1.6. Known gap: the Turso/D1 live smoke tests have not yet been run against the hosted services.

Two things were waived on the way here, both in writing rather than by omission: the W4-02 48-hour rusqlite soak, accepted on 15.56 h / 1.46 B ops / 0 errors (see SoakReport.md), and the two-week RC feedback window, because no external consumer existed to provide the feedback (see Stability).

See Stability for the semver policy and the public-dependency list — notably, the 1.0 line is pinned to sqlx 0.8 — and Known limitations for deliberate boundaries.

Quick example

// schema.ruprizzle
datasource db {
  provider = "postgres"
  url      = env("DATABASE_URL")
}

generator client {
  output      = "src/db"
  module_name = "db"
}

model User {
  id        Uuid     @id @default(uuid7())
  email     String   @unique
  posts     Post[]
  createdAt DateTime @default(now()) @map("created_at")

  @@map("users")
}

model Post {
  id       Uuid   @id @default(uuid7())
  title    String
  authorId Uuid   @map("author_id")
  author   User   @relation(fields: [authorId], references: [id], onDelete: Cascade)

  @@map("posts")
}
#![allow(unused)]
fn main() {
// Drizzle flavour: the call shape mirrors the SQL.
let admins = db
    .user()
    .find_many()
    .filter(user::EMAIL.ends_with("@acme.com"))
    .order_by(user::CREATED_AT.desc())
    .limit(20)
    .fetch_all()
    .await?;

// Prisma flavour: relation-aware, one query per level — never N+1.
let users = db
    .user()
    .find_many()
    .include(user::posts().filter(post::PUBLISHED.eq(true)).take(5))
    .fetch_all()
    .await?;
}

Wrong-typed and cross-model filters are compile errors, not runtime ones:

#![allow(unused)]
fn main() {
user::EMAIL.eq(42)                              // error: expected String, found i32
db.post().find_many().filter(user::EMAIL.eq(""))  // error: expected Filter<Post>, found Filter<User>
}

Install

cargo install ruprizzle-cli  # the `ruprizzle` command
cargo add ruprizzle          # the runtime crate your app uses

In a new or existing project:

ruprizzle init --provider postgres
# Edit schema.ruprizzle, then:
ruprizzle migrate dev --name init

Add the generated module to src/lib.rs or src/main.rs:

#![allow(unused)]
fn main() {
mod db;
}

Workflow

StepCommand
Scaffold a projectruprizzle init --provider postgres|postgresql|sqlite|mysql|mariadb
Generate the clientruprizzle generate
Auto-watch in devruprizzle generate --watch
Create & apply a migrationruprizzle migrate dev --name <name>
Apply migrations in CI/prodruprizzle migrate deploy
Check migration statusruprizzle migrate status
Mark a migration appliedruprizzle migrate resolve <id>
Reset and replay migrationsruprizzle migrate reset --force
Squash migration historyruprizzle migrate squash --force
Validate for CIruprizzle validate
Canonicalise schemaruprizzle format
Introspect an existing databaseruprizzle db pull
Seed fixture dataruprizzle db seed
Prototype schema pushruprizzle db push
Run the language serverruprizzle lsp
Offline query checkruprizzle check --manifest <path>

migrate dev and migrate deploy are deliberately separate: the production command never diffs or writes migration files, so habit cannot carry a dangerous prototyping invocation into CI.

Why another Rust ORM?

FeatureruprizzleDieselSeaORMsqlxpraxPrismaDrizzle
Schema-first code generation✅partial❌❌✅✅❌
Type-safe nested include✅❌partial❌✅✅✅
SQL-first query API✅❌❌✅partialpartial✅
Migrations from schema diff✅❌partial❌✅✅partial
Compile-time query checking✅✅❌✅✅N/A❌
Native driver backends (no sqlx::Any)✅✅❌N/A✅❌❌
Advanced SQL (CTEs, subqueries, set ops)✅partialpartial✅partialpartialpartial

The trade-off is intentional: ruprizzle targets teams that want a single source of truth in the schema file, compile-time type safety across relations, and the ability to drop down to raw SQL without leaving the query builder.

Repository layout

CrateRolePhase
crates/coreIR, spans, diagnostics✅ P0
crates/parserSchema DSL → validated IR✅ P1
crates/dialectDbDialect trait, Postgres + MySQL + SQLite✅ P2
crates/codegenIR → Rust source✅ P3
crates/runtimeruprizzle, the crate your app depends on✅ P4
crates/migrateSnapshot, diff, plan, apply✅ P6
crates/cliThe ruprizzle binary✅ P7
crates/lspLanguage server for schema.ruprizzle✅ P8
crates/checkOffline / compile-time query checking✅ P8
crates/testkitDual-database test harness✅ P0

Quickstart

From an empty directory to a working query in under five minutes.

Prerequisites

  • Rust 1.85 or later.
  • A running PostgreSQL, MySQL/MariaDB, or SQLite 3 database. SQLite needs no server; just a writable file path.

This guide uses PostgreSQL. To use SQLite, replace --provider postgres with --provider sqlite and set DATABASE_URL to a file path such as sqlite://./dev.db.

1. Install the CLI

1.5.1 is the current release on crates.io, so a bare cargo install resolves to the latest stable:

cargo install ruprizzle-cli

2. Scaffold a project

mkdir my-app && cd my-app
ruprizzle init --provider postgres

This creates:

my-app/
  schema.ruprizzle
  .env
  .gitignore
  migrations/
    README.md
  src/
    main.rs

Open .env and update DATABASE_URL:

DATABASE_URL="postgres://user:password@localhost:5432/my_app_db?sslmode=disable"

3. Edit the schema

Replace schema.ruprizzle with:

datasource db {
  provider = "postgres"
  url      = env("DATABASE_URL")
}

generator client {
  output      = "src/db"
  module_name = "db"
}

model User {
  id    Int    @id @default(autoincrement())
  email String @unique
  name  String
}

4. Create and run the first migration

ruprizzle migrate dev --name init

This diffs the empty database against the schema, writes a migration under migrations/, applies it, and regenerates the client.

5. Add dependencies

cargo add ruprizzle
cargo add tokio --features tokio/full
cargo add dotenvy
cargo add sqlx@0.8.6 --no-default-features --features "runtime-tokio-rustls,postgres"
cargo add serde

Or edit Cargo.toml:

[dependencies]
ruprizzle = "1.5"
tokio = { version = "1", features = ["full"] }
dotenvy = "0.15"
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio-rustls", "postgres"] }
serde = "1.0.229"

6. Write the first query

Make src/main.rs:

mod db;

#[tokio::main]
async fn main() -> Result<(), ruprizzle::Error> {
    dotenvy::dotenv().ok();
    let db_url =
        std::env::var("DATABASE_URL").map_err(|e| ruprizzle::Error::Message(e.to_string()))?;
    let db = db::Db::connect(&db_url).await?;

    let alice = db
        .user()
        .create(db::UserInsert {
            id: None,
            email: "alice@example.com".into(),
            name: "Alice".into(),
        })
        .exec()
        .await?;

    let users = db
        .user()
        .find_many()
        .filter(db::user::EMAIL.ends_with("@example.com"))
        .order_by(db::user::NAME.asc())
        .fetch_all()
        .await?;

    println!("created: {:?}", alice);
    println!("users: {:?}", users);
    Ok(())
}

Run it:

cargo run

7. Iterate

Change schema.ruprizzle and run:

ruprizzle migrate dev --name add_field

migrate dev already regenerates the client. For live code generation while you edit the schema without migrating, use:

ruprizzle generate --watch

Common first errors

  • Failed to acquire connection: DATABASE_URL is wrong or the database is not running.
  • table users already exists: the database already has a users table from a previous prototype. Use ruprizzle migrate reset --force in development to drop and re-apply, or delete migrations/ and start fresh.
  • no column named ...: the generated client is stale. Run ruprizzle generate.

Next steps

Schema reference

Every type, attribute, and function available in schema.ruprizzle. See Dialect notes for backend-specific mappings and limitations.

Top-level blocks

datasource

datasource db {
  provider = "postgres" | "mysql" | "sqlite"
  url      = env("DATABASE_URL") | "literal://..."
  strict   = true
}
  • provider: the database backend. Supported: postgres, mysql, sqlite.
  • url: an environment variable name or a literal URL. env() is recommended; literal URLs are useful for quick tests.
  • strict: when true, the CLI and runtime reject constructs that the active provider cannot express well.

generator

generator client {
  output            = "src/db"
  module_name       = "db"
  max_include_depth = 3
}
  • output: directory where the Rust client is emitted.
  • module_name: the name your crate uses to mod the output.
  • max_include_depth: the deepest level of nested include the codegen will generate.

Scalars

TypePostgresMySQL / MariaDBSQLiteNotes
StringTEXTVARCHAR(255)TEXT
IntINTEGERINTINTEGER32-bit signed.
BigIntBIGINTBIGINTINTEGERSQLite stores in 64-bit INTEGER.
FloatDOUBLE PRECISIONDOUBLEREAL
DecimalNUMERICDECIMAL(65,30)TEXTAvoid arithmetic on SQLite.
BooleanBOOLEANTINYINT(1)INTEGERMySQL and SQLite use 0/1.
DateTimeTIMESTAMPTZDATETIME(6)TEXTISO-8601 in SQLite.
DateDATEDATETEXT
TimeTIMETIMETEXT
UuidUUIDCHAR(36)TEXT
JsonJSONBJSONTEXTSQLite stores as text; JSON1 filters work.
BytesBYTEABLOBBLOB

Native type annotations

Use @db.<native> to override the default physical type for the active dialect.

AnnotationPostgresMySQL / MariaDBSQLite
@db.UuidUUIDCHAR(36)TEXT
@db.VarChar(n)VARCHAR(n)VARCHAR(n)TEXT
@db.TextTEXTTEXTTEXT
@db.IntegerINTEGERINTINTEGER
@db.SmallIntSMALLINTSMALLINTINTEGER
@db.BigIntBIGINTBIGINTINTEGER
@db.SerialSERIALAUTO_INCREMENTINTEGER
@db.BigSerialBIGSERIALAUTO_INCREMENTINTEGER
@db.RealREALFLOATREAL
@db.DoubleDOUBLE PRECISIONDOUBLEREAL
@db.Decimal(p,s)NUMERIC(p,s)DECIMAL(p,s)TEXT
@db.BooleanBOOLEANTINYINT(1)INTEGER
@db.TimestampTIMESTAMPDATETIME(6)TEXT
@db.TimestamptzTIMESTAMPTZDATETIME(6)TEXT
@db.DateDATEDATETEXT
@db.TimeTIMETIMETEXT
@db.JsonJSONBJSONTEXT
@db.JsonbJSONBJSONTEXT
@db.BytesBYTEABLOBBLOB
@db.Generated("...")generated columngenerated columnstored as text

Field attributes

  • @id — primary key. Auto-detected for Int/BigInt/Uuid with @default.
  • @default(<expr>) — default value. See the expressions below.
  • @unique — single-column unique constraint.
  • @map("column_name") — override the physical column name.
  • @relation(...) — define the owner side of a relation.
  • @ignore — omit from the generated client.
  • @db.<native> — override the native type.
  • @updatedAt — automatically set to now() on every update (Postgres/MySQL).
  • @deletedAt — marks the model soft-deletable. The field must be DateTime?; the parser rejects any other type with a diagnostic. Generated queries then add WHERE <column> IS NULL by default — see soft deletes for the opt-outs.

Default expressions

ExpressionReturnsExample
autoincrement()integerid Int @id @default(autoincrement())
uuid7()Uuidid Uuid @id @default(uuid7())
now()DateTimecreatedAt DateTime @default(now())
dbgenerated("...")dialect-specifictoken String @default(dbgenerated("gen_random_uuid()"))
literal valuethe literalrole Role @default(USER)

Model-level attributes

  • @@map("table_name") — override the physical table name.
  • @@unique([a, b, ...]) — composite unique constraint.
  • @@index([a, b, ...]) — index on the listed fields.
  • @@id([a, b, ...]) — composite primary key.
  • @@ignore — omit the model from the generated client.

Index attributes

Basic index

@@index([email])

Named index

@@index([email, createdAt], name: "user_email_created_idx")

Index type

@@index([email], type: "Hash")   // Postgres only

Expression index

@@index([lower(email)])

Expression indexes are supported on Postgres and SQLite 3.31+ where the expression can be emitted directly.

Partial index

@@index([email], where: "verified = true")

Partial indexes are supported on Postgres and SQLite.

Generated columns

A generated column is computed from other columns or expressions:

model User {
  id       Int    @id @default(autoincrement())
  first    String
  last     String
  fullName String @db.Generated("first | ' ' | last")
}

On SQLite, generated columns are stored as text or as the underlying native representation, depending on the dialect.

Enums

enum Role {
  USER
  ADMIN
}

Postgres uses a native CREATE TYPE. MySQL and SQLite emulate enums with a CHECK constraint on TEXT.

Relations

Only the owner side of a relation carries @relation:

model Post {
  authorId Uuid @map("author_id")
  author   User @relation(fields: [authorId], references: [id], onDelete: Cascade)
}

model User {
  posts Post[]
}

@relation arguments

  • fields — the foreign-key column(s) on this model.
  • references — the target column(s) on the related model.
  • onDelete / onUpdate — referential action.
  • name — optional relation name, used for disambiguation.
  • map — override the physical foreign-key constraint name.

Referential actions

Supported: Cascade, Restrict, SetNull, SetDefault, NoAction.

Many-to-many

Many-to-many relations are explicit join models:

model Tag {
  id   Uuid    @id @default(uuid7())
  name String  @unique
  posts PostTag[]
}

model PostTag {
  id      Uuid  @id @default(uuid7())
  postId  Uuid  @map("post_id")
  tagId   Uuid  @map("tag_id")
  post    Post  @relation(fields: [postId], references: [id], onDelete: Cascade)
  tag     Tag   @relation(fields: [tagId], references: [id], onDelete: Cascade)

  @@unique([postId, tagId])
}

PostgreSQL extensions

datasource db {
  provider   = "postgres"
  url        = env("DATABASE_URL")
  extensions = ["uuid-ossp", "pgcrypto"]
}

uuid-ossp is required for uuid7()-style defaults unless another extension provides equivalent functionality.

Naming

  • Model and field identifiers use camelCase by convention.
  • @@map and @map are used to produce snake_case physical names.
  • Physical names are limited by the target database (Postgres: 63 bytes; MySQL: 64 characters; SQLite: no hard limit).

Example schema

datasource db {
  provider = "postgres"
  url      = env("DATABASE_URL")
  extensions = ["uuid-ossp"]
}

generator client {
  output      = "src/db"
  module_name = "db"
  max_include_depth = 3
}

model User {
  id        Uuid     @id @default(uuid7())
  email     String   @unique @db.VarChar(255)
  name      String?
  role      Role     @default(USER)
  metadata  Json?    @db.Jsonb
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
  posts     Post[]

  @@index([email, createdAt])
  @@map("users")
}

model Post {
  id        Uuid     @id @default(uuid7())
  title     String
  published Boolean  @default(false)
  authorId  Uuid     @map("author_id")
  author    User     @relation(fields: [authorId], references: [id], onDelete: Cascade)

  @@index([authorId], where: "published = true")
  @@map("posts")
}

enum Role {
  USER
  ADMIN
}

Query guide

The generated client gives you two ways to build a query. The model repository (db.user(), db.post()) is the Prisma-flavoured starting point for application code. The raw builders (db.select::<User>(), db.insert::<User>()) are the Drizzle-flavoured escape hatch when you want full control.

All snippets below assume a generated db module from the examples/blog/schema.ruprizzle and are wrapped in rust,ignore because they depend on generated code.

Select and fetch helpers

find_many() starts a SELECT for a model. Add filters, ordering, pagination, and then call a fetch method.

let users: Vec<User> = db.user()
    .find_many()
    .filter(user::EMAIL.eq("alice@example.com"))
    .order_by(user::NAME.asc())
    .limit(10)
    .offset(20)
    .fetch_all()
    .await?;

For a single row without include():

let user: User = db.user()
    .find_many()
    .filter(user::EMAIL.eq("alice@example.com"))
    .fetch_one()
    .await?;

let maybe: Option<User> = db.user()
    .find_many()
    .filter(user::EMAIL.eq("alice@example.com"))
    .fetch_optional()
    .await?;

The generated repo does not expose a separate find_by_id or find_unique. Use find_many().filter(user::ID.eq(id)) and one of the fetch helpers.

Include-aware execution

Once you add .include(...), the fetch methods are disabled and the include-aware methods take over. This is enforced at compile time so you cannot accidentally return rows with unloaded relations.

let user = db.user()
    .find_many()
    .filter(user::ID.eq(alice_id))
    .include(user::posts().take(5))
    .exec_one()
    .await?;

for post in user.posts.get() {
    println!("{}", post.title);
}

exec() returns Vec<M>, exec_one() returns exactly one row, and exec_optional() returns Option<M>.

Filters

Column tokens are typed, so values and other columns are checked at compile time.

user::EMAIL.eq("alice@example.com")                       // equality
user::EMAIL.ne("alice@example.com")                       // inequality
user::CREATED_AT.gt(start) | user::CREATED_AT.gte(start)  // ordering
user::CREATED_AT.lt(end) | user::CREATED_AT.lte(end)
user::CREATED_AT.between(start, end)                      // BETWEEN
user::ROLE.in_set(vec![Role::User, Role::Admin])          // IN
user::ROLE.not_in_set(vec![Role::User])                   // NOT IN
user::EMAIL.starts_with("alice@")                         // string matchers
user::EMAIL.ends_with("@example.com")
user::EMAIL.contains("acme")
user::EMAIL.ilike("alice")                                // ILIKE on Postgres, LIKE on SQLite

is_null() and is_not_null() are available on Column<M, Option<T>>. Generated tokens for nullable fields currently use the underlying T type, so for generated columns use Filter::raw("name IS NULL") or the column's set_null/eq_optional helpers in inserts/updates.

Combine filters with and, or, all, and any:

use ruprizzle::{all, any};

let f = all([
    user::CREATED_AT.gte(week_ago),
    user::EMAIL.ends_with("@example.com"),
]);

let f = any([
    user::ROLE.eq(Role::Admin),
    user::EMAIL.starts_with("admin@"),
]);

Filter parents by a condition on their children with the generated relation filters:

user::posts_some(post::PUBLISHED.eq(true))    // at least one child matches
user::posts_every(post::PUBLISHED.eq(true))   // every child matches (vacuously true if none)
user::posts_none(post::PUBLISHED.eq(true))    // no child matches

For the low-level correlated EXISTS shape, use Filter::exists and Column::correlated_to:

use ruprizzle::Filter;

let sub = db.select::<Post>()
    .columns(post::ID)
    .filter(post::AUTHOR_ID.correlated_to(user::ID));

let authors = db.user()
    .find_many()
    .filter(Filter::exists(sub))
    .fetch_all()
    .await?;

Conditional / dynamic building

Every builder has *_if variants that skip the call when the value is None, so you can assemble queries from optional inputs without changing the builder type.

let mut q = db.user().find_many();

if let Some(email) = maybe_email {
    q = q.filter(user::EMAIL.eq(email));
}

let users = q
    .filter_if(maybe_after.map(|t| user::CREATED_AT.gte(t)))
    .order_by_if(maybe_sort.map(|_| user::NAME.asc()))
    .limit_if(maybe_limit)
    .offset_if(maybe_offset)
    .fetch_all()
    .await?;

Inserts, updates, and deletes have the same conditional helpers:

let user = db.user()
    .create(UserInsert {
        id: None,
        email: "alice@example.com".into(),
        name: None,
        role: None,
        created_at: None,
        updated_at: None,
    })
    .set_if(user::NAME, Some("Alice".to_string()))
    .exec()
    .await?;

let affected = db.user()
    .update()
    .set_if(user::NAME, Some("Alicia".to_string()))
    .set_if(user::ROLE, None::<Role>)        // skipped
    .filter_if(Some(user::EMAIL.eq("alice@example.com")))
    .exec()
    .await?;

let deleted = db.user()
    .delete()
    .filter_if(Some(user::EMAIL.eq("alice@example.com")))
    .exec()
    .await?;

For delete, passing None to filter_if makes the query unfiltered. You can also call .all_rows() explicitly when you mean to touch every row.

Projections

columns(...) restricts the SELECT list and changes the output type. A single column decodes to a one-tuple; multiple columns decode to a tuple.

let names: Vec<(String,)> = db.user()
    .find_many()
    .columns(user::NAME)
    .fetch_all()
    .await?;

let rows: Vec<(String, String)> = db.user()
    .find_many()
    .columns((user::NAME, user::EMAIL))
    .fetch_all()
    .await?;

Other projection helpers are available on any SelectQuery:

let count: i64 = db.user().find_many().filter(user::ROLE.eq(Role::Admin)).count().await?;
let any: bool = db.user().find_many().filter(user::EMAIL.starts_with("admin@")).exists().await?;

let emails: Vec<(String,)> = db.user()
    .find_many()
    .columns(user::EMAIL)
    .distinct()
    .fetch_all()
    .await?;

count() and exists() ignore ORDER BY, LIMIT, and OFFSET.

Aggregates and grouping

Aggregates are built from column tokens and carry their return type at the type level.

let rows: Vec<(Option<f64>, i64)> = db.select::<Employee>()
    .group_by(employee::ROLE)
    .aggregate((employee::SALARY.sum(), employee::ID.count()))
    .having(employee::ROLE.eq("Manager"))
    .order_by(employee::ROLE.asc())
    .fetch_all()
    .await?;

Available aggregate methods are sum, avg, min, max, count, and count_distinct. group_by can take a single column or a tuple. having accepts the same Filter<M> as filter.

The code generator also emits a model aggregate struct and input. For User, the generated types are UserAggregate and UserAggregateInput:

let rows: Vec<UserAggregate> = db.user()
    .find_many()
    .group_by(user::ROLE)
    .aggregate(UserAggregateInput {
        count_id: Some(user::ID.count()),
        count_distinct_email: Some(user::EMAIL.count_distinct()),
        ..Default::default()
    })
    .fetch_all()
    .await?;

Ordering, pagination, and cursors

let first = db.user()
    .find_many()
    .order_by(user::CREATED_AT.desc())
    .page(20)
    .await?;

for user in &first.items {
    println!("{}", user.email);
}

if first.has_next {
    let last_id = first.items.last().unwrap().id;
    let next = db.user()
        .find_many()
        .order_by(user::ID.asc())
        .after(user::ID, last_id, 20)
        .fetch_all()
        .await?;
}

page(size) fetches size + 1 rows and discards the extra one, so has_next is exact. after(column, value, size) and before(column, value, size) are convenience helpers that add > value or < value, order by the column, and limit the result.

For offset-based pagination, use limit and offset directly:

let rows = db.user()
    .find_many()
    .order_by(user::NAME.asc())
    .limit(10)
    .offset(40)
    .fetch_all()
    .await?;

Insert and upsert

The generated create helper accepts the model's Insert struct:

let user = db.user()
    .create(UserInsert {
        id: None,
        email: "alice@example.com".into(),
        name: Some("Alice".to_string()),
        role: Some(Role::User),
        created_at: None,
        updated_at: None,
    })
    .exec()
    .await?;

For multi-row inserts, use create_many:

let users = db.user()
    .create_many(vec![
        UserInsert { id: None, email: "a@example.com".into(), name: None, role: None, created_at: None, updated_at: None },
        UserInsert { id: None, email: "b@example.com".into(), name: None, role: None, created_at: None, updated_at: None },
    ])
    .exec()
    .await?;

The Drizzle-style entry point is db.insert::<M>():

let user = db.insert::<User>()
    .set(user::EMAIL, "alice@example.com")
    .set_optional(user::NAME, Some("Alice".to_string()))
    .set_optional(user::ROLE, Some(Role::User))
    .exec()
    .await?;

set_optional (and its alias set_if) sets a column only when the value is Some.

Upserts are on_conflict plus do_update:

db.insert::<User>()
    .set(user::EMAIL, "alice@example.com")
    .set(user::NAME, "Alice")
    .on_conflict(["email"])
    .do_update(["name"])
    .exec()
    .await?;

Nested writes on insert use InsertQuery::with_related for one-to-many and with_m2m for many-to-many:

use ruprizzle::{Encodable, InsertManyQuery, NestedSetter, Value};

struct SetPosts;
impl NestedSetter<User> for SetPosts {
    fn set(&self, parent: &mut User, batch: ruprizzle::executor::RowBatch) {
        parent.posts = ruprizzle::Related::Loaded(ruprizzle::executor::decode_rows::<Post>(batch).unwrap());
    }
}

let children = InsertManyQuery::<Post>::new(db.raw_pool())
    .row([("title", Value::Str("Hello".into()))])
    .row([("title", Value::Str("World".into()))]);

let user = db.user()
    .create(UserInsert {
        id: None,
        email: "alice@example.com".into(),
        name: Some("Alice".to_string()),
        role: None,
        created_at: None,
        updated_at: None,
    })
    .with_related(|u| u.id.to_value(), "author_id", children, SetPosts)
    .exec()
    .await?;

For a many-to-many relation, the generated helpers return an M2mWrite that can be passed to with_m2m:

let post = db.post()
    .create(PostInsert {
        id: None,
        title: "A post".into(),
        body: None,
        published: Some(true),
        author_id: user_id,
        created_at: None,
    })
    .with_m2m(post::tags_set(vec![rust_tag_id, orm_tag_id]))
    .exec()
    .await?;

Update and delete

let affected = db.user()
    .update()
    .set(user::NAME, "Alicia")
    .set_null(user::NAME)                        // set a nullable column to NULL
    .filter(user::EMAIL.eq("alice@example.com"))
    .exec()
    .await?;

Delete requires a filter or an explicit .all_rows() call:

let deleted = db.user()
    .delete()
    .filter(user::EMAIL.eq("alice@example.com"))
    .exec()
    .await?;

// Delete every row
let deleted = db.user().delete().all_rows().exec().await?;

Nested one-to-many writes on update use connect, disconnect, and set_related:

use ruprizzle::Encodable;

// Connect existing posts to this user
let affected = db.user()
    .update()
    .filter(user::ID.eq(user_id))
    .connect::<Post, _, _>(|u| u.id.to_value(), "author_id", "id", vec![post_id])
    .exec()
    .await?;

// Disconnect specific posts
let affected = db.user()
    .update()
    .filter(user::ID.eq(user_id))
    .disconnect::<Post, _, _>(|u| u.id.to_value(), "author_id", "id", vec![post_id])
    .exec()
    .await?;

// Replace the user's posts with one post
let affected = db.user()
    .update()
    .filter(user::ID.eq(user_id))
    .set_related::<Post, _, _>(|u| u.id.to_value(), "author_id", "id", vec![post_id])
    .exec()
    .await?;

connect and set_related on UpdateQuery require the query to match exactly one parent row.

Many-to-many updates use the generated *_attach, *_set, and *_detach helpers:

let post = db.post()
    .update()
    .set(post::TITLE, "Updated title")
    .filter(post::ID.eq(post_id))
    .with_m2m(post::tags_attach(vec![tag_id_1, tag_id_2]))
    .exec()
    .await?;

// Replace all tags for a post
db.post()
    .update()
    .filter(post::ID.eq(post_id))
    .with_m2m(post::tags_set(vec![tag_id_1]))
    .exec()
    .await?;

Cascading deletes use DeleteQuery::cascade and a DeleteAction that matches the schema's onDelete:

use ruprizzle::DeleteAction;

let deleted = db.user()
    .delete()
    .filter(user::ID.eq(user_id))
    .cascade::<Post>("author_id", DeleteAction::Cascade)
    .exec()
    .await?;

DeleteAction has the variants Cascade, Restrict, SetNull, SetDefault, and NoAction.

Relations and include

Relations are loaded with a single query per level. Basic one-to-many and many-to-one includes look like this:

let users = db.user()
    .find_many()
    .include(user::posts().take(5))
    .exec()
    .await?;

let posts = db.post()
    .find_many()
    .include(post::author())
    .exec()
    .await?;

The returned relations are Related<Vec<Post>> and Related<Option<User>>. Access them with .get() after using the include-aware exec/exec_one/exec_optional methods.

Filter, order, and limit the included children:

let users = db.user()
    .find_many()
    .include(
        user::posts()
            .filter(post::PUBLISHED.eq(true))
            .order_by(post::CREATED_AT.desc())
            .take(10),
    )
    .exec()
    .await?;

Nested includes are supported:

let users = db.user()
    .find_many()
    .include(
        user::posts()
            .take(5)
            .include(post::author())
    )
    .exec()
    .await?;

Explicit joins

Explicit joins produce Join2 or LeftJoin2 result tuples.

let rows: Vec<Join2<User, Post>> = db.select::<User>()
    .inner_join::<Post>(user::ID.on(post::AUTHOR_ID))
    .fetch_all()
    .await?;

let rows: Vec<LeftJoin2<User, Post>> = db.select::<User>()
    .left_join::<Post>(user::ID.on(post::AUTHOR_ID))
    .fetch_all()
    .await?;

LeftJoin2 wraps the right side in Maybe<T>, which dereferences to Option<T>. Right and full joins are also available, but SQLite does not support them.

Self-joins use an alias and Column::aliased:

let rows: Vec<Join2<Employee, Employee>> = db.select::<Employee>()
    .inner_join_aliased::<Employee>("mgr", employee::MANAGER_ID.on(employee::ID.aliased("mgr")))
    .fetch_all()
    .await?;

Subqueries and CTEs

in_subquery and not_in_subquery accept a SelectQuery whose projection matches the column type:

let sub = db.select::<Post>()
    .columns(post::AUTHOR_ID)
    .filter(post::PUBLISHED.eq(true))
    .distinct();

let authors = db.user()
    .find_many()
    .filter(user::ID.in_subquery(sub))
    .fetch_all()
    .await?;

Correlated subqueries use correlated_to and Filter::exists/Filter::not_exists:

use ruprizzle::Filter;

let sub = db.select::<Post>()
    .columns(post::ID)
    .filter(post::AUTHOR_ID.correlated_to(user::ID));

let authors = db.user()
    .find_many()
    .filter(Filter::exists(sub))
    .fetch_all()
    .await?;

Non-recursive CTEs are added with with:

use ruprizzle::Filter;

let managers = db.select::<Employee>()
    .filter(employee::ROLE.eq("manager"))
    .columns((employee::ID, employee::NAME));

let rows = db.select::<Employee>()
    .with("managers", managers)
    .filter(Filter::exists(
        db.select::<Manager>()
            .filter(manager::ID.correlated_to(employee::ID)),
    ))
    .fetch_all()
    .await?;

Recursive CTEs use with_recursive:

let anchor = db.select::<Employee>().filter(employee::ID.eq(2));

let recursive = db.select::<Employee>()
    .filter(Filter::exists(
        db.select::<Reports>()
            .filter(reports::MANAGER_ID.correlated_to(employee::ID)),
    ));

let rows = db.select::<Reports>()
    .with_recursive("reports", anchor, recursive)
    .fetch_all()
    .await?;

Set operations

SelectQuery supports union, union_all, intersect, and except. Both sides must have the same output type.

let admins = db.user()
    .find_many()
    .filter(user::ROLE.eq(Role::Admin))
    .columns(user::EMAIL);

let users = db.user()
    .find_many()
    .filter(user::AGE.gte(18))
    .columns(user::EMAIL);

let emails: Vec<(String,)> = admins.union(users).fetch_all().await?;

union_all preserves duplicates. intersect and except are not supported by MySQL.

JSON operators

JSON columns expose path extraction and containment filters. The path can be chained with .get(...), .get_text(...), and .at(...).

// Requires a model with a serde_json::Value column, e.g. Item::META
let rows = db.select::<Item>()
    .filter(item::META.get("status").eq("active"))
    .filter(item::META.get("nested").get("score").gt(10))
    .filter(item::META.at(0).get_text("name").eq("first"))
    .filter(item::META.has_key("tags"))
    .filter(item::META.contains(serde_json::json!({ "flag": true })))
    .order_by(item::META.get("priority").desc())
    .fetch_all()
    .await?;

In updates, json_set and jsonb_set modify a single key:

UpdateQuery::<Item>::new(db.raw_pool())
    .set(item::TITLE, "New title")
    .jsonb_set(item::META, "status", serde_json::json!("archived"))
    .filter(item::ID.eq(item_id))
    .exec()
    .await?;

Array operators

Array columns (or JSON-array columns on MySQL/SQLite) support contains, contained_by, and overlaps, plus three aliases and an emptiness test:

MethodMeaningAlias of
has(value)the array contains this one element—
has_every(values)the array contains all of thesecontains
has_some(values)the array contains any of theseoverlaps
is_empty() / is_not_empty()length is / is not zero—

On Postgres these compile to native array operators (= ANY, @>, <@, &&, cardinality); on MySQL and SQLite to the equivalent JSON functions.

// Requires a model with a Vec<String> column, e.g. Article::TAGS
let rows = db.select::<Article>()
    .filter(article::TAGS.contains(["rust"]))
    .filter(article::TAGS.contained_by(["rust", "orm", "sql"]))
    .filter(article::TAGS.overlaps(["orm", "sql"]))
    .fetch_all()
    .await?;

matches() on a String or Option<String> column compiles to each backend's native full-text construct.

DialectCompiles to
Postgresto_tsvector('english', col) @@ plainto_tsquery('english', $1)
MySQLMATCH(col) AGAINST (?)
SQLitecol MATCH ?, with a LIKE fallback when no FTS table is in play
let hits = db.select::<Article>()
    .filter(article::BODY.matches("database migrations"))
    .fetch_all()
    .await?;

The query text is always bound as a parameter, never interpolated.

Soft deletes

When a model has a DateTime? field marked @deletedAt (see the schema reference), every generated query filters soft-deleted rows out by default. Two builder methods opt out, and they are mutually exclusive — the last one called wins.

db.post().find_many().fetch_all().await?;                 // live rows only
db.post().find_many().with_deleted().fetch_all().await?;  // live + deleted
db.post().find_many().only_deleted().fetch_all().await?;  // the recycle bin

.to_sql() shows the added WHERE deleted_at IS NULL predicate, so you can always see which of the three you built.

The same predicate applies wherever a soft-deletable model is read as a related row:

  • Includes, with or without .take(n).
  • Relation filters (_some, _none, _every). A soft-deleted child does not count, and _every ranges over live children only.
  • The right-hand side of a join. The predicate goes in the ON clause, so a left_join to a deleted row yields NULLs rather than dropping the left row. .with_deleted() opts both sides out; .only_deleted() applies to the left model only.
  • Tree queries (ancestors / descendants). A deleted node is skipped, and so is everything reached only through it. .with_deleted() (since 1.6) walks deleted nodes and their subtrees too.
  • The rows an m2m write reloads onto the parent.

Before 1.5.2, the .take(n) include, relation filters, joins, tree queries and m2m reloads returned soft-deleted rows.

Prepared statements

Prepare a query once and rebind the placeholders for each execution. Bind positions are zero-based.

let mut prep = db.user()
    .find_many()
    .filter(user::EMAIL.eq(""))
    .prepare()?;

prep.bind(0, "alice@example.com".to_string());
let alice = prep.fetch_one().await?;

prep.bind(0, "bob@example.com".to_string());
let bob = prep.fetch_one().await?;

bind_many replaces all binds at once with a Vec<Value>.

Raw SQL escape hatch

The raw! macro builds an injection-safe RawFragment. Values are bound as parameters; they are never interpolated into the SQL string.

use ruprizzle::{raw, Filter};

let fragment = raw!("email LIKE {}", "%@example.com");
let rows = db.user()
    .find_many()
    .filter(Filter::raw(fragment))
    .fetch_all()
    .await?;

For a statement that does not fit the typed builders, run it directly through the pool:

use ruprizzle::raw;

let fragment = raw!("UPDATE posts SET published = {} WHERE author_id = {}", true, author_id);
db.raw_pool()
    .execute_raw(fragment.sql().into(), fragment.binds().to_vec())
    .await?;

You can also embed a raw fragment inside a typed Filter:

use ruprizzle::Filter;

let rows = db.user()
    .find_many()
    .filter(Filter::raw(raw!("created_at > {}", since)))
    .fetch_all()
    .await?;

SQL transparency

Call .to_sql() on any builder to inspect the generated SQL and bind values before execution.

let sql = db.user()
    .find_many()
    .filter(user::EMAIL.eq("alice@example.com"))
    .to_sql()?;

println!("{}", sql.sql);

to_sql() returns a CompiledSql with sql and binds fields. SelectQuery, UpdateQuery, DeleteQuery, and SetOpQuery return Result<CompiledSql, _>; InsertQuery and AggregateQuery return CompiledSql directly.

Relations guide

ruprizzle generates one relation loader per relation. The loader is a value-level description of how to fetch the other side, and the actual loading is batched so the query count is bounded by the number of levels, not the number of parent rows.

All snippets below assume a generated db module. They are wrapped in rust,ignore because they depend on generated code.

One-to-many and many-to-one

Given the blog schema, User has many Posts and each Post has one author:

let users = db.user()
    .find_many()
    .include(user::posts().take(5))
    .exec()
    .await?;

for user in &users {
    for post in user.posts.get() {
        println!("{}: {}", user.name, post.title);
    }
}

let posts = db.post()
    .find_many()
    .include(post::author())
    .exec()
    .await?;

for post in &posts {
    if let Some(author) = post.author.get() {
        println!("{} by {}", post.title, author.name);
    }
}

include() changes the execution method. Use exec(), exec_one(), or exec_optional() instead of fetch_all()/fetch_one()/fetch_optional() so the relation is loaded.

Accessing loaded relations

Relation fields are Related<T>. Access the loaded value with .get():

  • Related<Vec<Post>> decodes to &Vec<Post>.
  • Related<Option<User>> decodes to &Option<User>.
let user = db.user()
    .find_many()
    .filter(user::ID.eq(alice_id))
    .include(user::posts())
    .exec_one()
    .await?;

for post in user.posts.get() {
    println!("{}", post.title);
}

try_get() returns Option<&T> and is useful when you are not sure whether a relation was included. is_absent() and is_loaded() let you check the state without panicking.

Filtering included children

Add filters, ordering, and a per-parent limit to the include:

let users = db.user()
    .find_many()
    .include(
        user::posts()
            .filter(post::PUBLISHED.eq(true))
            .order_by(post::CREATED_AT.desc())
            .take(10),
    )
    .exec()
    .await?;

take(n) is a per-parent limit, not a global limit. It is compiled to a ROW_NUMBER() OVER (PARTITION BY ...) window on dialects that support it.

Single-row includes

fetch_one() and fetch_optional() are unavailable once include() is present. Use the include-aware equivalents:

let user = db.user()
    .find_many()
    .filter(user::ID.eq(alice_id))
    .include(user::posts().take(5))
    .exec_one()
    .await?;

let maybe = db.user()
    .find_many()
    .filter(user::EMAIL.eq("nobody@example.com"))
    .include(user::posts())
    .exec_optional()
    .await?;

Many-to-many without a join model

When two models declare list fields pointing at each other and neither names a through model, the join table is inferred rather than declared:

model Post {
  id   Int    @id
  tags Tag[]
}

model Tag {
  id    Int    @id
  posts Post[]
}

The parser synthesises a join model named _<A>To<B> — the two model names sorted alphabetically, so _PostToTag — with columns A and B holding the two primary keys. A @relation(name: "...") on the pair produces _<A>To<B>_<name> instead, which is how two independent many-to-many links between the same pair stay apart.

The generated *_attach, *_set and *_detach helpers work the same way as for an explicit join model; the difference is only in what you write in the schema. Declare the join model explicitly (below) when it needs columns of its own — an ordering index, a timestamp, a role.

Many-to-many with an explicit join model

ruprizzle does not hide join tables. A Post with many Tags through an explicit PostTag model looks like this:

model Post {
  id   Int   @id
  tags Tag[] @relation(through: PostTag)
}

model Tag {
  id    Int     @id
  posts Post[]  @relation(through: PostTag)
}

model PostTag {
  post_id Int
  tag_id  Int
  post    Post @relation(fields: [post_id], references: [id])
  tag     Tag  @relation(fields: [tag_id], references: [id])

  @@id([post_id, tag_id])
  @@map("post_tags")
}

The generated code provides an IncludeMany loader and a query helper:

let posts = db.post()
    .find_many()
    .include(post::tags())
    .exec()
    .await?;

for post in &posts {
    for tag in post.tags.get() {
        println!("{} has tag {}", post.id, tag.id);
    }
}

// Or load tags for a single post directly
let tags = post::tags_query(db.raw_pool(), post_id).fetch_all().await?;

Nested writes on insert

Create a parent and its children in one call. The children must be supplied as an InsertManyQuery, and a NestedSetter attaches the loaded child rows to the parent.

use ruprizzle::{Encodable, InsertManyQuery, NestedSetter, Value};

struct SetPosts;
impl NestedSetter<User> for SetPosts {
    fn set(&self, parent: &mut User, batch: ruprizzle::executor::RowBatch) {
        parent.posts = ruprizzle::Related::Loaded(
            ruprizzle::executor::decode_rows::<Post>(batch).unwrap(),
        );
    }
}

let children = InsertManyQuery::<Post>::new(db.raw_pool())
    .row([("title", Value::Str("Hello".into()))])
    .row([("title", Value::Str("World".into()))]);

let user = db.user()
    .create(UserInsert {
        id: None,
        email: "alice@example.com".into(),
        name: Some("Alice".to_string()),
        role: None,
        created_at: None,
        updated_at: None,
    })
    .with_related(|u| u.id.to_value(), "author_id", children, SetPosts)
    .exec()
    .await?;

// Many-to-many on insert uses the generated *_set helper
let post = db.post()
    .create(PostInsert {
        id: None,
        title: "A post".into(),
        body: None,
        published: Some(true),
        author_id: user_id,
        created_at: None,
    })
    .with_m2m(post::tags_set(vec![rust_tag_id, orm_tag_id]))
    .exec()
    .await?;

Nested writes on update

For one-to-many relations, use connect, disconnect, and set_related. The update must match exactly one parent row.

use ruprizzle::Encodable;

// Attach existing posts to a user
db.user()
    .update()
    .filter(user::ID.eq(user_id))
    .connect::<Post, _, _>(|u| u.id.to_value(), "author_id", "id", vec![post_id_1, post_id_2])
    .exec()
    .await?;

// Detach specific posts
db.user()
    .update()
    .filter(user::ID.eq(user_id))
    .disconnect::<Post, _, _>(|u| u.id.to_value(), "author_id", "id", vec![post_id_1])
    .exec()
    .await?;

// Replace the user's posts with a new set
db.user()
    .update()
    .filter(user::ID.eq(user_id))
    .set_related::<Post, _, _>(|u| u.id.to_value(), "author_id", "id", vec![post_id_3])
    .exec()
    .await?;

For many-to-many relations, the generated *_attach, *_set, and *_detach helpers return an M2mWrite:

db.post()
    .update()
    .set(post::TITLE, "Updated title")
    .filter(post::ID.eq(post_id))
    .with_m2m(post::tags_attach(vec![tag_id_1, tag_id_2]))
    .exec()
    .await?;

// Replace all tags for a post
db.post()
    .update()
    .filter(post::ID.eq(post_id))
    .with_m2m(post::tags_set(vec![tag_id_1]))
    .exec()
    .await?;

// Detach a tag
db.post()
    .update()
    .filter(post::ID.eq(post_id))
    .with_m2m(post::tags_detach(vec![tag_id_1]))
    .exec()
    .await?;

Cascading deletes

DeleteQuery::cascade runs the referential action in a transaction before deleting the parent rows. The action must match the onDelete declared on the relation.

use ruprizzle::DeleteAction;

let deleted = db.user()
    .delete()
    .filter(user::ID.eq(user_id))
    .cascade::<Post>("author_id", DeleteAction::Cascade)
    .exec()
    .await?;

DeleteAction has the variants Cascade, Restrict, SetNull, SetDefault, and NoAction. SetDefault is accepted by the schema parser, but DeleteQuery::cascade will return an error at runtime if you use it; default-value handling is not yet wired to the cascade runner.

Self-referential relations

A model that references itself, such as an Employee with a manager_id, can be loaded with aliased includes:

// Each employee has one manager
let employees = db.select::<Employee>()
    .include(employee::manager())
    .exec()
    .await?;

// Each manager has many reports
let managers = db.select::<Employee>()
    .include(employee::reports().take(10))
    .exec()
    .await?;

The generated module provides manager() and reports() relation loaders for self-referential schemas. Include depth is limited by the schema's max_include_depth generator setting.

Tree hierarchies

A self-referential model — one whose parent foreign key points at its own primary key — also gets recursive-CTE traversal helpers, so an arbitrarily deep tree is one query rather than one query per level.

// Every ancestor of a node, walking up to the root.
let chain = db.category().ancestors(node_id).all().await?;

// The whole subtree below a node, bounded to three levels.
let subtree = db.category()
    .descendants(node_id)
    .max_depth(3)
    .all()
    .await?;

// The subtree reassembled in memory as a `HierarchyNode<Category>`.
let tree = db.category().tree_from_root(root_id).await?;

ancestors and descendants return a HierarchyQuery, which has max_depth, order_by_depth_asc / order_by_depth_desc, cycle_protection, with_deleted (since 1.6; includes soft-deleted nodes and the subtrees below them), and — like every other builder — to_sql(), so the generated WITH RECURSIVE statement is inspectable. Cycle protection is on by default: each path carries the keys it has visited and never steps onto one again, so a corrupted parent chain returns each node once instead of spinning. It also caps the walk at 100 levels unless max_depth is set. The visited keys are kept as a comma-separated string, so a text key that contains a comma can be mistaken for a visited node. Pass cycle_protection(false) only when the data is known to be acyclic: with it off and no max_depth, a cycle recurses until Postgres or SQLite cancel the statement, or MySQL hits cte_max_recursion_depth. (Before 1.5.2, protection was only the depth cap, and a cycle came back as dozens of duplicate rows.)

some, every, and none relation filters

For each relation, the generator emits *_some, *_every, and *_none functions that return a Filter on the parent model.

// Users with at least one published post
let authors = db.user()
    .find_many()
    .filter(user::posts_some(post::PUBLISHED.eq(true)))
    .fetch_all()
    .await?;

// Users whose every post is published
let all_published = db.user()
    .find_many()
    .filter(user::posts_every(post::PUBLISHED.eq(true)))
    .fetch_all()
    .await?;

// Users with no published posts
let no_posts = db.user()
    .find_many()
    .filter(user::posts_none(post::PUBLISHED.eq(true)))
    .fetch_all()
    .await?;

For a many-to-one relation, the generated helpers are named from the child side:

let posts = db.post()
    .find_many()
    .filter(post::author_some(user::NAME.eq("Alice")))
    .fetch_all()
    .await?;

Why this avoids N+1

A naive loop would issue one query per parent to fetch children. include works in two batched stages:

  1. Run the parent query.
  2. Collect the parent keys, run one IN (...) or full-table query per child level, and distribute the child rows back into the parent structs in Rust.

The per-parent limit in take(n) is implemented with a ROW_NUMBER() OVER (PARTITION BY ...) window on dialects that support it. If the dialect does not support window functions, it falls back to one query per parent, which is the only case where the query count is linear in the parent count.

Full-table fast path and its bound

When the parent query is an unfiltered full-table fetch and the include has no extra filter, order, or per-parent limit, ruprizzle can load the whole child table in one query instead of building a large IN (...) list. Before taking that path, it COUNT(*)s the child table and only uses the full-table load when the count is below PoolConfig::full_table_include_limit (default 100_000). If the child table is larger, the loader falls back to a chunked IN (...) list, which preserves the bounded-query guarantee without materialising millions of rows. Set the field to None to disable the fast path entirely.

Migrations guide

ruprizzle generates migrations by diffing your current schema.ruprizzle against the state of the migration history. You edit the schema, run a command, and the tool writes, applies, and tracks the SQL for you.

The two commands

CommandWhen to useWhat it does
ruprizzle migrate devLocal developmentDiff schema → write migration files → apply → regenerate client.
ruprizzle migrate deployCI / productionApply pending migrations/*.sql files only.

These are deliberately separate. deploy never writes migration files, prompts, or diffs the schema, so a habit of running migrate deploy cannot accidentally drop a production column.

Development workflow

# 1. Edit schema.ruprizzle
# 2. Create, apply, and regenerate the client
ruprizzle migrate dev --name add_profile

# If the migration would lose data and you accept it:
ruprizzle migrate dev --name drop_legacy --accept-data-loss

# Write the migration without applying it:
ruprizzle migrate dev --name draft --create-only

migrate dev is the only command that diffs, writes, and applies. Every other command is read-only or apply-only.

Backfills

Adding a NOT NULL column without a default requires a three-step migration:

  1. Add the column as nullable.
  2. Fill existing rows (RUPRIZZLE:BACKFILL block in the generated up.sql).
  3. Alter the column to NOT NULL.

Edit the generated up.sql and replace the placeholder expression before applying. The RUPRIZZLE:BACKFILL block is preserved when you re-run migrate dev.

Drift and migrate status

ruprizzle migrate status introspects the live database and compares it to the migration history. If someone hand-edited the database, it reports the differences.

ruprizzle migrate status

Resolve drift by either:

  • writing a new migration that brings the schema back into sync, or
  • ruprizzle migrate reset --force in development to drop everything and replay.

Prototyping: db push

ruprizzle db push

# If the change would lose data:
ruprizzle db push --accept-data-loss

This diffs and applies directly with no migration file. It is intended for prototyping only and prints a warning every time. Do not use it in production.

Introspection: db pull

db pull reads an existing database and generates a schema.ruprizzle from it. Use it to adopt an existing database or to inspect a schema that was not created by ruprizzle.

ruprizzle db pull

The command will:

  • read the live database from DATABASE_URL,
  • generate a schema.ruprizzle that describes the current tables, columns, indexes, and foreign keys,
  • overwrite schema.ruprizzle in place (review the diff before committing).

Review the generated schema before committing it. Names and types may need manual cleanup, especially for columns that do not map cleanly to ruprizzle scalar types.

Seeding: db seed

db seed loads fixture data from a JSON file and upserts it by primary key.

  1. Create seeds/main.json next to schema.ruprizzle:
{
  "User": [
    { "id": 1, "email": "alice@example.com", "name": "Alice" },
    { "id": 2, "email": "bob@example.com", "name": "Bob" }
  ]
}
  1. Run:
ruprizzle db seed

Seed rows are upserted by primary key in a single transaction. The legacy seeds/main.sql file is also supported if no seeds/main.json exists. The client is not regenerated; run ruprizzle generate afterwards if you added new models.

migrate squash

Squashing collapses the existing migration history into a baseline and archives the old up.sql / down.sql files.

# Use an auto-generated baseline name:
ruprizzle migrate squash --force

# Or name the baseline explicitly:
ruprizzle migrate squash --name baseline --force

Requirements:

  • the migration history must be fully applied,
  • all checksums must be valid,
  • the database must be in the exact state described by the final migration.

This rewrites history; pass --force to confirm. Old migrations are archived under migrations/.archive/ and a new baseline migration is created.

migrate resolve

If a migration was partially applied or failed outside ruprizzle, you can mark it as applied without re-running it.

ruprizzle migrate resolve 20260101000000_broken

Use this only after manually inspecting the database and confirming it is in the state the migration would have produced.

migrate reset

Drop the database and replay the full migration history from the beginning.

ruprizzle migrate reset --force

This is destructive and --force is required. It is intended for development prototyping only.

Running migrations in CI / production

In CI and production, use migrate deploy.

ruprizzle migrate deploy

This command:

  • reads migrations/ in order,
  • skips migrations that are already recorded in the _ruprizzle_migrations table,
  • applies each pending up.sql inside a transaction,
  • never diffs or writes new migration files.

A typical container deploy looks like this:

# Build the application image first
...
# At container start, before binding the port:
CMD ["sh", "-c", "ruprizzle migrate deploy && exec ./my-app"]

Destructive changes and --accept-data-loss

migrate dev will stop and warn when a change would drop data, such as:

  • dropping a column,
  • dropping a table,
  • changing a NOT NULL column to nullable and then back,
  • narrowing a BigInt to Int where values may not fit.

Pass --accept-data-loss when the loss is intentional in development.

The 12 change classes

The migration engine is tested against all common schema changes:

  1. Add / drop a model
  2. Add nullable column
  3. Add NOT NULL column with default
  4. Add NOT NULL column without default
  5. Drop column
  6. Widen / narrow Int ↔ BigInt
  7. Nullable → NOT NULL
  8. Add / drop index or unique
  9. Add / drop foreign key
  10. Add / drop enum variant
  11. Rename column / model (with @renamedFrom or heuristic detection)
  12. Add / remove default expression

Rename detection

Renames are detected by comparing column/model fingerprints. If ruprizzle is confident, it suggests a RENAME change. If you know a rename happened, use @renamedFrom in the schema:

model User {
  email String @renamedFrom("email_address")
}

Without @renamedFrom, the engine may produce a DROP + ADD pair, which loses data. Always review renames.

If the new name is already taken by a column that still exists — for example email is renamed to legacy_email in the database you are migrating, and a new email field says @renamedFrom("email_address") — the existing email column is dropped first and then email_address is renamed onto its name (since 1.6; earlier versions planned a RENAME that failed at apply time). The drop is destructive, so migrate dev / migrate deploy require --accept-data-loss for it. Copy anything you need out of the old column before applying.

Mutual foreign-key cycles

If two or more models reference each other in a closed loop, the migration planner will:

  • add DEFERRABLE INITIALLY IMMEDIATE to the generated foreign key constraints;
  • wrap the up.sql with a backend-specific command that defers enforcement until the end of the migration transaction;
  • add the matching re-enable command before COMMIT.

The generated SQL is:

DialectPreamblePostambledown.sql behaviour
PostgresSET CONSTRAINTS ALL DEFERRED;SET CONSTRAINTS ALL IMMEDIATE;DROP TABLE ... CASCADE for cycle tables
SQLitePRAGMA defer_foreign_keys = ON;PRAGMA defer_foreign_keys = OFF;PRAGMA foreign_keys = OFF; before drops, then PRAGMA foreign_key_check; and PRAGMA foreign_keys = ON;
MySQLSET FOREIGN_KEY_CHECKS = 0;SET FOREIGN_KEY_CHECKS = 1;SET FOREIGN_KEY_CHECKS = 0/1 around drops

This lets you create, populate, and roll back schemas with cyclic foreign keys without having to split them across multiple migrations by hand.

SQLite migration notes

SQLite handles some of the change classes (notably type changes and NOT NULL transitions) by rebuilding the table. Postgres uses direct ALTER statements where possible. MySQL uses ALTER TABLE and MODIFY COLUMN.

Best practices

  • Commit migrations/ with the same PR that changes schema.ruprizzle.
  • Run ruprizzle migrate deploy in CI before running the application.
  • Never run migrate dev on a production database.
  • Review up.sql and down.sql before applying destructive changes.
  • Use --create-only to draft a migration for review in a team PR.

Examples

A worked example of a small blog application. The schema is in examples/blog/schema.ruprizzle in the repository.

Project layout

my-blog/
  Cargo.toml
  .env
  schema.ruprizzle
  src/
    main.rs
    db/          # generated by `ruprizzle generate`
      mod.rs
      ...

schema.ruprizzle

datasource db {
  provider = "postgres"
  url      = env("DATABASE_URL")
}

generator client {
  output      = "src/db"
  module_name = "db"
}

enum Role {
  USER
  ADMIN
}

model User {
  id        Uuid     @id @default(uuid7())
  email     String   @unique
  name      String?
  role      Role     @default(USER)
  posts     Post[]
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt      @map("updated_at")

  @@index([email])
  @@map("users")
}

model Post {
  id        Uuid    @id @default(uuid7())
  title     String  @db.VarChar(200)
  body      String?
  published Boolean @default(false)

  authorId  Uuid    @map("author_id")
  author    User    @relation(fields: [authorId], references: [id], onDelete: Cascade)

  createdAt DateTime @default(now()) @map("created_at")

  @@index([authorId, published])
  @@map("posts")
}

Cargo.toml

[package]
name = "my-blog"
version = "0.1.0"
edition = "2024"

[dependencies]
ruprizzle = "1.6"
dotenvy = "0.15"
tokio = { version = "1", features = ["full"] }

# ruprizzle re-exports sqlx and serde, but the generated client uses sqlx
# derives directly, so list them in your own Cargo.toml.
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio-rustls", "postgres"] }
serde = "1.0.229"

If you are working from a local clone of the ruprizzle-orm repository, use path = "../crates/runtime" for ruprizzle and add the project to the workspace members list.

src/main.rs

mod db;

#[tokio::main]
async fn main() -> Result<(), ruprizzle::Error> {
    dotenvy::dotenv().ok();
    let db_url =
        std::env::var("DATABASE_URL").map_err(|e| ruprizzle::Error::Message(e.to_string()))?;
    let db = db::Db::connect(&db_url).await?;

    // Create an author and a post.
    let author = db
        .user()
        .create(db::UserInsert {
            id: None,
            email: "alice@example.com".into(),
            name: Some("Alice".into()),
            role: Some(db::enums::Role::Admin),
            created_at: None,
            updated_at: None,
        })
        .exec()
        .await?;

    let _post = db
        .post()
        .create(db::PostInsert {
            id: None,
            title: "Hello, ruprizzle".into(),
            body: Some("This is the first post.".into()),
            published: Some(true),
            author_id: author.id,
            created_at: None,
        })
        .exec()
        .await?;

    // List published posts with their authors (one query per level).
    let posts = db
        .post()
        .find_many()
        .filter(db::post::PUBLISHED.eq(true))
        .order_by(db::post::CREATED_AT.desc())
        .include(db::post::author())
        .limit(10)
        .exec()
        .await?;

    for post in &posts {
        let author_name = post
            .author
            .get()
            .as_ref()
            .and_then(|a| a.name.as_ref())
            .map(|s| s.as_str())
            .unwrap_or("unknown");
        println!("{} by {}", post.title, author_name);
    }

    // Show the SQL for a query.
    let compiled = db
        .post()
        .find_many()
        .filter(db::post::PUBLISHED.eq(true))
        .to_sql()?;
    println!("{}", compiled.sql);

    Ok(())
}

.env

DATABASE_URL="postgres://user:password@localhost:5432/my_blog?sslmode=disable"

Running the example

cd examples/blog
ruprizzle migrate dev --name init
cargo run

Variations

SQLite

Change provider to sqlite and set:

DATABASE_URL="sqlite://./blog.db"

MySQL / MariaDB

Change provider to mysql and set a MySQL URL:

DATABASE_URL="mysql://user:password@localhost:3306/my_blog"

Feature Master Comparison

This doc compares the ORMs benchmarked in this repo on features, architecture, and the measured SQLite numbers. It is intended as a reference for choosing a tool, not as a definitive ranking.

Caveats: Benchmark numbers are from the versions measured in docs/BenchmarkResults.md (2026-08-18); the feature cells were re-audited against current upstream releases on 2026-09-13 (SeaORM 2.0, Prisma 7 — Rust-free client — and Drizzle 0.45 / 1.0-RC changed several answers since the measurements were taken). ruprizzle was measured at 1.0.0, before it was published — the published 1.5.1 is a superset of what was measured, and the v1.1–v1.5 additions are listed in this table even though the numbers were not re-run. Maturity and exact feature availability can change quickly, especially for alpha/early projects. Always verify against the upstream docs for your specific use case.

Legend

  • Yes — first-class, documented, supported.
  • Partial — possible with caveats, extra tooling, or limited scope.
  • No — not supported or not the intended workflow.
  • N/A — not applicable to the tool's design.

ruprizzle (rusqlite) is the same runtime and query builder as ruprizzle (sqlx); it only swaps the SQLite driver from sqlx::Any to the native rusqlite crate. PostgreSQL connections still go through sqlx in both variants.

High-level architecture

Featureruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
LanguageRustRustRustRustRustTypeScriptTypeScript
Measured version1.0.01.0.00.111.12.26.19.30.43.0
Latest version (2026-10)1.6.01.6.00.112.0.x2.3.x7.x (8 in RC)0.45.x (1.0 in RC)
Primary driversqlx (Any)sqlx for Postgres, rusqlite for SQLitetokio-postgres / sqlx / mysql_async / tokio-rusqlitesqlxlibsqlite3-sys / mysqlclient / libpqPrisma query engine + driver adaptersNode database drivers
Async APIYesYes (sync driver called on Tokio task)YesYesSync (blocking)YesYes / sync driver option
Query styleSchema-first typed builderSame as sqlx variantPrisma-like fluent builderActiveRecord / Entity + builderType-safe DSLGenerated fluent clientSQL-like typed builder
Schema source of truthschema.ruprizzleSame.prax schemaEntity files or DB firsttable! macros / schema.rsschema.prismaTypeScript schema files
No hidden query engine / sidecar binaryYesYesYesYesYesYes (Rust-free client since 7.0)Yes
SQL transparency (.to_sql() on every builder)YesYesPartialNoPartialPartialYes (SQL-first)
CLI for generate / migrateruprizzleSamepraxsea-orm-clidiesel_cliprismadrizzle-kit
Multi-tenancy / row-level securityNoNoYesYes (2.0 RBAC)NoPartialYes (RLS since 0.36)
Vector / pgvector searchNoNoYesPartialNoNoNo
Framework integrationsAny async runtimeSameAxum, Actix, ArmatureAxum, Actix, Loco, Salvo, PoemAnyNest, Next, etc.Any TS framework

Database support

Databaseruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
PostgreSQLYesYesYesYesYesYesYes
MySQL / MariaDBYesYesYesYesYesYesYes
SQLiteYesYes (native)YesYesYesYesYes
Microsoft SQL ServerNoNoYesYes (SeaORM X)NoYesYes
MongoDBNoNoYesNoNoYesNo
CockroachDBNoNoPartialPartialNoYesYes
DuckDBNoNoYesNoNoNoNo
ScyllaDB / CassandraNoNoYesNoNoNoNo
SingleStoreNoNoNoNoNoNoYes
Serverless / edge (Neon, Turso, D1, PlanetScale)YesYesPartialPartialNoYesYes
Turso / libSQL (dedicated adapter)Yes (ruprizzle-turso)Yes (ruprizzle-turso)PartialPartialNoYesYes
Cloudflare D1 (dedicated adapter)Yes (ruprizzle-d1)Yes (ruprizzle-d1)NoNoNoYesYes

Schema & code generation

Featureruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
Declarative schema DSLYesYesYesNoNoYesNo
Code-first schema in sourceNoNoNoYes (2.0 entity-first sync)PartialNoYes
Generated typed clientYesYesYesPartialPartialYesNo
Schema-first migrations (diff from schema)YesYesYesPartialNoYesPartial
Introspection / codegen from existing DBYes (db pull)Yes (db pull)PartialYesPartial (print-schema)YesYes
Compile-time query checkingYes (ruprizzle check)Yes (ruprizzle check)YesNoYesN/ANo
Type-safe column tokensYesYesYesYes (2.0 COLUMN constants)YesYes (generated types)Yes (typed columns)
Type-safe nested includeYesYesYesPartialNoYesYes
LSP for schema DSLYesYesNoNoNoYesNo
Partial indexesYes (Postgres / SQLite)Yes (Postgres / SQLite)PartialNoPartialPartialNo
Expression indexesYes (Postgres / SQLite)Yes (Postgres / SQLite)PartialNoPartialNoNo
Generated columnsYes (Postgres / SQLite)Yes (Postgres / SQLite)PartialNoPartialPartialNo
PostgreSQL extensions from schemaYesYesNoNoNoPartialNo
Enum code generationYesYesYesPartialPartialYesYes
No runtime parser/codegen in dependency treeYesYesPartialPartialYesNoYes

Query builder & type safety

Featureruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
CRUD buildersYesYesYesYesYesYesYes
Raw SQL escape hatchYesYesYesYesYesYesYes
Type-safe filtersYesYesYesPartialYesPartialPartial
Boolean filter combinators (and / or)YesYesYesYesYesYesYes
Projections (select subset)YesYesYesYesYesYesYes
Pagination (limit / offset / cursor)YesYesYesYesYesYesYes
OrderingYesYesYesYesYesYesYes
Upsert / on-conflictYesYesYesYesYesYesYes
Bulk insert manyYesYesYesYesYesYesYes
Window functions / row numberingYesYesYesPartialYesYesYes
AggregatesYesYesYesYesYesYesYes
JSON operatorsYes*Yes*PartialPartialPartialYesPartial
Array filter operatorsYesYesPartialPartialPartialYesPartial
Full-text searchYes (typed tsvector/tsquery, Postgres)Yes (same builder)PartialPartialPartialYesPartial
Soft deletesYesYesPartialPartialPartialPartialPartial
Streaming / cursorsYes (buffered + unbuffered)Yes (buffered + unbuffered)YesYesYesYesYes

Relations & advanced loading

Featureruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
One-to-many / many-to-oneYesYesYesYesYesYesYes
One-to-oneYesYesYesYesYesYesYes
Many-to-manyYes 1Yes 1YesYesYesYesYes
Self-referential relationsYesYesYesYesYesYesYes
Nested relation includeYesYesYesYes (2.0 Entity Loader)NoYesYes
Batched / auto N+1 avoidanceYes (bounded 1 query/level)SameYesYes (data loader)Manual joinYes (join or query)Yes
Per-relation filters and takeYesYesYesPartialNoYesYes
Tree / hierarchy helpersYesYesPartialPartialPartialPartialPartial
Nested writes (create/update in one call)YesYesPartialPartialNoYesPartial
Lazy loadingNoNoYesYesNoYesNo

Migrations & tooling

Featureruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
Automatic migration diffing from schemaYesYesYesPartialNoYesYes
Migration rollback (down.sql)YesYesYesYesYesYesYes
CLI for migrate / seed / statusYesYesYesYesYesYesYes
DB push (prototyping without migration files)YesYesYesNoNoYesYes
Drift detectionYesYesPartialNoNoPartialNo
Offline / embedded migrationsNoNoNoPartialYesNoNo
Transactional migrationsYesYesYesYesYesYesYes
Generated-crate compile-time benchmarkYes (xtask bench-compile)Yes (xtask bench-compile)NoNoNoNoNo
Browser Studio UIYes (ruprizzle studio)Yes (ruprizzle studio)NoPartial (SeaORM Pro, commercial)NoYesYes

Advanced query builder & SQL features

Featureruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
Conditional / dynamic filtersYesYesPartialPartialPartialPartialYes
IN set filtersYesYesYesYesYesYesYes
Count / exists queriesYesYesYesYesYesYesYes
Prepared statement builderYesYesPartialPartialPartialPartialPartial
Unbuffered streaming cursorYesYesPartialPartialPartialPartialPartial
CTEs (non-recursive)YesYesPartialPartialYesPartialYes
Recursive CTEsYesPartialNoNoPartialNoNo
Set operations (UNION / INTERSECT / EXCEPT)YesYesPartialPartialYesPartialYes
EXISTS subqueriesYesYesPartialPartialYesNoPartial
IN subqueriesYesYesPartialPartialYesNoPartial
Nested insertsYesYesPartialYes (2.0 nested ActiveModel)PartialYesNo
Nested updatesYesYesPartialYes (2.0 nested ActiveModel)PartialYesNo
Explicit JOINsYesYesPartialPartialYesNoYes
PostGIS / geospatial typesYes (typed geo-types, Postgres)Yes (same builder)PartialPartialPartialPartialPartial

Note: "Partial" for advanced SQL constructs usually means the feature is possible via raw SQL or a lower-level API, while "Yes" means a first-class builder method. ruprizzle's benchmark harness exercises every row above; availability in other ORMs is based on public documentation and the measured harness.

Observability & production

Featureruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
OpenTelemetry tracingYesYesPartialPartialNoYesNo
Read-replica routingYes (typed pool routing)YesPartialPartialPartialYesYes
Query result cacheYes (in-flight merge + TTL eviction)YesNoNoNoPartialPartial

Measured SQLite benchmark (µs/op)

Numbers are from the latest local/cross-orm-bench/BENCHMARKS.log (2026-08-18, 1 warm-up + 10 measured trials, medians reported; lower is better).

End-to-end operations

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk25.13.117.966.89.9173.139.0
find_many_10001,634.4386.3741.91,559.1305.42,820.7409.9
find_filtered_ordered1,797.4565.4925.61,603.9425.33,225.3504.7
find_filtered_paginated386.1300.0361.7455.4307.9629.8357.0
find_in_list107.730.098.8130.739.6404.299.0
find_complex_filter314.2162.1251.8340.4164.2774.0228.6
count_filtered40.120.344.491.325.7170.145.8
exists_filtered20.72.722.170.09.6151.441.6
include_posts21,139.97,553.310,741.220,856.53,627.040,867.0188,946.9
include_author20,764.97,122.68,779.820,716.53,285.478,985.716,595.5
include_posts_and_comments131,693.459,759.241,534.5114,364.320,605.2251,942.49,214,149.0
include_posts_with_tags54,108.528,362.624,896.254,784.98,156.6280,121.637,234.5
find_popular_posts1,458.41,266.32,058.71,671.51,275.62,805.25,655.4
prepared_select_by_pk24.62.34.984.710.0194.214.9
stream_find_many_10002,296.3705.657.11,807.1225.63,290.1327.0
bulk_insert_10001,912.41,383.11,059.06,027.36,689.714,142.59,069.6

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.70.70.47.60.70.111.6
to_sql_select_filter_order1.71.71.112.31.00.117.1
to_sql_select_in_list2.52.54.325.82.70.739.4
to_sql_select_complex_filter2.02.01.514.31.10.119.8
to_sql_select_paginated1.71.71.111.81.00.118.2
to_sql_prepared_select_by_pk0.70.70.42.70.80.111.9
prepared_rebind_select_by_pk0.00.00.10.10.20.10.1
to_sql_conditional_filter1.01.00.49.10.80.315.3
to_sql_select_with_cte1.91.90.819.10.20.136.5
to_sql_select_with_recursive_cte2.82.80.525.60.20.10.1
to_sql_set_union1.81.60.917.11.10.127.3
to_sql_select_with_join1.01.00.111.41.10.130.1
to_sql_select_exists_subquery1.31.30.118.01.10.124.3
to_sql_select_in_subquery1.71.70.113.10.80.119.1
to_sql_nested_insert1.31.40.40.00.60.120.3
to_sql_nested_update0.91.00.30.00.30.117.6

Best-fit summary

CriterionBest choiceWhy
Compile-time type safety, generated typed clientDiesel or ruprizzleBoth schema-first and fully typed; Diesel has the larger ecosystem, ruprizzle the more ergonomic generated client.
Maximum simple-query throughput on SQLiteruprizzle (rusqlite)3.1 µs on select_by_pk — faster than Diesel's 10.0 µs — with zero async dispatch overhead.
Multi-row reads and filtered queries on SQLiteDiesel, then ruprizzle (rusqlite)Diesel is fastest on most multi-row reads; ruprizzle (rusqlite) is within 20–40% and beats Drizzle/prax/Sea-ORM.
Bulk inserts on SQLiteprax, then ruprizzle (rusqlite)prax leads at ~1.2 ms; ruprizzle (rusqlite) at ~1.4 ms is still roughly 4× faster than Diesel/Sea-ORM.
Nested relation loading, automatic batchingruprizzle (rusqlite), then prax, then Diesel (manual)ruprizzle's auto-batched loader is ~2× faster than Sea-ORM/Prisma; Diesel is fastest if you hand-write the join.
TypeScript ecosystem, migrations, team familiarityPrismaLargest community, mature migrations, schema-first.
Zero build-step / runtime schemaDrizzleSchema is plain TypeScript, no code generation.
SQL transparency / .to_sql() on every builderruprizzle, Diesel, or Drizzleruprizzle and Diesel expose SQL cheaply; Drizzle exposes it too but is slower to construct.
Production Postgresruprizzle, Prisma, or Dieselruprizzle's performance.md shows it within ~5% of hand-written sqlx on Postgres; Diesel and Drizzle are also strong on Postgres but were not measured here.
Multi-tenancy or vector search out of the boxprax, SeaORM 2.0 (RBAC), or Drizzle (RLS helpers)prax advertises row-level security, schema/database isolation, and pgvector; SeaORM 2.0 ships table-scoped RBAC; Drizzle has Postgres RLS helpers since 0.36.

Footnotes

  1. ruprizzle (rusqlite) is a backend feature, not a separate ORM. It reuses the same runtime, query builder, and schema.ruprizzle as ruprizzle (sqlx), but uses the synchronous rusqlite crate for SQLite connections instead of sqlx::Any. Postgres still uses sqlx in both variants.

  2. Prisma ships a Rust query engine inside the client and uses a Node.js CLI for migration generation, so it is not "no hidden engine" in the same sense as the Rust-native libraries.

  3. Drizzle is SQL-first and code-first by design; there is no separate declarative schema DSL. You write the schema in TypeScript and drizzle-kit can generate or push migrations from it.

  4. Diesel migrations are file-based (up.sql / down.sql) and not auto-generated from a declarative schema diff, although diesel print-schema can generate a schema.rs from an existing database.

  5. Sea-ORM is entity-first: you can generate entity files from an existing DB with sea-orm-cli generate entity, or write them by hand. It does not have a single declarative schema file as the source of truth by default.

  6. prax advertises very broad database support (PostgreSQL, MySQL, SQLite, MSSQL, MongoDB, DuckDB, ScyllaDB) plus pgvector, multi-tenancy, and schema import, but it is a younger project and its implementation coverage should be verified for production workloads.

  7. SQLite-only benchmark: These numbers are from a single local SQLite file. Driver choice dominates simple queries, and the relative ordering can change on Postgres or with network latency. See docs/BenchmarkResults.md for the full methodology.

  8. Newer entrants not benchmarked here: Toasty (tokio-rs, 0.x — async ORM spanning SQL plus NoSQL/DynamoDB, with Turso support) and Welds (async, sqlx/Tiberius — the only Rust ORM in this list with MSSQL). Neither was part of the August 2026 measurement; both are worth watching. SeaORM Pro is a commercial admin panel on top of SeaORM — the closest paid analogue of Ruprizzle Studio / Prisma Studio.

  9. ruprizzle JSON operators are supported on Postgres (jsonb), MySQL (JSON), and SQLite (JSON1). Postgres and MySQL support full JSON containment (@>); SQLite approximates containment with a key-existence check because JSON1 has no containment operator. See KnownLimitations.md.

  10. v1.1–v1.5 features added to this comparison: partial indexes, expression indexes, generated columns, PostgreSQL extensions from datasource, ruprizzle check offline query validation, the ruprizzle-lsp language server, and the xtask bench-compile generated-crate compile-time benchmark (v1.1–v1.2); array filter operators, full-text search, soft deletes, declarative seeding (v1.1–v1.2); implicit many-to-many, nested writes, tree helpers (v1.3); OpenTelemetry, replica routing, query cache, PostGIS (v1.4); Ruprizzle Studio and the Turso/D1 adapters (v1.5). All shipped together in the published 1.5.1.


  1. ruprizzle supports both implicit many-to-many (tags Tag[] on both sides) and explicit join models (ADR-006). With an explicit PostTag model you declare tags Tag[] @relation(through: PostTag) to get post.tags, post.tags_attach(...), post.tags_set(...), and post.tags_detach(...) with batched include and transactional nested writes. ↩ ↩2

Migrating from other ORMs

From Diesel

Dieselruprizzle
table! macroschema.ruprizzle + ruprizzle generate
Selectable, Queryablegenerated Model structs
QueryDslselect(), filter(), order_by(), limit() builders
Migrations by handruprizzle migrate dev from schema diff

Quick translation

#![allow(unused)]
fn main() {
// Diesel
users::table.filter(users::email.eq("alice@example.com")).first::<User>(conn)?

// ruprizzle
db.user()
    .find_many()
    .filter(user::EMAIL.eq("alice@example.com"))
    .fetch_one()
    .await?
}

From SeaORM

SeaORMruprizzle
ActiveModelgenerated Set builders
Entityschema.ruprizzle model
Relation traitinclude() with generated relation helpers

Quick translation

#![allow(unused)]
fn main() {
// SeaORM
User::find_by_id(1).one(db).await?

// ruprizzle
db.user()
    .find_many()
    .filter(user::ID.eq(1))
    .fetch_one()
    .await?
}

From sqlx

sqlxruprizzle
Raw SQL with macrosdb.raw_pool().fetch_all_raw for escape hatches, generated builders for common cases
Manual FromRowgenerated FromRow impls per model
No migrationsruprizzle migrate

Quick translation

#![allow(unused)]
fn main() {
// sqlx
sqlx::query_as::<_, User>("SELECT * FROM users WHERE email = $1")
    .bind("alice@example.com")
    .fetch_one(&pool).await?

// ruprizzle
db.user()
    .find_many()
    .filter(user::EMAIL.eq("alice@example.com"))
    .fetch_one()
    .await?
}

From Prisma / Drizzle (TypeScript)

ruprizzle follows the Prisma shape most closely — a declarative schema file that drives both codegen and migration diffs — so most concepts map one-to-one. Feature names differ:

Prisma / Drizzleruprizzle (as of 1.5.1)
schema.prisma / drizzle-orm table defsschema.ruprizzle + ruprizzle generate
prisma migrate / drizzle-kitruprizzle migrate dev
Prisma Client extensions / Drizzle .$with()include() on the generated query builders
Prisma full-text search@@fulltext + search() filter (Postgres)
Soft-delete middleware@softDelete on the model
@@schema multi-tenancynot supported — see docs/KnownLimitations.md
pgvector extensionsnot supported
Prisma read replicas / Drizzle withReplicasPoolConfig replica routing (typed, v1.4)
Prisma Accelerate / Drizzle cachein-process query cache (v1.4)
Prisma Studio / Drizzle Studioruprizzle studio (local, per-run token auth since 1.6)
@libsql/client, @cloudflare/d1 driversruprizzle-turso, ruprizzle-d1 adapters

Performance

The end-to-end benchmark compares ruprizzle against hand-written sqlx::query for the same operations, because ruprizzle sits on top of sqlx. The interesting number is therefore our overhead, not our speed versus another ORM on different hardware.

The benchmark uses ruprizzle::connect_with for the ruprizzle side and a matching native sqlx::Postgres pool for the hand-written baseline. This is the same path a normal postgres:// URL takes by default, and it avoids the additional text-marshalling cost of the generic sqlx::Any driver.

Run it with:

RUPRIZZLE_TEST_PG_URL=postgres://ruprizzle:ruprizzle@localhost:5432/ruprizzle_test \
  cargo bench -p ruprizzle --bench end_to_end

If no database is reachable, the bench skips automatically so cargo bench still works offline.

Full-table include fast path

Unfiltered parent queries use a fast path that loads the entire child table in one query instead of building a large IN (...) list. To avoid unbounded materialisation on huge child tables, ruprizzle first COUNT(*)s the child table and only takes the fast path when the count is below PoolConfig::full_table_include_limit (default 100_000). Larger child tables fall back to a chunked IN (...) path, preserving the one-query-per-level guarantee without decoding millions of rows into memory. Set the field to None to disable the fast path entirely.

P8-02 thresholds and measured results

Measured on a single workstation (Intel Core Ultra 7 265K, 20 logical cores, 32 GB RAM) against a local PostgreSQL database using native sqlx::Postgres (via ruprizzle::connect_with). These numbers predate the 1.5.1 release and were not re-run for it; the v1.4 additions that can shift a workload's cost — replica routing, the query cache and OpenTelemetry spans — are off by default and described in docs/Operations.md.

BenchmarkHand-written sqlxruprizzleAcceptanceStatus
single-row select by PK49.9 µs53.5 µswithin 5%exceeds (+7.2%)
1 000-row select602.3 µs674.7 µswithin 5%exceeds (+12.0%)
2-level include (100 parents × 10 children × 10 grandchildren)7.14 ms7.84 mswithin 15%within threshold (+9.8%)
bulk insert 10 000 rows35.4 ms36.0 mswithin 10%within threshold (+1.8%)

The bulk-insert case now completes successfully on the local PostgreSQL instance; the previous run was blocked by a tmpfs WAL-space exhaustion.

On this run the 1 000-row and single-row selects are both above the 5% parity target. The 2-level include and bulk insert are within their thresholds. The single/1 000-row overhead is likely dominated by the extra row-by-row decoding in the ORM path; the 2-level include grouping has improved substantially. P8-02 measures this overhead against the thresholds; actually optimising the remaining per-row decode cost belongs to a separate work item.

Prepared statements

SelectQuery::prepare() compiles a SELECT once and returns a PreparedSelect that re-uses the compiled SQL. Bind values can be swapped with bind or bind_many and the statement can be executed again without recompiling.

Measured with cargo bench -p ruprizzle --features sqlite-rusqlite --bench query_construction on the same workstation:

BenchmarkTime
to_sql_select_by_pk614 ns
prepare_select_by_pk553 ns
prepared_rebind_select_by_pk53 ns

Compiling the SQL is ~600 ns; rebinding a prepared statement is an order of magnitude cheaper. For query shapes that are executed repeatedly with different parameters, prepare() removes that per-call compilation cost.

Text-marshalling cost

sqlx::Any serialises Uuid, Decimal, DateTime, Date, Time and Json to text on every outbound bind and parses them from text on every inbound row. That cost is real, but the default postgres:// connection path uses the native sqlx::Postgres driver and binds rich types directly, so most Postgres users are not affected. The cost only applies if you explicitly construct Pool::Any(...) or use a generic Any URL.

On SQLite, enable the sqlite-rusqlite feature and connect with ?driver=rusqlite in the URL. This bypasses sqlx::Any text marshalling for Uuid, Decimal, DateTime, Date, Time and Json and decodes them from the native SQLite value directly. It is still stored as text in the database, so exact Decimal arithmetic should use Int minor units or a PostgreSQL backend. The synchronous rusqlite call is offloaded to tokio::task::spawn_blocking so it does not pin the async runtime's worker threads; this trades a small per-call dispatch cost for runtime responsiveness.

In a real workload with rich types the gap between ruprizzle and hand-written sqlx is expected to be dominated by the ORM decode path, not by driver marshalling, as long as the native driver is selected. If you profile, compare against hand-written sqlx::query using the same native sqlx::Postgres pool.

See also

  • Benchmark results — cross-ORM SQLite numbers for ruprizzle (sqlx), ruprizzle (rusqlite), prax, Sea-ORM, Diesel, Prisma, and Drizzle, including the new query-construction operations added in the latest benchmark run.
  • Feature master comparison — full feature and architecture comparison, including the advanced SQL builder feature matrix.

Cross-ORM benchmark results

This document records an apples-to-apples benchmark of ruprizzle, prax, Sea-ORM, Diesel, Prisma, and Drizzle against the same SQLite dataset and the same query shapes. ruprizzle is shown in two configurations: the sqlx backend and the new native rusqlite backend.

Environment

  • Host: Windows 11, local SQLite file
  • Dataset:
    • users: 1,000 rows
    • categories: 20 rows
    • posts: 10,000 rows (10 posts per user)
    • comments: 50,000 rows (5 comments per post)
    • tags: 100 rows
    • post_tags: 30,000 rows (3 tags per post)
    • followers: 5,000 rows
    • likes: 20,000 rows
    • bench_bulk: empty table used for bulk-insert tests
  • Versions:
    • ruprizzle 1.0.0 (this repo; pre-release snapshot — the published 1.5.1 shares this code path but these numbers were not re-run for it)
    • prax-orm 0.11
    • Sea-ORM 1.1
    • Diesel 2.2
    • Prisma 6.19.3
    • Drizzle ORM 0.43.0
    • better-sqlite3 13.0.3
    • rusqlite 0.32.1

Important: this run used SQLite because no Postgres / Docker was available. The numbers are therefore dominated as much by driver choice as by the ORM layer. ruprizzle (sqlx backend) uses sqlx::Any, ruprizzle (rusqlite backend) offloads the synchronous rusqlite call to tokio::task::spawn_blocking so it does not pin the async runtime's worker threads, prax and Sea-ORM use sqlx-sqlite, Diesel uses libsqlite3-sys/diesel with a bundled SQLite, Drizzle uses the synchronous better-sqlite3 binding, and Prisma uses its in-process Rust query engine.

Harness and raw data

  • ruprizzle: crates/runtime/examples/cross_orm_bench.rs
  • ruprizzle (rusqlite): same example with RUST_BENCH_DRIVER=rusqlite
  • prax: local/cross-orm-bench/rust/prax-bench/src/main.rs
  • Sea-ORM: local/cross-orm-bench/rust/sea-orm-bench/src/main.rs
  • Diesel: local/cross-orm-bench/rust/diesel-bench/src/main.rs
  • Prisma / Drizzle: local/cross-orm-bench/node/
  • Database: local/cross-orm-bench/node/bench.sqlite3
  • Result JSONs:
    • local/cross-orm-bench/raw_results.json — all measured trials
    • local/cross-orm-bench/results.json — aggregated statistics
    • local/cross-orm-bench/BENCHMARKS.log — human-readable summary
    • local/cross-orm-bench/node/ruprizzle-results.json
    • local/cross-orm-bench/node/ruprizzle-rusqlite-results.json
    • local/cross-orm-bench/node/prax-results.json
    • local/cross-orm-bench/node/sea-orm-results.json
    • local/cross-orm-bench/node/diesel-results.json
    • local/cross-orm-bench/node/prisma-results.json
    • local/cross-orm-bench/node/drizzle-results.json

End-to-end results

All times are microseconds per operation (lower is better).

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk25.13.117.966.89.9173.139.0
find_many_10001,634.4386.3741.91,559.1305.42,820.7409.9
find_filtered_ordered1,797.4565.4925.61,603.9425.33,225.3504.7
include_posts21,139.97,553.310,741.220,856.53,627.040,867.0188,946.9
bulk_insert_10001,912.41,383.11,059.06,027.36,689.714,142.59,069.6

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.70.70.47.60.7—11.6
to_sql_select_filter_order1.71.71.112.31.0—17.1

Codegen / build-step comparison

  • Drizzle: no code generation; the schema is plain TypeScript.
  • ruprizzle: 50-model schema generation = 17.8 ms (cargo bench -p ruprizzle-codegen).
  • Prisma: prisma generate for the 3-model benchmark schema took ~36 ms; it scales linearly with schema size and is heavier than ruprizzle for large schemas.

Analysis

Simple reads

The synchronous, native-driver ORMs lead here:

  • Diesel: 9.9 µs
  • ruprizzle (rusqlite): 3.1 µs
  • prax: 17.9 µs
  • ruprizzle (sqlx): 25.1 µs
  • Drizzle: 39.0 µs
  • Sea-ORM: 66.8 µs
  • Prisma: 173.1 µs

The rusqlite query is offloaded to tokio::task::spawn_blocking, which adds a small dispatch overhead per call while keeping async worker threads unblocked. ruprizzle (rusqlite) is now the fastest on single-row PK lookups for this run. Direct ToSql impls on Value avoid the extra string clone that used to happen per bind. Diesel and ruprizzle (sqlx) are the next tier.

Multi-row and filtered reads

Diesel is still fastest, but ruprizzle (rusqlite) is now within striking distance:

  • find_many_1000: 305.4 µs (Diesel) vs 386.3 µs (ruprizzle rusqlite) vs 409.9 µs (Drizzle) vs 741.9 µs (prax) vs 1,559.1 µs (Sea-ORM) vs 2,820.7 µs (Prisma)
  • find_filtered_ordered: 425.3 µs (Diesel) vs 504.7 µs (Drizzle) vs 565.4 µs (ruprizzle rusqlite) vs 925.6 µs (prax) vs 1,603.9 µs (Sea-ORM) vs 3,225.3 µs (Prisma)

The remaining gap on multi-row reads is mostly per-row decoding overhead in ruprizzle's intermediate Row/FromValue path. The native drivers avoid the per-row async worker-thread hop used by sqlx-sqlite, which still shows up clearly in Sea-ORM and ruprizzle (sqlx).

Relation includes

Diesel's manually-written join query is fastest, while ruprizzle's auto-batched loader remains the strongest automatic option:

  • Diesel: 3.6 ms (manual join)
  • ruprizzle (rusqlite): 7.6 ms (auto-batched)
  • prax: 10.7 ms
  • ruprizzle (sqlx): 21.1 ms
  • Sea-ORM: 20.9 ms
  • Prisma: 40.9 ms
  • Drizzle: 188.9 ms (correlated subquery per parent row)

Offloading the synchronous rusqlite call to spawn_blocking adds a small per-call and per-row overhead compared to running it synchronously on the caller, but it prevents long-running workloads from pinning tokio worker threads. The remaining gap vs Diesel is the in-memory grouping of 10,000 child rows into 1,000 parent Vecs. Diesel does not group in this benchmark. Drizzle's SQLite relational query still emits a correlated subquery with json_group_array per parent row.

Bulk insert

The rusqlite and sqlx backends are fastest:

  • prax: 1.1 ms
  • ruprizzle (rusqlite): 1.4 ms
  • ruprizzle (sqlx): 1.9 ms
  • Sea-ORM: 6.0 ms
  • Diesel: 6.7 ms
  • Drizzle: 9.1 ms
  • Prisma: 14.1 ms

Diesel's bulk insert is slower here despite using a single INSERT statement. ruprizzle and prax both use a multi-value statement with RETURNING * and still come out ahead.

Query construction

Turning a builder into SQL+binds is cheap for all the Rust ORMs, while the TypeScript/JavaScript ORMs are an order of magnitude slower:

  • prax: 0.4 µs, Diesel: 0.7 µs, ruprizzle (rusqlite): 0.7 µs, ruprizzle (sqlx): 0.7 µs
  • Sea-ORM: 7.6–12.3 µs
  • Drizzle: 11.6–17.1 µs
  • Prisma: not exposed

Query construction remains a sub-microsecond win for the Rust ORMs; the bigger wins in this round came from removing per-query SQL string clones and moving the soak harness onto the native rusqlite pool.

Usage criteria

CriterionBest choiceWhy
Compile-time type safety, generated typed clientDiesel or ruprizzleBoth are schema-first and fully typed; Diesel has the larger ecosystem, ruprizzle the more ergonomically generated client.
Maximum simple-query throughput on SQLiteruprizzle (rusqlite)3.1 µs on select_by_pk — ahead of Diesel's 9.9 µs — with spawn_blocking dispatch overhead.
Multi-row reads and filtered queries on SQLiteDiesel, then ruprizzle (rusqlite)Diesel is fastest; ruprizzle (rusqlite) is within 20–40% and beats Drizzle/prax.
Bulk inserts on SQLiteprax, then ruprizzle (rusqlite)1.1–1.4 ms, faster than Diesel/Sea-ORM/Drizzle.
Nested relation loading, automatic batchingDiesel (manual), then ruprizzle (rusqlite), then praxDiesel's manual join is fastest; ruprizzle's auto-batched loader beats Sea-ORM/Prisma.
TypeScript ecosystem, migrations, team familiarityPrismaLargest community, mature migrations, schema-first.
Zero build-step / runtime schemaDrizzleSchema is plain TypeScript, no code generation.
SQL transparency / .to_sql() on every builderruprizzle, Diesel, or Drizzleruprizzle and Diesel expose SQL cheaply; Drizzle exposes it too but is slower to construct.
Production Postgresruprizzle, Prisma, or Dieselruprizzle's performance.md shows it within ~5% of hand-written sqlx on Postgres; Diesel and Drizzle are also strong on Postgres but were not measured here.

Caveats

  1. SQLite is not Postgres. These numbers are from a single SQLite file. The relative ordering can change with network latency, a different driver, or a different database. Do not cite these numbers for a Postgres comparison until they are re-run on Postgres.
  2. Driver and dispatch differences dominate simple reads. ruprizzle (rusqlite) offloads rusqlite queries to tokio::task::spawn_blocking, trading a small per-call dispatch cost for the ability to keep the async runtime responsive. ruprizzle (rusqlite) wins on single-row PK lookups for this run, with Diesel close behind running the native SQLite call synchronously on the caller. Diesel uses libsqlite3-sys directly, and Drizzle uses the synchronous better-sqlite3 binding. All of these avoid the per-row async worker-thread hop used by sqlx-sqlite (which powers ruprizzle (sqlx), prax, and Sea-ORM). The measured row-hop cost is roughly 0.9 µs/row for sqlx-sqlite versus ~0.3 µs/row for the synchronous bindings, which is why Diesel, ruprizzle (rusqlite), and Drizzle cluster near the top for simple reads.
  3. Drizzle relational query is SQLite/driver-specific. On Postgres Drizzle can use joins/CTEs and would likely be far faster for include_posts; do not take the 188.9 ms as a universal Drizzle number.
  4. No network. All ORMs talked to a local file, so result-set decoding and ORM overhead are the main differentiators.
  5. This run used 1 warm-up + 10 measured trials per driver. Medians are reported. See local/cross-orm-bench/BENCHMARKS.log and local/cross-orm-bench/raw_results.json for full per-trial data. Run-to-run variance can be 5–10% on Windows. The main take-away is the relative shape between backends, not single-digit absolute values.

See also

  • Performance — Postgres vs sqlx measurements and the sqlx::Any text-marshalling note.
  • Known limitations — honest boundaries of the alpha.
  • Feature master comparison — feature and architecture comparison across all ORMs, including the extended benchmark table.
  • ProjectPlan/ImplementationPlan/ImplPlan09TestingRelease.md — original testing-and-benchmark plan.

Benchmark run: 2026-08-13 07:25 UTC

Environment

  • Warm-up trials: 1
  • Measured trials: 2
  • Dataset:
    • 1,000 users
    • 20 categories
    • 10,000 posts
    • 50,000 comments
    • 100 tags
    • 30,000 post_tags
    • 5,000 followers
    • 20,000 likes

End-to-end results

All times are microseconds per operation (lower is better).

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk24.03.124.783.711.2196.750.8
find_many_10001,725.2367.5731.31,641.7306.92,844.8461.6
find_filtered_ordered1,767.5566.3880.51,648.0413.13,351.1585.5
find_filtered_paginated404.1298.5350.0421.9307.8717.8375.7
find_in_list114.228.4125.3131.437.7434.4143.5
find_complex_filter331.9157.9302.0337.4158.1905.1258.0
count_filtered46.120.551.685.126.8203.862.9
exists_filtered31.42.644.457.19.6152.059.2
include_posts22,034.97,133.611,112.620,362.43,845.743,635.5202,045.1
include_author21,274.47,341.28,882.520,066.13,305.285,683.719,261.1
include_posts_and_comments134,962.355,612.443,914.9110,351.220,711.9260,752.610,445,301.8
include_posts_with_tags54,808.525,538.126,189.554,337.68,326.9265,723.746,585.6
find_popular_posts1,471.41,253.01,980.71,616.61,295.72,590.96,567.2
bulk_insert_10001,907.81,238.31,139.96,456.86,765.014,355.79,612.8

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.50.60.47.80.7—11.4
to_sql_select_filter_order1.51.51.112.41.0—16.4
to_sql_select_in_list2.32.34.328.42.7—38.3
to_sql_select_complex_filter1.81.81.514.61.1—19.0
to_sql_select_paginated1.51.51.111.91.0—19.2

Benchmark run: 2026-08-13 11:45 UTC

Environment

  • Warm-up trials: 1
  • Measured trials: 3
  • Dataset:
    • 1,000 users
    • 20 categories
    • 10,000 posts
    • 50,000 comments
    • 100 tags
    • 30,000 post_tags
    • 5,000 followers
    • 20,000 likes

End-to-end results

All times are microseconds per operation (lower is better).

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk25.43.020.563.210.0209.838.1
find_many_10001,648.4375.9737.51,641.6296.83,078.2405.6
find_filtered_ordered1,882.6556.7900.51,618.2413.33,465.3539.6
find_filtered_paginated392.6297.0353.6421.1304.1801.8361.1
find_in_list115.130.298.6131.237.6481.9130.0
find_complex_filter306.9163.8232.3352.8159.2873.4234.0
count_filtered35.521.540.377.525.7203.751.6
exists_filtered16.52.616.957.79.6159.744.5
include_posts21,069.97,185.710,711.719,915.23,743.742,498.5186,426.8
include_author20,702.47,231.69,064.720,774.23,438.083,394.216,330.6
include_posts_and_comments131,291.156,928.343,907.2108,491.820,990.9262,741.69,093,560.6
include_posts_with_tags51,677.926,213.626,020.851,054.78,071.8257,371.436,273.0
find_popular_posts1,506.31,306.02,021.41,620.31,297.82,547.25,556.0
bulk_insert_10001,865.91,273.51,102.56,171.27,060.813,761.89,778.8

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.60.50.47.30.7—11.6
to_sql_select_filter_order1.51.61.112.11.0—17.0
to_sql_select_in_list2.42.34.324.92.7—38.8
to_sql_select_complex_filter1.81.91.514.21.1—18.8
to_sql_select_paginated1.51.51.111.71.0—17.2

Benchmark run: 2026-08-17 10:31 UTC

Environment

  • Warm-up trials: 1
  • Measured trials: 3
  • Dataset:
    • 1,000 users
    • 20 categories
    • 10,000 posts
    • 50,000 comments
    • 100 tags
    • 30,000 post_tags
    • 5,000 followers
    • 20,000 likes

End-to-end results

All times are microseconds per operation (lower is better).

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk26.83.224.568.410.5205.540.6
find_many_10001,672.0421.8737.91,685.6303.62,929.8445.3
find_filtered_ordered1,820.5588.5867.51,664.3458.03,364.7592.5
find_filtered_paginated380.8323.0367.2425.3313.9688.5383.7
find_in_list107.630.493.5130.338.0443.8153.2
find_complex_filter317.9169.4254.2351.6161.2847.0281.9
count_filtered36.119.838.781.126.7200.951.6
exists_filtered19.02.728.761.39.6184.448.5
include_posts22,552.88,064.811,167.220,926.73,740.344,188.7209,266.2
include_author22,017.37,805.19,258.220,993.03,563.987,114.521,389.2
include_posts_and_comments139,103.659,680.645,911.1116,811.122,209.8271,459.59,939,872.7
include_posts_with_tags58,117.228,041.026,128.755,850.48,884.1282,784.339,234.7
find_popular_posts1,504.41,376.11,980.91,639.01,414.52,686.26,129.3
prepared_select_by_pk20.42.4—————
stream_find_many_10001,922.2704.1—————
bulk_insert_10002,100.21,502.01,044.014,892.67,632.813,908.49,867.8

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.60.60.47.60.8—12.3
to_sql_select_filter_order1.51.51.112.21.0—18.0
to_sql_select_in_list2.32.34.526.12.8—41.8
to_sql_select_complex_filter1.81.81.614.31.2—20.9
to_sql_select_paginated1.51.61.111.71.0—18.9
to_sql_prepared_select_by_pk0.60.7—————
prepared_rebind_select_by_pk0.00.0—————
to_sql_conditional_filter0.80.8—————
to_sql_select_with_cte1.61.6—————
to_sql_select_with_recursive_cte2.32.4—————
to_sql_set_union1.61.4—————
to_sql_select_with_join0.90.9—————
to_sql_select_exists_subquery1.01.1—————
to_sql_select_in_subquery1.31.4—————
to_sql_nested_insert1.21.2—————
to_sql_nested_update0.80.8—————

Benchmark run: 2026-08-17 12:00 UTC

Environment

  • Warm-up trials: 1
  • Measured trials: 3
  • Dataset:
    • 1,000 users
    • 20 categories
    • 10,000 posts
    • 50,000 comments
    • 100 tags
    • 30,000 post_tags
    • 5,000 followers
    • 20,000 likes

End-to-end results

All times are microseconds per operation (lower is better).

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk20.93.117.666.510.1174.839.3
find_many_10001,620.4424.2794.71,710.1303.82,879.6406.8
find_filtered_ordered1,841.1549.2925.31,810.3421.83,332.9480.2
find_filtered_paginated393.1309.0347.4472.9307.7667.1372.6
find_in_list107.132.880.8131.841.4445.1104.8
find_complex_filter310.3156.7230.3355.2167.2836.1248.4
count_filtered35.519.534.989.925.4187.046.7
exists_filtered17.12.616.158.69.5155.946.1
include_posts22,514.67,411.610,818.122,010.83,725.542,982.6189,412.7
include_author21,994.27,115.18,845.521,775.03,417.683,281.317,031.6
include_posts_and_comments137,868.357,814.543,439.2118,143.120,724.0262,781.59,280,171.7
include_posts_with_tags55,864.726,187.525,400.958,378.98,063.9266,997.037,587.5
find_popular_posts1,518.61,306.81,993.91,661.41,324.32,646.55,636.3
prepared_select_by_pk18.22.64.563.79.9177.014.9
stream_find_many_10002,024.0689.757.72,760.6237.32,643.1314.8
bulk_insert_10001,966.01,434.71,195.36,279.67,080.613,614.58,518.1

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.60.60.47.50.70.111.8
to_sql_select_filter_order1.51.51.112.71.00.117.2
to_sql_select_in_list2.32.34.425.32.70.739.6
to_sql_select_complex_filter1.81.81.514.31.10.119.4
to_sql_select_paginated1.51.51.112.01.00.117.7
to_sql_prepared_select_by_pk0.60.60.42.70.80.111.8
prepared_rebind_select_by_pk0.00.00.10.10.20.10.1
to_sql_conditional_filter0.80.80.48.30.80.315.0
to_sql_select_with_cte1.61.60.815.80.20.136.1
to_sql_select_with_recursive_cte2.42.40.521.30.30.10.1
to_sql_set_union1.41.40.914.01.10.126.4
to_sql_select_with_join0.90.90.19.21.10.129.2
to_sql_select_exists_subquery1.01.00.115.01.10.123.8
to_sql_select_in_subquery1.41.40.110.60.80.119.0
to_sql_nested_insert1.21.20.40.00.60.119.9
to_sql_nested_update0.80.80.30.00.30.117.6

Benchmark run: 2026-08-17 16:16 UTC

Environment

  • Warm-up trials: 1
  • Measured trials: 10
  • Dataset:
    • 1,000 users
    • 20 categories
    • 10,000 posts
    • 50,000 comments
    • 100 tags
    • 30,000 post_tags
    • 5,000 followers
    • 20,000 likes

End-to-end results

All times are microseconds per operation (lower is better).

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk22.63.022.965.815.5196.439.2
find_many_10001,644.7383.2770.61,684.5311.23,061.4411.1
find_filtered_ordered1,781.2569.4946.21,777.0446.43,469.7498.7
find_filtered_paginated381.8308.6403.6460.7314.5730.7347.7
find_in_list102.129.6107.3147.853.2463.5100.6
find_complex_filter306.6164.9262.0372.8182.1850.3221.4
count_filtered39.420.044.487.133.7199.447.1
exists_filtered17.32.718.464.613.4166.741.3
include_posts22,236.77,679.711,498.621,707.33,801.745,196.0187,172.4
include_author22,262.87,436.99,581.221,619.03,453.087,424.816,660.2
include_posts_and_comments132,481.457,545.444,265.0117,815.921,704.7270,511.99,144,201.9
include_posts_with_tags55,727.327,186.326,821.057,127.18,494.4274,363.437,185.9
find_popular_posts1,478.61,268.72,160.11,661.81,317.82,689.45,543.8
prepared_select_by_pk26.02.34.674.915.0179.614.9
stream_find_many_10002,035.8686.059.72,485.3245.52,754.3316.6
bulk_insert_10001,962.51,346.01,222.49,403.513,988.213,118.68,341.6

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.60.60.47.60.70.112.2
to_sql_select_filter_order1.51.61.112.41.00.118.0
to_sql_select_in_list2.32.44.425.42.80.740.6
to_sql_select_complex_filter1.81.81.514.61.20.120.0
to_sql_select_paginated1.51.51.112.01.00.118.4
to_sql_prepared_select_by_pk0.60.60.42.70.80.112.0
prepared_rebind_select_by_pk0.00.00.10.10.20.10.1
to_sql_conditional_filter0.80.80.48.40.90.315.4
to_sql_select_with_cte1.61.60.815.70.20.136.9
to_sql_select_with_recursive_cte2.32.40.521.40.20.10.1
to_sql_set_union1.61.40.914.11.20.127.4
to_sql_select_with_join0.90.90.19.21.10.130.3
to_sql_select_exists_subquery1.01.10.115.11.10.124.3
to_sql_select_in_subquery1.41.40.110.70.80.119.3
to_sql_nested_insert1.21.30.40.00.60.120.6
to_sql_nested_update0.80.80.30.00.30.118.4

Benchmark run: 2026-08-17 16:55 UTC

Environment

  • Warm-up trials: 1
  • Measured trials: 10
  • Dataset:
    • 1,000 users
    • 20 categories
    • 10,000 posts
    • 50,000 comments
    • 100 tags
    • 30,000 post_tags
    • 5,000 followers
    • 20,000 likes

End-to-end results

All times are microseconds per operation (lower is better).

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk27.93.122.576.810.0182.938.3
find_many_10001,741.1385.8771.01,616.5297.42,935.7414.2
find_filtered_ordered1,918.1569.6966.11,669.8433.83,358.3506.7
find_filtered_paginated412.9312.6371.2426.0307.9666.1360.0
find_in_list125.629.5101.0129.439.9427.7101.9
find_complex_filter324.8166.8256.8343.9172.2838.5229.3
count_filtered39.620.640.781.325.9178.947.7
exists_filtered18.52.719.357.99.8157.742.4
include_posts22,881.27,545.511,712.920,333.53,647.444,300.7186,014.4
include_author23,033.27,332.09,596.420,500.23,362.586,517.416,450.2
include_posts_and_comments136,207.957,665.944,929.0110,745.120,997.0267,560.29,098,301.2
include_posts_with_tags57,895.027,607.227,132.654,141.48,209.3276,963.636,364.1
find_popular_posts1,579.21,268.02,221.21,564.61,296.92,662.85,553.4
prepared_select_by_pk20.52.35.360.210.2165.514.8
stream_find_many_10002,096.7706.558.12,576.9231.72,659.3330.7
bulk_insert_10002,099.71,395.01,174.65,031.36,619.313,236.68,536.1

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.60.60.47.40.70.111.8
to_sql_select_filter_order1.61.61.212.21.00.117.2
to_sql_select_in_list2.32.44.525.62.70.740.3
to_sql_select_complex_filter1.81.91.614.21.10.119.1
to_sql_select_paginated1.51.51.111.81.00.117.7
to_sql_prepared_select_by_pk0.60.60.42.70.70.111.7
prepared_rebind_select_by_pk0.00.00.10.10.20.10.1
to_sql_conditional_filter0.80.80.48.30.80.314.6
to_sql_select_with_cte1.61.60.815.30.20.135.6
to_sql_select_with_recursive_cte2.32.40.520.80.20.10.1
to_sql_set_union1.61.40.913.71.10.126.0
to_sql_select_with_join0.90.90.19.01.10.129.0
to_sql_select_exists_subquery1.01.10.114.41.10.124.0
to_sql_select_in_subquery1.41.40.110.50.80.118.6
to_sql_nested_insert1.21.20.40.00.50.119.8
to_sql_nested_update0.80.80.30.00.30.117.4

Benchmark run: 2026-08-18 06:04 UTC

Environment

  • Warm-up trials: 1
  • Measured trials: 10
  • Concurrency levels: [1, 10, 100]
  • Duration per throughput run: 5.0s
  • Dataset:
    • 1,000 users
    • 20 categories
    • 10,000 posts
    • 50,000 comments
    • 100 tags
    • 30,000 post_tags
    • 5,000 followers
    • 20,000 likes

End-to-end results

All times are microseconds per operation (lower is better).

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk25.13.117.966.89.9173.139.0
find_many_10001,634.4386.3741.91,559.1305.42,820.7409.9
find_filtered_ordered1,797.4565.4925.61,603.9425.33,225.3504.7
find_filtered_paginated386.1300.0361.7455.4307.9629.8357.0
find_in_list107.730.098.8130.739.6404.299.0
find_complex_filter314.2162.1251.8340.4164.2774.0228.6
count_filtered40.120.344.491.325.7170.145.8
exists_filtered20.72.722.170.09.6151.441.6
include_posts21,139.97,553.310,741.220,856.53,627.040,867.0188,946.9
include_author20,764.97,122.68,779.820,716.53,285.478,985.716,595.5
include_posts_and_comments131,693.459,759.241,534.5114,364.320,605.2251,942.49,214,149.0
include_posts_with_tags54,108.528,362.624,896.254,784.98,156.6280,121.637,234.5
find_popular_posts1,458.41,266.32,058.71,671.51,275.62,805.25,655.4
prepared_select_by_pk24.62.34.984.710.0194.214.9
stream_find_many_10002,296.3705.657.11,807.1225.63,290.1327.0
bulk_insert_10001,912.41,383.11,059.06,027.36,689.714,142.59,069.6

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.70.70.47.60.70.111.6
to_sql_select_filter_order1.71.71.112.31.00.117.1
to_sql_select_in_list2.52.54.325.82.70.739.4
to_sql_select_complex_filter2.02.01.514.31.10.119.8
to_sql_select_paginated1.71.71.111.81.00.118.2
to_sql_prepared_select_by_pk0.70.70.42.70.80.111.9
prepared_rebind_select_by_pk0.00.00.10.10.20.10.1
to_sql_conditional_filter1.01.00.49.10.80.315.3
to_sql_select_with_cte1.91.90.819.10.20.136.5
to_sql_select_with_recursive_cte2.82.80.525.60.20.10.1
to_sql_set_union1.81.60.917.11.10.127.3
to_sql_select_with_join1.01.00.111.41.10.130.1
to_sql_select_exists_subquery1.31.30.118.01.10.124.3
to_sql_select_in_subquery1.71.70.113.10.80.119.1
to_sql_nested_insert1.31.40.40.00.60.120.3
to_sql_nested_update0.91.00.30.00.30.117.6

Latency percentiles (ruprizzle sqlx)

Operationp50p95p99
select_by_pk25.132.533.5
find_many_10001,634.41,701.21,725.8
find_filtered_ordered1,797.41,863.11,863.7
find_filtered_paginated386.1407.9408.7
find_in_list107.7122.2125.4
find_complex_filter314.2338.3342.2
count_filtered40.148.249.8
exists_filtered20.730.833.0
include_posts21,139.923,082.523,460.9
include_author20,764.921,973.522,057.2
include_posts_and_comments131,693.4138,897.9139,415.8
include_posts_with_tags54,108.557,747.557,792.9
find_popular_posts1,458.41,482.61,484.6
prepared_select_by_pk24.632.332.7
stream_find_many_10002,296.32,385.92,397.2
bulk_insert_10001,912.42,980.83,497.2
to_sql_select_by_pk0.70.70.7
to_sql_select_filter_order1.71.71.8
to_sql_select_in_list2.52.52.6
to_sql_select_complex_filter2.02.12.2
to_sql_select_paginated1.71.81.9
to_sql_prepared_select_by_pk0.70.70.7
prepared_rebind_select_by_pk0.00.00.0
to_sql_conditional_filter1.01.01.0
to_sql_select_with_cte1.91.91.9
to_sql_select_with_recursive_cte2.82.92.9
to_sql_set_union1.81.81.8
to_sql_select_with_join1.01.01.0
to_sql_select_exists_subquery1.31.41.4
to_sql_select_in_subquery1.71.71.7
to_sql_nested_insert1.31.41.4
to_sql_nested_update0.91.01.0

Throughput (ops/sec)

BackendConcurrencyselect_by_pkfind_many_1000bulk_insert_1000

Benchmark run: 2026-08-31 13:17 UTC

Environment

  • Warm-up trials: 1
  • Measured trials: 10
  • Concurrency levels: [1, 10, 100]
  • Duration per throughput run: 5.0s
  • Dataset:
    • 1,000 users
    • 20 categories
    • 10,000 posts
    • 50,000 comments
    • 100 tags
    • 30,000 post_tags
    • 5,000 followers
    • 20,000 likes

End-to-end results

All times are microseconds per operation (lower is better).

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
select_by_pk25.13.117.966.89.9173.139.0
find_many_10001,634.4386.3741.91,559.1305.42,820.7409.9
find_filtered_ordered1,797.4565.4925.61,603.9425.33,225.3504.7
find_filtered_paginated386.1300.0361.7455.4307.9629.8357.0
find_in_list107.730.098.8130.739.6404.299.0
find_complex_filter314.2162.1251.8340.4164.2774.0228.6
count_filtered40.120.344.491.325.7170.145.8
exists_filtered20.72.722.170.09.6151.441.6
include_posts21,139.97,553.310,741.220,856.53,627.040,867.0188,946.9
include_author20,764.97,122.68,779.820,716.53,285.478,985.716,595.5
include_posts_and_comments131,693.459,759.241,534.5114,364.320,605.2251,942.49,214,149.0
include_posts_with_tags54,108.528,362.624,896.254,784.98,156.6280,121.637,234.5
find_popular_posts1,458.41,266.32,058.71,671.51,275.62,805.25,655.4
prepared_select_by_pk24.62.34.984.710.0194.214.9
stream_find_many_10002,296.3705.657.11,807.1225.63,290.1327.0
bulk_insert_10001,912.41,383.11,059.06,027.36,689.714,142.59,069.6

Query construction (no I/O)

Operationruprizzle (sqlx)ruprizzle (rusqlite)praxsea-ormdieselprismadrizzle
to_sql_select_by_pk0.70.70.47.60.70.111.6
to_sql_select_filter_order1.71.71.112.31.00.117.1
to_sql_select_in_list2.52.54.325.82.70.739.4
to_sql_select_complex_filter2.02.01.514.31.10.119.8
to_sql_select_paginated1.71.71.111.81.00.118.2
to_sql_prepared_select_by_pk0.70.70.42.70.80.111.9
prepared_rebind_select_by_pk0.00.00.10.10.20.10.1
to_sql_conditional_filter1.01.00.49.10.80.315.3
to_sql_select_with_cte1.91.90.819.10.20.136.5
to_sql_select_with_recursive_cte2.82.80.525.60.20.10.1
to_sql_set_union1.81.60.917.11.10.127.3
to_sql_select_with_join1.01.00.111.41.10.130.1
to_sql_select_exists_subquery1.31.30.118.01.10.124.3
to_sql_select_in_subquery1.71.70.113.10.80.119.1
to_sql_nested_insert1.31.40.40.00.60.120.3
to_sql_nested_update0.91.00.30.00.30.117.6

Latency percentiles (ruprizzle sqlx)

Operationp50p95p99
select_by_pk25.132.533.5
find_many_10001,634.41,701.21,725.8
find_filtered_ordered1,797.41,863.11,863.7
find_filtered_paginated386.1407.9408.7
find_in_list107.7122.2125.4
find_complex_filter314.2338.3342.2
count_filtered40.148.249.8
exists_filtered20.730.833.0
include_posts21,139.923,082.523,460.9
include_author20,764.921,973.522,057.2
include_posts_and_comments131,693.4138,897.9139,415.8
include_posts_with_tags54,108.557,747.557,792.9
find_popular_posts1,458.41,482.61,484.6
prepared_select_by_pk24.632.332.7
stream_find_many_10002,296.32,385.92,397.2
bulk_insert_10001,912.42,980.83,497.2
to_sql_select_by_pk0.70.70.7
to_sql_select_filter_order1.71.71.8
to_sql_select_in_list2.52.52.6
to_sql_select_complex_filter2.02.12.2
to_sql_select_paginated1.71.81.9
to_sql_prepared_select_by_pk0.70.70.7
prepared_rebind_select_by_pk0.00.00.0
to_sql_conditional_filter1.01.01.0
to_sql_select_with_cte1.91.91.9
to_sql_select_with_recursive_cte2.82.92.9
to_sql_set_union1.81.81.8
to_sql_select_with_join1.01.01.0
to_sql_select_exists_subquery1.31.41.4
to_sql_select_in_subquery1.71.71.7
to_sql_nested_insert1.31.41.4
to_sql_nested_update0.91.01.0

Frequently asked questions

What is ruprizzle-orm?

A schema-first ORM for Rust. You write a Prisma-style .ruprizzle schema, and the CLI generates typed entities, a Drizzle-style query builder, and migration SQL. It targets PostgreSQL, MySQL/MariaDB, and SQLite 3+.

Is it production-ready?

Yes, within the limits below. 1.5.1 (2026-09-13) was the first stable release and the public API is covered by semantic versioning from there on; the current release is 1.6.0 (2026-10-03). Earlier tags — v1.0.0, v1.0.1, v1.5.0 — are git tags whose publish runs failed before uploading anything; none of them exists on crates.io.

The design is complete and the test suite is broad, and the release gate ran green end-to-end for 1.5.1 and 1.6.0. Known gaps are still stated plainly in the release notes: the Turso and D1 adapters have opt-in live smoke tests that have not yet been run against the hosted services. See Known limitations for the deliberate boundaries before making it a mission-critical dependency.

Two gates were waived along the way, both in writing rather than by omission: the 48-hour rusqlite soak, accepted on 15.56 h / 1.46 B ops / 0 errors, and the two-week release-candidate feedback window, because the project had no external consumers to collect feedback from. See Stability for the semver policy, the waivers, and the public-dependency list (the 1.x line is pinned to sqlx 0.8).

The v1.1–v1.5 line (what's new) shipped inside 1.5.1, including Ruprizzle Studio and the Turso and D1 adapters. There is no Neon adapter: Neon is Postgres over TLS, so its connection string goes straight to ruprizzle::connect.

Which version should I install?

1.5.1 — the current stable release on crates.io.

[dependencies]
ruprizzle = "1.5"

If you are still on 1.0.0-rc.1, see Upgrading from 1.0.0-rc.1 to 1.5.1 — most applications need no code changes.

What databases does ruprizzle support?

PostgreSQL, MySQL/MariaDB and SQLite 3+, behind a DbDialect trait. Connections go through sqlx by default. Two native drivers are available as optional features: sqlite-rusqlite for synchronous SQLite, and an experimental postgres-tokio-postgres for PostgreSQL. Turso/libSQL and Cloudflare D1 adapters are published on crates.io (ruprizzle-turso, ruprizzle-d1), speaking their providers' HTTP APIs, but have not been validated against a live hosted database.

Is ruprizzle free? What licence is it under?

Yes — free and open source, dual-licensed MIT OR Apache-2.0, the standard arrangement in the Rust ecosystem. There is no paid tier, no telemetry and no commercial licence to buy.

How is it different from Diesel or SeaORM?

  • It is schema-first: the schema file is the single source of truth.
  • It generates a type-safe, token-based query builder where cross-model or wrong-typed filters are compile errors.
  • It supports nested include with per-relation filters in a bounded number of queries.
  • It diffs the schema to generate migrations automatically.
  • It exposes .to_sql() on every builder.

Which databases are supported?

PostgreSQL 17+, MySQL/MariaDB, and SQLite 3+ through SQLx. Native rusqlite and tokio-postgres drivers are available behind feature flags for better SQLite and PostgreSQL performance.

Does it require a query engine sidecar?

No. The runtime is a library built on sqlx. There is no separate process or hidden query engine binary.

Does it support compile-time query checking?

Yes. Use ruprizzle check --manifest <path> with a query manifest captured from tests or examples. See ADR-012 for the design.

Is there an LSP?

Yes. ruprizzle lsp (and the ruprizzle-lsp crate) provide completion, hover, formatting, diagnostics, and go-to-definition for schema.ruprizzle. A VS Code extension is in editor/.

How do I report bugs or request features?

Open an issue on the GitHub repository.

Operations guide

This document is for the person running ruprizzle in production: what the runtime emits, what to watch, and what to do when it misbehaves.

Telemetry

ruprizzle uses two telemetry systems:

  • tracing for events and spans. Enable a subscriber that captures the ruprizzle::query, ruprizzle::slow_query, ruprizzle::migrate, ruprizzle::pool, and ruprizzle::connection targets.
  • metrics (behind the metrics feature) for counters, histograms, and gauges. Install a recorder such as metrics-exporter-prometheus or an OpenTelemetry adapter.

Both systems deliberately avoid PII. Binds are reported as a count, never as values.

What each span means

ruprizzle::query

DEBUG event emitted after every executed statement.

  • sql — the SQL shape, with placeholders intact.
  • binds — number of placeholder values.
  • rows / rows_affected — result summary.
  • elapsed_ms — how long the statement took.

Enable this target when debugging latency or when you need a query log for auditing.

ruprizzle::slow_query

WARN event emitted when a query exceeds PoolConfig::slow_query_threshold.

  • sql — the SQL shape.
  • binds — placeholder count.
  • elapsed_ms — actual duration.

Set the threshold to the 99th percentile of normal queries. A slow query is not an outage by itself, but a sustained spike in these events is a leading indicator of saturation or a missing index.

ruprizzle::migrate

INFO events emitted during migration application.

  • migration — the migration id.
  • statements — number of statements in the file.
  • elapsed_ms — how long the migration took.

A long elapsed_ms on a migration is expected for backfills. A sudden failure is a WARN or ERROR with the migration id.

ruprizzle::pool and ruprizzle::connection

INFO/WARN events for connection lifecycle (see W3-04).

  • connect, disconnect, acquire_timeout, reconnect.

Metrics

Enable the metrics feature and install a recorder.

Query metrics

NameTypeLabelsMeaning
ruprizzle_query_totalcounter—Total executed statements.
ruprizzle_query_duration_secondshistogram—Query latency.
ruprizzle_query_errors_totalcounterkindErrors by Error::kind().

Slow queries are emitted as WARN events on the ruprizzle::slow_query tracing target, not as a metric counter.

Pool metrics

NameTypeMeaning
ruprizzle_pool_sizegaugeConnections held by the pool.
ruprizzle_pool_idlegaugeConnections available for checkout.
ruprizzle_pool_in_usegaugeConnections currently checked out.
ruprizzle_pool_waitersgaugeTasks waiting for a connection.

Migration metrics

NameTypeMeaning
ruprizzle_migration_applied_totalcounterMigrations applied.
ruprizzle_migration_duration_secondshistogramPer-migration duration.

How to read PoolStats

#![allow(unused)]
fn main() {
use ruprizzle::pool;

let stats = pool::report_metrics(&pool);
println!("size={} idle={} in_use={} waiters={}",
         stats.size, stats.idle, stats.in_use, stats.waiters);
}

report_metrics also emits the current values to the metrics recorder.

Interpretation:

  • in_use near size for a sustained period means the pool is fully utilized.
  • waiters > 0 means requests are queueing. Increase max_connections or reduce query latency.
  • idle near 0 means the pool is sized at the edge. min_connections can smooth out cold-start latency.

What to do when ping fails

pool::ping runs SELECT 1. If it fails:

  1. Check the ruprizzle::connection target for connect and reconnect events. Repeated reconnects mean the network or database process is unstable.
  2. Check ruprizzle::query_errors_total{kind="connection"}. A rising count confirms connection-level failures.
  3. Verify acquire_timeout is not too aggressive for a remote database.
  4. If using sqlite-rusqlite, ensure the database file is on a local volume with write access.

Read-replica routing

RoutedPool sends reads to replicas and keeps writes and transactions on the primary. A raw statement goes to a replica only if it starts with SELECT, WITH, VALUES, TABLE or SHOW and contains none of INSERT, UPDATE, DELETE, MERGE, INTO, RETURNING, LOCK, SHARE, NEXTVAL or SETVAL as a word; anything else, such as SELECT … FOR UPDATE or INSERT … RETURNING, runs on the primary.

use ruprizzle::{connect, LoadBalancing, RoutedPool};

let routed = RoutedPool::builder(connect(&primary_url).await?)
    .add_replica(connect(&replica_a_url).await?)
    .add_replica(connect(&replica_b_url).await?)
    .load_balancing(LoadBalancing::LeastConnections)
    .fallback_to_primary(true)
    .build();

let read_pool = routed.select_replica();   // a healthy replica, or the primary
let tx = routed.begin().await?;            // always the primary

LoadBalancing is RoundRobin (the default), LeastConnections, or Random. A replica is only ever chosen while it is marked healthy, and check_health() pings every replica and updates those flags. Nothing pings in the background unless you ask: let _checks = routed.spawn_health_checks(Duration::from_secs(5)); (since 1.6) runs check_health() on that interval until the returned handle is dropped, or call check_health() from your own supervisor. With fallback_to_primary(true), a read is served by the primary when no replica is healthy rather than failing; set it to false when moving read load onto the primary is worse than an error: reads through the router then fail with a fallback_to_primary error. LeastConnections counts the reads in flight through the router on each replica (a stream counts until dropped); Random draws uniformly per call.

Query result cache

QueryCache is the trait; InMemoryCache is the bundled implementation, bounded by a maximum entry count and invalidated either by TTL or by tag.

use ruprizzle::{InMemoryCache, QueryCache};
use std::time::Duration;

let cache = InMemoryCache::new(10_000);
cache.set("users:active", encoded, Some(Duration::from_secs(30)), &["users"]);

let hit = cache.get("users:active");       // None once the TTL has passed
cache.invalidate_tag("users");             // drop everything tagged `users`

Tags are the invalidation unit: tag each cached result with the tables it was read from, and invalidate that tag on every write to those tables. Entries expire lazily on read; prune_expired() reclaims memory eagerly if you would rather not wait for the next lookup. Implement QueryCache yourself to put the same interface in front of Redis or any other shared store — nothing in the trait assumes a single process.

The cache is manual. Query execution never reads or writes it: you call get before a query and set after it, and ruprizzle_cache_hits_total / ruprizzle_cache_misses_total are not emitted. SelectQuery::cache, cache_key and cache_tag exist in the 1.5 API but do nothing, and are deprecated since 1.5.2. So are SelectQuery::use_primary and use_replica. To choose a pool, build the query on RoutedPool::primary(), on the RoutedPool itself, or on select_replica().

Alerts

Suggested thresholds for a health dashboard:

  • Error rate: rate(ruprizzle_query_errors_total[5m]) > 0.01/sec.
  • Slow query rate: use the ruprizzle_query_duration_seconds histogram (e.g. p99 above your PoolConfig::slow_query_threshold) or watch WARN events on the ruprizzle::slow_query tracing target.
  • Pool saturation: ruprizzle_pool_waiters > 0 for more than 30 seconds.
  • Migrations stuck: ruprizzle_migration_applied_total not increasing while a deployment is expected.

Example Prometheus scrape

[dependencies]
ruprizzle = { version = "1.5", features = ["metrics"] }
metrics-exporter-prometheus = "0.15"
#![allow(unused)]
fn main() {
use metrics_exporter_prometheus::PrometheusBuilder;

PrometheusBuilder::new()
    .install_recorder()
    .expect("failed to install Prometheus recorder");
}

The recorder will expose ruprizzle_* metrics on the configured endpoint. Point Grafana at the same endpoint for the dashboard above.

Dialect notes

Postgres, MySQL/MariaDB, and SQLite share the same schema DSL but differ in what they can express natively.

Type mapping

DSL typePostgresMySQL / MariaDBSQLiteNotes
StringTEXTVARCHAR(255)TEXT
IntINTEGERINTINTEGER
BigIntBIGINTBIGINTINTEGERSQLite only has one integer type.
FloatDOUBLE PRECISIONDOUBLEREAL
DecimalNUMERICDECIMAL(65,30)TEXTAvoid arithmetic on SQLite.
BooleanBOOLEANTINYINT(1)INTEGERMySQL and SQLite use 0/1.
DateTimeTIMESTAMPTZDATETIME(6)TEXTISO-8601 in SQLite.
DateDATEDATETEXT
TimeTIMETIMETEXT
UuidUUIDCHAR(36)TEXT
JsonJSONBJSONTEXTSQLite stores as text.
BytesBYTEABLOBBLOB

Migrations

ChangePostgresMySQL / MariaDBSQLite
Add / drop columnALTER TABLEALTER TABLEALTER TABLE (3.35+) or table rebuild.
Rename columnALTER TABLE ... RENAME COLUMNALTER TABLE ... CHANGE COLUMNTable rebuild.
Change typeALTER TABLE ... ALTER COLUMN ... TYPEALTER TABLE ... MODIFY COLUMNTable rebuild.
Add / drop FKALTER TABLE ... ADD/DROP CONSTRAINTALTER TABLE ... ADD/DROP FOREIGN KEYTable rebuild (cannot add FK after create).
Add enum variantALTER TYPE ... ADD VALUERebuild the column check constraint.Rebuild CHECK constraint on each using column.

MySQL has no DML RETURNING clause. The runtime executes the insert and then selects the inserted row by its primary key; auto-increment keys use LAST_INSERT_ID(). Upserts use ON DUPLICATE KEY UPDATE. MariaDB-specific RETURNING syntax is intentionally not emitted so the same schema remains valid on both MySQL and MariaDB.

Capabilities

#![allow(unused)]
fn main() {
let cap = SqliteDialect.capabilities();
assert!(!cap.native_enums);       // enums are emulated
assert!(!cap.native_uuid);        // stored as text
assert!(!cap.alter_column_type);  // type changes require rebuild
assert!(cap.drop_column);         // SQLite 3.35+
}

ruprizzle validate prints warnings when you use a construct that the active provider handles poorly, e.g. Decimal on SQLite.

Query builder

The runtime query builder compiles to SQL per dialect. If a construct cannot be expressed on the target database, to_sql() returns Error::Message(...) instead of emitting unsupported SQL:

ConstructPostgresMySQL / MariaDBSQLite
INNER JOINyesyesyes
LEFT JOINyesyesyes
RIGHT JOINyesyesno
FULL OUTER JOINyesnono
UNION / UNION ALLyesyesyes
INTERSECTyesnoyes
EXCEPTyesnoyes

MySQL does not support INTERSECT or EXCEPT; MariaDB does not support INTERSECT or EXCEPT either. SQLite supports both but does not support RIGHT JOIN or FULL OUTER JOIN.

v1.1–v1.5 features per dialect

The feature line shipped in 1.5.1 lands differently on each backend:

FeaturePostgresMySQL / MariaDBSQLite
Array columns + filter operatorsNative T[]JSON + JSON_CONTAINS / JSON_OVERLAPSTEXT (JSON)
Full-text searchNative tsvector / tsquery, @@fulltext + generated columnMATCH ... AGAINSTFTS5 virtual table
Soft deletes@softDelete field + transparent WHERE filtersamesame
PostGIS / geospatialgeo-types mapping, spatial indexesnono
Implicit many-to-manyjoin table emitted by migrate devsamesame
Read-replica routing / query cache / OTelruntime-level, dialect-agnosticsamesame
Serverless adapters——ruprizzle-turso (Hrana over HTTP), ruprizzle-d1 (Cloudflare REST)

Turso and D1 are SQLite-family dialects reached over HTTP: one request per statement, no interactive transactions — see docs/KnownLimitations.md for the full caveat list.

MySQL-specific notes

  • No RETURNING clause. Inserts and upserts rely on a primary-key follow-up query or LAST_INSERT_ID() for auto-increment keys.
  • No native ENUM types. Enumerations are enforced with CHECK constraints.
  • No FULL OUTER JOIN or RIGHT JOIN on older versions. Prefer LEFT JOIN or emulate with UNION where necessary.
  • String[] is stored as JSON. Array containment and overlap are implemented with JSON_CONTAINS and JSON_OVERLAPS.
  • Uuid is stored as CHAR(36); Decimal uses DECIMAL(65,30) (or a narrower DECIMAL(19,4) when declared with @db.Decimal(p,s)).
  • Upserts use ON DUPLICATE KEY UPDATE, keyed on the primary key and unique constraints.

Known limitations

This is an honest list of what ruprizzle does and does not do. It is a feature, not an apology: knowing the boundaries up front is how you decide whether the tool is right for your project.

Current release (1.5.1)

  • Heuristic renames are suggested automatically. Add @renamedFrom to confirm or ignore the prompt; the diff never renames silently.
  • db push does not write migration files and is only for prototyping.
  • LSP for schema.ruprizzle is available via ruprizzle-lsp and the VS Code extension in editor/. Syntax highlighting is also available as a TextMate grammar.
  • Offline query checking (ruprizzle check) is available using query manifests captured at test time. See ADR-012.
  • Decimal on SQLite is stored as text by the default sqlx::Any path. The sqlite-rusqlite feature parses it back from text at decode time, which removes the sqlx::Any text round-trip but still stores it as text on disk. If you need real decimal math on SQLite, use Int minor units (e.g. cents) or a PostgreSQL backend.
  • SQLite Json is stored as text, but the JSON1 extension is used for json_extract, json_type, and json_set. The sqlite-rusqlite feature also decodes Json without the sqlx::Any text round-trip. JSON containment (@>) is only a partial key-existence approximation because SQLite JSON1 has no containment operator.
  • Array columns (T[]) are supported for scalar and enum types. PostgreSQL stores them as native arrays; SQLite and MySQL store them as JSON text using the dialect's JSON facilities. Array filter operators (has, has_every, has_some, contains, contained_by, overlaps, is_empty, is_not_empty) are implemented across all three backends.
  • Rich types through sqlx::Any are limited. On SQLite, Uuid, Decimal, DateTime, Date, Time, and Json round-trip as text. The sqlite-rusqlite feature parses them from text at decode time, which is faster but still stores them as text in the database. On Postgres, the default postgres:// connection uses the native sqlx::Postgres driver and binds rich types directly, so sqlx::Any text marshalling only applies if you explicitly construct Pool::Any(...) or use a non-default URL. The postgres-tokio-postgres feature is available as an additional native driver with its own performance characteristics. See ADR-009.
  • SelectQuery::stream is buffered, not a true cursor. The current implementation buffers the full result set and yields decoded rows. Using sqlx's .fetch() stream is ~64% slower per row on SQLite, so the buffered design is deliberate. See BenchmarkResults.
  • SelectQuery::stream_unbuffered is available for true streaming. It uses sqlx's .fetch() cursor for the SQLx backends and a server-side portal for postgres-tokio-postgres. To satisfy sqlx's lifetime model, the owned SQL string and bind values are leaked for the lifetime of the stream (they are typically small). stream_unbuffered must not be used inside a transaction, because a transaction holds a single connection and a streaming cursor would prevent any other statement from running on it.
  • MySQL/MariaDB carries an unpatched advisory in its auth path. sqlx-mysql pulls in rsa 0.9.x, which is affected by RUSTSEC-2023-0071 (a Marvin timing side-channel in RSA decryption). No patched rsa release exists as of 2026-08-21, so the exception is recorded in deny.toml rather than fixed. The side-channel is reachable only through MySQL's caching_sha2_password RSA key exchange, which is skipped when the connection uses TLS or a unix socket. Use TLS or a unix socket for MySQL connections. Until a patched rsa or sqlx ships, MySQL/MariaDB is supported and tested but is not marketed as production-grade; Postgres and SQLite carry no such exception.

Release-specific gaps (1.6.0)

  • Ruprizzle Studio has token authentication only. Since 1.6 every request needs the per-run session token (random, or --token / RUPRIZZLE_STUDIO_TOKEN): the launch URL Studio prints (/studio?token=…) sets it as an HttpOnly, SameSite=Strict cookie, and scripts send it as x-studio-token or Authorization: Bearer. There are no user accounts or roles and no TLS, so off loopback the token crosses the network in cleartext. It binds 127.0.0.1 by default and refuses --allow-writes on a non-loopback host without --yes-i-know; do not expose it on an untrusted network. Since 1.5.2 it refuses requests whose Host is not Studio's own name (DNS rebinding) and mutations without Studio's Origin and session token (CSRF), so a web page open in the same browser cannot drive it. Scripted POSTs from curl are refused for the same reason.
  • The Turso and D1 adapters are unverified against the live hosted services. ruprizzle-turso (Hrana 2 over HTTP) and ruprizzle-d1 (Cloudflare REST API) are tested end-to-end against local HTTP fakes, not real Turso/D1 databases. Live smoke tests exist (cargo test -p ruprizzle-turso --test live, likewise for ruprizzle-d1, and the edge-live workflow) but skip without credentials and have not yet been run against the hosted services. Both send one HTTP request per statement, so neither supports interactive transactions, and stream_raw on each is a streaming interface over a fully buffered response. Turso has no embedded-replica support (that needs the native libSQL library), and D1 has no in-Worker/wasm32 binding.
  • D1 parameters and results are JSON. Binary parameters and non-finite floats (NaN, ±inf) are refused with D1Error::Unsupported. Integers beyond ±2^53 are rounded by D1's JavaScript runtime before the adapter sees them, in both directions; store 64-bit identifiers as text on D1.
  • There is no Neon adapter, by design. Neon is ordinary Postgres over TLS; its connection string goes straight to ruprizzle::connect.
  • Studio templates use askama 0.14, not the latest 0.15+/0.16, because those need Rust 1.88 and the workspace MSRV is 1.85.

Deferred / not implemented

  • Polymorphic relations.
  • Row-level security and multi-tenancy (@@tenant/@@policy are rejected at validation; they were removed from the LSP so they cannot appear to work).
  • Vector / pgvector search.
  • Support for additional databases (MSSQL).

When to choose something else

  • Use sqlx directly if you want hand-written SQL and compile-time checked queries today.
  • Use Diesel if you need a mature, stable query builder and are comfortable with its DSL.
  • Use SeaORM if you want an active-record style API and do not need schema-first code generation.

API Stability Policy

This document defines what ruprizzle commits to under semantic versioning, from the first stable release onward, and how that commitment is enforced. It exists so that "we follow semver" is a checkable claim rather than a habit — see W6-02 in ProjectPlan/v1/PathToStableV1.md.

1.5.1 — the first published stable release — shipped on 2026-09-13, so this policy is now in force — it is no longer a description of a target. Everything below applies to the published 1.x line. The v1.0.0 and v1.0.1 tags were cut earlier but their publish runs never uploaded, so they carry no stability commitment of their own. The 0.x prereleases are superseded; see docs/MigrationGuideToV1.md for what changed getting here from 0.1.1-beta.1.

Two things about how the stable line was reached are recorded rather than glossed: the release-candidate feedback window was waived (see the waiver at the end of this document), and the 1.x line is pinned to sqlx 0.8 because ruprizzle re-exports it (see "Public dependencies").

What is covered by semver

The following are covered — a breaking change to any of them requires a major version bump:

  • ruprizzle (the runtime crate). Its public items as enumerated by cargo public-api: the query builder (SelectQuery, InsertQuery, UpdateQuery, DeleteQuery, InsertManyQuery, and their terminal methods), Pool and PoolConfig, Transaction, Error and its variants' matchable kind() strings, Related<T>, the raw! macro re-export, and the prelude module.
  • ruprizzle-migrate. The diff engine's public API (diff, change-class types), the migration runner (MigrationRunner, MigrationMeta), and squashing/rename-detection entry points that ruprizzle-cli and third-party tooling can call directly.
  • ruprizzle-core, ruprizzle-dialect, ruprizzle-parser, ruprizzle-codegen. These are published, and their public surfaces are semver-covered like any other published crate, but they are lower-level than ruprizzle and ruprizzle-migrate and are expected to see fewer direct downstream consumers. ruprizzle-core::ir's IR types are exposed with wide field visibility by design (ADR-007) rather than through an accessor API — this means the IR's shape is part of the semver surface, not just its module paths. Exception: W2-02's join result typing is explicitly called out in PathToStableV1.md as provisional and reviewed by W6-01; if it needs to change shape before 1.0.0, that change is not held to the RC feedback window described below.
  • Generated client code's public shape. The entity structs, column tokens, and query-builder entry points that ruprizzle generate emits from a .ruprizzle schema are part of the user contract: a schema that generates and compiles today must keep generating and compiling after a patch or minor bump. The internal implementation of the generated code (exact token names for private helpers, module layout inside the generated file, exact TokenStream shape before prettyplease formatting) is not covered — only the parts a user's own code references (entity field names/types, relation accessors, query builder methods you call from application code).
  • The ruprizzle-cli binary's command surface (subcommands, flags, exit codes) is treated as semver-covered even though it has no library API: a script that calls ruprizzle migrate deploy today should still work after a minor bump.

What is explicitly NOT covered

These may change in any release, including a patch release, without a major version bump:

  • ruprizzle-testkit. Ships publish = false and its own README says "not published." It exists to give the workspace's own test suites a dual-database harness and is not intended for external use.
  • xtask. Repository automation only (publish = false), not a crate anyone depends on.
  • Anything under a crate's benches/ directory, including the end_to_end benchmark harness in crates/runtime/benches, and any type that exists solely to support it.
  • Generated code's internal helpers — private (non-pub, or pub only within the generated crate) items in generated output. See "generated client code's public shape" above for the boundary.
  • Anything marked #[doc(hidden)]. Used for items that must be pub for a macro or trait bound to work but are not part of the intended API surface.
  • Anything under an unstable Cargo feature flag, should one be introduced. No crate currently defines one; if a genuinely experimental capability needs to ship ahead of a stability commitment, it goes behind --features unstable, is documented as such in its rustdoc, and is exempt from the semver guarantee and from cargo-semver-checks gating described below.
  • Error message text. Error's Display output and miette diagnostic rendering may be reworded at any time; only Error's variant shapes and kind() strings are semver-covered, because those are what calling code is expected to match on.
  • Dependency versions. Bumping a dependency (e.g. sqlx, chrono) is not itself a breaking change to ruprizzle's own API, even though it can occasionally change what types are re-exported through trait bounds; those re-export changes are evaluated case by case against the categories above.

MSRV policy

Current MSRV: Rust 1.85 (rust-version = "1.85" in the workspace Cargo.toml, inherited by every crate via rust-version.workspace = true, and checked in CI's msrv job in .github/workflows/ci.yml, which reads the same field and runs cargo test --workspace against it).

Policy for the published 1.x line:

  • MSRV may be bumped in a minor release (e.g. 1.6.0), not a patch release.
  • An MSRV bump is called out explicitly in CHANGELOG.md under its own heading, not buried in "Changed."
  • MSRV is bumped no more than roughly once every six months, and only to pick up a toolchain feature actually used by the codebase or a dependency's own MSRV bump that cannot reasonably be pinned around.
  • The CI msrv job is the enforcement mechanism: it fails the build if any crate's code requires a newer toolchain than the declared rust-version.

Public dependencies

Some of ruprizzle's dependencies are part of its own public API, because their types appear in signatures users write. crates/runtime/src/lib.rs re-exports them so that a caller's version and ours are guaranteed to be the same crate:

CrateVersion on the 1.0 lineWhere it surfaces
sqlx0.8pub use sqlx;, Pool, Tx, Executor, every FromRow impl
serde1pub use serde;, derives on generated entities
serde_json1pub use serde_json;, the Json column type
rusqlite0.32pub use ::rusqlite::{Row, types} behind sqlite-rusqlite

A major bump of any crate in this table is a breaking change to ruprizzle and requires a major version bump of ruprizzle itself. This is not a policy choice — it is a consequence of the type system. If your application depends on sqlx 0.9 and ruprizzle 1.x, Cargo will link two incompatible copies of sqlx and your PgPool will not be our PgPool.

Two consequences worth stating plainly, because they will surprise someone:

  • The 1.0 line is pinned to sqlx 0.8. sqlx 0.9.0 shipped 2026-05-06 and was considered for 1.0.0. It was deferred: it makes all query*() functions take impl SqlSafeStr (133 call sites here build SQL dynamically), makes SqliteValue !Sync and SqliteValueRef !Send on the decode path, removes lifetimes from AnyArguments and the Arguments trait, changes MySQL text/blob conversion behaviour, and raises the toolchain floor to 1.86. That is a 2.0.0-sized change, and doing it hastily on the way out the door was judged worse than doing it deliberately. See ProjectPlan/v1/V1StableRelease.md D2 for the full reasoning, and ProjectPlan/v2/V2FeaturesPlan.md for where it is tracked.
  • Non-public dependencies carry no such promise. pest, syn, quote, prettyplease, miette, tracing, clap, notify, criterion, and metrics are implementation details. They may be bumped across major versions in a minor release of ruprizzle, because none of their types reach a user's code.

Deprecation process

  • An item slated for removal is marked #[deprecated(since = "X.Y.Z", note = "...")] with a note that says what to use instead (or that there is no replacement and why).
  • Deprecated items remain functional — not just present but working — for at least one full minor version after the deprecation is introduced, and are only removed in the next major version after that. Concretely: an item deprecated in 1.2.0 stays working through at least 1.3.x, and can only be removed starting at 2.0.0.
  • Every deprecation and every removal of a previously-deprecated item is recorded in CHANGELOG.md, under "Deprecated" and "Removed" respectively (Keep a Changelog's standard headings), with the same before/after treatment docs/MigrationGuideToV1.md uses for the 0.x-to-1.0 transition.
  • cargo-semver-checks (see below) does not currently model deprecation windows — it flags true breaking changes (removed items, changed signatures). It does not stop a deprecated item's removal at a major version; that discipline is a matter of the PR review process documented in CONTRIBUTING.md, not a mechanical gate.

Enforcement: cargo-semver-checks in CI

Mechanical enforcement of everything above lives in the semver-checks CI job (see .github/workflows/ci.yml), added under W6-03. It runs cargo-semver-checks against every published, semver-covered crate on every pull request, comparing the working tree's public API to the latest version published on crates.io. A detected breaking change without a corresponding major (pre-1.0: minor) version bump fails the job.

cargo-semver-checks does not (yet) understand the "generated code" or "CLI command surface" carve-outs above by construction — it checks Rust-level API surface. Breaking changes confined to those categories are still expected to be called out by hand in CHANGELOG.md and reviewed in PR, same as any other user-facing change.

Release candidates (W6-04)

1.0.0 is not cut directly from a 0.x release. Before it, the project publishes 1.0.0-rc.1 (and, if feedback requires changes, 1.0.0-rc.2, etc.) as an ordinary crates.io prerelease.

  • What 1.0.0-rc.1 means: the public API is believed frozen — everything in "What is covered by semver" above is intended to be the final 1.0.0 shape — but the release is not yet a stability commitment. A breaking change discovered during the RC window is still fixed by breaking the API again in 1.0.0-rc.2, not by shipping the mistake into 1.0.0 and deprecating it.
  • Feedback window: at least two weeks of real-world use between publishing 1.0.0-rc.1 and cutting 1.0.0, and longer if substantive feedback arrives near the end of the window (each round of feedback that produces an API change restarts a shorter, focused window rather than the full two weeks). The plan's rationale (PathToStableV1.md) is explicit that the current download count (43, across four 0.x prereleases) is not enough exposure to freeze an API on without external eyes on the RC specifically.
  • What reviewers should focus on: exactly the semver-covered surface above — does the query builder read naturally from application code, does Error matching work the way its kind() strings imply, does a generated schema from 0.1.1-beta.1 still compile after following docs/MigrationGuideToV1.md. Feedback on the generated-code internals or xtask is out of scope for the RC gate, since those are not semver-covered.
  • What this repository does not do during an RC window: merge new features into the RC branch. Only fixes to bugs found during the window and, if needed, API corrections land; anything else waits for 1.1.0.

This section documents the process; it does not itself cut a release. 1.0.0-rc.1 was published to crates.io on 2026-08-21 from tag v1.0.0-rc.1. The stable release this RC fed into was eventually published as 1.5.1 on 2026-09-13 — the v1.0.0 and v1.0.1 tags in between never produced a package. See the W6-04/W6-05 status note in ProjectPlan/v1/PathToStableV1.md.

Waiver: the 1.0.0-rc.1 feedback window (2026-08-21)

The two-week window described above was waived for the 1.0 stable line. The v1.0.0 tag was cut the same day 1.0.0-rc.1 was published, rather than on or after 2026-09-04 (its publish run then failed before uploading; the first published stable became 1.5.1). This is recorded here rather than left implicit, because a policy the project did not follow is worse than a policy it amended on purpose. The decision, its rationale, and the alternative considered are written up as decision D1 in ProjectPlan/v1/V1StableRelease.md; it follows the same pattern as the W4-02 soak waiver in docs/SoakReport.md.

  • Why. The window's purpose is external eyes on a frozen API. Across seven 0.x prereleases the project has 43 total downloads and no known external consumer, so the two weeks would have bought calendar time and no feedback. The related definition-of-done item — "at least one external project reporting a successful upgrade" — is waived for the same reason: there is no such project to report one.
  • What stands in its place. The full gate matrix in V1StableRelease.md §6, run against the tagged commit: fmt, clippy -D warnings across the feature matrix, the workspace test suite against a live PostgreSQL, cargo doc --all-features with -D warnings, cargo deny check, cargo xtask harden, and cargo xtask release-check --tag. Plus cargo-semver-checks, which continues to compare every published crate's API against the last release on crates.io — from the first published stable (1.5.1) onward that comparison is the semver gate.
  • What this waiver does not do. It does not repeal the policy. A future 2.0.0-rc.1, or any RC published once real downstream users exist, gets the full window. It also does not weaken the semver commitment: if an API defect surfaces in the field, the answer is the next minor for an addition and 2.0.0 for a break, under the deprecation process above — not a retroactive redefinition of what 1.0.0 promised.

One-time exception: 1.0.0-rc.1 → 1.5.1

1.5.1 is the first stable release after 1.0.0-rc.1. Its public API differs from the RC in ways cargo-semver-checks classifies as major: new variants on exhaustive enums, new fields on constructible structs, three diagnostic enums made #[non_exhaustive], and four internal modules made #[doc(hidden)]. As the release-candidates section above allows, these are accepted as RC → stable changes rather than forcing 2.0.0. Two conditions apply:

  • Every item is documented with a fix in Upgrading from 1.0.0-rc.1, together with what was verified to stay compatible: clients generated by rc.1, migration snapshots and query manifests.
  • The exception covered this one upgrade only. With 1.5.1 published, the CI semver job's temporary release-type: major has been removed and the public-api baseline is 1.5.1 with --deny=all; every rule on this page now applies unchanged.

Versioning policy

One number for everything

Every crate in the workspace and the VS Code extension in editor/vscode carry the same version number, moved in lockstep. There are no independently-versioned components.

The reason is that they are not independently useful. ruprizzle-cli embeds the parser, the codegen and the migration engine; the extension talks to the LSP binary those crates build. A user who has ruprizzle 1.5.0 and extension 1.2.0 cannot tell from the numbers whether they match, and the only honest answer would be a compatibility table nobody maintains. One number removes the question.

The cost is accepted deliberately: a crate with no changes in a release still gets a new version. That is cheaper than the table.

Where the number lives

PlaceHow it is set
[workspace.package] version in the root Cargo.tomlThe source of truth.
Every crate manifestversion.workspace = true. Never write a literal.
[workspace.dependencies] internal pins in the root Cargo.tomlLiteral, and must equal the workspace version. cargo publish needs a version alongside path.
editor/vscode/package.jsonLiteral. Must equal the workspace version.

editor/vscode drifted to 1.2.0 while every crate sat at 1.0.0, because nothing tied the two together and no policy said which was right. That is what this document exists to prevent (ProjectPlan/v2/ProductionReadinessV1_5.md §5.2).

Semver

The public API is covered by semantic versioning from the first published stable release — 1.5.1 — onward. What counts as public, and what a breaking change is, is defined in Stability.

Crates marked publish = false are outside the semver promise: ruprizzle-testkit and xtask. They still carry the workspace version, because they are built from the same tree.

Cutting a release

  1. Bump [workspace.package] version and the internal [workspace.dependencies] pins in the root Cargo.toml.
  2. Bump editor/vscode/package.json to match.
  3. Add the version heading to CHANGELOG.md, dated.
  4. cargo xtask release-check --tag vX.Y.Z — this verifies the tag, the workspace version and the CHANGELOG.md heading agree, and fails if they do not.
  5. cargo xtask harden — among other audits this checks that every publishable crate is in PUBLISH_ORDER and that .github/workflows/release.yml publishes exactly that list, in that order.
  6. Tag and push. release.yml runs the full gate and publishes.

Steps 4 and 5 are mechanical gates, not conventions. Neither can be satisfied by remembering to do something.

Soak test report

Context: all evidence on this page was gathered on the pre-release 1.0.x codebase, ahead of the 1.5.1 publish. The waived W4-02 gate below is the evidence 1.5.1 shipped on; the run was not repeated on 1.5.1.

Harness

crates/runtime/tests/soak.rs runs a configurable mixed load:

  • RUPRIZZLE_SOAK_DURATION_SECONDS — how long to run (default 30).
  • RUPRIZZLE_SOAK_WORKERS — concurrent workers (default 8).

Workers repeatedly perform one of INSERT, UPDATE, SELECT, or DELETE on a soak_kv table using different keys. Every seventh operation is wrapped in a transaction to exercise connection acquire/release cycles. Every five seconds the harness prints:

  • elapsed time
  • total operations
  • errors
  • pool size, idle, in-use, and waiter counts
  • process RSS in bytes

Smoke run (10 s, 8 workers) — before key-cycle fix

soak health: elapsed=15.9074ms ops=2 errors=0 size=4 idle=0 in_use=4 waiters=0 memory_bytes=15462400
soak health: elapsed=5.00219s ops=4873 errors=0 size=4 idle=0 in_use=4 waiters=0 memory_bytes=16437248
soak health: elapsed=10.0021929s ops=9043 errors=0 size=4 idle=0 in_use=4 waiters=0 memory_bytes=16551936
soak finished: 9051 operations, 2261 rows remaining

On the local SQLite file backend the test observed zero errors and stable memory (≈ 15.5 MiB → 16.5 MiB). Pool saturation stayed within the configured max_connections = 4 with no waiters.

On the same hardware against a local PostgreSQL instance:

soak health: elapsed=10.0003162s ops=113077 errors=0 size=4 idle=0 in_use=4 waiters=0 memory_bytes=15929344
soak finished: 113078 operations, 28266 rows remaining

Again zero errors and stable memory.

Smoke run (10 s, 8 workers) — after key-cycle fix

crates/runtime/tests/soak.rs was fixed so each key goes through a full INSERT → UPDATE → SELECT → DELETE cycle. This keeps the table size bounded and makes the UPDATE/SELECT/DELETE operations meaningful.

soak health: elapsed=145.2µs ops=0 errors=0 size=4 idle=0 in_use=4 waiters=0 memory_bytes=10383360
soak health: elapsed=5.0034805s ops=3648 errors=0 size=4 idle=0 in_use=4 waiters=0 memory_bytes=10952704
soak health: elapsed=10.0111943s ops=6943 errors=0 size=4 idle=0 in_use=4 waiters=0 memory_bytes=10952704
soak health: elapsed=10s ops=6951 errors=0 size=4 idle=3 in_use=1 waiters=0 memory_bytes=10977280
soak finished: 6951 operations, 6 rows remaining

Native rusqlite smoke run (60 s, 8 workers) — after backend fixes

After the rusqlite backend fixes (WAL mode, 60-second busy timeout, Condvar-based connection checkout, tokio::task::spawn_blocking, and a corrected soak.rs that uses fetch_all for SELECT), the native rusqlite backend passes a 60-second soak with zero errors:

$env:RUPRIZZLE_TEST_RUSQLITE=1
$env:RUPRIZZLE_SOAK_DURATION_SECONDS=60
$env:RUPRIZZLE_SOAK_WORKERS=8
cargo test -p ruprizzle --test soak --features 'sqlite-rusqlite,ruprizzle-testkit/sqlite-rusqlite' --release -- sqlite --nocapture
soak health: elapsed=60s ops=2584520 errors=0 size=0 idle=0 in_use=0 waiters=0 memory_bytes=12189696
soak finished: 2584520 operations, 6 rows remaining

size/idle/in_use are reported as 0 because RusqlitePool does not yet expose pool saturation to the Pool metrics facade; the important signal is the zero error count and stable memory.

48-hour run — root cause fixed, 1-hour validation in progress

A 48-hour SQLite rusqlite soak was started on 2026-08-17 19:09 UTC with the following configuration:

RUST_LOG=info
RUST_BACKTRACE=1
RUPRIZZLE_SOAK_DURATION_SECONDS=172800
RUPRIZZLE_SOAK_WORKERS=8
cargo test -p ruprizzle --test soak --features sqlite-rusqlite --release -- sqlite --nocapture

The process was stopped at 2026-08-17 19:56 UTC after approximately 47 minutes because the error count was climbing monotonically:

soak health: elapsed=2790.0010417s ops=384624 errors=304 size=4 idle=0 in_use=4 waiters=0 memory_bytes=3031040
soak health: elapsed=2835.0050862s ops=385688 errors=316 size=4 idle=0 in_use=4 waiters=0 memory_bytes=3031040

The root causes have since been fixed:

  1. crates/runtime/src/rusqlite.rs now opens connections with PRAGMA journal_mode = WAL, a 60-second busy_timeout, and an explicit foreign_keys = ON setting.
  2. RusqlitePool now uses a Condvar-based checkout model: execute, fetch_all, and begin_transaction wait for an available connection instead of returning PoolExhausted.
  3. All synchronous rusqlite work is dispatched through tokio::task::spawn_blocking, so the async runtime is not pinned by blocking pool waits.
  4. crates/runtime/tests/soak.rs uses fetch_all_raw for the SELECT op and passes the correct number of parameters for DELETE.

After these fixes, 60-second and 1-hour rusqlite runs pass with zero errors. The W4-02 48-hour gate has been waived; the resumable segmented run reached 15.56 h / 1.46 B ops / 0 errors and is recorded in the "48-hour gate — waived" section below.

1-hour rusqlite validation run

A 1-hour extended run was started with the native rusqlite backend to confirm that the 60-second smoke fix scales:

$env:RUPRIZZLE_TEST_RUSQLITE=1
$env:RUPRIZZLE_SOAK_DURATION_SECONDS=3600
$env:RUPRIZZLE_SOAK_WORKERS=8
cargo test -p ruprizzle --test soak --features 'sqlite-rusqlite,ruprizzle-testkit/sqlite-rusqlite' --release -- sqlite --nocapture

Final result:

soak health: elapsed=3600s ops=84242039 errors=0 size=0 idle=0 in_use=0 waiters=0 memory_bytes=13008896
soak finished: 84242039 operations, 7 rows remaining
test soak_mixed_load_with_connection_churn::sqlite ... ok

The run completed with zero database is locked errors and a stable working-set memory footprint, so the 60-second fix has been promoted to a 1-hour validation.

The 48-hour W4-02 gate was started on 2026-08-18 14:50 UTC and was later stopped and replanned as a resumable segmented soak:

$env:RUPRIZZLE_TEST_RUSQLITE=1
$env:RUST_BACKTRACE=1
$env:RUPRIZZLE_SOAK_DURATION_SECONDS=172800
$env:RUPRIZZLE_SOAK_WORKERS=8
cargo test -p ruprizzle --test soak --features "sqlite-rusqlite,ruprizzle-testkit/sqlite-rusqlite" --release -- sqlite --nocapture

The resumable harness stores state in local/soak-48h/soak-rusqlite.db, writes logs to local/soak-48h/soak.log and local/soak-48h/soak.err, and has been waived after 15.56 h / 1.46 B ops / 0 errors.

48-hour run instructions

Note: The W4-02 48-hour gate is waived on the evidence already recorded in the "48-hour gate — waived" section below. These instructions remain available for optional future soak validation.

The W4 exit gate originally called for a 48-hour sustained run on the native rusqlite backend. The feature must be enabled on ruprizzle-testkit as well, or the test harness will silently fall back to the sqlx SQLite path.

On PowerShell:

$env:RUST_LOG="info"
$env:RUST_BACKTRACE=1
$env:RUPRIZZLE_TEST_RUSQLITE=1
$env:RUPRIZZLE_SOAK_DURATION_SECONDS=172800
$env:RUPRIZZLE_SOAK_WORKERS=32
cargo test -p ruprizzle --test soak --features 'sqlite-rusqlite,ruprizzle-testkit/sqlite-rusqlite' --release -- sqlite --nocapture

On Unix:

RUST_LOG=info \
RUST_BACKTRACE=1 \
RUPRIZZLE_TEST_RUSQLITE=1 \
RUPRIZZLE_SOAK_DURATION_SECONDS=172800 \
RUPRIZZLE_SOAK_WORKERS=32 \
cargo test -p ruprizzle --test soak --features 'sqlite-rusqlite,ruprizzle-testkit/sqlite-rusqlite' --release -- sqlite --nocapture

For the PostgreSQL variant:

export RUPRIZZLE_TEST_PG_URL=postgres://...
RUPRIZZLE_SOAK_DURATION_SECONDS=172800 \
RUPRIZZLE_SOAK_WORKERS=32 \
cargo test -p ruprizzle --test soak --release -- postgres --nocapture

Redirect stderr to a log and post-process with:

grep 'soak health' soak.log

Watch for:

  • errors > 0 (other than the expected tail at shutdown).
  • waiters sustained > 0 (pool exhaustion).
  • memory_bytes growing without bound.

Connection churn and failover

This smoke run exercises connection churn through repeated begin/commit cycles. Any future optional 48-hour run should also include a forced database restart or Pool::close()/connect_with() cycle mid-run to verify that the pool recovers and that in-flight work receives a clean AcquireTimeout or ConnectionFailure rather than a panic.

48-hour run — terminated at ~11 hours

The 48-hour rusqlite run started on 2026-08-18 14:50 UTC stopped before completion. The last health line in logs/soak-48h-rusqlite.err was:

soak health: elapsed=40215.0007672s ops=889382385 errors=2 size=0 idle=0 in_use=0 waiters=0 memory_bytes=6320128

That is approximately 11 h 10 m and 889 M operations. The test process (soak-9c6b6ecac4cbf8a3.exe, PID 31040) was no longer running at 2026-08-19 ~02:00 UTC, and the log does not contain a soak finished or test-result line, so the run did not complete cleanly.

Approximately two hours into the run (elapsed=8520s), the harness recorded two soak op error: disk I/O error events and a thread panic while printing to stderr:

soak op error: disk I/O error
thread 'soak_mixed_load_with_connection_churn::sqlite' (36088) panicked at /rustc/59807616e1fa2540724bfbac14d7976d7e4a3860/library\std\src\io\stdio.rs:1165:9:
failed printing to stderr: Insufficient system resources exist to complete the requested service. (os error 1450)
soak op error: disk I/O error

The error count remained at 2 for the remaining ~9 hours of the run, but the premature termination and the I/O / system-resource events mean this is not a passing 48-hour gate. The root cause was investigated, the resumable harness was fixed, and W4-02 has been waived on 15.56 h / 0-errors evidence.

Resumable segmented soak — W4-02 replan

Because the test machine cannot stay on for 48 continuous hours, the gate was replanned as a resumable segmented soak:

  • A new test file, crates/runtime/tests/soak_resumable.rs, stores cumulative progress in a soak_state table inside the same SQLite database it stresses.
  • Each segment uses the persistent database in local/soak-48h/ (workspace folder, not C: or a temp directory). The database and logs are in local/soak-48h/ which is gitignored.
  • crates/testkit/src/lib.rs now honours RUPRIZZLE_SOAK_DB_PATH for SQLite, allowing TestDb to use a persistent file instead of a tempfile temp directory.
  • Health and error lines are written to local/soak-48h/soak.log and local/soak-48h/soak.err; eprintln! was replaced with a non-panicking write to avoid the failed printing to stderr: ... (os error 1450) crash that killed the original 48-hour worker.
  • The runner local/run-soak-segment.ps1 runs one segment, auto-detecting whether to resume from an existing database.

60-second verification

$env:RUPRIZZLE_SOAK_DURATION_SECONDS=60
.\local\run-soak-segment.ps1

Result:

soak health: elapsed=60.0021532s ops=2380046 errors=0 size=0 idle=0 in_use=0 waiters=0 memory_bytes=13283328
soak segment finished: cumulative_elapsed=60.033s ops=2380049 errors=0 rows=6; rerun with RUPRIZZLE_SOAK_RESUME=1

Zero errors, stable memory, and the cumulative state was persisted to the SQLite database, so the next run-soak-segment.ps1 invocation will resume and add the next segment until 48 * 3600 seconds of cumulative elapsed time is reached.

Segmented 48-hour run instructions

Note: The W4-02 gate is waived; these scripts remain available only for optional future soak validation.

# First (or next) segment — 6 hours by default.
.\local\run-soak-segment.ps1

# Custom segment length, e.g. 1 hour.
$env:RUPRIZZLE_SOAK_DURATION_SECONDS=3600
.\local\run-soak-segment.ps1

# Repeat until the test prints `soak finished` instead of `soak segment finished`,
# or stop once the W4-02 evidence is accepted (currently waived).

Watch local/soak-48h/soak.log for errors > 0, waiters sustained > 0, or unbounded memory_bytes growth.


48-hour gate — waived

Date: 2026-08-21

The maintainer has decided that the cumulative evidence from the resumable segmented rusqlite soak is sufficient and that the remaining 32.4 % of the 48-hour W4-02 gate will not be pursued. The gate is waived, not failed.

Final accepted evidence

MetricValue
Cumulative elapsed56,028.6 s (15.56 h) of 172,800 s (48 h) — 32.4 %
Total operations1,464,277,925
Total errors0
soak_kv rows at last save5
soak.err size0 bytes
Last state save2026-08-20 23:26:31 (state file last write)
Peak RSS~19.0 MiB; plateaued at ~18.2 MiB

The earlier continuous 48-hour run that stopped at ~11 h with two disk I/O error events and an os error 1450 stderr panic has not re-occurred in the resumable harness. The fixes that produced this clean run are WAL mode, a 60-second busy timeout, Condvar-based connection checkout, tokio::task::spawn_blocking, and non-panicking log writes. Pool saturation (waiters=4 in ~10 % of health samples) was observed but produced no errors.

local/soak-48h/soak-rusqlite.db retains the final state. The local/run-soak-segment.ps1 and local/run-soak-48h.ps1 scripts remain available for optional future soak validation, but the W4-02 release gate is closed.

What's new in v1.1 – v1.5

This page covers the feature line developed on dev-v2-x after 1.0.0.

Release status. All of it shipped as 1.5.1, published to crates.io on 2026-09-13. The v1.5.0 tag records a publish run that failed before uploading and was deliberately not moved; the line ships under the new patch number instead. The workspace never moved off 1.0.0 while these five milestones landed, so the intermediate numbers were never cut and one release carries the whole line.

This line was assessed and initially blocked; the findings and what each of them became are in ProjectPlan/v2/ProductionReadinessV1_5.md.

Upgrading from 1.0.0-rc.1? Most applications need no code changes: queries, the generated client and existing migrations keep working. A few lower-level types did change shape (new enum variants, new struct fields, #[non_exhaustive] diagnostics). Upgrading from 1.0.0-rc.1 lists each one with its fix.


Postgres array filters

Array columns get a dedicated filter set, compiled to native Postgres array operators rather than to a subquery:

MethodMeaning
has(value)the array contains this one element
has_every(values)the array contains all of these
has_some(values)the array contains any of these
contains(values)the array is a superset of these
contained_by(values)the array is a subset of these
overlaps(values)the arrays intersect
is_empty() / is_not_empty()length is / is not zero
#![allow(unused)]
fn main() {
let rust_posts = Post::find_many()
    .filter(Post::tags.has("rust"))
    .fetch_all(&pool)
    .await?;

let both = Post::find_many()
    .filter(Post::tags.has_every(["rust", "orm"]))
    .fetch_all(&pool)
    .await?;
}

As always, .to_sql() shows you exactly what will be sent.

Full-text search

matches() on a text column compiles to each backend's native full-text construct:

DialectCompiles to
Postgresto_tsvector('english', col) @@ plainto_tsquery('english', $1)
MySQLMATCH(col) AGAINST (?)
SQLitecol MATCH ?, with a LIKE fallback when no FTS table is in play
#![allow(unused)]
fn main() {
let hits = Post::find_many()
    .filter(Post::body.matches("database migrations"))
    .fetch_all(&pool)
    .await?;
}

Soft deletes

Mark a nullable DateTime field with @deletedAt and the model becomes soft-deletable:

model Post {
  id        Uuid      @id @default(uuid7())
  title     String
  deletedAt DateTime? @deletedAt @map("deleted_at")

  @@map("posts")
}

@deletedAt requires a DateTime? field; the parser rejects anything else with a diagnostic. Once it is present, every generated query filters WHERE deleted_at IS NULL by default, and two builder methods opt out:

#![allow(unused)]
fn main() {
Post::find_many().fetch_all(&pool).await?;                  // live rows only
Post::find_many().with_deleted().fetch_all(&pool).await?;   // live + deleted
Post::find_many().only_deleted().fetch_all(&pool).await?;   // the recycle bin
}

Until 1.5.2 this did not hold for includes with .take(n), relation filters, joins, tree queries or m2m reloads. See the query guide for how each of them applies it now.


v1.2 — Developer tooling and zero-database CI

ruprizzle check — offline query validation

ruprizzle-check validates SQL against your schema without a live database, so it runs in CI with no service container. It reports:

  • UnknownTable — with a did-you-mean suggestion when the name is close
  • UnknownColumn — scoped to the table it was expected on, also with a suggestion
  • TypeMismatch — a bind parameter whose type cannot match the column

Each carries a source location, so failures point at the line that wrote the query rather than at the SQL string.

LSP 2.0

ruprizzle-lsp gains broader completion and hover across schema attributes. The VS Code extension lives in editor/vscode.

⚠️ The LSP currently offers a @@tenant completion and hover text for it, but the attribute is not implemented — the parser rejects it. Row-level security and multi-tenancy are not available. Ignore that suggestion.

Declarative seeding

ruprizzle seed applies a JSON document in a single transaction. The top-level object maps model or table names to arrays of rows; every row must carry the model's primary key, and existing rows are updated on primary-key conflict, so re-running a seed is safe and idempotent.

{
  "User": [
    { "id": "0192...", "email": "ada@example.com", "name": "Ada" }
  ],
  "Post": [
    { "id": "0192...", "title": "Hello", "authorId": "0192..." }
  ]
}

v1.3 — Relations, trees and nested writes

Implicit many-to-many

Join tables for many-to-many relations are inferred from the schema instead of being declared by hand, matching Prisma's implicit-m2m behaviour. The link operations are modelled by M2mAction / M2mWrite.

Nested relational writes

Related records can be created and linked inside a single mutation, via NestedCreate, NestedConnectOrCreate and the RelNestedOp set — create, connect, connectOrCreate, set and disconnect. NestedCreate::set_if takes an Option, so optional fields do not need a branch at the call site.

Tree hierarchies

Self-referencing models get recursive-CTE traversal through HierarchyQuery:

#![allow(unused)]
fn main() {
// Flat list of the subtree, at most 5 levels down.
let subtree = db.category().descendants(root_id).max_depth(5).all().await?;

// In-memory tree rooted at `root_id`.
let tree = db.category().tree_from_root(root_id).await?;
tree.count();               // nodes in the tree
tree.max_subtree_depth();   // deepest level reached
tree.flatten();             // depth-first Vec<&Category>
}

ancestors() walks the other direction, and HierarchyQuery::to_sql() prints the CTE like every other builder.


v1.4 — Observability, caching and scaled routing

OpenTelemetry and Metrics 2.0

Spans follow the OpenTelemetry database-client semantic conventions, so traces land in the right place in any OTel-aware backend without per-field mapping. Prometheus metrics remain behind the existing metrics Cargo feature.

Primary / read-replica routing

RoutedPool sends SELECT traffic to replicas and keeps writes and transactions on the primary:

#![allow(unused)]
fn main() {
let pool = RoutedPool::builder(primary)
    .add_replica(replica_a)
    .add_replica(replica_b)
    .load_balancing(LoadBalancing::LeastConnections)
    .build();
}

Three strategies are available — RoundRobin, LeastConnections and Random. Unhealthy replicas are skipped, and when no replica is healthy the router falls back to the primary rather than failing, unless fallback_to_primary(false) is set. Health is only updated when you call check_health(), or, since 1.6, in the background with pool.spawn_health_checks(Duration::from_secs(10)) (keep the returned handle alive).

Before 1.5.2, fallback_to_primary(false) was ignored, LeastConnections always chose the first replica (nothing counted in-flight reads), Random was a fixed stride, and a raw INSERT … RETURNING or SELECT … FOR UPDATE run through the router went to a replica. All four are fixed in 1.5.2. begin() always opens the transaction on the primary, so read-your-writes inside a transaction is never at risk.

Query result cache

A QueryCache trait with an InMemoryCache implementation:

#![allow(unused)]
fn main() {
let cache = InMemoryCache::new(10_000);

cache.set("users:active", bytes, Some(Duration::from_secs(60)), &["users"]);
let hit = cache.get("users:active");

cache.invalidate_tag("users");   // drop everything tagged `users`
cache.prune_expired();           // reclaim expired entries
}

Entries carry a TTL and a set of tags; invalidate_tag / invalidate_tags drop every entry sharing a tag, which is the practical way to expire a table's worth of cached reads after a write. The trait exists so a Redis or other shared backend can be dropped in without touching call sites.

The cache is manual. Query execution never reads or writes it: you call get before a query and set after it, and ruprizzle_cache_hits_total / ruprizzle_cache_misses_total are not emitted. SelectQuery::cache, cache_key and cache_tag exist in the 1.5 API but do nothing, and are deprecated since 1.5.2. So are SelectQuery::use_primary and use_replica. To choose a pool, build the query on RoutedPool::primary(), on the RoutedPool itself, or on select_replica().

PostGIS geospatial types

Point, LineString, Polygon and MultiPolygon, each with to_wkt() (and to_ewkt() on Point), plus spatial filters and orderings on geometry columns:

#![allow(unused)]
fn main() {
let nearby = Store::find_many()
    .filter(Store::location.within_radius(&here, 5_000.0))   // metres
    .order_by(Store::location.distance_asc(&here))
    .fetch_all(&pool)
    .await?;
}

Also available: intersects, within_polygon, contains, contains_point and distance_desc.


v1.5 — Ruprizzle Studio

ruprizzle studio (behind the non-default studio Cargo feature) starts an embedded Axum + HTMX workbench on 127.0.0.1:5555 with no Node or npm dependency.

ruprizzle studio --allow-writes
ScreenWhat it does
Dashboard and ERDRender the parsed schema: models, fields and the relation graph
Table browserSELECTs the model's columns, ordered by primary key, 50 rows a page; the filter box compiles to a parameterised LIKE across the scalar columns
Cell editorUPDATE … WHERE pk = ?, then re-reads the stored value — what you see afterwards is what the database kept, not what you typed
Row insert / deleteParameterised INSERT and DELETE. A delete that matched nothing returns 404, not 200
Relation drawerSELECTs the record the foreign key points at; a dangling key says so
SQL sandboxRuns your statement and shows the real columns, rows and affected count, or the database's own error message
EXPLAIN viewerThe plan the database returns for your statement. EXPLAIN only, never ANALYZE, so the statement is not executed. Costs and row estimates appear only where the plan carries them
Migration safety diffReads the live catalog and classifies each difference against the data: a dropped column counts its non-NULL rows and is DESTRUCTIVE when data would be lost; a NOT NULL addition to a populated table is CAUTION with the row count that will fail the migration

When Studio cannot reach the database, every screen says so and renders nothing else. That matters most on the diff: it shows a failure banner rather than a green badge, so an unreachable database can never be mistaken for a safe migration.

Two limits worth knowing:

  • Studio authentication (since 1.6). Every request needs the per-run session token: open the URL Studio prints (/studio?token=…), or send x-studio-token / Authorization: Bearer; --token or RUPRIZZLE_STUDIO_TOKEN fixes it. Before 1.6 Studio had no authentication. It binds 127.0.0.1 by default. --allow-writes on a non-loopback host is refused unless you pass --yes-i-know, because that combination publishes INSERT, UPDATE and DELETE to anyone who can reach the port.
  • The production check is a name check. It matches prod, aws.neon.tech and turso.io in the URL. It will not catch an RDS endpoint or a bare IP. Treat it as a speed bump.

ruprizzle-turso and ruprizzle-d1 — adapters over their providers’ HTTP APIs

Both are real drivers, published, and tested end to end against a local HTTP server so neither the tests nor a contributor need an account.

CrateProtocolEndpoint
ruprizzle-tursoHrana 2 over HTTPPOST {url}/v2/pipeline
ruprizzle-d1Cloudflare REST APIPOST /accounts/{account}/d1/database/{database}/query
#![allow(unused)]
fn main() {
let pool = TursoPool::builder()
    .url("libsql://your-db.turso.io")
    .auth_token(std::env::var("TURSO_AUTH_TOKEN")?)
    .build()?;
}

Both speak the SQLite dialect, bind parameters positionally with ?, and store booleans as 1 and 0. Credentials are sent as bearer tokens and are redacted from Debug output.

What they do not do, in both cases for the same reason — one HTTP request per statement, with no server-side session:

  • No interactive transactions. BEGIN and COMMIT sent separately would not share a connection. Batch the work into one statement, or use a SQLite file through ruprizzle::connect.
  • No streaming transport. stream_raw is a streaming interface; the whole result set arrives in one response.

Turso also has no embedded-replica support — that needs the native libSQL library — and D1 takes no binary parameter over HTTP, so a Bytes value is refused rather than mangled. Inside a Cloudflare Worker you have a D1 binding, which is faster and needs no token; ruprizzle-d1 is for talking to D1 from outside one.

There is no Neon adapter

ruprizzle-neon has been deleted. Neon speaks ordinary Postgres over TLS, so its connection string goes straight to ruprizzle::connect and an adapter crate would have been a wrapper around nothing. The stub was carrying a promise the provider never needed.

The genuinely useful piece of this milestone is underneath: the runtime Executor trait is now decoupled from sqlx, so a third-party backend can implement it directly.

What's new in 1.6

1.6.0 (2026-10-03) is additive over 1.5.1, with one behaviour change in Ruprizzle Studio. It also includes every fix from 1.5.2, which was prepared but never published. The full list is in the changelog.

[dependencies]
ruprizzle = "1.6"
cargo install ruprizzle-cli --features studio   # --features studio only if you want Studio

Studio requires its session token

Every Studio request, reads included, now needs the per-run session token.

ruprizzle studio
# ⚡ Ruprizzle Studio running at: http://127.0.0.1:5555/studio?token=3f9c…
  • Browser: open the printed URL. Studio stores the token in an HttpOnly, SameSite=Strict cookie and redirects to /studio; later visits in that browser work without the query string until Studio restarts.
  • Scripts: send the token as x-studio-token: <token> or Authorization: Bearer <token>.
  • A fixed token: ruprizzle studio --token <value> or set RUPRIZZLE_STUDIO_TOKEN. Otherwise a new random token is generated each run.
  • Writes (--allow-writes) additionally need a same-origin Origin header and the token in the x-studio-token header, which the Studio page sends for you; the cookie alone cannot perform a write.

What changes for you: a bookmark to a bare /studio URL now returns 401. Open the printed URL instead. The token travels over plain HTTP and there are no user accounts, so keep Studio on loopback.

with_deleted() on tree queries

Hierarchy queries skip soft-deleted nodes and everything reached only through them. with_deleted() includes them:

#![allow(unused)]
fn main() {
let everything = db
    .category()
    .descendants(root_id)
    .with_deleted()
    .all()
    .await?;
}

It has no effect on models without a @deletedAt column.

Background replica health checks

Replica health used to change only when you called check_health(). You can now run it on a timer:

#![allow(unused)]
fn main() {
use std::time::Duration;

let routed = /* RoutedPool::builder(...)...build() */;
let health = routed.spawn_health_checks(Duration::from_secs(10));
// ... health checks run every 10 s while `health` is alive ...
drop(health); // or health.stop()
}

It must be called inside a Tokio runtime. Keep the handle alive: dropping it stops the checks.

@renamedFrom onto an existing column name

When a @renamedFrom target name is still used by an existing column, the migration now drops that column before the rename, instead of producing a RENAME that fails at apply time. The drop needs --accept-data-loss. See Migrations.

Under the hood

  • Studio's templates use askama 0.14 (newer releases need Rust 1.88; the MSRV stays 1.85).
  • CI runs the integration and Studio suites on MariaDB 11.4 as well as MySQL 8.4, and Studio's MySQL read-only path has its own test.
  • ruprizzle-turso and ruprizzle-d1 have opt-in live smoke tests (cargo test -p ruprizzle-turso --test live), which run when the provider credentials are set. They have not yet been run against the hosted services.

Upgrading from 1.0.0-rc.1 to 1.5.1

1.0.0-rc.1 is the only ruprizzle version published before 1.5.1, so every existing user upgrades along this path. It is a large jump: the whole v1.1–v1.5 feature line lands at once (see What's new in v1.1–v1.5).

Most applications need no code changes. If your code uses the generated client and the query builders, bump the versions, build, and you are done. The breaking changes below affect code that goes underneath the generated client: matching on diagnostic or IR enums, building IR or query-manifest structs by hand, or calling the internal modules that generated code uses.

Why this happened: rc.1 was a release candidate, and Stability allows breaking changes before the first stable release. cargo-semver-checks counts these as major. They are accepted once, for this upgrade only, and each one is listed here with the compiler error you will see and the fix. From 1.5.1 on, normal semver applies.


Contents

  1. Before you upgrade: pin exactly
  2. Upgrade in five steps
  3. Am I affected?
  4. What stays compatible (verified)
  5. Breaking changes and how to fix them
  6. Compiler error lookup
  7. Rolling back

1. Before you upgrade: pin exactly

To Cargo, the requirement ruprizzle = "1.0.0-rc.1" means >=1.0.0-rc.1, <2.0.0. That range includes 1.5.1, so a routine cargo update would upgrade you without asking. If you are not ready, pin the exact version now:

[dependencies]
ruprizzle         = "=1.0.0-rc.1"
ruprizzle-migrate = "=1.0.0-rc.1"   # only if you depend on it

Remove the = when you decide to upgrade.

2. Upgrade in five steps

Step 1 — bump every ruprizzle crate together. All workspace crates and the CLI share one version (Versioning). Mixing 1.0.0-rc.1 and 1.5.1 crates in one build is not supported.

[dependencies]
ruprizzle         = "1.5.1"
ruprizzle-migrate = "1.5.1"   # only if you depend on it
cargo install ruprizzle-cli --version 1.5.1 --locked
ruprizzle --version            # should print 1.5.1
cargo update -p ruprizzle

Step 2 — build. cargo build --all-targets. If it compiles, skip to step 4. If not, look up the error in section 6.

Step 3 — fix what the compiler reports using section 5. Every fix is mechanical, and none changes runtime behaviour.

Step 4 — regenerate the client. ruprizzle generate. This is recommended but not required, because a client generated by rc.1 still compiles against 1.5.1 (section 4). Regenerating gives you the codegen fixes and the generated API for new schema features such as @deletedAt and PostGIS types. Commit the regenerated files on their own so the diff is easy to review.

Step 5 — check migrations before deploying.

ruprizzle migrate status
ruprizzle migrate dev --name upgrade_check   # against a development database

Your existing migrations/.ruprizzle/snapshot.ruprizzle loads unchanged. If you have not edited your schema, expect no new migration. If migrate dev proposes one anyway, read the generated SQL before applying it, and report it as a bug.

3. Am I affected?

Your code…Affected?Go to
Uses the generated Db client, repos and query buildersNo—
Has migrations created with rc.1No (loads unchanged)4
Has ruprizzle check query-manifest JSON filesNo (loads unchanged)4
matches on SchemaError, DialectError or QueryCheckErrorMaybe5.1
matches on ScalarType, RustType, FilterNode or ArrayFilterOpYes, if exhaustive5.2
Casts ArrayFilterOp to an integer (op as u8)Yes5.3
Builds FieldAttrs, IndexDef, QueryEntry, QueryManifest or QueryCheckError::UnknownTable by handYes5.4
Imports from ruprizzle::compile, ::decode, ::counting or ::nestedStill compiles5.5

4. What stays compatible (verified)

These were tested for 1.5.1, not assumed:

  • Generated clients. The rc.1 code generator's committed output for five schemas (blog, ecommerce, m2m, saas-tenant, minimal) builds unchanged against the 1.5.1 runtime.
  • Migration snapshots. rc.1 snapshots have no is_created_at / is_deleted_at keys, and 1.5.1 loads them as false. The regression test is snapshot_from_1_0_0_rc_1_without_new_field_attrs_still_loads in crates/core/tests/ir_roundtrip.rs. (An unpublished 1.5.0 source build failed here with missing field `is_created_at` . If you ever built 1.5.0 from git, move to 1.5.1.)
  • Query manifests. Every field added to QueryManifest and QueryEntry has a serde default (version defaults to 1), so rc.1 manifest JSON parses unchanged.
  • Hidden internals. No function or struct in compile, decode or counting changed its signature. Items were only added.

5. Breaking changes and how to fix them

5.1 Diagnostic errors are #[non_exhaustive]

Affects: ruprizzle_core::SchemaError, ruprizzle_dialect::DialectError, ruprizzle_check::QueryCheckError.

Why: new validation rules and dialects add variants. With #[non_exhaustive], future additions will not break your build again.

Error: error[E0004]: non-exhaustive patterns: _ not covered

#![allow(unused)]
fn main() {
// before (rc.1)
match err {
    SchemaError::Syntax { .. } => report_syntax(&err),
    SchemaError::UnknownType { .. } => report_type(&err),
    // ...every other variant listed
}

// after (1.5.1)
match err {
    SchemaError::Syntax { .. } => report_syntax(&err),
    SchemaError::UnknownType { .. } => report_type(&err),
    _ => report_generic(&err), // required; also catches variants added later
}
}

These types implement miette::Diagnostic / std::error::Error. If you only display them, use {err} or the diagnostic renderer and skip the match.

5.2 New enum variants

EnumCrateNew variantsFeature
ScalarTyperuprizzle-corePoint, Polygon, MultiPolygon, LineStringPostGIS
RustTyperuprizzle-dialectPoint, Polygon, MultiPolygon, LineStringPostGIS
FilterNoderuprizzleFullTextMatch { .. }, Spatial { .. }full-text search, PostGIS
ArrayFilterOpruprizzleHas, IsEmpty, IsNotEmptyarray filters

Error: error[E0004]: non-exhaustive patterns: ScalarType::Point, … not covered

Fix: handle the new variants. The compiler lists every missing one.

#![allow(unused)]
fn main() {
// after (1.5.1)
let sql_kind = match scalar {
    ScalarType::String => "text",
    // ...existing arms unchanged...
    ScalarType::Point
    | ScalarType::Polygon
    | ScalarType::MultiPolygon
    | ScalarType::LineString => "geometry",
};
}

These four enums are still exhaustive in 1.5.1. Listing the variants keeps the compiler checking your code. A _ => arm also compiles, but then you get no warning when a variant you should handle is added.

5.3 ArrayFilterOp discriminants changed

Has was added as the first variant, so Contains, ContainedBy and Overlaps moved from 0, 1, 2 to 1, 2, 3. ArrayFilterOp has no #[repr], so its numeric value was never a stable contract.

Affects you only if you wrote op as u8 (or any integer cast), stored or sent that number, or compared it with a constant. Nothing fails to compile. The number is just wrong.

Fix: match on the variant instead of using its number:

#![allow(unused)]
fn main() {
fn op_code(op: ArrayFilterOp) -> &'static str {
    match op {
        ArrayFilterOp::Has => "has",
        ArrayFilterOp::Contains => "contains",
        ArrayFilterOp::ContainedBy => "contained_by",
        ArrayFilterOp::Overlaps => "overlaps",
        ArrayFilterOp::IsEmpty => "is_empty",
        ArrayFilterOp::IsNotEmpty => "is_not_empty",
    }
}
}

If you stored integers produced by rc.1, map 0 → Contains, 1 → ContainedBy, 2 → Overlaps when you read them back.

5.4 New struct fields

Error: error[E0063]: missing fields …in initializer of…`` (or error[E0027]: pattern does not mention fields … when destructuring).

StructNew fieldsFix
ruprizzle_core::ir::FieldAttrsis_created_at: bool, is_deleted_at: boolend the literal with ..Default::default()
ruprizzle_core::ir::IndexDefindex_type: Option<IndexType>add index_type: None (same behaviour as rc.1)
ruprizzle_check::QueryManifestversion: u32add version: 1
ruprizzle_check::QueryEntryid, params, result_columns, locationadd id: None, params: Vec::new(), result_columns: Vec::new(), location: None
QueryCheckError::UnknownTablesuggestion, locationwhen building: suggestion: None, location: None; when matching: add ..
#![allow(unused)]
fn main() {
// FieldAttrs: `..Default::default()` protects you from future fields as well
let attrs = FieldAttrs { is_id: true, ..Default::default() };

// IndexDef
let index = IndexDef {
    db_name, targets, where_clause, span,
    index_type: None,
};

// QueryManifest / QueryEntry: or skip the literals and deserialize JSON,
// which fills in every default for you
let manifest: QueryManifest = serde_json::from_str(&json)?;

// matching a struct variant
if let QueryCheckError::UnknownTable { table, .. } = &e { /* ... */ }
}

The added fields default to "feature not used" (false, None, empty), so behaviour stays the same as rc.1.

5.5 Internal modules are hidden from docs

ruprizzle::compile, ruprizzle::decode, ruprizzle::counting and ruprizzle::nested are now #[doc(hidden)]. Your code still compiles. Paths and signatures are unchanged. These modules no longer appear on docs.rs, because they exist for generated code and are not covered by semver (Stability).

Move to the crate-root re-exports, which are covered:

#![allow(unused)]
fn main() {
// before
use ruprizzle::compile::{CompiledSql, select, insert, insert_many, update, delete};
use ruprizzle::counting::CountingExecutor;

// after
use ruprizzle::{CompiledSql, CountingExecutor, delete, insert, insert_many, select, update};
}

dialect_for_pool and the Nested* writers are also re-exported from the root. For anything with no root re-export (the decode::* helpers, compile::count, compile::exists, compile::upsert and similar), use the generated repo and query builder methods. Those items may change in a minor release.

6. Compiler error lookup

You seeSection
E0004 non-exhaustive patterns on SchemaError / DialectError / QueryCheckError5.1
E0004 on ScalarType / RustType / FilterNode / ArrayFilterOp5.2
E0063 missing fields in a struct literal5.4
E0027 pattern does not mention fields suggestion, location5.4
No error, but array-filter codes are wrong at runtime5.3
missing field `is_created_at` from ruprizzle migrateYou are on a 1.5.0 source build. Use 1.5.1 (4)
Two versions of ruprizzle-core in cargo tree -dBump every ruprizzle crate together (step 1)

Anything else that breaks when moving from rc.1 to 1.5.1 is not documented here and is a bug in this guide. Please open an issue with the error message.

7. Rolling back

Go back to "=1.0.0-rc.1" in Cargo.toml, run cargo install ruprizzle-cli --version 1.0.0-rc.1 --locked, and restore your generated client from version control. Migrations applied while on 1.5.1 stay applied. Check whether any of them use a 1.5-only feature (soft-delete columns, PostGIS types, GIN/GiST indexes) before rolling back a database that rc.1 code will read.

Migration guide: pre-1.0 to 1.0.0

This covers every API-shape change between the 0.1.1-beta.1 publish (commit 95ec17b, 2026-08-13) and 1.0.0, tagged 2026-08-21. 1.0.0-rc.1 and 1.0.0 are identical in API shape, so a client that compiles against one compiles against the other.

Note: 1.0.0 was tagged but never published to crates.io — its publish run failed before uploading, as did 1.0.1's and 1.5.0's. The first published stable carrying this API is 1.5.1 (2026-09-13); upgrade straight to it. If you are on 1.0.0-rc.1, also read Upgrading from 1.0.0-rc.1 to 1.5.1 for the handful of RC → stable breaking changes that landed after 1.0.0 was tagged.

Purely additive features (savepoints, array binds, streaming, new query operators, MySQL, db pull, seeding, migration squashing, rename detection, metrics — see the parity table in ProjectPlan/v1/PathToStableV1.md) are not covered here unless they changed an existing signature; see CHANGELOG.md's [1.0.0-rc.1] and [1.5.0] sections for the full feature list.

If you generated a schema client against 0.1.1-beta.1, regenerate it (ruprizzle generate) after upgrading — none of the changes below require editing your .ruprizzle schema itself, but generated code should be refreshed to pick up any codegen-side fixes.

1. Queries with .include(...) no longer support .fetch_one() / .fetch_optional()

Why: SelectQuery::fetch_one() and fetch_optional() used to compile even when the query had .include(...) attached, but they never actually loaded the included relations — every Related<T> field silently came back Related::Absent. Calling .get() on it then panicked with a message that only mentioned .include(), not the terminal method that was the actual bug. (BUG-04 in CHANGELOG.md.)

What changed: a query with .include(...) is now a different builder state. It only exposes .exec_one() / .exec_optional(), which load the requested relations before returning. .fetch_one() / .fetch_optional() remain available, but only on queries with no .include(...) calls.

Before:

#![allow(unused)]
fn main() {
let user = User::query()
    .filter(User::id().eq(1))
    .include(User::posts())
    .fetch_one(&pool)   // compiled, but `user.posts` was always Related::Absent
    .await?;

let posts = user.posts.get(); // panicked: "call .include() first"
}

After:

#![allow(unused)]
fn main() {
let user = User::query()
    .filter(User::id().eq(1))
    .include(User::posts())
    .exec_one(&pool)     // relations are actually loaded
    .await?;

let posts = user.posts.get(); // works
}

If you don't need the included relation on a particular call, drop .include(...) and keep .fetch_one() / .fetch_optional() — no behavior changes for queries that never called .include(...).

2. Related::get()'s panic message now points at the right fix

Not an API-shape change, but worth knowing during migration: if you still hit the panic in Related::get(), its text now says to call .exec() / .exec_one() / .exec_optional() rather than only mentioning .include(). If you see this message after upgrading, it means you're still on a .fetch_*() terminal with .include(...) attached — apply the fix in section 1.

3. Pool exhaustion is now a typed, matchable error variant

Why: pool exhaustion on the native drivers used to surface as a stringly-typed error message, which meant catching it required matching on Display text — fragile across releases and inconsistent with the rest of Error's variants.

What changed: Error::PoolExhausted { backend: &'static str } was added, with a stable kind() == "pool_exhausted".

Before:

#![allow(unused)]
fn main() {
match pool.acquire().await {
    Err(e) if e.to_string().contains("exhausted") => { /* handle it */ }
    Err(e) => return Err(e),
    Ok(conn) => conn,
};
}

After:

#![allow(unused)]
fn main() {
match pool.acquire().await {
    Err(Error::PoolExhausted { backend }) => { /* handle it, backend tells you which driver */ }
    Err(e) => return Err(e),
    Ok(conn) => conn,
};
}

If you match on Error exhaustively (match e { ... } without a wildcard arm), adding this variant requires adding an arm for it — this is the one place the change is a compile-time break rather than a silent behavior difference. If you match with a wildcard (_ => ...) or only match specific variants you care about, no change is required, but you can now catch pool exhaustion specifically where you previously couldn't.

4. InsertManyQuery now validates row shape before building SQL

Why: batched inserts where a later row had different columns (or the same columns in a different order) than row 0 either produced silently wrong SQL or an opaque driver error, depending on the database. (BUG-09.)

What changed: InsertManyQuery::exec and nested with_related child inserts now check every row against row 0's column set and order before running, and return a descriptive Error naming the offending row and column if they don't match — instead of a bad query or a generic driver error.

#![allow(unused)]
fn main() {
// This now fails fast with a clear error identifying which row/column is
// inconsistent, instead of either silently reordering values into the wrong
// columns or bubbling up an opaque driver error:
User::insert_many(vec![
    User::new().name("Alice").email("a@example.com"),
    User::new().email("b@example.com").name("Bob"), // same columns, different order
])
.exec(&pool)
.await?;
}

No code changes are required to adopt this — it only affects call sites that were already relying on (or accidentally triggering) the old inconsistent-row behavior. If your batch inserts always build rows with User::new() and the same builder call order, or all rows come from the same struct/iterator shape, you will not observe any difference.

5. IncludeList distributes children to every matching parent

Why: .include(...) on a one-to-many relation with a shared join key only attached the loaded children to the first parent row that matched, leaving every other parent with the relation empty. (BUG-08.)

What changed: children are now correctly attached to every parent row sharing the join key. This is a bug fix, not an API signature change, but if your code compensated for the old behavior (e.g., deduplicating parents before calling .include(...), or only reading the relation off the first row in a group), that workaround is no longer necessary and may now produce duplicate data if left in place.

6. RusqliteTransaction no longer implements Clone

Why: Clone on a transaction handle let one pooled connection be returned to the pool twice — once per clone dropped — corrupting the pool's accounting. (BUG-06.)

What changed: if your code cloned a RusqliteTransaction (only reachable with the sqlite-rusqlite feature enabled), that call site no longer compiles. There is no supported replacement for cloning a transaction handle — restructure the call site to pass &Transaction (a shared reference) to whatever needed the clone, or to scope the work inside a single transaction borrow instead.

7. New PoolConfig::reset_on_recycle field (additive, but affects exhaustive struct literals)

What changed: PoolConfig gained reset_on_recycle: bool (default false), which selects deadpool's Clean recycling for the native tokio-postgres backend — discarding session state on every checkout, at roughly 2x the per-checkout latency, in exchange for defence-in-depth against any session-state leak beyond the abandoned-transaction rollback fix in section 8.

If you construct PoolConfig with ..Default::default() or a builder method, nothing changes. If you construct it as a full struct literal naming every field, add reset_on_recycle: false (or your preferred value) to keep compiling.

8. Abandoned transactions on native drivers now roll back instead of leaking or corrupting state

Not an API-shape change — no signature changed — but a correctness fix worth knowing if you relied on (or worked around) the old behavior:

  • rusqlite: a transaction dropped without an explicit .commit()/.rollback() (which happens on every early return via ?) used to permanently lose its connection from the pool; enough of these exhausted the pool and required a process restart. It now rolls back and returns the connection on drop, without panicking. A related bug made RusqlitePool::acquire panic with a divide-by-zero once the pool was fully exhausted by leaked connections — this is now the typed Error::PoolExhausted from section 3.
  • tokio-postgres: an abandoned transaction didn't leak a connection, but recycled it back into the pool with BEGIN still open — so the next request to receive that connection silently ran inside the previous request's transaction. Drop now spawns a ROLLBACK before the connection is released.

If your application caught and ignored errors from begin() under sustained load (as a workaround for the old exhaustion panic/leak), you can remove that workaround — pool exhaustion now surfaces as the typed Error::PoolExhausted described in section 3 rather than a panic.

9. New escape hatch: the raw! macro and RawFragment

Purely additive, but worth flagging if you previously worked around missing raw-SQL support by reaching into sqlx directly: ruprizzle_macros::raw! (re-exported from ruprizzle) now provides an injection-safe raw SQL fragment with bound parameters, usable inside the query builder. This does not replace or change any existing method — it is a new capability, not a signature change.

Not covered by this guide

Everything else that changed since 0.1.1-beta.1 is additive (new query operators, savepoints, array binds, streaming, MySQL support, prepared statements, metrics export, migration squashing, rename detection) and does not require call-site changes to code that already compiled against 0.1.1-beta.1. See CHANGELOG.md for the complete list, and ProjectPlan/v1/PathToStableV1.md section 5 for how each feature maps to its workstream.

ruprizzle-orm 1.0.0 (archived announcement)

This announcement was never accurate and is kept only as a record. The v1.0.0 publish run did not upload anything, so 1.0.0 was never on crates.io. The first published stable release is 1.5.1 (2026-09-13) — see What's new in v1.1–v1.5 for what actually shipped. See the FAQ and RELEASES.md for the current state. The rest of this page is left as originally written.

ruprizzle-orm 1.0.0 is out on crates.io. It is a schema-first ORM for Rust: write a Prisma-style schema.ruprizzle, get typed entities, a Drizzle-style query builder that shows you its SQL, and automatic migrations generated by diffing your schema. PostgreSQL, MySQL/MariaDB, and SQLite 3+ are supported. No query engine binary.

This is a stable release. From 1.0.0 onward the public API is covered by semantic versioning: it does not change without a major bump. See Stability for exactly what that covers — including which dependencies are part of our public API — and Known limitations for the deliberate boundaries.

What we claim

  • Automatic migration diffing from a declarative schema — no other Rust ORM has it.
  • include with per-relation filters, in a bounded query count.
  • Column-token typing that rejects cross-model and wrong-type filters at compile time.
  • Identical Rust API across PostgreSQL, MySQL/MariaDB, and SQLite.
  • .to_sql() on every query.
  • Native rusqlite and tokio-postgres backends behind feature flags.
  • Advanced SQL builders: CTEs (recursive and non-recursive), set operations, EXISTS/IN subqueries, conditional filters, nested inserts/updates, explicit JOINs, aggregates, GROUP BY / HAVING, and JSON path operators.
  • Offline / compile-time query checking with ruprizzle check and query manifests.
  • LSP for schema.ruprizzle via ruprizzle-lsp and the VS Code extension in editor/.

What we explicitly do not claim

  • Feature parity with Prisma or Drizzle on every edge-case (vector search, full-text, PostGIS, and implicit many-to-many join tables are deferred to 1.1+).
  • That the 1.0 API will not need a second RC if feedback reveals a real problem.

Every one of those would be checked by someone within a day of the post, and being caught overclaiming would cost more than the attention gained.

Supported in this release

  • Grammar-driven .ruprizzle parser with span-preserving diagnostics.
  • IR lowering, fingerprinting, and round-trip serialisation.
  • PostgreSQL, MySQL/MariaDB, and SQLite 3+ dialects with conformance suites.
  • Rust entity and query-builder code generation.
  • Runtime CRUD, transactions, savepoints, pagination, include loading, prepared statements, buffered and unbuffered streaming, and metrics export.
  • Advanced query builders: conditional/dynamic filters, IN sets, count/exists, aggregates, GROUP BY / HAVING, CTEs, set operations, EXISTS/IN subqueries, nested inserts/updates, explicit JOINs, and JSON path operators.
  • 12 migration change classes with up.sql / down.sql generation, drift detection, squashing, rename detection, and FK-cycle handling.
  • CLI: init, generate, generate --watch, validate, format, migrate dev, migrate deploy, migrate status, migrate resolve, migrate reset, migrate squash, db push, db pull, and db seed.
  • trybuild compile-fail tests that enforce the type-safe query API.
  • cargo xtask helpers for CI, examples, hardening, and release.
  • sqlite-rusqlite and postgres-tokio-postgres feature flags for native driver performance.
  • ruprizzle-lsp language server and VS Code extension.
  • ruprizzle check for offline query validation against a schema snapshot.

Get it

cargo install ruprizzle-cli    # the `ruprizzle` command
cargo add ruprizzle            # the runtime crate your app uses

MSRV is Rust 1.85.

Quickstart

mkdir my-app && cd my-app
ruprizzle init --provider postgres
# Edit schema.ruprizzle, then:
ruprizzle migrate dev --name init
cargo add ruprizzle tokio
cargo run

See the quickstart for the full five-minute walkthrough.

Known limitations

See Known limitations for the full list. Highlights:

  • Heuristic renames are suggested automatically; use @renamedFrom to confirm.
  • db push does not write migration files and is only for prototyping.
  • Decimal and Json on SQLite are stored as text; JSON1 path operators and filters work.
  • Full-text search, PostGIS, soft deletes, polymorphic relations, and implicit many-to-many join tables are deferred to 1.1+.

Feedback

1.0.0-rc.1 was published on 2026-08-21 and 1.0.0 was cut the same day. The two-week RC feedback window the project had committed to was waived, in writing and with its reasoning, in Stability: across seven prereleases there was no known external consumer to provide the feedback the window exists to collect. What ran instead was the full release gate matrix — see ProjectPlan/v1/V1StableRelease.md.

That makes your report the first one. If you find an API problem, open an issue on the GitHub repository. Under semver the fix ships as 1.1.0 if it is additive and 2.0.0 if it is not; neither is a reason to sit on a defect.

One consequence worth knowing before you upgrade: the 1.0 line is pinned to sqlx 0.8, because ruprizzle re-exports sqlx and the two must be the same crate. sqlx 0.9 is a 2.0.0 change. Stability.md's "Public dependencies" section has the details.

Architecture Decision Records

These records capture significant design decisions in ruprizzle-orm. Each ADR explains the decision, the rationale, and the costs.

ADR-001: Build on sqlx rather than a custom driver

Date: 2026-08-13
Status: Accepted

Decision: sqlx provides connection pooling, the wire protocols, TLS, and type encoding. We generate code that calls it.

Why: writing a Postgres wire-protocol implementation is a multi-month project with a large security surface and no differentiation. Every hour spent there is an hour not spent on the schema DSL, diffing, and relation loading — which is where the actual product is.

Cost: we inherit sqlx's release cadence and any breaking changes. Mitigated by an exact version pin in the runtime crate.

ADR-002: Codegen, not proc-macros-over-structs

Date: 2026-08-13
Status: Accepted

Decision: a CLI generates source files that the user commits (or gitignores).

Why: three reasons. Generated code is readable — users can open it, understand it, and debug it, which proc-macro output never is. IDE completion works perfectly with no macro expansion. And compile times are better, because the user's build does not run the parser and codegen on every cargo check.

Cost: an explicit generate step. Mitigated by --watch (P7-03).

Rejected alternative: #[derive(Model)] on hand-written structs, SeaORM-style. That inverts the source of truth — the schema stops being declarative and migrations can no longer be diffed from it, which forfeits the headline feature.

ADR-003: Related<T> instead of Option<T> for relations

Date: 2026-08-13
Status: Accepted

Decision: a three-state-by-construction type distinguishing "not loaded" from "loaded and empty."

Why: Option<Vec<Post>> makes None ambiguous, and the ambiguity produces a silent wrong answer rather than an error. Loud failure with an actionable message beats a quiet bug.

Cost: one unfamiliar type in the public API, and one sanctioned panic.

ADR-004: Batched relation loading, not JOINs

Date: 2026-08-13
Status: Accepted

Decision: one query per relation level.

Why: see the comparison table in ImplPlan06 P5-03. JOINs cause row explosion, make per-relation take and filter hard, and require de-duplication.

Cost: more round trips than a single JOIN for shallow queries. Acceptable — the count is bounded by schema depth, not data size.

ADR-005: Column tokens, not a type-level query DSL

Date: 2026-08-13
Status: Accepted

Decision: Column<M, T> consts with inherent methods, rather than Diesel's type-level relational algebra.

Why: Diesel's approach is more powerful and catches strictly more at compile time, but its error messages are the single most cited reason people bounce off it. Column tokens catch the errors that actually happen in practice — wrong value type, wrong model, wrong operator for the type — with errors a human can read.

Cost: some invalid queries (a malformed GROUP BY, say) fail at the database rather than at compile time.

ADR-006: Explicit join models for many-to-many

Date: 2026-08-13
Status: Accepted

Decision: no implicit join tables in v1.

Why: hidden tables violate the predictable-SQL principle, and Prisma's implicit _AToB tables become a migration dead end the moment you need a column on the join. Sugar can be added later without breaking anyone.

ADR-007: Snapshot = serialized IR

Date: 2026-08-13
Status: Accepted

Decision: the migration snapshot is serde_json of ir::Schema.

Why: one type means the differ compares exactly what the parser produces, with no second schema representation to drift out of sync. It is also human-readable in diffs and easy to inspect during debugging.

Cost: IR changes require a snapshot format version and a migration path. A version field is present from day one for this reason.

ADR-008: Postgres and SQLite together from day one

Date: 2026-08-13
Status: Accepted

Decision: both dialects in v1, not Postgres first and SQLite later.

Why: an abstraction with one implementation is not proven to be an abstraction. Adding SQLite in month two would mean discovering every Postgres assumption baked into codegen and migrations at the worst possible moment. SQLite also makes the test suite fast and dependency-free for contributors.

Cost: roughly three extra days in P2 and P6, mostly the SQLite table-rebuild path. Paid deliberately.

ADR-009: Runtime dialect selection via sqlx::Any

Date: 2026-08-13
Status: Accepted, with costs recorded.

Context

The product promises one identical Rust API across Postgres and SQLite, with the backend chosen by URL scheme at runtime. sqlx::Any is the only sqlx facility that provides this without generating a separate client per dialect.

Decision

Route all runtime queries through sqlx::Any.

Consequences

  • Any implements neither Encode nor Decode for rich types, so Uuid, Decimal, DateTime, Date, Time, and Json are serialised to text outbound (crates/runtime/src/value.rs) and parsed from text inbound (crates/runtime/src/decode.rs), on every row.
  • Comparisons on rich-typed columns rely on server-side parameter inference. If inference resolves to text rather than the column type, the comparison stops using the index — a silent performance cliff, not an error.
  • DateTime correctness depends on server DateStyle and session timezone.
  • Postgres arrays, LISTEN/NOTIFY, COPY, and composite types are unreachable. Array binds are rejected at runtime.
  • The abstraction has leaked repeatedly: three of the last four commits before this plan were fixes in this layer.

Revisit when

Any of: a third dialect is added; benchmarks (PR-12) show the text round-trip exceeding the P8-02 thresholds; or users need Postgres arrays. The exit is generating dialect-specific native code paths behind a feature flag, which is additive but costs the runtime-selection property.

ADR-010 — Postgres arrays and a SQLite JSON fallback

Context

Value::Array exists in the runtime but is rejected at bind time on every backend. Postgres arrays are a headline feature (text[], int4[], uuid[]); SQLite has no native array type. We need a design that is honest about backend capability rather than silently divergent.

Decision

  1. Postgres gets native arrays. When the runtime is talking to Postgres through either sqlx::Postgres or tokio-postgres, Value::Array binds as a Postgres array of the element type. Nested arrays and mixed element types are not supported; the array must be one-dimensional and homogeneous.

  2. SQLite uses an explicit JSON fallback. Value::Array bound to SQLite is encoded as a JSON string and decoded back at read time. The schema side records this as a text[] column that stores JSON. This makes the degradation explicit: users see text[] in the schema, but the data on disk is JSON text.

  3. sqlx::Any + Postgres still errors until supported. sqlx::Any does not expose a typed array argument in the tested version. Instead of the bare "array bind values are not supported yet" message, we return an actionable Error telling the user to use the native Postgres feature (postgres-tokio-postgres or sqlx::Postgres directly) for arrays.

  4. Schema-side String[], Int[], etc. The schema parser already accepts T[] field notation. Scalar lists are allowed for primitive scalar types and enums. They map to Postgres native arrays where possible and to the JSON fallback on SQLite.

  5. Filter operators for Postgres. For one-dimensional Postgres arrays we support contains (@>), contained_by (<@), and overlaps (&&). These are only meaningful on Postgres; on SQLite the JSON fallback cannot be indexed and the operators are not supported.

Consequences

  • Postgres users get first-class arrays. Migration DDL emits text[], int4[], etc.
  • SQLite users can still model T[] columns, but the data is stored as JSON. The same Rust type (Vec<T>) works on both backends.
  • sqlx::Any users that hit Postgres get a clear error rather than a confusing runtime rejection.
  • The query builder gains typed array operators behind Column<M, Vec<T>>.

ADR-011 — Explicit joins alongside batched relations

Date: 2026-08-17
Status: Accepted

Context

ADR-004 chose batched relation loading over JOINs for include. That decision remains correct for relation loading: it avoids row explosion, keeps take and filter per relation simple, and only adds a bounded number of round trips. However, batched loading cannot express every query. Reporting queries, joins on non-relation keys, and self-joins all need an explicit JOIN in the SQL.

Decision

  1. Batched loading stays the default for include. ADR-004 is not weakened. include still issues one query per relation level.

  2. Explicit joins are a separate, opt-in query-builder feature. They are exposed through SelectQuery::inner_join, left_join, right_join, and full_join for cases the batcher cannot express.

  3. Join conditions are inferred from declared relations when possible. If the join target is a model related to the source through a schema relation, the builder uses the foreign-key columns from the relation definition.

  4. Arbitrary join conditions are supported via typed column tokens from both sides. A JoinOn or On builder lets users write A::id.eq(B::a_id) across two models, even when no schema relation connects them.

  5. Joined queries return tuples of model types. An inner join returns (A, B). A left join returns (A, Option<B>). A right join returns (Option<A>, B). A full join returns (Option<A>, Option<B>). This is the natural SQL semantics and is enforced at compile time.

  6. Self-joins use table aliasing. The builder generates a unique alias for the joined side and prefixes its columns so the two sides of a self-join are distinguishable in the result set and in FromRow decoding.

  7. Dialects emit the appropriate JOIN keywords. RIGHT JOIN and FULL OUTER JOIN are not supported by SQLite before 3.39. The dialect capability check reports this and the builder emits a clear construction-time error rather than SQL that fails at the server.

Consequences

  • Users can write SQL-like typed joins without losing the batched include path.
  • The query surface covers Drizzle's leftJoin/innerJoin and Diesel's join DSL parity.
  • Compile-time type safety for outer-join nullability (left/right/full).
  • SQLite users get a helpful error for right/full joins unless they target a backend that supports them.
  • See docs/design/JoinResultDecoding.md for the concrete decoding plan for joined result sets.

ADR-012: Offline query checking

Status

Accepted.

Context

The runtime query builder and raw! macro produce SQL at compile time or at run time. Today those strings are only validated by a live database during execution. We want CI to catch mistakes — unknown tables, misspelled columns, malformed SQL fragments — before the application is deployed, without requiring a database connection.

Decision

Use a manifest of captured SQL plus a schema snapshot:

  • RUPRIZZLE_RECORD_QUERIES=1 makes the runtime record every to_sql() output into an in-memory buffer.
  • ruprizzle_check::write_manifest serialises the buffer to query-manifest.json.
  • RUPRIZZLE_OFFLINE_SCHEMA=path/to/schema.ruprizzle makes the raw! macro parse the schema at compile time and reject unknown table/column references with a syn error.
  • ruprizzle check --schema schema.ruprizzle --manifest query-manifest.json validates captured queries against the parsed schema.

The validation is intentionally coarse: it tokenises the SQL and checks identifiers against model/table and column names. It is not a full SQL parser; that would be brittle and re-invent sqlx's query analysis. The goal is to catch obvious typos and drift, not prove query correctness.

Consequences

  • CI can run RUPRIZZLE_RECORD_QUERIES=1 cargo test && ruprizzle check ... to detect schema drift.
  • raw! fragments gain compile-time guard rails when RUPRIZZLE_OFFLINE_SCHEMA is set.
  • The validation does not understand aliases, CTEs, or subqueries in depth. False negatives are expected for complex SQL.