Skip to main content

WhereClause

Enum WhereClause 

Source
#[non_exhaustive]
pub enum WhereClause { Field { path: Vec<String>, operator: WhereOperator, value: Value, }, And(Vec<WhereClause>), Or(Vec<WhereClause>), Not(Box<WhereClause>), NativeField { column: String, pg_cast: String, operator: WhereOperator, value: Value, }, Typed { types: Arc<FieldTypeMap>, inner: Box<WhereClause>, }, InHierarchy { context: HierarchyContext, inner: Box<WhereClause>, }, Guarded { under: Vec<String>, guard: Box<WhereClause>, inner: Box<WhereClause>, }, KeyIn { path: Vec<String>, key_type: ScalarFieldType, view: String, target_key: Vec<String>, predicate: Box<WhereClause>, }, }
Expand description

WHERE clause abstract syntax tree.

Represents a type-safe WHERE condition that can be compiled to database-specific SQL.

§Example

use fraiseql_db::{WhereClause, WhereOperator};
use serde_json::json;

// Simple condition: email ILIKE '%example.com%'
let where_clause = WhereClause::Field {
    path: vec!["email".to_string()],
    operator: WhereOperator::Icontains,
    value: json!("example.com"),
};

// Complex condition: (published = true) AND (views >= 100)
let where_clause = WhereClause::And(vec![
    WhereClause::Field {
        path: vec!["published".to_string()],
        operator: WhereOperator::Eq,
        value: json!(true),
    },
    WhereClause::Field {
        path: vec!["views".to_string()],
        operator: WhereOperator::Gte,
        value: json!(100),
    },
]);

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Field

Single field condition.

Fields

§path: Vec<String>

JSONB path (e.g., ["email"] or ["posts", "title"]).

§operator: WhereOperator

Comparison operator.

§value: Value

Value to compare against.

§

And(Vec<WhereClause>)

Logical AND of multiple conditions.

§

Or(Vec<WhereClause>)

Logical OR of multiple conditions.

§

Not(Box<WhereClause>)

Logical NOT of a condition.

§

NativeField

Native column condition — bypasses JSONB extraction.

Used when a direct query argument maps to a native column on sql_source, detected at compile time. Generates "column" = $N (with an optional PostgreSQL type cast on the parameter, e.g. $1::uuid) instead of the default data->>'column' = $N.

Fields

§column: String

Native column name (e.g., "id").

§pg_cast: String

PostgreSQL parameter cast suffix (e.g., "uuid", "int4"). Empty string means no cast is applied.

§operator: WhereOperator

Comparison operator.

§value: Value

Value to compare against.

§

Typed

A subtree whose fields carry their declared scalar types.

