---
name: diesel-orm
description: Type-safe Rust ORM with compile-time query validation.
metadata:
  labels: [rust, diesel, orm, database, postgresql]
  triggers:
    files: ['**/schema.rs', 'diesel.toml']
    keywords: [diesel, Queryable, Insertable, table]
---

# Diesel ORM Standards

## Schema Definition

```rust
// Generated by diesel migration run
// src/schema.rs
diesel::table! {
    users (id) {
        id -> Int4,
        name -> Varchar,
        email -> Varchar,
        created_at -> Timestamp,
    }
}
```

## Model Structs

```rust
use diesel::prelude::*;
use crate::schema::users;

#[derive(Queryable, Selectable, Debug)]
#[diesel(table_name = users)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub email: String,
    pub created_at: NaiveDateTime,
}

#[derive(Insertable)]
#[diesel(table_name = users)]
pub struct NewUser<'a> {
    pub name: &'a str,
    pub email: &'a str,
}

#[derive(AsChangeset)]
#[diesel(table_name = users)]
pub struct UpdateUser<'a> {
    pub name: Option<&'a str>,
    pub email: Option<&'a str>,
}
```

## Connection Pool

```rust
use diesel::pg::PgConnection;
use diesel::r2d2::{Pool, ConnectionManager};

type DbPool = Pool<ConnectionManager<PgConnection>>;

fn establish_pool(database_url: &str) -> DbPool {
    let manager = ConnectionManager::<PgConnection>::new(database_url);
    Pool::builder()
        .max_size(15)
        .build(manager)
        .expect("Failed to create pool")
}
```

## CRUD Operations

```rust
use diesel::prelude::*;
use crate::schema::users::dsl::*;

// Create
fn create_user(conn: &mut PgConnection, new_user: &NewUser) -> QueryResult<User> {
    diesel::insert_into(users)
        .values(new_user)
        .get_result(conn)
}

// Read
fn find_user(conn: &mut PgConnection, user_id: i32) -> QueryResult<User> {
    users.find(user_id).first(conn)
}

fn list_users(conn: &mut PgConnection) -> QueryResult<Vec<User>> {
    users.load(conn)
}

// Update
fn update_user(conn: &mut PgConnection, user_id: i32, changes: &UpdateUser) -> QueryResult<User> {
    diesel::update(users.find(user_id))
        .set(changes)
        .get_result(conn)
}

// Delete
fn delete_user(conn: &mut PgConnection, user_id: i32) -> QueryResult<usize> {
    diesel::delete(users.find(user_id)).execute(conn)
}
```

## Query Building

```rust
// Filtering
let active_users = users
    .filter(active.eq(true))
    .filter(created_at.gt(cutoff_date))
    .load::<User>(conn)?;

// Ordering and pagination
let page = users
    .order(created_at.desc())
    .limit(10)
    .offset(20)
    .load::<User>(conn)?;

// Select specific columns
let emails: Vec<String> = users
    .select(email)
    .load(conn)?;

// Joins
let user_posts = users
    .inner_join(posts::table)
    .select((users::name, posts::title))
    .load::<(String, String)>(conn)?;
```

## Transactions

```rust
conn.transaction(|conn| {
    diesel::insert_into(users)
        .values(&new_user)
        .execute(conn)?;

    diesel::insert_into(audit_log)
        .values(&log_entry)
        .execute(conn)?;

    Ok(())
})
```

## Migrations

```bash
# Create migration
diesel migration generate create_users

# Run pending migrations
diesel migration run

# Revert last migration
diesel migration revert

# Redo last migration
diesel migration redo
```

## Best Practices

1. **Schema sync**: Run `diesel migration run` before compile
2. **Pool sizing**: Match to expected concurrent connections
3. **Derive macros**: Use `Queryable` for reads, `Insertable` for writes
4. **Nullable**: Use `Option<T>` for nullable columns
5. **Raw SQL**: Use `sql_query()` for complex queries when needed


---
Source attribution: ngxtm
Original project: https://github.com/ngxtm/devkit/blob/9439f27ce3fa7fe53ff9278a1ee9a44bffa70eba/rules/rust/diesel-orm/SKILL.md
License: MIT
License information: https://opensource.org/license/mit
Original upstream instructions; downloaded from Dave AI.

## Upstream license notice

MIT License

Copyright (c) 2024

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.



# Dave AI resource metadata

Creator / publisher: ngxtm
Original project: https://github.com/ngxtm/devkit/blob/9439f27ce3fa7fe53ff9278a1ee9a44bffa70eba/rules/rust/diesel-orm/SKILL.md
Attribution basis: Recovered original package and original project license at a pinned revision

Fields of work: Development & Engineering
Roles: Backend Developer, Data Engineer, Database Administrator
Specialties: Database
Tools: PostgreSQL
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: 4dd503976081348ed46e97e0a6b84333f27b9f52cd84385380bcd194328a7f31
Metadata reviewed: 2026-10-27
This metadata supersedes earlier Dave AI catalog attribution. Original instruction and supporting files are preserved.
