Diesel provides a type-safe query builder and ORM for Rust, catching SQL mistakes at compile time. UUID v7 primary keys work through Diesel’s built-in UUID support — the uuid crate generates v7 values, and Diesel maps them to PostgreSQL uuid columns with full type safety. See UUID in Rust for the ecosystem overview.
Cargo.toml
[dependencies]
diesel = { version = "2", features = ["postgres", "uuid", "r2d2"] }
uuid = { version = "1", features = ["v7"] }
dotenvy = "0.15"
PostgreSQL schema
CREATE EXTENSION IF NOT EXISTS pg_uuidv7;
CREATE TABLE orders (
id UUID NOT NULL DEFAULT gen_random_uuid_v7() PRIMARY KEY,
customer_id UUID NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
total NUMERIC(10,2) NOT NULL
);
Diesel schema (schema.rs)
// src/schema.rs — generated by diesel print-schema or written manually
diesel::table! {
orders (id) {
id -> Uuid,
customer_id -> Uuid,
status -> Text,
total -> Numeric,
}
}
Model structs
use diesel::prelude::*;
use uuid::Uuid;
use crate::schema::orders;
#[derive(Queryable, Selectable, Debug)]
#[diesel(table_name = orders)]
pub struct Order {
pub id: Uuid,
pub customer_id: Uuid,
pub status: String,
pub total: bigdecimal::BigDecimal,
}
#[derive(Insertable)]
#[diesel(table_name = orders)]
pub struct NewOrder {
pub id: Uuid, // application-generated UUID v7
pub customer_id: Uuid,
pub total: bigdecimal::BigDecimal,
}
Insert with UUID v7
use uuid::{Uuid, Timestamp, NoContext};
use diesel::prelude::*;
pub fn create_order(
conn: &mut PgConnection,
customer_id: Uuid,
total: bigdecimal::BigDecimal,
) -> QueryResult<Order> {
use crate::schema::orders::dsl::*;
// Generate UUID v7 — encodes creation time
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap();
let ts = Timestamp::from_unix(NoContext, now.as_secs(), now.subsec_nanos());
let new_id = Uuid::new_v7(ts);
let new_order = NewOrder { id: new_id, customer_id, total };
diesel::insert_into(orders)
.values(&new_order)
.get_result(conn)
}
Cursor pagination
use diesel::prelude::*;
use uuid::Uuid;
use crate::schema::orders::dsl::*;
pub struct Page {
pub data: Vec<Order>,
pub next_cursor: Option<Uuid>,
}
pub fn list_orders(
conn: &mut PgConnection,
owner: Uuid,
cursor: Option<Uuid>,
limit: i64,
) -> QueryResult<Page> {
let mut query = orders
.filter(customer_id.eq(owner))
.order(id.asc()) // UUID v7 sort = chronological
.limit(limit + 1)
.into_boxed();
if let Some(c) = cursor {
// UUID v7 lexicographic > c means created after c
query = query.filter(id.gt(c));
}
let mut rows: Vec<Order> = query.load(conn)?;
let has_more = rows.len() > limit as usize;
if has_more { rows.pop(); }
let next_cursor = if has_more { rows.last().map(|r| r.id) } else { None };
Ok(Page { data: rows, next_cursor })
}
Connection pool setup (r2d2)
use diesel::r2d2::{ConnectionManager, Pool};
use diesel::PgConnection;
pub type DbPool = Pool<ConnectionManager<PgConnection>>;
pub fn build_pool(database_url: &str) -> DbPool {
let manager = ConnectionManager::<PgConnection>::new(database_url);
Pool::builder().build(manager).expect("Failed to build pool")
}
Further reading
- UUID in Rust — uuid Crate and Diesel
- UUID v7 for Cursor Pagination
- UUID v7 in Actix-web
- UUID in Databases — Storage and Indexing
- UUID v7 in Prisma + PostgreSQL
External references
Frequently asked questions
How do I enable UUID support in Diesel?
Add diesel = { version = "2", features = ["postgres", "uuid"] } and uuid = { version = "1", features = ["v7"] } to Cargo.toml. Diesel's uuid feature provides the Uuid type mappings for PostgreSQL uuid columns. UUID v7 is generated with Uuid::new_v7(Timestamp::now(NoContext)) from the uuid crate. See UUID in Rust.
How do I define a UUID v7 primary key in a Diesel schema?
In the Diesel schema macro, declare the column as id -> Uuid. In the Rust struct, use pub id: uuid::Uuid. For database-generated defaults (requires pg_uuidv7 extension), omit id from the Insertable struct and set DEFAULT gen_random_uuid_v7() on the column. For application-generated UUID v7, include id in the insertable struct and assign before inserting. See UUID v7 in Prisma + PostgreSQL.
How does UUID v7 cursor pagination work in Diesel?
Use Diesel's .filter(schema::table::id.gt(cursor)) combined with .order(schema::table::id.asc()). The gt filter on a Uuid column compiles to WHERE id > $1 — UUID v7 lexicographic ordering equals chronological, so this is a time-based cursor without a created_at column. See UUID v7 for Cursor Pagination.