The generator needs the field’s type to pick a SQL cast; deciding the cast from the operator instead is what made every non-numeric range filter a hard error (#798). The annotation is a node of the clause rather than a parameter of the generator on purpose: a clause travels through ProjectionRequest, the relay cursor path, the wire adapter, federation and the cache key, and an extra argument on any one of those seams is an extra place to drop it. Carried by the clause, it cannot be dropped without deleting the clause.

Only the user-supplied filter is wrapped. RLS and injected-parameter conditions are composed separately and stay untyped — they compare tenant identifiers as text.

Fields

§types: Arc<FieldTypeMap>

Declared type per dotted snake_case field path.

§inner: Box<WhereClause>

The annotated subtree.

§

InHierarchy

A subtree whose ID-based ltree operators resolve against context (#1396).

descendantOfId / ancestorOfId take a node’s id and need to know which table holds that node’s path. That is a property of the filtered field — its hierarchy link in the schema — so the parser, which knows the field, wraps the leaf in this node, and the generator reads the context from it. As with Typed, carrying it in the clause means no seam the clause travels through can drop it.

Fields

§context: HierarchyContext

Where the field’s hierarchy keeps node paths.

§inner: Box<WhereClause>

The leaf the context applies to.

§

Guarded

A subtree whose values under under are visible only where guard holds.

Every path in inner that runs through under reads its value through the guard — CASE WHEN <guard> THEN <value> END — so where the guard fails the value is NULL: exactly what the response serves for a related row the caller may not read. The guard’s paths are absolute (they start with under). The executor builds it for a client filter through a relation into a row-gated type; like Typed, it is a node of the clause so that no seam the clause travels through can drop it.

Fields

§under: Vec<String>

The path of the relation whose embedded documents the guard gates.

§guard: Box<WhereClause>

The row predicate the related document must meet, over absolute paths.

§inner: Box<WhereClause>

The guarded subtree.

§

KeyIn

Whether the key stored at path is among the target_key values of the rows of view that satisfy predicate, both compared as key_type (ruling AL).

A related row’s visibility, decided over the related type’s own view: where a type’s row predicate cannot be read off the document its parent’s view embedded, the related level is read from its view through the declared relationship, and a filter through the relation asks the same question here, as the guard of a Guarded. Rendered as <key> IN (SELECT <target key> FROM <view> WHERE <predicate>) — uncorrelated, so predicate reads the view’s rows and path this row. Built by the executor, never parsed from a client. predicate is over the view’s rows: its native columns are the view’s, not this row’s.

Fields

§path: Vec<String>

The stored path of the key on this row.

§key_type: ScalarFieldType

The declared scalar type both keys are compared as.

§view: String

The related type’s view.

§target_key: Vec<String>

The stored path of the key on the view’s rows.

§predicate: Box<WhereClause>

The related type’s row predicate, over the view’s rows.

Implementations§

Source§

impl WhereClause

Source

pub fn is_empty(&self) -> bool

Check if WHERE clause is empty.

Source

pub fn typed(self, types: Arc<FieldTypeMap>) -> WhereClause

Annotate this clause with the declared scalar types of its fields.

Source

pub fn native_column_names(&self) -> Vec<&str>

Collect all native column names referenced in this WHERE clause.

Used to enrich error messages when a native column does not exist on the target table — the caller can hint that the column was auto-inferred from an ID/UUID-typed argument and suggest adding the column or using explicit native_columns annotation.

Source

pub fn from_graphql_json( value: &Value, schema: &WhereFieldSchema, ) -> Result<WhereClause, FraiseQLError>

Parse a WhereClause from a nested GraphQL JSON where variable.

Expected format (nested object with field → operator → value):

{
  "status": { "eq": "active" },
  "name": { "icontains": "john" },
  "_and": [ { "age": { "gte": 18 } }, { "age": { "lte": 65 } } ],
  "_or": [ { "role": { "eq": "admin" } } ],
  "_not": { "deleted": { "eq": true } }
}

Each top-level key is either a field name (mapped to WhereClause::Field with operator sub-keys) or a logical combinator (_and, _or, _not). Multiple top-level keys are combined with AND.

types carries the declared scalar type of each filterable field, taken from the compiled schema. It is a required argument rather than an optional enrichment step because the cast a filter needs is a property of the field: a caller that has a schema and forgets to consult it produces SQL that errors on dates and silently under-matches on numbers. Callers that genuinely have no schema pass SharedFieldTypes::default and get value-shape inference.

§Errors

Returns FraiseQLError::Validation if the JSON structure is invalid or contains unknown operators.

§Panics

Cannot panic: the internal .expect("checked len == 1") is only reached after verifying conditions.len() == 1.

Trait Implementations§

Source§

impl Clone for WhereClause

Source§

fn clone(&self) -> WhereClause

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 WhereClause

Source§

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

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

impl<'de> Deserialize<'de> for WhereClause

Source§

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

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

impl PartialEq for WhereClause

Source§

fn eq(&self, other: &WhereClause) -> 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 WhereClause

Source§

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

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

impl StructuralPartialEq for WhereClause

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<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> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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