Diesel provides type-safe database interactions for Rust — queries that don’t compile are SQL errors caught at build time. UUID v7 primary keys fit Diesel’s model naturally: the uuid crate provides the Uuid type, Diesel maps it to PostgreSQL uuid columns, and cursor pagination compiles to simple WHERE id > $1 queries. See UUID in Rust for the full Rust UUID ecosystem.

Cargo.toml

[dependencies]
diesel    = { version = "2", features = ["postgres", "uuid", "r2d2"] }
uuid      = { version = "1", features = ["v7"] }
dotenvy   = "0.15"
bigdecimal = "0.4"

Database setup

CREATE EXTENSION IF NOT EXISTS pg_uuidv7;

CREATE TABLE products (
    id          UUID NOT NULL DEFAULT gen_random_uuid_v7() PRIMARY KEY,
    sku         TEXT NOT NULL UNIQUE,
    name        TEXT NOT NULL,
    price_cents INTEGER NOT NULL
);

Diesel schema

// src/schema.rs
diesel::table! {
    products (id) {
        id          -> Uuid,
        sku         -> Text,
        name        -> Text,
        price_cents -> Integer,
    }
}

Model and insertable structs

// src/models.rs
use diesel::prelude::*;
use uuid::Uuid;
use crate::schema::products;

// Queryable — for SELECT results
#[derive(Queryable, Selectable, Debug, Clone)]
#[diesel(table_name = products)]
pub struct Product {
    pub id:          Uuid,
    pub sku:         String,
    pub name:        String,
    pub price_cents: i32,
}

// Insertable — application-generated UUID v7
#[derive(Insertable)]
#[diesel(table_name = products)]
pub struct NewProduct<'a> {
    pub id:          Uuid,    // UUID v7
    pub sku:         &'a str,
    pub name:        &'a str,
    pub price_cents: i32,
}

// Insertable — database-generated UUID v7 (omits id)
#[derive(Insertable)]
#[diesel(table_name = products)]
pub struct NewProductDb<'a> {
    pub sku:         &'a str,
    pub name:        &'a str,
    pub price_cents: i32,
}

UUID v7 generation helper

use uuid::{Uuid, Timestamp, NoContext};
use std::time::{SystemTime, UNIX_EPOCH};

pub fn new_uuid_v7() -> Uuid {
    let d = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("time before unix epoch");
    let ts = Timestamp::from_unix(NoContext, d.as_secs(), d.subsec_nanos());
    Uuid::new_v7(ts)
}

CRUD operations

use diesel::prelude::*;
use crate::{models::*, schema::products::dsl::*, new_uuid_v7};

pub fn create_product(conn: &mut PgConnection, sku: &str, name: &str, price: i32)
    -> QueryResult<Product>
{
    let new = NewProduct { id: new_uuid_v7(), sku, name, price_cents: price };

    diesel::insert_into(products)
        .values(&new)
        .get_result(conn)
}

pub fn get_product(conn: &mut PgConnection, product_id: Uuid) -> QueryResult<Product> {
    products.find(product_id).first(conn)
}

pub fn update_price(conn: &mut PgConnection, product_id: Uuid, new_price: i32)
    -> QueryResult<Product>
{
    diesel::update(products.find(product_id))
        .set(price_cents.eq(new_price))
        .get_result(conn)
}

pub fn delete_product(conn: &mut PgConnection, product_id: Uuid) -> QueryResult<usize> {
    diesel::delete(products.find(product_id)).execute(conn)
}

Cursor pagination

pub struct ProductPage {
    pub data:        Vec<Product>,
    pub next_cursor: Option<Uuid>,
}

pub fn list_products(
    conn:   &mut PgConnection,
    cursor: Option<Uuid>,
    limit:  i64,
) -> QueryResult<ProductPage> {
    let mut query = products
        .order(id.asc())           // UUID v7 lexicographic = chronological
        .limit(limit + 1)
        .into_boxed();

    if let Some(c) = cursor {
        query = query.filter(id.gt(c));   // created after cursor
    }

    let mut rows: Vec<Product> = query.load(conn)?;
    let has_more = rows.len() > limit as usize;
    if has_more { rows.truncate(limit as usize); }

    let next_cursor = if has_more { rows.last().map(|r| r.id) } else { None };
    Ok(ProductPage { data: rows, next_cursor })
}

Connection pool

use diesel::r2d2::{ConnectionManager, Pool};
use diesel::PgConnection;

pub type DbPool = Pool<ConnectionManager<PgConnection>>;

pub fn create_pool(url: &str) -> DbPool {
    let mgr = ConnectionManager::<PgConnection>::new(url);
    Pool::builder().build(mgr).expect("pool creation failed")
}

Further reading

External references

Frequently asked questions

How do I add UUID v7 support to a Diesel project?

Add to Cargo.toml: diesel = { version = "2", features = ["postgres", "uuid"] } and uuid = { version = "1", features = ["v7"] }. The Diesel uuid feature provides Uuid type mapping for PostgreSQL uuid columns. Generate UUID v7 with Uuid::new_v7(Timestamp::from_unix(NoContext, secs, nanos)). See UUID v7 in Diesel ORM for Rust.

Can Diesel use a database-side UUID v7 default?

Yes. Install the pg_uuidv7 PostgreSQL extension, set DEFAULT gen_random_uuid_v7() on the column, and omit id from the Insertable struct. Diesel will not include id in the INSERT statement, and PostgreSQL assigns the UUID v7. Use .get_result(conn) or .returning(id) to retrieve the generated value. See UUID v7 in Drizzle + PostgreSQL for the pg_uuidv7 extension setup.

How do I implement cursor pagination with UUID v7 in Diesel?

Use schema::table::id.gt(cursor) with order(schema::table::id.asc()). Diesel compiles this to WHERE id > $1 ORDER BY id ASC. UUID v7 lexicographic ordering equals chronological, so this is a time-based cursor with no created_at column. Use .limit(n + 1) and check if more than n rows were returned to detect the next page. See UUID v7 for Cursor Pagination.