Skip to main content

sort

Attribute Macro sort 

Source
#[sort]
Expand description

Define a sort enum for compile-time verified dynamic ORDER BY clauses.

§Usage

#[bsql::sort]
pub enum TicketSort {
    #[sql("t.updated_at DESC, t.id DESC")]
    UpdatedAt,
    #[sql("t.deadline ASC NULLS LAST, t.id ASC")]
    Deadline,
    #[sql("t.id DESC")]
    Id,
}

Use with the $[sort: EnumType] placeholder in bsql::query!:

let tickets = bsql::query!(
    "SELECT id, title FROM tickets ORDER BY $[sort: TicketSort] LIMIT $limit: i64"
).fetch_all(&pool)?;

Each variant must have a #[sql("...")] attribute mapping it to the SQL ORDER BY fragment. The macro generates:

  • The enum with Debug, Clone, Copy, PartialEq, Eq, Hash
  • A sql(&self) -> &'static str method returning the SQL fragment
  • Display — formats as the SQL fragment

Unlike #[bsql::pg_enum], sort enums are NOT parameterized values. The SQL fragment is spliced directly into the query string.