Skip to main content

OrderByClause

Struct OrderByClause 

Source
#[non_exhaustive]
pub struct OrderByClause { pub field: String, pub direction: OrderDirection, pub field_type: ScalarFieldType, pub native_column: Option<String>, pub native_type: Option<String>, pub native_not_null: bool, pub vector: Option<VectorDistanceOrder>, pub relevance: Option<RelevanceOrder>, pub identity: bool, pub collation: Option<String>, pub localized: Option<Vec<String>>, }
Expand description

ORDER BY clause with optional type and native column information.

The SQL generator uses field_type to emit the correct type cast for JSONB-extracted values, and native_column to bypass JSONB extraction entirely when the view exposes a dedicated typed column.

§Sort correctness by source

SourceText fieldsNumeric fieldsDate fields
JSONB (no cast)CorrectWrong (lexicographic)Correct (ISO-8601)
JSONB (with cast)CorrectCorrectCorrect
Native columnCorrectCorrectCorrect + indexable

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§field: String

Field to order by (GraphQL camelCase name).

§direction: OrderDirection

Sort direction.

§field_type: ScalarFieldType

Field type for SQL cast generation. Text (default) means no cast.

§native_column: Option<String>

Native column name if the view exposes this field as a typed column. When set, ORDER BY uses this column directly instead of JSONB extraction, enabling index support and correct typing without casts.

§native_type: Option<String>

The PostgreSQL type of native_column (int8, uuid, …), when the view declares it: a keyset value compared with the column is cast to it (#1521). None reads it as the field’s scalar type.

§native_not_null: bool

Whether PostgreSQL proves native_column NOT NULL, as compile --database recorded it (#1533). Only such a key lets a relay page seek its index with a row comparison: a NULL in a row comparison drops the row silently. Never set from a client’s orderBy.

§vector: Option<VectorDistanceOrder>

Vector-distance ordering (#386): when set, this clause orders by {column} {operator} '{query_vector}'::vector — the pgvector ANN shape. Requires native_column (a JSONB-extracted text value would defeat every vector index and re-parse per row).

§relevance: Option<RelevanceOrder>

Full-text relevance ordering (#1284): when set, this clause orders by ts_rank(to_tsvector(document), websearch_to_tsquery($n)), where the document is built from the searchable fields the same ?search= predicate matched on.

field is not read for such a clause — there is no single field a relevance rank belongs to — and is empty by construction.

§identity: bool

This clause is the entity identity, whatever it is spelled as (#1303).

Set only by identity, which the runtime uses to lower the compiled pagination_order into an ordering. Read only by the tie-breaker, which appends nothing to an ordering that already carries one.

A flag rather than a name comparison because the identity is a schema fact: it may be data->>'id', a native id, or pk_user, and this module cannot tell the last from any other column. Without the flag the renderer would append its own data->>'id' on top of a pk_user ordering — a second, redundant sort key on every paged read of every Trinity view.

§collation: Option<String>

The collation a text key sorts under (#1512): the request locale’s ICU collation (fr-CA-x-icu), rendered as … COLLATE "fr-CA-x-icu". Set by the runtime, only for a text key and only from a configured locale; None sorts under the column’s own collation, as before.

§localized: Option<Vec<String>>

A localized key’s fallback chain (#1513): the clause sorts the label the chain reads from the stored locale map, under collation, rather than the map. Set by the runtime from the request locale.

Implementations§

Source§

impl OrderByClause

Source

pub fn new(field: String, direction: OrderDirection) -> Self

Create a new OrderByClause with default field type (text) and no native column.

Source

pub const fn identity(field: String, native_column: Option<String>) -> Self

A clause that orders by the entity identity, ascending (#1303).

native_column when the relation exposes the identity as a column (id, pk_user), None for the JSONB extraction data->>'id'. Which one is a compile-time decision recorded in QueryDefinition::pagination_order; this is its lowering.

ASC unconditionally. A total order is all this has to be, and which of two otherwise-tied rows comes first is not a property any client asked about. Matching a requested clause’s direction would suggest it is.

Source

pub fn by_relevance(relevance: RelevanceOrder) -> Self

A clause that orders by full-text relevance, most relevant first (#1284).

field is left empty deliberately. A relevance rank is computed over several fields at once, so naming one of them would be a lie, and naming a sentinel like _relevance would put the sort kind back into a string — which is the defect this constructor exists to replace: [{"_relevance": "desc"}] type-checked at every layer that touched it and failed only in the ORDER BY parser, three layers below the handler that wrote it.

Source

pub const fn binds_parameter(&self) -> bool

Whether rendering this clause binds a SQL parameter.

True only for full-text relevance (#1284), whose operand is arbitrary client text and is therefore bound rather than interpolated. A SQL builder that assembles ORDER BY as a bare string — the relay keyset query, the fraiseql-wire adapter — asks this before rendering, so that “this ordering cannot be expressed here” is a named refusal instead of a dropped sort or an escaped literal.

Source

pub fn storage_key(&self) -> String

Convert the GraphQL camelCase field name to the JSONB snake_case storage key.

§Examples
use fraiseql_db::OrderByClause;
use fraiseql_db::OrderDirection;

let clause = OrderByClause::new("createdAt".to_string(), OrderDirection::Asc);
assert_eq!(clause.storage_key(), "created_at");
Source

pub fn validate_field_name(field: &str) -> Result<()>

Validate that a field name matches the GraphQL identifier pattern [_A-Za-z][_0-9A-Za-z]*.

This is a security boundary: field names are interpolated into SQL data->>'field' expressions. Any character outside the GraphQL identifier set must be rejected before the OrderByClause is constructed.

§Errors

Returns FraiseQLError::Validation if the field contains invalid characters.

Source

pub fn from_graphql_json(value: &Value) -> Result<Vec<Self>>

Parse orderBy from a GraphQL variables JSON value.

Accepts two formats:

  • Object: { "name": "DESC", "created_at": "ASC" }
  • Array: [{ "field": "name", "direction": "DESC" }]

Direction strings are case-insensitive.

§Errors

Returns FraiseQLError::Validation for invalid structure or direction values.

Trait Implementations§

Source§

impl Clone for OrderByClause

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for OrderByClause

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for OrderByClause

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Eq for OrderByClause

Source§

impl PartialEq for OrderByClause

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for OrderByClause

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for OrderByClause

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more