Skip to main content

type_bridge/
query.rs

1#![deny(missing_docs)]
2//! Owner-branded query sessions, bindings, predicates, and the one query
3//! facade (Flight 3: F3-01 foundation, F3-02 algebra, F3-03 singular shapes).
4
5use std::marker::PhantomData;
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8
9use type_bridge_contract::codec::from_canonical_json;
10use type_bridge_contract::decimal::parse_decimal;
11use type_bridge_contract::id::{FunctionId, TypeId, TypeKind};
12use type_bridge_contract::limits::QueryLimits;
13use type_bridge_contract::projection::ProjectionHandler;
14use type_bridge_contract::query_plan::CompatibilityValueV2;
15use type_bridge_contract::temporal::{
16    CanonicalDate, CanonicalDateTime, CanonicalDateTimeTz, CanonicalDuration,
17};
18use type_bridge_orm::_descriptor::TypeDescriptorRef;
19use type_bridge_orm::_registry::DescriptorRegistry;
20use type_bridge_orm::match_request::handles::{
21    BindingHandle as OrmBindingHandle, FieldHandle as OrmFieldHandle,
22    FunctionArgumentHandle as OrmFunctionArgumentHandle,
23    FunctionCallHandle as OrmFunctionCallHandle, OrderHandle as OrmOrderHandle,
24    PredicateHandle as OrmPredicateHandle, QueryHandle as OrmQueryHandle,
25    SelectionHandle as OrmSelectionHandle, SessionHandle as OrmSessionHandle,
26    ShapeHandle as OrmShapeHandle,
27};
28use type_bridge_orm::match_request::model::{
29    ComparisonOp, MissingOrder, RowCardinality, SortDirection, Window,
30};
31use type_bridge_orm::match_request::result::{
32    HydratedThing, MatchResult, MatchRow, ReducedValue, SlotValue, ValidatedMatchResult,
33};
34use type_bridge_orm::match_request::validation::ValidatedMatchRequest;
35use type_bridge_orm::{
36    AnswerCancellation, AttributeValue, DynamicEntityRow, DynamicRelationRow, DynamicRolePlayer,
37    InstalledRuntimeProjection, ProjectedAttributeValue, ProjectedQueryOrigin, ProjectedQueryRow,
38    ProjectedQuerySlotValue, ProjectedQueryValue, ProjectedReducedValue, ProjectedReductionGroup,
39    ProjectedThing, QueryExecutionDeadline, QueryExecutionResourceLimits, QueryTarget,
40};
41
42use crate::__codegen::{
43    CompleteModel, EncodedScalar, FieldToken, FunctionToken, GroupedQueryValue, HydratedRow,
44    HydrationCapability, Model, QueryValued, RelationModel, RolePlayerBinding, RoleToken,
45    RoleTokenCompatible, SubtypeRootModel, ThingModel, TypeToken, ValidationError,
46};
47use crate::entity_codec::{hydrate_entity, map_validation_error};
48use crate::error::{Error, ModelValidationPhase};
49use crate::projected_codec::projected_to_hydrated_row;
50use crate::relation_codec::hydrate_relation;
51use crate::schema::Schema;
52use crate::{Database, Result};
53
54#[cfg(test)]
55mod tests;
56
57static QUERY_SESSION_NONCE: AtomicU64 = AtomicU64::new(1);
58
59fn schema_not_bound() -> Error {
60    Error::model_validation(
61        ModelValidationPhase::Input,
62        "schema_not_bound",
63        vec![],
64        "database is not schema-bound",
65        None,
66    )
67}
68
69fn cross_session_handle() -> Error {
70    Error::model_validation(
71        ModelValidationPhase::Input,
72        "cross_session_handle",
73        vec![],
74        "binding belongs to a different query session",
75        None,
76    )
77}
78
79fn model_label(type_id_json: &'static str) -> Result<String> {
80    let id = from_canonical_json::<TypeId>(type_id_json.as_bytes()).map_err(|source| {
81        Error::model_validation(
82            ModelValidationPhase::Input,
83            "invalid_model_identity",
84            vec!["type".into()],
85            "generated model identity is not canonical",
86            Some(Box::new(source)),
87        )
88    })?;
89    Ok(id.label().as_str().to_owned())
90}
91
92fn parse_owns_identity(owns_id_json: &'static str) -> Result<(String, String)> {
93    let invalid = || {
94        Error::model_validation(
95            ModelValidationPhase::Input,
96            "invalid_field_identity",
97            vec!["type".into()],
98            "generated field identity is not canonical",
99            None,
100        )
101    };
102    let value: serde_json::Value = serde_json::from_str(owns_id_json).map_err(|_| invalid())?;
103    let attribute = value
104        .get("attribute")
105        .and_then(serde_json::Value::as_str)
106        .ok_or_else(invalid)?;
107    let owner = value
108        .get("owner")
109        .and_then(|owner| owner.get("label"))
110        .and_then(serde_json::Value::as_str)
111        .ok_or_else(invalid)?;
112    Ok((owner.to_owned(), attribute.to_owned()))
113}
114
115fn parse_role_identity(role_id_json: &'static str) -> Result<type_bridge_contract::id::RoleId> {
116    from_canonical_json::<type_bridge_contract::id::RoleId>(role_id_json.as_bytes()).map_err(
117        |source| {
118            Error::model_validation(
119                ModelValidationPhase::Input,
120                "invalid_role_identity",
121                vec!["type".into()],
122                "generated role identity is not canonical",
123                Some(Box::new(source)),
124            )
125        },
126    )
127}
128
129mod mode_sealed {
130    pub trait Sealed {}
131}
132
133/// Sealed marker for a binding's exact-versus-subtypes selection behavior.
134pub trait SelectionMode: mode_sealed::Sealed + 'static {}
135
136/// Exact-match selection: results materialize as the bound concrete model.
137#[derive(Clone, Copy, Debug)]
138pub struct Exact;
139impl mode_sealed::Sealed for Exact {}
140impl SelectionMode for Exact {}
141
142/// Subtype-inclusive selection: results materialize as the generated leaf or
143/// closed family associated with the bound root.
144#[derive(Clone, Copy, Debug)]
145pub struct Subtypes;
146impl mode_sealed::Sealed for Subtypes {}
147impl SelectionMode for Subtypes {}
148
149/// One isolated owner-branded query authoring session.
150///
151/// Every binding call allocates a fresh binding identity; bindings are
152/// lightweight `Copy` values valid only for the session that created them.
153/// Bindings from another session fail before I/O with
154/// `cross_session_handle`.
155pub struct QuerySession<'db, S: Schema> {
156    cancellation: AnswerCancellation,
157    installed: &'db InstalledRuntimeProjection,
158    execution: QueryExecution<'db, S>,
159    resources: QueryExecutionResourceLimits,
160    session: OrmSessionHandle,
161    registry: Arc<DescriptorRegistry>,
162    nonce: u64,
163    bindings: Vec<OrmBindingHandle>,
164    closed: AtomicBool,
165    marker: PhantomData<fn() -> S>,
166}
167
168enum QueryExecution<'db, S: Schema> {
169    Local(&'db Database<S>),
170    Borrowed(&'db type_bridge_orm::session::context::TransactionContext),
171    Remote(&'db crate::remote::ProxyDatabase<S>),
172}
173
174impl<S: Schema> std::fmt::Debug for QuerySession<'_, S> {
175    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        formatter
177            .debug_struct("QuerySession")
178            .field("session", &self.nonce)
179            .field("bindings", &self.bindings.len())
180            .field("closed", &self.closed.load(Ordering::Acquire))
181            .finish_non_exhaustive()
182    }
183}
184
185/// Opaque session-scoped binding identity carried by `Copy` handles.
186#[doc(hidden)]
187#[derive(Clone, Copy, Debug, PartialEq, Eq)]
188pub struct BindingKey {
189    pub(crate) nonce: u64,
190    pub(crate) index: u32,
191}
192
193/// One schema/model-branded `Copy` binding token allocated by a
194/// [`QuerySession`]. Copying preserves the binding identity; only a fresh
195/// session binding call creates a new occurrence.
196pub struct Binding<S: Schema, M: ThingModel<Schema = S>, Mode: SelectionMode = Exact> {
197    key: BindingKey,
198    #[allow(clippy::type_complexity)]
199    marker: PhantomData<fn() -> (S, M, Mode)>,
200}
201
202impl<S: Schema, M: ThingModel<Schema = S>, Mode: SelectionMode> Copy for Binding<S, M, Mode> {}
203impl<S: Schema, M: ThingModel<Schema = S>, Mode: SelectionMode> Clone for Binding<S, M, Mode> {
204    fn clone(&self) -> Self {
205        *self
206    }
207}
208impl<S: Schema, M: ThingModel<Schema = S>, Mode: SelectionMode> PartialEq for Binding<S, M, Mode> {
209    fn eq(&self, other: &Self) -> bool {
210        self.key == other.key
211    }
212}
213impl<S: Schema, M: ThingModel<Schema = S>, Mode: SelectionMode> Eq for Binding<S, M, Mode> {}
214impl<S: Schema, M: ThingModel<Schema = S>, Mode: SelectionMode> std::fmt::Debug
215    for Binding<S, M, Mode>
216{
217    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        formatter
219            .debug_struct("Binding")
220            .field("session", &self.key.nonce)
221            .field("index", &self.key.index)
222            .finish()
223    }
224}
225
226impl<S: Schema, M: ThingModel<Schema = S>, Mode: SelectionMode> Binding<S, M, Mode> {
227    pub(crate) fn key(self) -> BindingKey {
228        self.key
229    }
230
231    /// Match this generated binding by one canonical TypeDB thing IID.
232    #[must_use]
233    pub fn iid(self, iid: impl Into<String>) -> Predicate<S> {
234        Predicate::new(PredicateExpr::BindingIid {
235            binding: self.key,
236            iid: iid.into(),
237        })
238    }
239
240    /// Match this generated binding by one of a non-empty bounded IID set.
241    #[must_use]
242    pub fn iid_in(self, iids: impl IntoIterator<Item = impl Into<String>>) -> Predicate<S> {
243        Predicate::new(PredicateExpr::BindingIidIn {
244            binding: self.key,
245            iids: iids.into_iter().map(Into::into).collect(),
246        })
247    }
248
249    /// Select this binding as an owned collection per distinct page root,
250    /// preserving match multiplicity by default.
251    #[must_use]
252    pub fn collect(self) -> Collected<S, Self>
253    where
254        Self: Selectable<S>,
255    {
256        Collected {
257            selection: self,
258            distinct: false,
259            order: Vec::new(),
260        }
261    }
262
263    /// Lower this exact session binding into one generated schema-function
264    /// argument. Nominal generated wrappers call this method; applications do
265    /// not construct untyped function arguments directly.
266    #[doc(hidden)]
267    #[must_use]
268    pub fn __function_argument(self) -> FunctionArgument<S> {
269        FunctionArgument {
270            nonce: self.key.nonce,
271            expression: FunctionArgumentExpr::Binding(self.key),
272            marker: PhantomData,
273        }
274    }
275}
276
277#[derive(Clone, Debug, PartialEq)]
278pub(crate) struct FunctionInputExpr {
279    attribute_type: TypeId,
280    value: AttributeValue,
281}
282
283#[derive(Clone, Debug, PartialEq)]
284pub(crate) enum FunctionArgumentExpr {
285    Binding(BindingKey),
286    Value(FunctionInputExpr),
287    Call(FunctionCallExpr),
288}
289
290#[derive(Clone, Debug, PartialEq)]
291pub(crate) struct FunctionCallExpr {
292    function_id: String,
293    arguments: Vec<FunctionArgumentExpr>,
294}
295
296/// One immutable schema- and session-branded scalar function input.
297///
298/// Generated packages expose nominal domain aliases such as `IntegerInput`
299/// and construct them only from projected attribute wrappers in that domain.
300#[doc(hidden)]
301#[derive(Clone, Debug, PartialEq)]
302pub struct FunctionInput<S: Schema, Domain> {
303    nonce: u64,
304    expression: FunctionInputExpr,
305    marker: PhantomData<fn() -> (S, Domain)>,
306}
307
308impl<S: Schema, Domain> FunctionInput<S, Domain> {
309    /// Use this scalar as one argument of the exact generated function call.
310    #[doc(hidden)]
311    #[must_use]
312    pub fn __function_argument(&self) -> FunctionArgument<S> {
313        FunctionArgument {
314            nonce: self.nonce,
315            expression: FunctionArgumentExpr::Value(self.expression.clone()),
316            marker: PhantomData,
317        }
318    }
319}
320
321/// One immutable schema- and session-branded scalar function call.
322///
323/// Generated packages expose nominal domain aliases such as `IntegerCall`.
324#[doc(hidden)]
325#[derive(Clone, Debug, PartialEq)]
326pub struct FunctionCall<S: Schema, Domain> {
327    nonce: u64,
328    expression: FunctionCallExpr,
329    marker: PhantomData<fn() -> (S, Domain)>,
330}
331
332impl<S: Schema, Domain> FunctionCall<S, Domain> {
333    /// Use this call result as one argument to a later generated function.
334    #[doc(hidden)]
335    #[must_use]
336    pub fn __function_argument(&self) -> FunctionArgument<S> {
337        FunctionArgument {
338            nonce: self.nonce,
339            expression: FunctionArgumentExpr::Call(self.expression.clone()),
340            marker: PhantomData,
341        }
342    }
343
344    fn field_predicate<Owner, Value>(
345        &self,
346        operator: ComparisonOp,
347        field: BoundField<S, Owner, Value>,
348    ) -> Predicate<S>
349    where
350        Owner: Model<Schema = S>,
351        Value: QueryValued<Domain = Domain>,
352    {
353        Predicate::new(PredicateExpr::FunctionField {
354            call: self.expression.clone(),
355            operator,
356            binding: field.key,
357            owns_id_json: field.owns_id_json,
358        })
359    }
360
361    fn value_predicate(
362        &self,
363        operator: ComparisonOp,
364        value: &FunctionInput<S, Domain>,
365    ) -> Result<Predicate<S>> {
366        if self.nonce != value.nonce {
367            return Err(cross_session_handle());
368        }
369        Ok(Predicate::new(PredicateExpr::FunctionValue {
370            call: self.expression.clone(),
371            operator,
372            value: value.expression.clone(),
373        }))
374    }
375
376    fn call_predicate(&self, operator: ComparisonOp, other: &Self) -> Result<Predicate<S>> {
377        if self.nonce != other.nonce {
378            return Err(cross_session_handle());
379        }
380        Ok(Predicate::new(PredicateExpr::FunctionCall {
381            left: self.expression.clone(),
382            operator,
383            right: other.expression.clone(),
384        }))
385    }
386
387    /// Compare this call for equality with one same-domain bound field.
388    #[must_use]
389    pub fn eq_field<Owner, Value>(&self, field: BoundField<S, Owner, Value>) -> Predicate<S>
390    where
391        Owner: Model<Schema = S>,
392        Value: QueryValued<Domain = Domain>,
393    {
394        self.field_predicate(ComparisonOp::Equal, field)
395    }
396
397    /// Compare this call for inequality with one same-domain bound field.
398    #[must_use]
399    pub fn ne_field<Owner, Value>(&self, field: BoundField<S, Owner, Value>) -> Predicate<S>
400    where
401        Owner: Model<Schema = S>,
402        Value: QueryValued<Domain = Domain>,
403    {
404        self.field_predicate(ComparisonOp::NotEqual, field)
405    }
406
407    /// Compare this call as less than one same-domain bound field.
408    #[must_use]
409    pub fn lt_field<Owner, Value>(&self, field: BoundField<S, Owner, Value>) -> Predicate<S>
410    where
411        Owner: Model<Schema = S>,
412        Value: QueryValued<Domain = Domain>,
413    {
414        self.field_predicate(ComparisonOp::LessThan, field)
415    }
416
417    /// Compare this call as less than or equal to one same-domain bound field.
418    #[must_use]
419    pub fn le_field<Owner, Value>(&self, field: BoundField<S, Owner, Value>) -> Predicate<S>
420    where
421        Owner: Model<Schema = S>,
422        Value: QueryValued<Domain = Domain>,
423    {
424        self.field_predicate(ComparisonOp::LessThanOrEqual, field)
425    }
426
427    /// Compare this call as greater than one same-domain bound field.
428    #[must_use]
429    pub fn gt_field<Owner, Value>(&self, field: BoundField<S, Owner, Value>) -> Predicate<S>
430    where
431        Owner: Model<Schema = S>,
432        Value: QueryValued<Domain = Domain>,
433    {
434        self.field_predicate(ComparisonOp::GreaterThan, field)
435    }
436
437    /// Compare this call as greater than or equal to one same-domain bound field.
438    #[must_use]
439    pub fn ge_field<Owner, Value>(&self, field: BoundField<S, Owner, Value>) -> Predicate<S>
440    where
441        Owner: Model<Schema = S>,
442        Value: QueryValued<Domain = Domain>,
443    {
444        self.field_predicate(ComparisonOp::GreaterThanOrEqual, field)
445    }
446
447    /// Compare this call for equality with one same-domain projected input.
448    pub fn eq_value(&self, value: &FunctionInput<S, Domain>) -> Result<Predicate<S>> {
449        self.value_predicate(ComparisonOp::Equal, value)
450    }
451
452    /// Compare this call for inequality with one same-domain projected input.
453    pub fn ne_value(&self, value: &FunctionInput<S, Domain>) -> Result<Predicate<S>> {
454        self.value_predicate(ComparisonOp::NotEqual, value)
455    }
456
457    /// Compare this call as less than one same-domain projected input.
458    pub fn lt_value(&self, value: &FunctionInput<S, Domain>) -> Result<Predicate<S>> {
459        self.value_predicate(ComparisonOp::LessThan, value)
460    }
461
462    /// Compare this call as less than or equal to one same-domain projected input.
463    pub fn le_value(&self, value: &FunctionInput<S, Domain>) -> Result<Predicate<S>> {
464        self.value_predicate(ComparisonOp::LessThanOrEqual, value)
465    }
466
467    /// Compare this call as greater than one same-domain projected input.
468    pub fn gt_value(&self, value: &FunctionInput<S, Domain>) -> Result<Predicate<S>> {
469        self.value_predicate(ComparisonOp::GreaterThan, value)
470    }
471
472    /// Compare this call as greater than or equal to one same-domain projected input.
473    pub fn ge_value(&self, value: &FunctionInput<S, Domain>) -> Result<Predicate<S>> {
474        self.value_predicate(ComparisonOp::GreaterThanOrEqual, value)
475    }
476
477    /// Compare this call for equality with another same-domain call.
478    pub fn eq_call(&self, other: &Self) -> Result<Predicate<S>> {
479        self.call_predicate(ComparisonOp::Equal, other)
480    }
481
482    /// Compare this call for inequality with another same-domain call.
483    pub fn ne_call(&self, other: &Self) -> Result<Predicate<S>> {
484        self.call_predicate(ComparisonOp::NotEqual, other)
485    }
486
487    /// Compare this call as less than another same-domain call.
488    pub fn lt_call(&self, other: &Self) -> Result<Predicate<S>> {
489        self.call_predicate(ComparisonOp::LessThan, other)
490    }
491
492    /// Compare this call as less than or equal to another same-domain call.
493    pub fn le_call(&self, other: &Self) -> Result<Predicate<S>> {
494        self.call_predicate(ComparisonOp::LessThanOrEqual, other)
495    }
496
497    /// Compare this call as greater than another same-domain call.
498    pub fn gt_call(&self, other: &Self) -> Result<Predicate<S>> {
499        self.call_predicate(ComparisonOp::GreaterThan, other)
500    }
501
502    /// Compare this call as greater than or equal to another same-domain call.
503    pub fn ge_call(&self, other: &Self) -> Result<Predicate<S>> {
504        self.call_predicate(ComparisonOp::GreaterThanOrEqual, other)
505    }
506}
507
508mod function_scalar_argument_sealed {
509    pub trait Sealed {}
510}
511
512/// A sealed, exact-domain scalar argument accepted by generated schema
513/// function wrappers.
514///
515/// Implementations are limited to a session-branded projected scalar input
516/// and a prior scalar function call in the same schema and scalar domain.
517/// This permits generated wrappers to build an immutable call DAG without
518/// exposing an untyped argument constructor.
519#[doc(hidden)]
520pub trait FunctionScalarArgument<S: Schema, Domain>:
521    function_scalar_argument_sealed::Sealed
522{
523    /// Lower this branded scalar into one function argument.
524    #[doc(hidden)]
525    fn __function_argument(&self) -> FunctionArgument<S>;
526}
527
528impl<S: Schema, Domain> function_scalar_argument_sealed::Sealed for FunctionInput<S, Domain> {}
529
530impl<S: Schema, Domain> FunctionScalarArgument<S, Domain> for FunctionInput<S, Domain> {
531    fn __function_argument(&self) -> FunctionArgument<S> {
532        FunctionInput::__function_argument(self)
533    }
534}
535
536impl<S: Schema, Domain> function_scalar_argument_sealed::Sealed for FunctionCall<S, Domain> {}
537
538impl<S: Schema, Domain> FunctionScalarArgument<S, Domain> for FunctionCall<S, Domain> {
539    fn __function_argument(&self) -> FunctionArgument<S> {
540        FunctionCall::__function_argument(self)
541    }
542}
543
544/// One opaque argument admitted by a nominal generated schema-function wrapper.
545#[doc(hidden)]
546#[derive(Clone, Debug, PartialEq)]
547pub struct FunctionArgument<S: Schema> {
548    nonce: u64,
549    expression: FunctionArgumentExpr,
550    marker: PhantomData<fn() -> S>,
551}
552
553impl<S: Schema> Database<S> {
554    /// Start one owner-branded query authoring session over this
555    /// schema-bound database.
556    pub fn query(&self) -> Result<QuerySession<'_, S>> {
557        self.query_with_resources(
558            QueryExecutionResourceLimits::default(),
559            AnswerCancellation::default(),
560        )
561    }
562
563    /// Start one owner-branded query authoring session with one common
564    /// tighten-only resource policy and caller-owned cancellation signal.
565    pub fn query_with_resources(
566        &self,
567        resources: QueryExecutionResourceLimits,
568        cancellation: AnswerCancellation,
569    ) -> Result<QuerySession<'_, S>> {
570        let registry = self.match_registry().ok_or_else(schema_not_bound)?;
571        let installed = self
572            .installed_schema()
573            .map(Arc::as_ref)
574            .ok_or_else(schema_not_bound)?;
575        Ok(QuerySession::new(
576            installed,
577            Arc::clone(registry),
578            QueryExecution::Local(self),
579            self.operation_limits(resources),
580            cancellation,
581        ))
582    }
583}
584
585impl<'db, S: Schema> QuerySession<'db, S> {
586    fn new(
587        installed: &'db InstalledRuntimeProjection,
588        registry: Arc<DescriptorRegistry>,
589        execution: QueryExecution<'db, S>,
590        resources: QueryExecutionResourceLimits,
591        cancellation: AnswerCancellation,
592    ) -> Self {
593        Self {
594            cancellation,
595            installed,
596            execution,
597            resources: resources.effective(),
598            session: OrmSessionHandle::new(Arc::clone(&registry)),
599            registry,
600            nonce: QUERY_SESSION_NONCE.fetch_add(1, Ordering::Relaxed),
601            bindings: Vec::new(),
602            closed: AtomicBool::new(false),
603            marker: PhantomData,
604        }
605    }
606
607    pub(crate) fn borrowed(
608        installed: &'db InstalledRuntimeProjection,
609        registry: Arc<DescriptorRegistry>,
610        transaction: &'db type_bridge_orm::session::context::TransactionContext,
611        resources: QueryExecutionResourceLimits,
612        cancellation: AnswerCancellation,
613    ) -> Self {
614        Self::new(
615            installed,
616            registry,
617            QueryExecution::Borrowed(transaction),
618            resources,
619            cancellation,
620        )
621    }
622
623    pub(crate) fn remote(
624        installed: &'db InstalledRuntimeProjection,
625        registry: Arc<DescriptorRegistry>,
626        remote: &'db crate::remote::ProxyDatabase<S>,
627        resources: QueryExecutionResourceLimits,
628        cancellation: AnswerCancellation,
629    ) -> Self {
630        Self::new(
631            installed,
632            registry,
633            QueryExecution::Remote(remote),
634            resources,
635            cancellation,
636        )
637    }
638
639    fn begin_invocation(&self) -> Result<QueryExecutionDeadline> {
640        self.ensure_open(ModelValidationPhase::Input)?;
641        let deadline = QueryExecutionDeadline::for_limits(self.resources);
642        self.check_invocation(deadline, ModelValidationPhase::Input)?;
643        Ok(deadline)
644    }
645
646    fn check_invocation(
647        &self,
648        deadline: QueryExecutionDeadline,
649        phase: ModelValidationPhase,
650    ) -> Result<()> {
651        self.ensure_open(phase)?;
652        deadline
653            .check(&self.cancellation)
654            .map_err(|error| Error::from_sdk_execution(error, phase))
655    }
656
657    fn ensure_open(&self, phase: ModelValidationPhase) -> Result<()> {
658        if self.closed.load(Ordering::Acquire) {
659            Err(Error::from_sdk_execution(
660                type_bridge_orm::query_resource_closed_diagnostic(),
661                phase,
662            ))
663        } else {
664            Ok(())
665        }
666    }
667
668    fn uses_successor_projected_materialization(&self) -> bool {
669        self.installed.projection().generator_handlers() == [ProjectionHandler::rust_v2()]
670    }
671
672    fn projected_query_origin(&self) -> Result<ProjectedQueryOrigin> {
673        match &self.execution {
674            QueryExecution::Local(database) => {
675                Ok(ProjectedQueryOrigin::for_database(database.inner_orm()))
676            }
677            QueryExecution::Borrowed(transaction) => {
678                ProjectedQueryOrigin::for_transaction(transaction).map_err(|error| {
679                    Error::from_sdk_execution(error, ModelValidationPhase::Hydration)
680                })
681            }
682            QueryExecution::Remote(_) => Ok(ProjectedQueryOrigin::remote_unbound()),
683        }
684    }
685
686    fn materialize_projected_query_value(
687        &self,
688        validated: &ValidatedMatchRequest,
689        result: &ValidatedMatchResult,
690        deadline: QueryExecutionDeadline,
691    ) -> Result<ProjectedQueryValue> {
692        self.check_invocation(deadline, ModelValidationPhase::Hydration)?;
693        self.projected_query_origin()?
694            .materialize_borrowed_with_budget(
695                self.installed,
696                &self.registry,
697                validated,
698                result,
699                self.resources.projected(),
700                &self.cancellation,
701                Some(deadline),
702            )
703            .map(|(value, _measure)| value)
704            .map_err(|error| Error::from_sdk_execution(error, ModelValidationPhase::Hydration))
705    }
706}
707
708impl<'db, S: Schema> QuerySession<'db, S> {
709    /// Explicitly close this authoring session.
710    ///
711    /// Closing is idempotent. Existing query lineages retain their immutable
712    /// values but reject later composition and execution before provider I/O.
713    pub fn close(&self) {
714        self.closed.store(true, Ordering::Release);
715    }
716
717    /// Return whether this session was explicitly closed.
718    #[must_use]
719    pub fn is_closed(&self) -> bool {
720        self.closed.load(Ordering::Acquire)
721    }
722
723    /// Validate, encode, and execute every query of this session under
724    /// `limits` instead of the canonical query limits.
725    ///
726    /// Call this before creating any binding: bindings belong to the limits
727    /// they were created under. `limits` is admitted by the shared engine,
728    /// so an unsupported value fails here rather than at the first query.
729    pub fn with_query_limits(mut self, limits: QueryLimits) -> Result<Self> {
730        if !self.bindings.is_empty() {
731            return Err(Error::model_validation(
732                ModelValidationPhase::Input,
733                "query_limits_after_binding",
734                vec![],
735                "query limits must be set before the session creates a binding",
736                None,
737            ));
738        }
739        let limits = limits.validate().map_err(|error| {
740            Error::model_validation(
741                ModelValidationPhase::Input,
742                "query_limits_invalid",
743                vec![],
744                error.to_string(),
745                None,
746            )
747        })?;
748        self.session = OrmSessionHandle::with_limits(Arc::clone(&self.registry), limits);
749        Ok(self)
750    }
751
752    fn push_binding<M: ThingModel<Schema = S>, Mode: SelectionMode>(
753        &mut self,
754        handle: OrmBindingHandle,
755    ) -> Result<Binding<S, M, Mode>> {
756        let index = u32::try_from(self.bindings.len()).map_err(|source| {
757            Error::model_validation(
758                ModelValidationPhase::Input,
759                "too_many_bindings",
760                vec![],
761                "query session binding capacity exceeded",
762                Some(Box::new(source)),
763            )
764        })?;
765        self.bindings.push(handle);
766        Ok(Binding {
767            key: BindingKey {
768                nonce: self.nonce,
769                index,
770            },
771            marker: PhantomData,
772        })
773    }
774
775    /// Allocate a fresh exact-match binding for one concrete complete
776    /// generated model. Abstract models have no exact binding constructor.
777    pub fn exact<M>(&mut self) -> Result<Binding<S, M, Exact>>
778    where
779        M: ThingModel<Schema = S> + CompleteModel,
780    {
781        self.ensure_open(ModelValidationPhase::Input)?;
782        let label = model_label(M::TYPE_ID_JSON)?;
783        let handle = self.session.exact(&label).map_err(Error::from_orm)?;
784        self.push_binding(handle)
785    }
786
787    /// Allocate a fresh subtype-inclusive binding for one generated subtype
788    /// root; results materialize as the generated leaf or closed family.
789    pub fn subtypes<M>(&mut self) -> Result<Binding<S, M, Subtypes>>
790    where
791        M: ThingModel<Schema = S> + SubtypeRootModel,
792    {
793        self.ensure_open(ModelValidationPhase::Input)?;
794        let label = model_label(M::TYPE_ID_JSON)?;
795        let handle = self.session.subtypes(&label).map_err(Error::from_orm)?;
796        self.push_binding(handle)
797    }
798
799    pub(crate) fn handle_by_key(&self, key: BindingKey) -> Result<&OrmBindingHandle> {
800        self.ensure_open(ModelValidationPhase::Input)?;
801        if key.nonce != self.nonce {
802            return Err(cross_session_handle());
803        }
804        self.bindings
805            .get(key.index as usize)
806            .ok_or_else(cross_session_handle)
807    }
808
809    /// Brand one generated projected attribute wrapper as a scalar
810    /// schema-function input. Generated packages expose domain-specific
811    /// constructors and keep this generic seam out of their public vocabulary.
812    #[doc(hidden)]
813    pub fn __function_input<Value>(&self, value: &Value) -> Result<FunctionInput<S, Value::Domain>>
814    where
815        Value: Model<Schema = S> + QueryValued,
816    {
817        self.ensure_open(ModelValidationPhase::Input)?;
818        let attribute_type = from_canonical_json::<TypeId>(Value::TYPE_ID_JSON.as_bytes())
819            .map_err(|source| {
820                Error::model_validation(
821                    ModelValidationPhase::Input,
822                    "invalid_function_attribute_identity",
823                    vec!["function".into()],
824                    "generated function input attribute identity is not canonical",
825                    Some(Box::new(source)),
826                )
827            })?;
828        if attribute_type.kind() != TypeKind::Attribute {
829            return Err(Error::model_validation(
830                ModelValidationPhase::Input,
831                "function_input_not_attribute",
832                vec!["function".into()],
833                "generated scalar function input must be a projected attribute wrapper",
834                None,
835            ));
836        }
837        let expression = FunctionInputExpr {
838            attribute_type,
839            value: encoded_query_operand(value.into_encoded_scalar()),
840        };
841        self.lower_function_input(&expression)?;
842        Ok(FunctionInput {
843            nonce: self.nonce,
844            expression,
845            marker: PhantomData,
846        })
847    }
848
849    /// Construct one exact projected scalar function call from a generated
850    /// nominal function token and already session-branded arguments.
851    #[doc(hidden)]
852    pub fn __call_function<Arguments, Output>(
853        &self,
854        function: FunctionToken<S, Arguments, Output>,
855        arguments: impl IntoIterator<Item = FunctionArgument<S>>,
856    ) -> Result<FunctionCall<S, Output>> {
857        self.ensure_open(ModelValidationPhase::Input)?;
858        let arguments = arguments.into_iter().collect::<Vec<_>>();
859        if arguments
860            .iter()
861            .any(|argument| argument.nonce != self.nonce)
862        {
863            return Err(cross_session_handle());
864        }
865        let expression = FunctionCallExpr {
866            function_id: function.__function_id().to_owned(),
867            arguments: arguments
868                .into_iter()
869                .map(|argument| argument.expression)
870                .collect(),
871        };
872        self.lower_function_call(&expression)?;
873        Ok(FunctionCall {
874            nonce: self.nonce,
875            expression,
876            marker: PhantomData,
877        })
878    }
879
880    fn lower_function_input(
881        &self,
882        input: &FunctionInputExpr,
883    ) -> Result<type_bridge_orm::FunctionValueHandle> {
884        let projected = ProjectedAttributeValue::try_from_attribute_value(
885            self.installed,
886            input.attribute_type.clone(),
887            &input.value,
888        )
889        .map_err(|error| Error::from_sdk_execution(error, ModelValidationPhase::Input))?;
890        self.session
891            .function_value(&projected)
892            .map_err(Error::from_orm)
893    }
894
895    fn lower_function_argument(
896        &self,
897        argument: &FunctionArgumentExpr,
898    ) -> Result<OrmFunctionArgumentHandle> {
899        match argument {
900            FunctionArgumentExpr::Binding(binding) => {
901                Ok(self.handle_by_key(*binding)?.function_argument())
902            }
903            FunctionArgumentExpr::Value(value) => {
904                Ok(self.lower_function_input(value)?.function_argument())
905            }
906            FunctionArgumentExpr::Call(call) => {
907                Ok(self.lower_function_call(call)?.function_argument())
908            }
909        }
910    }
911
912    fn lower_function_call(&self, call: &FunctionCallExpr) -> Result<OrmFunctionCallHandle> {
913        let id = FunctionId::new(call.function_id.clone()).map_err(|source| {
914            Error::model_validation(
915                ModelValidationPhase::Input,
916                "invalid_function_identity",
917                vec!["function".into()],
918                "generated function identity is not canonical",
919                Some(Box::new(source)),
920            )
921        })?;
922        let function = self.session.function(&id).map_err(Error::from_orm)?;
923        let arguments = call
924            .arguments
925            .iter()
926            .map(|argument| self.lower_function_argument(argument))
927            .collect::<Result<Vec<_>>>()?;
928        function.call(arguments).map_err(Error::from_orm)
929    }
930
931    fn installed(&self) -> Result<&InstalledRuntimeProjection> {
932        Ok(self.installed)
933    }
934
935    fn field_name_for(&self, owner_label: &str, attribute_label: &str) -> Result<String> {
936        let descriptor = self.registry.get(owner_label).ok_or_else(|| {
937            Error::model_validation(
938                ModelValidationPhase::Input,
939                "unknown_field_owner",
940                vec!["type".into()],
941                format!("field owner '{owner_label}' is not registered in this session"),
942                None,
943            )
944        })?;
945        let found = match &descriptor {
946            TypeDescriptorRef::Entity(entity) => entity
947                .owned_attributes
948                .iter()
949                .find(|attribute| attribute.attr_name == attribute_label)
950                .map(|attribute| attribute.field_name.clone()),
951            TypeDescriptorRef::Relation(relation) => relation
952                .owned_attributes
953                .iter()
954                .find(|attribute| attribute.attr_name == attribute_label)
955                .map(|attribute| attribute.field_name.clone()),
956        };
957        found.ok_or_else(|| {
958            Error::model_validation(
959                ModelValidationPhase::Input,
960                "unknown_field",
961                vec!["type".into()],
962                format!("owner '{owner_label}' has no field for attribute '{attribute_label}'"),
963                None,
964            )
965        })
966    }
967
968    pub(crate) fn lower_field(
969        &self,
970        key: BindingKey,
971        owns_id_json: &'static str,
972    ) -> Result<OrmFieldHandle> {
973        let handle = self.handle_by_key(key)?;
974        let (owner_label, attribute_label) = parse_owns_identity(owns_id_json)?;
975        let field_name = self.field_name_for(&owner_label, &attribute_label)?;
976        handle
977            .field_owned_by(&owner_label, &field_name)
978            .map_err(Error::from_orm)
979    }
980
981    fn lower_order(&self, order: &Order<S>) -> Result<OrmOrderHandle> {
982        let field = self.lower_field(order.key, order.owns_id_json)?;
983        Ok(field.order(order.direction, order.missing))
984    }
985
986    fn lower_predicate(&self, expr: &PredicateExpr) -> Result<OrmPredicateHandle> {
987        match expr {
988            PredicateExpr::FieldValue {
989                binding,
990                owns_id_json,
991                operator,
992                value,
993            } => {
994                let field = self.lower_field(*binding, owns_id_json)?;
995                Ok(field.compare_value(*operator, value.clone()))
996            }
997            PredicateExpr::FieldField {
998                left_binding,
999                left_owns_id_json,
1000                operator,
1001                right_binding,
1002                right_owns_id_json,
1003            } => {
1004                let left = self.lower_field(*left_binding, left_owns_id_json)?;
1005                let right = self.lower_field(*right_binding, right_owns_id_json)?;
1006                left.compare_field(*operator, &right)
1007                    .map_err(Error::from_orm)
1008            }
1009            PredicateExpr::FieldPresence {
1010                binding,
1011                owns_id_json,
1012                present,
1013            } => Ok(self.lower_field(*binding, owns_id_json)?.presence(*present)),
1014            PredicateExpr::FunctionField {
1015                call,
1016                operator,
1017                binding,
1018                owns_id_json,
1019            } => self
1020                .lower_function_call(call)?
1021                .compare_field(*operator, &self.lower_field(*binding, owns_id_json)?)
1022                .map_err(Error::from_orm),
1023            PredicateExpr::FunctionValue {
1024                call,
1025                operator,
1026                value,
1027            } => self
1028                .lower_function_call(call)?
1029                .compare_value(*operator, &self.lower_function_input(value)?)
1030                .map_err(Error::from_orm),
1031            PredicateExpr::FunctionCall {
1032                left,
1033                operator,
1034                right,
1035            } => self
1036                .lower_function_call(left)?
1037                .compare_call(*operator, &self.lower_function_call(right)?)
1038                .map_err(Error::from_orm),
1039            PredicateExpr::BindingIid { binding, iid } => self
1040                .handle_by_key(*binding)?
1041                .iid(iid.clone())
1042                .map_err(Error::from_orm),
1043            PredicateExpr::BindingIidIn { binding, iids } => self
1044                .handle_by_key(*binding)?
1045                .iid_in(iids.clone())
1046                .map_err(Error::from_orm),
1047            PredicateExpr::Connects {
1048                relation,
1049                role_id_json,
1050                player,
1051            } => {
1052                let relation_handle = self.handle_by_key(*relation)?;
1053                let role = parse_role_identity(role_id_json)?;
1054                let role_handle = relation_handle
1055                    .role_owned_by(role.declaring_relation().as_str(), role.label().as_str())
1056                    .map_err(Error::from_orm)?;
1057                let player_handle = self.handle_by_key(*player)?;
1058                role_handle.connects(player_handle).map_err(Error::from_orm)
1059            }
1060            PredicateExpr::Reachable {
1061                relation_type_id_json,
1062                role_from_id_json,
1063                role_to_id_json,
1064                source,
1065                target,
1066                min_depth,
1067                max_depth,
1068            } => {
1069                let relation = model_label(relation_type_id_json)?;
1070                let role_from = parse_role_identity(role_from_id_json)?;
1071                let role_to = parse_role_identity(role_to_id_json)?;
1072                self.session
1073                    .reachable(
1074                        &relation,
1075                        role_from.label().as_str(),
1076                        role_to.label().as_str(),
1077                        self.handle_by_key(*source)?,
1078                        self.handle_by_key(*target)?,
1079                        *min_depth,
1080                        *max_depth,
1081                    )
1082                    .map_err(Error::from_orm)
1083            }
1084            PredicateExpr::And(terms) => self.lower_composed(terms, |left, right| {
1085                left.and(right).map_err(Error::from_orm)
1086            }),
1087            PredicateExpr::Or(terms) => {
1088                self.lower_composed(terms, |left, right| left.or(right).map_err(Error::from_orm))
1089            }
1090            PredicateExpr::Not(inner) => Ok(self.lower_predicate(inner)?.not()),
1091        }
1092    }
1093
1094    fn lower_composed(
1095        &self,
1096        terms: &[PredicateExpr],
1097        combine: impl Fn(&OrmPredicateHandle, &OrmPredicateHandle) -> Result<OrmPredicateHandle>,
1098    ) -> Result<OrmPredicateHandle> {
1099        let mut lowered = terms.iter().map(|term| self.lower_predicate(term));
1100        let mut combined = lowered.next().ok_or_else(|| {
1101            Error::model_validation(
1102                ModelValidationPhase::Input,
1103                "empty_predicate",
1104                vec![],
1105                "boolean composition requires at least one predicate",
1106                None,
1107            )
1108        })??;
1109        for term in lowered {
1110            combined = combine(&combined, &term?)?;
1111        }
1112        Ok(combined)
1113    }
1114
1115    fn client_row_for(&self, thing: &HydratedThing) -> Result<HydratedRow> {
1116        use type_bridge_orm::match_request::model::ThingKind as OrmThingKind;
1117        let installed = self.installed()?;
1118        let type_name = self
1119            .registry
1120            .descriptor_type_name(thing.concrete_descriptor())
1121            .ok_or_else(|| {
1122                Error::model_validation(
1123                    ModelValidationPhase::Hydration,
1124                    "invalid_installed_projection",
1125                    vec!["type".into()],
1126                    "selected concrete descriptor is absent from the installed registry",
1127                    None,
1128                )
1129            })?;
1130        let mut attributes = Vec::new();
1131        for attribute in thing.attributes() {
1132            let provider_name = self
1133                .registry
1134                .provider_attribute_name(attribute.field())
1135                .ok_or_else(|| {
1136                    Error::model_validation(
1137                        ModelValidationPhase::Hydration,
1138                        "invalid_installed_projection",
1139                        vec![],
1140                        "selected field identity has no provider attribute name",
1141                        None,
1142                    )
1143                })?;
1144            for value in attribute.values() {
1145                attributes.push((
1146                    provider_name.clone(),
1147                    canonicalize_selected_value(value.clone())?,
1148                ));
1149            }
1150        }
1151        match thing.kind() {
1152            OrmThingKind::Entity => {
1153                let id = TypeId::new(type_bridge_contract::id::TypeKind::Entity, &type_name)
1154                    .map_err(|source| {
1155                        Error::model_validation(
1156                            ModelValidationPhase::Hydration,
1157                            "invalid_discovered_type",
1158                            vec!["type".into()],
1159                            "selected entity type label is invalid",
1160                            Some(Box::new(source)),
1161                        )
1162                    })?;
1163                hydrate_entity(
1164                    DynamicEntityRow {
1165                        iid: Some(thing.concept_id().as_str().to_owned()),
1166                        type_name: Some(type_name),
1167                        attributes,
1168                    },
1169                    &id,
1170                    installed,
1171                )
1172            }
1173            OrmThingKind::Relation => {
1174                let id = TypeId::new(type_bridge_contract::id::TypeKind::Relation, &type_name)
1175                    .map_err(|source| {
1176                        Error::model_validation(
1177                            ModelValidationPhase::Hydration,
1178                            "invalid_discovered_type",
1179                            vec!["type".into()],
1180                            "selected relation type label is invalid",
1181                            Some(Box::new(source)),
1182                        )
1183                    })?;
1184                let mut role_players = Vec::new();
1185                for role in thing.roles() {
1186                    for player in role.players() {
1187                        let mut raw = Vec::new();
1188                        for attribute in player.attributes() {
1189                            let provider_name = self
1190                                .registry
1191                                .provider_attribute_name(attribute.field())
1192                                .ok_or_else(|| {
1193                                    Error::model_validation(
1194                                        ModelValidationPhase::Hydration,
1195                                        "invalid_installed_projection",
1196                                        vec![],
1197                                        "player field identity has no provider attribute name",
1198                                        None,
1199                                    )
1200                                })?;
1201                            for value in attribute.values() {
1202                                raw.push((
1203                                    provider_name.clone(),
1204                                    plain_json(&canonicalize_selected_value(value.clone())?),
1205                                ));
1206                            }
1207                        }
1208                        let player_type_name = self
1209                            .registry
1210                            .descriptor_type_name(player.concrete_descriptor())
1211                            .ok_or_else(|| {
1212                                Error::model_validation(
1213                                    ModelValidationPhase::Hydration,
1214                                    "invalid_installed_projection",
1215                                    vec!["roles".into(), role.role().name.clone()],
1216                                    "selected role-player descriptor is absent from the installed registry",
1217                                    None,
1218                                )
1219                            })?;
1220                        role_players.push(DynamicRolePlayer {
1221                            role_name: role.role().name.clone(),
1222                            player_iid: Some(player.concept_id().as_str().to_owned()),
1223                            player_type_name: Some(player_type_name),
1224                            attributes: raw,
1225                        });
1226                    }
1227                }
1228                hydrate_relation(
1229                    DynamicRelationRow {
1230                        iid: Some(thing.concept_id().as_str().to_owned()),
1231                        type_name: Some(type_name),
1232                        attributes,
1233                        role_players,
1234                    },
1235                    &id,
1236                    installed,
1237                )
1238            }
1239        }
1240    }
1241
1242    fn client_row_for_projected(&self, thing: &ProjectedThing) -> Result<HydratedRow> {
1243        projected_to_hydrated_row(thing, self.installed()?)
1244    }
1245}
1246
1247fn canonicalize_selected_value(value: AttributeValue) -> Result<AttributeValue> {
1248    let malformed = || {
1249        Error::model_validation(
1250            ModelValidationPhase::Hydration,
1251            "hydrated_attribute_value_type",
1252            vec![],
1253            "selected attribute value is outside its canonical scalar domain",
1254            None,
1255        )
1256    };
1257    match value {
1258        AttributeValue::Date(value) => value
1259            .parse::<CanonicalDate>()
1260            .map(|value| AttributeValue::Date(value.to_string()))
1261            .map_err(|_| malformed()),
1262        AttributeValue::DateTime(value) => normalize_provider_fraction(value)
1263            .parse::<CanonicalDateTime>()
1264            .map(|value| AttributeValue::DateTime(value.to_string()))
1265            .map_err(|_| malformed()),
1266        AttributeValue::DateTimeTZ(value) => normalize_provider_datetime_tz(value)
1267            .parse::<CanonicalDateTimeTz>()
1268            .map(|value| AttributeValue::DateTimeTZ(value.to_string()))
1269            .map_err(|_| malformed()),
1270        AttributeValue::Decimal(value) => parse_decimal(&value)
1271            .map(|value| AttributeValue::Decimal(value.canonical_string()))
1272            .ok_or_else(malformed),
1273        AttributeValue::Duration(value) => {
1274            let value = normalize_provider_fraction(value);
1275            match value.parse::<CanonicalDuration>() {
1276                Ok(value) => Ok(AttributeValue::Duration(value.to_string())),
1277                Err(_) => CompatibilityValueV2::released_duration(value.clone())
1278                    .map(|_| AttributeValue::Duration(value))
1279                    .map_err(|_| malformed()),
1280            }
1281        }
1282        value => Ok(value),
1283    }
1284}
1285
1286fn encoded_group_scalar(value: &AttributeValue) -> Result<EncodedScalar> {
1287    let value = canonicalize_selected_value(value.clone())?;
1288    let map = |error| map_validation_error(error, ModelValidationPhase::Hydration);
1289    match value {
1290        AttributeValue::String(value) => Ok(EncodedScalar::String(value)),
1291        AttributeValue::Long(value) => Ok(EncodedScalar::Long(value)),
1292        AttributeValue::Double(value) => crate::__codegen::CanonicalDouble::try_new(value)
1293            .map(EncodedScalar::Double)
1294            .map_err(map),
1295        AttributeValue::Boolean(value) => Ok(EncodedScalar::Boolean(value)),
1296        AttributeValue::Date(value) => crate::__codegen::Date::try_new(value)
1297            .map(EncodedScalar::Date)
1298            .map_err(map),
1299        AttributeValue::DateTime(value) => crate::__codegen::DateTime::try_new(value)
1300            .map(EncodedScalar::DateTime)
1301            .map_err(map),
1302        AttributeValue::DateTimeTZ(value) => crate::__codegen::DateTimeTz::try_new(value)
1303            .map(EncodedScalar::DateTimeTz)
1304            .map_err(map),
1305        AttributeValue::Decimal(value) => crate::__codegen::Decimal::try_new(value)
1306            .map(EncodedScalar::Decimal)
1307            .map_err(map),
1308        AttributeValue::Duration(value) => crate::__codegen::Duration::try_new(value)
1309            .map(EncodedScalar::Duration)
1310            .map_err(map),
1311    }
1312}
1313
1314fn decoded_projected_reduction_values(values: &[ProjectedReducedValue]) -> Vec<ReducedValue> {
1315    values
1316        .iter()
1317        .map(|value| match value {
1318            ProjectedReducedValue::Count(value) => ReducedValue::Count(*value),
1319            ProjectedReducedValue::Long(value) => ReducedValue::Long(*value),
1320            ProjectedReducedValue::Double(value) => {
1321                ReducedValue::Double(value.map(type_bridge_contract::value::CanonicalDouble::get))
1322            }
1323        })
1324        .collect()
1325}
1326
1327fn normalize_provider_datetime_tz(value: String) -> String {
1328    let mut normalized = normalize_provider_fraction(value);
1329    for zero_offset in ["+00:00:00", "-00:00:00", "+00:00", "-00:00"] {
1330        if normalized.ends_with(zero_offset) {
1331            normalized.truncate(normalized.len() - zero_offset.len());
1332            normalized.push('Z');
1333            break;
1334        }
1335    }
1336    normalized
1337}
1338
1339fn normalize_provider_fraction(value: String) -> String {
1340    let Some(dot) = value.find('.') else {
1341        return value;
1342    };
1343    let fraction_end = value[dot + 1..]
1344        .find(|character: char| !character.is_ascii_digit())
1345        .map_or(value.len(), |offset| dot + 1 + offset);
1346    let trimmed_end = value[dot + 1..fraction_end].trim_end_matches('0').len() + dot + 1;
1347    if trimmed_end == fraction_end {
1348        return value;
1349    }
1350    let mut normalized = String::with_capacity(value.len());
1351    normalized.push_str(
1352        &value[..if trimmed_end == dot + 1 {
1353            dot
1354        } else {
1355            trimmed_end
1356        }],
1357    );
1358    normalized.push_str(&value[fraction_end..]);
1359    normalized
1360}
1361
1362fn plain_json(value: &AttributeValue) -> serde_json::Value {
1363    match value {
1364        AttributeValue::String(value) => serde_json::Value::String(value.clone()),
1365        AttributeValue::Long(value) => serde_json::Value::from(*value),
1366        AttributeValue::Double(value) => {
1367            serde_json::Number::from_f64(*value).map_or(serde_json::Value::Null, Into::into)
1368        }
1369        AttributeValue::Boolean(value) => serde_json::Value::Bool(*value),
1370        AttributeValue::Date(value)
1371        | AttributeValue::DateTime(value)
1372        | AttributeValue::DateTimeTZ(value)
1373        | AttributeValue::Decimal(value)
1374        | AttributeValue::Duration(value) => serde_json::Value::String(value.clone()),
1375    }
1376}
1377
1378/// Sealed conversion from client literals and generated value wrappers into
1379/// canonical query operands.
1380pub trait QueryOperand: operand_sealed::Sealed {
1381    #[doc(hidden)]
1382    type Domain;
1383
1384    #[doc(hidden)]
1385    fn into_operand(self) -> AttributeValue;
1386}
1387
1388/// Sealed marker for canonically ordered query operands.
1389pub trait OrderedOperand: QueryOperand {}
1390
1391mod operand_sealed {
1392    pub trait Sealed {}
1393}
1394
1395macro_rules! operand {
1396    ($ty:ty, $domain:ty, $self_:ident => $convert:expr, ordered: $ordered:tt) => {
1397        impl operand_sealed::Sealed for $ty {}
1398        impl QueryOperand for $ty {
1399            type Domain = $domain;
1400
1401            fn into_operand($self_) -> AttributeValue {
1402                $convert
1403            }
1404        }
1405        operand!(@ordered $ty, $ordered);
1406    };
1407    (@ordered $ty:ty, true) => {
1408        impl OrderedOperand for $ty {}
1409    };
1410    (@ordered $ty:ty, false) => {};
1411}
1412
1413fn encoded_query_operand(value: EncodedScalar) -> AttributeValue {
1414    match value {
1415        EncodedScalar::String(value) => AttributeValue::String(value),
1416        EncodedScalar::Long(value) => AttributeValue::Long(value),
1417        EncodedScalar::Double(value) => AttributeValue::Double(value.get()),
1418        EncodedScalar::Boolean(value) => AttributeValue::Boolean(value),
1419        EncodedScalar::Date(value) => AttributeValue::Date(value.as_str().to_owned()),
1420        EncodedScalar::DateTime(value) => AttributeValue::DateTime(value.as_str().to_owned()),
1421        EncodedScalar::DateTimeTz(value) => AttributeValue::DateTimeTZ(value.as_str().to_owned()),
1422        EncodedScalar::Decimal(value) => AttributeValue::Decimal(value.as_str().to_owned()),
1423        EncodedScalar::Duration(value) => AttributeValue::Duration(value.as_str().to_owned()),
1424    }
1425}
1426
1427impl<T: QueryValued> operand_sealed::Sealed for T {}
1428impl<T: QueryValued> QueryOperand for T {
1429    type Domain = T::Domain;
1430
1431    fn into_operand(self) -> AttributeValue {
1432        encoded_query_operand(self.into_encoded_scalar())
1433    }
1434}
1435
1436impl OrderedOperand for i64 {}
1437
1438operand!(
1439    crate::value::Text,
1440    String,
1441    self => AttributeValue::String(self.into_string()),
1442    ordered: false
1443);
1444operand!(
1445    crate::value::Double,
1446    crate::__codegen::CanonicalDouble,
1447    self => AttributeValue::Double(self.get()),
1448    ordered: true
1449);
1450operand!(
1451    crate::value::Decimal,
1452    crate::__codegen::Decimal,
1453    self => AttributeValue::Decimal(self.into_string()),
1454    ordered: true
1455);
1456operand!(
1457    crate::value::Date,
1458    crate::__codegen::Date,
1459    self => AttributeValue::Date(self.into_string()),
1460    ordered: true
1461);
1462operand!(
1463    crate::value::DateTime,
1464    crate::__codegen::DateTime,
1465    self => AttributeValue::DateTime(self.into_string()),
1466    ordered: true
1467);
1468operand!(
1469    crate::value::DateTimeTz,
1470    crate::__codegen::DateTimeTz,
1471    self => AttributeValue::DateTimeTZ(self.into_string()),
1472    ordered: true
1473);
1474operand!(
1475    crate::value::Duration,
1476    crate::__codegen::Duration,
1477    self => AttributeValue::Duration(self.into_string()),
1478    ordered: true
1479);
1480
1481#[derive(Clone, Debug, PartialEq)]
1482pub(crate) enum PredicateExpr {
1483    FieldValue {
1484        binding: BindingKey,
1485        owns_id_json: &'static str,
1486        operator: ComparisonOp,
1487        value: AttributeValue,
1488    },
1489    FieldField {
1490        left_binding: BindingKey,
1491        left_owns_id_json: &'static str,
1492        operator: ComparisonOp,
1493        right_binding: BindingKey,
1494        right_owns_id_json: &'static str,
1495    },
1496    FieldPresence {
1497        binding: BindingKey,
1498        owns_id_json: &'static str,
1499        present: bool,
1500    },
1501    FunctionField {
1502        call: FunctionCallExpr,
1503        operator: ComparisonOp,
1504        binding: BindingKey,
1505        owns_id_json: &'static str,
1506    },
1507    FunctionValue {
1508        call: FunctionCallExpr,
1509        operator: ComparisonOp,
1510        value: FunctionInputExpr,
1511    },
1512    FunctionCall {
1513        left: FunctionCallExpr,
1514        operator: ComparisonOp,
1515        right: FunctionCallExpr,
1516    },
1517    BindingIid {
1518        binding: BindingKey,
1519        iid: String,
1520    },
1521    BindingIidIn {
1522        binding: BindingKey,
1523        iids: Vec<String>,
1524    },
1525    Connects {
1526        relation: BindingKey,
1527        role_id_json: &'static str,
1528        player: BindingKey,
1529    },
1530    Reachable {
1531        relation_type_id_json: &'static str,
1532        role_from_id_json: &'static str,
1533        role_to_id_json: &'static str,
1534        source: BindingKey,
1535        target: BindingKey,
1536        min_depth: u8,
1537        max_depth: u8,
1538    },
1539    And(Vec<PredicateExpr>),
1540    Or(Vec<PredicateExpr>),
1541    Not(Box<PredicateExpr>),
1542}
1543
1544/// One schema-branded, composable query predicate.
1545///
1546/// Operators are domain-restricted at construction; predicates compose with
1547/// `&`, `|`, and `!` (or the named [`Predicate::and`], [`Predicate::or`],
1548/// and [`Predicate::not`]) and are validated against the owning session
1549/// before any executor invocation.
1550#[derive(Debug, PartialEq)]
1551pub struct Predicate<S: Schema> {
1552    pub(crate) expr: PredicateExpr,
1553    marker: PhantomData<fn() -> S>,
1554}
1555
1556impl<S: Schema> Clone for Predicate<S> {
1557    fn clone(&self) -> Self {
1558        Self {
1559            expr: self.expr.clone(),
1560            marker: PhantomData,
1561        }
1562    }
1563}
1564
1565impl<S: Schema> Predicate<S> {
1566    fn new(expr: PredicateExpr) -> Self {
1567        Self {
1568            expr,
1569            marker: PhantomData,
1570        }
1571    }
1572
1573    /// Conjunction; equivalent to `self & other`.
1574    #[must_use]
1575    pub fn and(self, other: Predicate<S>) -> Predicate<S> {
1576        self & other
1577    }
1578
1579    /// Disjunction; equivalent to `self | other`.
1580    #[must_use]
1581    pub fn or(self, other: Predicate<S>) -> Predicate<S> {
1582        self | other
1583    }
1584
1585    /// Negation; equivalent to `!self`.
1586    #[must_use]
1587    #[allow(clippy::should_implement_trait)]
1588    pub fn not(self) -> Predicate<S> {
1589        !self
1590    }
1591}
1592
1593impl<'db, S: Schema> QuerySession<'db, S> {
1594    /// Require a bounded directed walk between two generated endpoint
1595    /// bindings through one exact generated relation.
1596    ///
1597    /// Each hop follows `role_from -> role_to`. Bounds are inclusive and a
1598    /// zero-hop branch requires identical endpoint concepts. Generated role
1599    /// compatibility and player-union evidence reject inactive roles and
1600    /// invalid endpoint models at compile time; bounds, session ownership,
1601    /// and installed-schema compatibility are validated before provider I/O.
1602    #[allow(clippy::too_many_arguments)]
1603    pub fn reachable<
1604        R,
1605        FromOwner,
1606        FromPlayers,
1607        ToOwner,
1608        ToPlayers,
1609        Source,
1610        SourceMode,
1611        Target,
1612        TargetMode,
1613    >(
1614        &self,
1615        relation: TypeToken<R>,
1616        role_from: RoleToken<FromOwner, FromPlayers>,
1617        role_to: RoleToken<ToOwner, ToPlayers>,
1618        source: Binding<S, Source, SourceMode>,
1619        target: Binding<S, Target, TargetMode>,
1620        min_depth: u8,
1621        max_depth: u8,
1622    ) -> Result<Predicate<S>>
1623    where
1624        R: RelationModel<Schema = S>
1625            + CompleteModel
1626            + RoleTokenCompatible<FromOwner, FromPlayers>
1627            + RoleTokenCompatible<ToOwner, ToPlayers>,
1628        FromOwner: RelationModel<Schema = S>,
1629        ToOwner: RelationModel<Schema = S>,
1630        FromPlayers: RolePlayerBinding<Source, SourceMode>,
1631        ToPlayers: RolePlayerBinding<Target, TargetMode>,
1632        Source: ThingModel<Schema = S>,
1633        SourceMode: SelectionMode,
1634        Target: ThingModel<Schema = S>,
1635        TargetMode: SelectionMode,
1636    {
1637        let predicate = Predicate::new(PredicateExpr::Reachable {
1638            relation_type_id_json: relation.type_id_json(),
1639            role_from_id_json: role_from.role_id_json(),
1640            role_to_id_json: role_to.role_id_json(),
1641            source: source.key,
1642            target: target.key,
1643            min_depth,
1644            max_depth,
1645        });
1646        self.lower_predicate(&predicate.expr)?;
1647        Ok(predicate)
1648    }
1649}
1650
1651impl<S: Schema> std::ops::BitAnd for Predicate<S> {
1652    type Output = Predicate<S>;
1653    fn bitand(self, other: Predicate<S>) -> Predicate<S> {
1654        let mut terms = match self.expr {
1655            PredicateExpr::And(terms) => terms,
1656            expr => vec![expr],
1657        };
1658        match other.expr {
1659            PredicateExpr::And(more) => terms.extend(more),
1660            expr => terms.push(expr),
1661        }
1662        Predicate::new(PredicateExpr::And(terms))
1663    }
1664}
1665
1666impl<S: Schema> std::ops::BitOr for Predicate<S> {
1667    type Output = Predicate<S>;
1668    fn bitor(self, other: Predicate<S>) -> Predicate<S> {
1669        let mut terms = match self.expr {
1670            PredicateExpr::Or(terms) => terms,
1671            expr => vec![expr],
1672        };
1673        match other.expr {
1674            PredicateExpr::Or(more) => terms.extend(more),
1675            expr => terms.push(expr),
1676        }
1677        Predicate::new(PredicateExpr::Or(terms))
1678    }
1679}
1680
1681impl<S: Schema> std::ops::Not for Predicate<S> {
1682    type Output = Predicate<S>;
1683    fn not(self) -> Predicate<S> {
1684        Predicate::new(PredicateExpr::Not(Box::new(self.expr)))
1685    }
1686}
1687
1688/// One generated field resolved against one session binding occurrence.
1689///
1690/// The token retains its declaring owner; owner/binding compatibility is
1691/// enforced against the installed registry when the predicate is lowered,
1692/// before any I/O.
1693pub struct BoundField<S: Schema, Owner: Model<Schema = S>, V> {
1694    key: BindingKey,
1695    owns_id_json: &'static str,
1696    marker: PhantomData<fn() -> (Owner, V)>,
1697}
1698
1699impl<S: Schema, Owner: Model<Schema = S>, V> Copy for BoundField<S, Owner, V> {}
1700impl<S: Schema, Owner: Model<Schema = S>, V> Clone for BoundField<S, Owner, V> {
1701    fn clone(&self) -> Self {
1702        *self
1703    }
1704}
1705
1706impl<S: Schema, M: ThingModel<Schema = S>, Mode: SelectionMode> Binding<S, M, Mode> {
1707    /// Resolve one generated owned field against this binding occurrence.
1708    ///
1709    /// The declaring owner must be this binding's model or a generated
1710    /// nominal ancestor; unrelated same-spelled owners fail to type-check,
1711    /// and the installed registry re-validates the admission at lowering.
1712    #[must_use]
1713    pub fn field<Owner, V>(self, token: FieldToken<Owner, V>) -> BoundField<S, Owner, V>
1714    where
1715        Owner: Model<Schema = S>,
1716        M: crate::__codegen::NominalUpcast<Owner>,
1717    {
1718        BoundField {
1719            key: self.key,
1720            owns_id_json: token.owns_id_json(),
1721            marker: PhantomData,
1722        }
1723    }
1724}
1725
1726impl<S: Schema, M: RelationModel<Schema = S> + ThingModel<Schema = S>, Mode: SelectionMode>
1727    Binding<S, M, Mode>
1728{
1729    /// Resolve one active generated relation role against this relation
1730    /// binding occurrence. Only relation bindings expose roles;
1731    /// specialized-away ancestor tokens have no generated compatibility
1732    /// evidence.
1733    #[must_use]
1734    pub fn role<Owner, Players>(
1735        self,
1736        token: RoleToken<Owner, Players>,
1737    ) -> BoundRole<S, Owner, Players>
1738    where
1739        Owner: RelationModel<Schema = S>,
1740        M: RoleTokenCompatible<Owner, Players>,
1741    {
1742        BoundRole {
1743            key: self.key,
1744            role_id_json: token.role_id_json(),
1745            marker: PhantomData,
1746        }
1747    }
1748}
1749
1750impl<S: Schema, Owner: Model<Schema = S>, V> BoundField<S, Owner, V> {
1751    pub(crate) fn reduction_input(self) -> (BindingKey, &'static str) {
1752        (self.key, self.owns_id_json)
1753    }
1754
1755    fn value_predicate(self, operator: ComparisonOp, value: AttributeValue) -> Predicate<S> {
1756        Predicate::new(PredicateExpr::FieldValue {
1757            binding: self.key,
1758            owns_id_json: self.owns_id_json,
1759            operator,
1760            value,
1761        })
1762    }
1763
1764    /// Equality against a canonical literal of the field's scalar domain.
1765    #[must_use]
1766    pub fn eq<O>(self, operand: O) -> Predicate<S>
1767    where
1768        V: QueryValued,
1769        O: QueryOperand<Domain = V::Domain>,
1770    {
1771        self.value_predicate(ComparisonOp::Equal, operand.into_operand())
1772    }
1773
1774    /// Inequality against a canonical literal of the field's scalar domain.
1775    #[must_use]
1776    pub fn ne<O>(self, operand: O) -> Predicate<S>
1777    where
1778        V: QueryValued,
1779        O: QueryOperand<Domain = V::Domain>,
1780    {
1781        self.value_predicate(ComparisonOp::NotEqual, operand.into_operand())
1782    }
1783
1784    /// Strictly-less ordering against a canonically ordered literal;
1785    /// admitted only for canonically ordered field domains.
1786    #[must_use]
1787    pub fn lt(self, operand: impl OrderedOperand) -> Predicate<S>
1788    where
1789        V: crate::__codegen::OrderedValued,
1790    {
1791        self.value_predicate(ComparisonOp::LessThan, operand.into_operand())
1792    }
1793
1794    /// Less-or-equal ordering against a canonically ordered literal;
1795    /// admitted only for canonically ordered field domains.
1796    #[must_use]
1797    pub fn le(self, operand: impl OrderedOperand) -> Predicate<S>
1798    where
1799        V: crate::__codegen::OrderedValued,
1800    {
1801        self.value_predicate(ComparisonOp::LessThanOrEqual, operand.into_operand())
1802    }
1803
1804    /// Strictly-greater ordering against a canonically ordered literal;
1805    /// admitted only for canonically ordered field domains.
1806    #[must_use]
1807    pub fn gt(self, operand: impl OrderedOperand) -> Predicate<S>
1808    where
1809        V: crate::__codegen::OrderedValued,
1810    {
1811        self.value_predicate(ComparisonOp::GreaterThan, operand.into_operand())
1812    }
1813
1814    /// Greater-or-equal ordering against a canonically ordered literal;
1815    /// admitted only for canonically ordered field domains.
1816    #[must_use]
1817    pub fn ge(self, operand: impl OrderedOperand) -> Predicate<S>
1818    where
1819        V: crate::__codegen::OrderedValued,
1820    {
1821        self.value_predicate(ComparisonOp::GreaterThanOrEqual, operand.into_operand())
1822    }
1823
1824    /// Text containment against bounded canonical text; admitted only for
1825    /// text field domains.
1826    #[must_use]
1827    pub fn contains(self, text: crate::value::Text) -> Predicate<S>
1828    where
1829        V: crate::__codegen::TextValued,
1830    {
1831        self.value_predicate(
1832            ComparisonOp::Contains,
1833            AttributeValue::String(text.into_string()),
1834        )
1835    }
1836
1837    /// Anchored text prefix against bounded canonical text; admitted only
1838    /// for text field domains.
1839    #[must_use]
1840    pub fn starts_with(self, text: crate::value::Text) -> Predicate<S>
1841    where
1842        V: crate::__codegen::TextValued,
1843    {
1844        self.value_predicate(
1845            ComparisonOp::StartsWith,
1846            AttributeValue::String(text.into_string()),
1847        )
1848    }
1849
1850    /// Anchored text suffix against bounded canonical text; admitted only
1851    /// for text field domains.
1852    #[must_use]
1853    pub fn ends_with(self, text: crate::value::Text) -> Predicate<S>
1854    where
1855        V: crate::__codegen::TextValued,
1856    {
1857        self.value_predicate(
1858            ComparisonOp::EndsWith,
1859            AttributeValue::String(text.into_string()),
1860        )
1861    }
1862
1863    /// Regular-expression match against a client-owned validated pattern;
1864    /// admitted only for text field domains.
1865    #[must_use]
1866    pub fn regex(self, pattern: crate::value::Regex) -> Predicate<S>
1867    where
1868        V: crate::__codegen::TextValued,
1869    {
1870        self.value_predicate(
1871            ComparisonOp::Regex,
1872            AttributeValue::String(pattern.into_string()),
1873        )
1874    }
1875
1876    /// Require at least one owned value for this generated field.
1877    #[must_use]
1878    pub fn is_present(self) -> Predicate<S> {
1879        Predicate::new(PredicateExpr::FieldPresence {
1880            binding: self.key,
1881            owns_id_json: self.owns_id_json,
1882            present: true,
1883        })
1884    }
1885
1886    /// Require no owned value for this generated field.
1887    #[must_use]
1888    pub fn is_missing(self) -> Predicate<S> {
1889        Predicate::new(PredicateExpr::FieldPresence {
1890            binding: self.key,
1891            owns_id_json: self.owns_id_json,
1892            present: false,
1893        })
1894    }
1895
1896    fn field_predicate<Owner2, V2>(
1897        self,
1898        operator: ComparisonOp,
1899        other: BoundField<S, Owner2, V2>,
1900    ) -> Predicate<S>
1901    where
1902        Owner2: Model<Schema = S>,
1903    {
1904        Predicate::new(PredicateExpr::FieldField {
1905            left_binding: self.key,
1906            left_owns_id_json: self.owns_id_json,
1907            operator,
1908            right_binding: other.key,
1909            right_owns_id_json: other.owns_id_json,
1910        })
1911    }
1912
1913    /// Compare for equality against another bound field in the same canonical
1914    /// scalar domain; the comparison carries no literal.
1915    #[must_use]
1916    pub fn eq_field<Owner2, V2>(self, other: BoundField<S, Owner2, V2>) -> Predicate<S>
1917    where
1918        Owner2: Model<Schema = S>,
1919        V: QueryValued,
1920        V2: QueryValued<Domain = V::Domain>,
1921    {
1922        self.field_predicate(ComparisonOp::Equal, other)
1923    }
1924
1925    /// Compare for inequality against another bound field in the same
1926    /// canonical scalar domain.
1927    #[must_use]
1928    pub fn ne_field<Owner2, V2>(self, other: BoundField<S, Owner2, V2>) -> Predicate<S>
1929    where
1930        Owner2: Model<Schema = S>,
1931        V: QueryValued,
1932        V2: QueryValued<Domain = V::Domain>,
1933    {
1934        self.field_predicate(ComparisonOp::NotEqual, other)
1935    }
1936
1937    /// Compare as less than another bound field in the same ordered canonical
1938    /// scalar domain.
1939    #[must_use]
1940    pub fn lt_field<Owner2, V2>(self, other: BoundField<S, Owner2, V2>) -> Predicate<S>
1941    where
1942        Owner2: Model<Schema = S>,
1943        V: QueryValued + crate::__codegen::OrderedValued,
1944        V2: QueryValued<Domain = V::Domain> + crate::__codegen::OrderedValued,
1945    {
1946        self.field_predicate(ComparisonOp::LessThan, other)
1947    }
1948
1949    /// Compare as less than or equal to another bound field in the same
1950    /// ordered canonical scalar domain.
1951    #[must_use]
1952    pub fn le_field<Owner2, V2>(self, other: BoundField<S, Owner2, V2>) -> Predicate<S>
1953    where
1954        Owner2: Model<Schema = S>,
1955        V: QueryValued + crate::__codegen::OrderedValued,
1956        V2: QueryValued<Domain = V::Domain> + crate::__codegen::OrderedValued,
1957    {
1958        self.field_predicate(ComparisonOp::LessThanOrEqual, other)
1959    }
1960
1961    /// Compare as greater than another bound field in the same ordered
1962    /// canonical scalar domain.
1963    #[must_use]
1964    pub fn gt_field<Owner2, V2>(self, other: BoundField<S, Owner2, V2>) -> Predicate<S>
1965    where
1966        Owner2: Model<Schema = S>,
1967        V: QueryValued + crate::__codegen::OrderedValued,
1968        V2: QueryValued<Domain = V::Domain> + crate::__codegen::OrderedValued,
1969    {
1970        self.field_predicate(ComparisonOp::GreaterThan, other)
1971    }
1972
1973    /// Compare as greater than or equal to another bound field in the same
1974    /// ordered canonical scalar domain.
1975    #[must_use]
1976    pub fn ge_field<Owner2, V2>(self, other: BoundField<S, Owner2, V2>) -> Predicate<S>
1977    where
1978        Owner2: Model<Schema = S>,
1979        V: QueryValued + crate::__codegen::OrderedValued,
1980        V2: QueryValued<Domain = V::Domain> + crate::__codegen::OrderedValued,
1981    {
1982        self.field_predicate(ComparisonOp::GreaterThanOrEqual, other)
1983    }
1984
1985    /// Order ascending by this bound field; missing keys fail closed unless
1986    /// an explicit missing-value policy is admitted.
1987    #[must_use]
1988    pub fn asc(self) -> Order<S> {
1989        Order {
1990            key: self.key,
1991            owns_id_json: self.owns_id_json,
1992            direction: SortDirection::Ascending,
1993            missing: MissingOrder::Reject,
1994            marker: PhantomData,
1995        }
1996    }
1997
1998    /// Order descending by this bound field; missing keys fail closed unless
1999    /// an explicit missing-value policy is admitted.
2000    #[must_use]
2001    pub fn desc(self) -> Order<S> {
2002        Order {
2003            key: self.key,
2004            owns_id_json: self.owns_id_json,
2005            direction: SortDirection::Descending,
2006            missing: MissingOrder::Reject,
2007            marker: PhantomData,
2008        }
2009    }
2010}
2011
2012/// One stable public ordering term over a bound field.
2013#[derive(Debug)]
2014pub struct Order<S: Schema> {
2015    key: BindingKey,
2016    owns_id_json: &'static str,
2017    direction: SortDirection,
2018    missing: MissingOrder,
2019    marker: PhantomData<fn() -> S>,
2020}
2021
2022impl<S: Schema> Copy for Order<S> {}
2023impl<S: Schema> Clone for Order<S> {
2024    fn clone(&self) -> Self {
2025        *self
2026    }
2027}
2028
2029impl<S: Schema> Order<S> {
2030    /// Admit missing keys and place them before all present keys.
2031    #[must_use]
2032    pub fn missing_first(mut self) -> Self {
2033        self.missing = MissingOrder::First;
2034        self
2035    }
2036
2037    /// Admit missing keys and place them after all present keys.
2038    #[must_use]
2039    pub fn missing_last(mut self) -> Self {
2040        self.missing = MissingOrder::Last;
2041        self
2042    }
2043}
2044
2045/// One typed collection selection used inside a distinct-root page shape.
2046pub struct Collected<S: Schema, B: Selectable<S>> {
2047    selection: B,
2048    distinct: bool,
2049    order: Vec<Order<S>>,
2050}
2051
2052impl<S: Schema, B: Selectable<S>> Clone for Collected<S, B> {
2053    fn clone(&self) -> Self {
2054        Self {
2055            selection: self.selection,
2056            distinct: self.distinct,
2057            order: self.order.clone(),
2058        }
2059    }
2060}
2061
2062impl<S: Schema, B: Selectable<S>> Collected<S, B> {
2063    /// Deduplicate collection members by TypeDB concept identity.
2064    #[must_use]
2065    pub fn distinct(mut self) -> Self {
2066        self.distinct = true;
2067        self
2068    }
2069
2070    /// Append one stable order term owned by this collected binding.
2071    pub fn order_by(mut self, order: Order<S>) -> Result<Self> {
2072        if order.key != self.selection.binding_key() {
2073            return Err(Error::model_validation(
2074                ModelValidationPhase::Input,
2075                "collection_order_binding_mismatch",
2076                vec![],
2077                "collection ordering must reference the collected binding",
2078                None,
2079            ));
2080        }
2081        self.order.push(order);
2082        Ok(self)
2083    }
2084}
2085
2086/// One generated relation role resolved against one relation binding
2087/// occurrence.
2088pub struct BoundRole<S: Schema, Owner: Model<Schema = S>, Players> {
2089    key: BindingKey,
2090    role_id_json: &'static str,
2091    marker: PhantomData<fn() -> (Owner, Players)>,
2092}
2093
2094impl<S: Schema, Owner: Model<Schema = S>, Players> Copy for BoundRole<S, Owner, Players> {}
2095impl<S: Schema, Owner: Model<Schema = S>, Players> Clone for BoundRole<S, Owner, Players> {
2096    fn clone(&self) -> Self {
2097        *self
2098    }
2099}
2100
2101impl<S: Schema, Owner: Model<Schema = S>, Players> BoundRole<S, Owner, Players> {
2102    /// Require this relation role to connect an admitted generated player
2103    /// binding.
2104    #[must_use]
2105    pub fn connects<MP: ThingModel<Schema = S>, ModeP: SelectionMode>(
2106        self,
2107        player: Binding<S, MP, ModeP>,
2108    ) -> Predicate<S>
2109    where
2110        Players: RolePlayerBinding<MP, ModeP>,
2111    {
2112        Predicate::new(PredicateExpr::Connects {
2113            relation: self.key,
2114            role_id_json: self.role_id_json,
2115            player: player.key,
2116        })
2117    }
2118}
2119
2120mod selectable_sealed {
2121    pub trait Sealed {}
2122}
2123
2124/// Sealed resolution from one selected binding to its typed query output.
2125pub trait Selectable<S: Schema>: selectable_sealed::Sealed + Copy {
2126    /// The materialized output type for one selected row.
2127    type Output;
2128    #[doc(hidden)]
2129    fn binding_key(self) -> BindingKey;
2130    #[doc(hidden)]
2131    fn materialize_output(row: &HydratedRow) -> std::result::Result<Self::Output, ValidationError>;
2132
2133    #[doc(hidden)]
2134    fn __materialize_projected_output(
2135        session: &QuerySession<'_, S>,
2136        thing: &ProjectedThing,
2137    ) -> Result<Self::Output> {
2138        let row = session.client_row_for_projected(thing)?;
2139        Self::materialize_output(&row)
2140            .map_err(|error| map_validation_error(error, ModelValidationPhase::Hydration))
2141    }
2142
2143    #[doc(hidden)]
2144    fn __selection_handle(self, session: &QuerySession<'_, S>) -> Result<OrmSelectionHandle> {
2145        Ok(session.handle_by_key(self.binding_key())?.one())
2146    }
2147
2148    #[doc(hidden)]
2149    fn __materialize_slot(
2150        self,
2151        session: &QuerySession<'_, S>,
2152        slot: &SlotValue,
2153    ) -> Result<Self::Output> {
2154        let SlotValue::One(thing) = slot else {
2155            return Err(Error::model_validation(
2156                ModelValidationPhase::Hydration,
2157                "wrong_result_shape",
2158                vec![],
2159                "provider returned a collection slot for a singular selection",
2160                None,
2161            ));
2162        };
2163        let row = session.client_row_for(thing)?;
2164        Self::materialize_output(&row)
2165            .map_err(|error| map_validation_error(error, ModelValidationPhase::Hydration))
2166    }
2167
2168    #[doc(hidden)]
2169    fn __materialize_slot_with_checkpoint(
2170        self,
2171        session: &QuerySession<'_, S>,
2172        slot: &SlotValue,
2173        checkpoint: &dyn Fn() -> Result<()>,
2174    ) -> Result<Self::Output> {
2175        checkpoint()?;
2176        let output = self.__materialize_slot(session, slot)?;
2177        checkpoint()?;
2178        Ok(output)
2179    }
2180}
2181
2182impl<S: Schema, M: ThingModel<Schema = S> + CompleteModel> selectable_sealed::Sealed
2183    for Binding<S, M, Exact>
2184{
2185}
2186impl<S: Schema, M: ThingModel<Schema = S> + CompleteModel> Selectable<S> for Binding<S, M, Exact> {
2187    type Output = M;
2188    fn binding_key(self) -> BindingKey {
2189        self.key()
2190    }
2191    fn materialize_output(row: &HydratedRow) -> std::result::Result<M, ValidationError> {
2192        M::materialize(row, &HydrationCapability::new())
2193    }
2194}
2195
2196impl<S: Schema, M: ThingModel<Schema = S> + SubtypeRootModel> selectable_sealed::Sealed
2197    for Binding<S, M, Subtypes>
2198{
2199}
2200impl<S: Schema, M: ThingModel<Schema = S> + SubtypeRootModel> Selectable<S>
2201    for Binding<S, M, Subtypes>
2202{
2203    type Output = M::Subtypes;
2204    fn binding_key(self) -> BindingKey {
2205        self.key()
2206    }
2207    fn materialize_output(row: &HydratedRow) -> std::result::Result<M::Subtypes, ValidationError> {
2208        M::__tb_dispatch_subtype(row, &HydrationCapability::new())
2209    }
2210}
2211
2212mod selected_slot_sealed {
2213    pub trait Sealed<S> {}
2214}
2215
2216/// Sealed resolution from one singular or collected selection to its typed
2217/// slot output.
2218#[doc(hidden)]
2219pub trait SelectedSlot<S: Schema>: selected_slot_sealed::Sealed<S> + Clone {
2220    type Output;
2221
2222    fn __selection_handle(&self, session: &QuerySession<'_, S>) -> Result<OrmSelectionHandle>;
2223
2224    fn __materialize_slot(
2225        &self,
2226        session: &QuerySession<'_, S>,
2227        slot: &SlotValue,
2228    ) -> Result<Self::Output>;
2229
2230    #[doc(hidden)]
2231    fn __materialize_projected_slot(
2232        &self,
2233        session: &QuerySession<'_, S>,
2234        slot: &ProjectedQuerySlotValue,
2235    ) -> Result<Self::Output>;
2236
2237    #[doc(hidden)]
2238    fn __materialize_slot_with_checkpoint(
2239        &self,
2240        session: &QuerySession<'_, S>,
2241        slot: &SlotValue,
2242        checkpoint: &dyn Fn() -> Result<()>,
2243    ) -> Result<Self::Output> {
2244        checkpoint()?;
2245        let output = self.__materialize_slot(session, slot)?;
2246        checkpoint()?;
2247        Ok(output)
2248    }
2249
2250    #[doc(hidden)]
2251    fn __materialize_projected_slot_with_checkpoint(
2252        &self,
2253        session: &QuerySession<'_, S>,
2254        slot: &ProjectedQuerySlotValue,
2255        checkpoint: &dyn Fn() -> Result<()>,
2256    ) -> Result<Self::Output> {
2257        checkpoint()?;
2258        let output = self.__materialize_projected_slot(session, slot)?;
2259        checkpoint()?;
2260        Ok(output)
2261    }
2262}
2263
2264impl<S: Schema, B: Selectable<S>> selected_slot_sealed::Sealed<S> for B {}
2265impl<S: Schema, B: Selectable<S>> SelectedSlot<S> for B {
2266    type Output = B::Output;
2267
2268    fn __selection_handle(&self, session: &QuerySession<'_, S>) -> Result<OrmSelectionHandle> {
2269        (*self).__selection_handle(session)
2270    }
2271
2272    fn __materialize_slot(
2273        &self,
2274        session: &QuerySession<'_, S>,
2275        slot: &SlotValue,
2276    ) -> Result<Self::Output> {
2277        (*self).__materialize_slot(session, slot)
2278    }
2279
2280    fn __materialize_projected_slot(
2281        &self,
2282        session: &QuerySession<'_, S>,
2283        slot: &ProjectedQuerySlotValue,
2284    ) -> Result<Self::Output> {
2285        let ProjectedQuerySlotValue::One(thing) = slot else {
2286            return Err(Error::model_validation(
2287                ModelValidationPhase::Hydration,
2288                "wrong_result_shape",
2289                vec![],
2290                "provider returned a collection slot for a singular selection",
2291                None,
2292            ));
2293        };
2294        B::__materialize_projected_output(session, thing)
2295    }
2296
2297    fn __materialize_slot_with_checkpoint(
2298        &self,
2299        session: &QuerySession<'_, S>,
2300        slot: &SlotValue,
2301        checkpoint: &dyn Fn() -> Result<()>,
2302    ) -> Result<Self::Output> {
2303        (*self).__materialize_slot_with_checkpoint(session, slot, checkpoint)
2304    }
2305
2306    fn __materialize_projected_slot_with_checkpoint(
2307        &self,
2308        session: &QuerySession<'_, S>,
2309        slot: &ProjectedQuerySlotValue,
2310        checkpoint: &dyn Fn() -> Result<()>,
2311    ) -> Result<Self::Output> {
2312        checkpoint()?;
2313        let output = self.__materialize_projected_slot(session, slot)?;
2314        checkpoint()?;
2315        Ok(output)
2316    }
2317}
2318
2319impl<S: Schema, B: Selectable<S>> selected_slot_sealed::Sealed<S> for Collected<S, B> {}
2320impl<S: Schema, B: Selectable<S>> SelectedSlot<S> for Collected<S, B> {
2321    type Output = Vec<B::Output>;
2322
2323    fn __selection_handle(&self, session: &QuerySession<'_, S>) -> Result<OrmSelectionHandle> {
2324        let binding = session.handle_by_key(self.selection.binding_key())?;
2325        let mut selection = binding
2326            .collect()
2327            .distinct(self.distinct)
2328            .map_err(Error::from_orm)?;
2329        for order in &self.order {
2330            selection = selection
2331                .order_by(session.lower_order(order)?)
2332                .map_err(Error::from_orm)?;
2333        }
2334        Ok(selection)
2335    }
2336
2337    fn __materialize_slot(
2338        &self,
2339        session: &QuerySession<'_, S>,
2340        slot: &SlotValue,
2341    ) -> Result<Self::Output> {
2342        let SlotValue::Many(things) = slot else {
2343            return Err(Error::model_validation(
2344                ModelValidationPhase::Hydration,
2345                "wrong_result_shape",
2346                vec![],
2347                "provider returned a singular slot for a collection selection",
2348                None,
2349            ));
2350        };
2351        let mut outputs = Vec::with_capacity(things.len());
2352        for thing in things {
2353            let row = session.client_row_for(thing)?;
2354            outputs.push(
2355                B::materialize_output(&row).map_err(|error| {
2356                    map_validation_error(error, ModelValidationPhase::Hydration)
2357                })?,
2358            );
2359        }
2360        Ok(outputs)
2361    }
2362
2363    fn __materialize_projected_slot(
2364        &self,
2365        session: &QuerySession<'_, S>,
2366        slot: &ProjectedQuerySlotValue,
2367    ) -> Result<Self::Output> {
2368        let ProjectedQuerySlotValue::Many(things) = slot else {
2369            return Err(Error::model_validation(
2370                ModelValidationPhase::Hydration,
2371                "wrong_result_shape",
2372                vec![],
2373                "provider returned a singular slot for a collection selection",
2374                None,
2375            ));
2376        };
2377        things
2378            .iter()
2379            .map(|thing| B::__materialize_projected_output(session, thing))
2380            .collect()
2381    }
2382
2383    fn __materialize_slot_with_checkpoint(
2384        &self,
2385        session: &QuerySession<'_, S>,
2386        slot: &SlotValue,
2387        checkpoint: &dyn Fn() -> Result<()>,
2388    ) -> Result<Self::Output> {
2389        let SlotValue::Many(things) = slot else {
2390            return Err(Error::model_validation(
2391                ModelValidationPhase::Hydration,
2392                "wrong_result_shape",
2393                vec![],
2394                "provider returned a singular slot for a collection selection",
2395                None,
2396            ));
2397        };
2398        checkpoint()?;
2399        let mut outputs = Vec::with_capacity(things.len());
2400        for thing in things {
2401            checkpoint()?;
2402            let row = session.client_row_for(thing)?;
2403            outputs.push(
2404                B::materialize_output(&row).map_err(|error| {
2405                    map_validation_error(error, ModelValidationPhase::Hydration)
2406                })?,
2407            );
2408        }
2409        checkpoint()?;
2410        Ok(outputs)
2411    }
2412
2413    fn __materialize_projected_slot_with_checkpoint(
2414        &self,
2415        session: &QuerySession<'_, S>,
2416        slot: &ProjectedQuerySlotValue,
2417        checkpoint: &dyn Fn() -> Result<()>,
2418    ) -> Result<Self::Output> {
2419        let ProjectedQuerySlotValue::Many(things) = slot else {
2420            return Err(Error::model_validation(
2421                ModelValidationPhase::Hydration,
2422                "wrong_result_shape",
2423                vec![],
2424                "provider returned a singular slot for a collection selection",
2425                None,
2426            ));
2427        };
2428        checkpoint()?;
2429        let mut outputs = Vec::with_capacity(things.len());
2430        for thing in things {
2431            checkpoint()?;
2432            outputs.push(B::__materialize_projected_output(session, thing)?);
2433        }
2434        checkpoint()?;
2435        Ok(outputs)
2436    }
2437}
2438
2439mod selected_shape_sealed {
2440    pub trait Sealed<S> {}
2441}
2442
2443/// Sealed typed selected-output shape accepted by the one query facade.
2444///
2445/// Implementations are supplied for one binding, positional tuples through
2446/// the canonical sixteen-slot ceiling, and derive-backed named rows.
2447pub trait SelectedShape<S: Schema>: selected_shape_sealed::Sealed<S> + Clone {
2448    /// One fully materialized public row.
2449    type Output;
2450
2451    #[doc(hidden)]
2452    fn __shape_handle(&self, session: &QuerySession<'_, S>) -> Result<OrmShapeHandle>;
2453
2454    #[doc(hidden)]
2455    fn __materialize_row(
2456        &self,
2457        session: &QuerySession<'_, S>,
2458        row: &MatchRow,
2459    ) -> Result<Self::Output>;
2460
2461    #[doc(hidden)]
2462    fn __materialize_projected_row(
2463        &self,
2464        session: &QuerySession<'_, S>,
2465        row: &ProjectedQueryRow,
2466    ) -> Result<Self::Output>;
2467
2468    #[doc(hidden)]
2469    fn __materialize_row_with_checkpoint(
2470        &self,
2471        session: &QuerySession<'_, S>,
2472        row: &MatchRow,
2473        checkpoint: &dyn Fn() -> Result<()>,
2474    ) -> Result<Self::Output> {
2475        checkpoint()?;
2476        let output = self.__materialize_row(session, row)?;
2477        checkpoint()?;
2478        Ok(output)
2479    }
2480
2481    #[doc(hidden)]
2482    fn __materialize_projected_row_with_checkpoint(
2483        &self,
2484        session: &QuerySession<'_, S>,
2485        row: &ProjectedQueryRow,
2486        checkpoint: &dyn Fn() -> Result<()>,
2487    ) -> Result<Self::Output> {
2488        checkpoint()?;
2489        let output = self.__materialize_projected_row(session, row)?;
2490        checkpoint()?;
2491        Ok(output)
2492    }
2493}
2494
2495impl<S: Schema, B: Selectable<S>> selected_shape_sealed::Sealed<S> for B {}
2496impl<S: Schema, B: Selectable<S>> SelectedShape<S> for B {
2497    type Output = B::Output;
2498
2499    fn __shape_handle(&self, session: &QuerySession<'_, S>) -> Result<OrmShapeHandle> {
2500        session
2501            .session
2502            .positional([SelectedSlot::__selection_handle(self, session)?])
2503            .map_err(Error::from_orm)
2504    }
2505
2506    fn __materialize_row(
2507        &self,
2508        session: &QuerySession<'_, S>,
2509        row: &MatchRow,
2510    ) -> Result<Self::Output> {
2511        let [slot] = row.slots() else {
2512            return Err(selected_shape_arity_error(1, row.slots().len()));
2513        };
2514        SelectedSlot::__materialize_slot(self, session, slot)
2515    }
2516
2517    fn __materialize_projected_row(
2518        &self,
2519        session: &QuerySession<'_, S>,
2520        row: &ProjectedQueryRow,
2521    ) -> Result<Self::Output> {
2522        let [slot] = row.slots() else {
2523            return Err(selected_shape_arity_error(1, row.slots().len()));
2524        };
2525        SelectedSlot::__materialize_projected_slot(self, session, slot.value())
2526    }
2527}
2528
2529impl<S: Schema, B: Selectable<S>> selected_shape_sealed::Sealed<S> for Collected<S, B> {}
2530impl<S: Schema, B: Selectable<S>> SelectedShape<S> for Collected<S, B> {
2531    type Output = Vec<B::Output>;
2532
2533    fn __shape_handle(&self, session: &QuerySession<'_, S>) -> Result<OrmShapeHandle> {
2534        session
2535            .session
2536            .positional([SelectedSlot::__selection_handle(self, session)?])
2537            .map_err(Error::from_orm)
2538    }
2539
2540    fn __materialize_row(
2541        &self,
2542        session: &QuerySession<'_, S>,
2543        row: &MatchRow,
2544    ) -> Result<Self::Output> {
2545        let [slot] = row.slots() else {
2546            return Err(selected_shape_arity_error(1, row.slots().len()));
2547        };
2548        SelectedSlot::__materialize_slot(self, session, slot)
2549    }
2550
2551    fn __materialize_projected_row(
2552        &self,
2553        session: &QuerySession<'_, S>,
2554        row: &ProjectedQueryRow,
2555    ) -> Result<Self::Output> {
2556        let [slot] = row.slots() else {
2557            return Err(selected_shape_arity_error(1, row.slots().len()));
2558        };
2559        SelectedSlot::__materialize_projected_slot(self, session, slot.value())
2560    }
2561
2562    fn __materialize_row_with_checkpoint(
2563        &self,
2564        session: &QuerySession<'_, S>,
2565        row: &MatchRow,
2566        checkpoint: &dyn Fn() -> Result<()>,
2567    ) -> Result<Self::Output> {
2568        let [slot] = row.slots() else {
2569            return Err(selected_shape_arity_error(1, row.slots().len()));
2570        };
2571        SelectedSlot::__materialize_slot_with_checkpoint(self, session, slot, checkpoint)
2572    }
2573
2574    fn __materialize_projected_row_with_checkpoint(
2575        &self,
2576        session: &QuerySession<'_, S>,
2577        row: &ProjectedQueryRow,
2578        checkpoint: &dyn Fn() -> Result<()>,
2579    ) -> Result<Self::Output> {
2580        let [slot] = row.slots() else {
2581            return Err(selected_shape_arity_error(1, row.slots().len()));
2582        };
2583        SelectedSlot::__materialize_projected_slot_with_checkpoint(
2584            self,
2585            session,
2586            slot.value(),
2587            checkpoint,
2588        )
2589    }
2590}
2591
2592mod singular_selected_shape_sealed {
2593    pub trait Sealed<S> {}
2594}
2595
2596/// Sealed marker for a selected shape containing singular slots only.
2597pub trait SingularSelectedShape<S: Schema>:
2598    SelectedShape<S> + singular_selected_shape_sealed::Sealed<S>
2599{
2600}
2601
2602impl<S: Schema, B: Selectable<S>> singular_selected_shape_sealed::Sealed<S> for B {}
2603impl<S: Schema, B: Selectable<S>> SingularSelectedShape<S> for B {}
2604
2605#[doc(hidden)]
2606pub trait SelectedTuple<S: Schema>: Clone {
2607    const ARITY: usize;
2608
2609    type Output;
2610
2611    fn __selection_handles(&self, session: &QuerySession<'_, S>)
2612    -> Result<Vec<OrmSelectionHandle>>;
2613
2614    fn __materialize_slots(
2615        &self,
2616        session: &QuerySession<'_, S>,
2617        slots: &[SlotValue],
2618    ) -> Result<Self::Output>;
2619
2620    #[doc(hidden)]
2621    fn __materialize_projected_slots(
2622        &self,
2623        session: &QuerySession<'_, S>,
2624        slots: &[type_bridge_orm::ProjectedQuerySlot],
2625    ) -> Result<Self::Output>;
2626
2627    #[doc(hidden)]
2628    fn __materialize_slots_with_checkpoint(
2629        &self,
2630        session: &QuerySession<'_, S>,
2631        slots: &[SlotValue],
2632        checkpoint: &dyn Fn() -> Result<()>,
2633    ) -> Result<Self::Output> {
2634        checkpoint()?;
2635        let output = self.__materialize_slots(session, slots)?;
2636        checkpoint()?;
2637        Ok(output)
2638    }
2639
2640    #[doc(hidden)]
2641    fn __materialize_projected_slots_with_checkpoint(
2642        &self,
2643        session: &QuerySession<'_, S>,
2644        slots: &[type_bridge_orm::ProjectedQuerySlot],
2645        checkpoint: &dyn Fn() -> Result<()>,
2646    ) -> Result<Self::Output> {
2647        checkpoint()?;
2648        let output = self.__materialize_projected_slots(session, slots)?;
2649        checkpoint()?;
2650        Ok(output)
2651    }
2652}
2653
2654#[doc(hidden)]
2655pub trait SingularSelectedTuple<S: Schema>: SelectedTuple<S> {}
2656
2657macro_rules! selected_tuple {
2658    ($length:literal; $(($type:ident, $index:tt)),+ $(,)?) => {
2659        impl<S: Schema, $($type: SelectedSlot<S>),+> SelectedTuple<S> for ($($type,)+) {
2660            const ARITY: usize = $length;
2661
2662            type Output = ($(<$type as SelectedSlot<S>>::Output,)+);
2663
2664            fn __selection_handles(
2665                &self,
2666                session: &QuerySession<'_, S>,
2667            ) -> Result<Vec<OrmSelectionHandle>> {
2668                Ok(vec![$(SelectedSlot::__selection_handle(&self.$index, session)?),+])
2669            }
2670
2671            fn __materialize_slots(
2672                &self,
2673                session: &QuerySession<'_, S>,
2674                slots: &[SlotValue],
2675            ) -> Result<Self::Output> {
2676                let slots: &[SlotValue; $length] = slots
2677                    .try_into()
2678                    .map_err(|_| selected_shape_arity_error($length, slots.len()))?;
2679                Ok(($(SelectedSlot::__materialize_slot(
2680                    &self.$index,
2681                    session,
2682                    &slots[$index],
2683                )?,)+))
2684            }
2685
2686            fn __materialize_projected_slots(
2687                &self,
2688                session: &QuerySession<'_, S>,
2689                slots: &[type_bridge_orm::ProjectedQuerySlot],
2690            ) -> Result<Self::Output> {
2691                let slots: &[type_bridge_orm::ProjectedQuerySlot; $length] = slots
2692                    .try_into()
2693                    .map_err(|_| selected_shape_arity_error($length, slots.len()))?;
2694                Ok(($(SelectedSlot::__materialize_projected_slot(
2695                    &self.$index,
2696                    session,
2697                    slots[$index].value(),
2698                )?,)+))
2699            }
2700
2701            fn __materialize_slots_with_checkpoint(
2702                &self,
2703                session: &QuerySession<'_, S>,
2704                slots: &[SlotValue],
2705                checkpoint: &dyn Fn() -> Result<()>,
2706            ) -> Result<Self::Output> {
2707                let slots: &[SlotValue; $length] = slots
2708                    .try_into()
2709                    .map_err(|_| selected_shape_arity_error($length, slots.len()))?;
2710                Ok(($(SelectedSlot::__materialize_slot_with_checkpoint(
2711                    &self.$index,
2712                    session,
2713                    &slots[$index],
2714                    checkpoint,
2715                )?,)+))
2716            }
2717
2718
2719            fn __materialize_projected_slots_with_checkpoint(
2720                &self,
2721                session: &QuerySession<'_, S>,
2722                slots: &[type_bridge_orm::ProjectedQuerySlot],
2723                checkpoint: &dyn Fn() -> Result<()>,
2724            ) -> Result<Self::Output> {
2725                let slots: &[type_bridge_orm::ProjectedQuerySlot; $length] = slots
2726                    .try_into()
2727                    .map_err(|_| selected_shape_arity_error($length, slots.len()))?;
2728                Ok(($(SelectedSlot::__materialize_projected_slot_with_checkpoint(
2729                    &self.$index,
2730                    session,
2731                    slots[$index].value(),
2732                    checkpoint,
2733                )?,)+))
2734            }
2735        }
2736
2737        impl<S: Schema, $($type: SelectedSlot<S>),+> selected_shape_sealed::Sealed<S>
2738            for ($($type,)+)
2739        {
2740        }
2741
2742        impl<S: Schema, $($type: SelectedSlot<S>),+> SelectedShape<S> for ($($type,)+) {
2743            type Output = <Self as SelectedTuple<S>>::Output;
2744
2745            fn __shape_handle(
2746                &self,
2747                session: &QuerySession<'_, S>,
2748            ) -> Result<OrmShapeHandle> {
2749                session
2750                    .session
2751                    .positional(self.__selection_handles(session)?)
2752                    .map_err(Error::from_orm)
2753            }
2754
2755            fn __materialize_row(
2756                &self,
2757                session: &QuerySession<'_, S>,
2758                row: &MatchRow,
2759            ) -> Result<Self::Output> {
2760                self.__materialize_slots(session, row.slots())
2761            }
2762
2763            fn __materialize_projected_row(
2764                &self,
2765                session: &QuerySession<'_, S>,
2766                row: &ProjectedQueryRow,
2767            ) -> Result<Self::Output> {
2768                self.__materialize_projected_slots(session, row.slots())
2769            }
2770
2771
2772            fn __materialize_row_with_checkpoint(
2773                &self,
2774                session: &QuerySession<'_, S>,
2775                row: &MatchRow,
2776                checkpoint: &dyn Fn() -> Result<()>,
2777            ) -> Result<Self::Output> {
2778                self.__materialize_slots_with_checkpoint(session, row.slots(), checkpoint)
2779            }
2780
2781
2782            fn __materialize_projected_row_with_checkpoint(
2783                &self,
2784                session: &QuerySession<'_, S>,
2785                row: &ProjectedQueryRow,
2786                checkpoint: &dyn Fn() -> Result<()>,
2787            ) -> Result<Self::Output> {
2788                self.__materialize_projected_slots_with_checkpoint(
2789                    session,
2790                    row.slots(),
2791                    checkpoint,
2792                )
2793            }
2794        }
2795
2796        impl<S: Schema, $($type: Selectable<S>),+> singular_selected_shape_sealed::Sealed<S>
2797            for ($($type,)+)
2798        {
2799        }
2800
2801        impl<S: Schema, $($type: Selectable<S>),+> SingularSelectedShape<S>
2802            for ($($type,)+)
2803        {
2804        }
2805
2806        impl<S: Schema, $($type: Selectable<S>),+> SingularSelectedTuple<S>
2807            for ($($type,)+)
2808        {
2809        }
2810    };
2811}
2812
2813selected_tuple!(1; (A, 0));
2814selected_tuple!(2; (A, 0), (B, 1));
2815selected_tuple!(3; (A, 0), (B, 1), (C, 2));
2816selected_tuple!(4; (A, 0), (B, 1), (C, 2), (D, 3));
2817selected_tuple!(5; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4));
2818selected_tuple!(6; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5));
2819selected_tuple!(7; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6));
2820selected_tuple!(8; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7));
2821selected_tuple!(9; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8));
2822selected_tuple!(10; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9));
2823selected_tuple!(11; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10));
2824selected_tuple!(12; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11));
2825selected_tuple!(13; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12));
2826selected_tuple!(14; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12), (N, 13));
2827selected_tuple!(15; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12), (N, 13), (O, 14));
2828selected_tuple!(16; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11), (M, 12), (N, 13), (O, 14), (P, 15));
2829
2830/// Construction contract generated by `#[derive(type_bridge::SelectedRow)]`.
2831#[doc(hidden)]
2832pub trait SelectedRowSpec<Outputs>: Sized {
2833    fn __from_selected_outputs(outputs: Outputs) -> Self;
2834}
2835
2836/// A declaration-ordered named selected shape produced by `SelectedRow`.
2837pub struct NamedSelection<S: Schema, Row, Slots> {
2838    slots: Slots,
2839    names: &'static [&'static str],
2840    marker: PhantomData<fn() -> (S, Row)>,
2841}
2842
2843impl<S: Schema, Row, Slots: Clone> Clone for NamedSelection<S, Row, Slots> {
2844    fn clone(&self) -> Self {
2845        Self {
2846            slots: self.slots.clone(),
2847            names: self.names,
2848            marker: PhantomData,
2849        }
2850    }
2851}
2852
2853impl<S: Schema, Row, Slots: SelectedTuple<S>> NamedSelection<S, Row, Slots> {
2854    #[doc(hidden)]
2855    pub fn __new(slots: Slots, names: &'static [&'static str]) -> Result<Self> {
2856        if names.len() != Slots::ARITY {
2857            return Err(Error::model_validation(
2858                ModelValidationPhase::Input,
2859                "invalid_selected_shape",
2860                vec![],
2861                format!(
2862                    "named selected shape has {} names for {} slots",
2863                    names.len(),
2864                    Slots::ARITY
2865                ),
2866                None,
2867            ));
2868        }
2869        Ok(Self {
2870            slots,
2871            names,
2872            marker: PhantomData,
2873        })
2874    }
2875}
2876
2877impl<S: Schema, Row, Slots> selected_shape_sealed::Sealed<S> for NamedSelection<S, Row, Slots> {}
2878
2879impl<S, Row, Slots> SelectedShape<S> for NamedSelection<S, Row, Slots>
2880where
2881    S: Schema,
2882    Slots: SelectedTuple<S>,
2883    Row: SelectedRowSpec<Slots::Output>,
2884{
2885    type Output = Row;
2886
2887    fn __shape_handle(&self, session: &QuerySession<'_, S>) -> Result<OrmShapeHandle> {
2888        let selections = self.slots.__selection_handles(session)?;
2889        session
2890            .session
2891            .named(
2892                self.names
2893                    .iter()
2894                    .copied()
2895                    .zip(selections)
2896                    .map(|(name, selection)| (name.to_owned(), selection)),
2897            )
2898            .map_err(Error::from_orm)
2899    }
2900
2901    fn __materialize_row(
2902        &self,
2903        session: &QuerySession<'_, S>,
2904        row: &MatchRow,
2905    ) -> Result<Self::Output> {
2906        Ok(Row::__from_selected_outputs(
2907            self.slots.__materialize_slots(session, row.slots())?,
2908        ))
2909    }
2910
2911    fn __materialize_projected_row(
2912        &self,
2913        session: &QuerySession<'_, S>,
2914        row: &ProjectedQueryRow,
2915    ) -> Result<Self::Output> {
2916        Ok(Row::__from_selected_outputs(
2917            self.slots
2918                .__materialize_projected_slots(session, row.slots())?,
2919        ))
2920    }
2921
2922    fn __materialize_row_with_checkpoint(
2923        &self,
2924        session: &QuerySession<'_, S>,
2925        row: &MatchRow,
2926        checkpoint: &dyn Fn() -> Result<()>,
2927    ) -> Result<Self::Output> {
2928        Ok(Row::__from_selected_outputs(
2929            self.slots
2930                .__materialize_slots_with_checkpoint(session, row.slots(), checkpoint)?,
2931        ))
2932    }
2933
2934    fn __materialize_projected_row_with_checkpoint(
2935        &self,
2936        session: &QuerySession<'_, S>,
2937        row: &ProjectedQueryRow,
2938        checkpoint: &dyn Fn() -> Result<()>,
2939    ) -> Result<Self::Output> {
2940        Ok(Row::__from_selected_outputs(
2941            self.slots.__materialize_projected_slots_with_checkpoint(
2942                session,
2943                row.slots(),
2944                checkpoint,
2945            )?,
2946        ))
2947    }
2948}
2949
2950impl<S, Row, Slots> singular_selected_shape_sealed::Sealed<S> for NamedSelection<S, Row, Slots>
2951where
2952    S: Schema,
2953    Slots: SingularSelectedTuple<S>,
2954    Row: SelectedRowSpec<Slots::Output>,
2955{
2956}
2957
2958impl<S, Row, Slots> SingularSelectedShape<S> for NamedSelection<S, Row, Slots>
2959where
2960    S: Schema,
2961    Slots: SingularSelectedTuple<S>,
2962    Row: SelectedRowSpec<Slots::Output>,
2963{
2964}
2965
2966fn selected_shape_arity_error(expected: usize, actual: usize) -> Error {
2967    Error::model_validation(
2968        ModelValidationPhase::Hydration,
2969        "wrong_result_shape",
2970        vec![],
2971        format!("selected row has {actual} slots; expected {expected}"),
2972        None,
2973    )
2974}
2975
2976/// Bounded options for one ordered row fetch.
2977#[derive(Debug)]
2978pub struct RowsOptions<S: Schema> {
2979    limit: u64,
2980    offset: u64,
2981    order: Vec<Order<S>>,
2982}
2983
2984impl<S: Schema> Clone for RowsOptions<S> {
2985    fn clone(&self) -> Self {
2986        Self {
2987            limit: self.limit,
2988            offset: self.offset,
2989            order: self.order.clone(),
2990        }
2991    }
2992}
2993
2994impl<S: Schema> RowsOptions<S> {
2995    /// Create resource-bounded row options with a nonzero limit.
2996    #[must_use]
2997    pub fn new(limit: u64) -> Self {
2998        Self {
2999            limit,
3000            offset: 0,
3001            order: Vec::new(),
3002        }
3003    }
3004
3005    /// Skip the first `offset` distinct rows.
3006    #[must_use]
3007    pub fn offset(mut self, offset: u64) -> Self {
3008        self.offset = offset;
3009        self
3010    }
3011
3012    /// Append one stable public ordering term.
3013    #[must_use]
3014    pub fn order_by(mut self, order: Order<S>) -> Self {
3015        self.order.push(order);
3016        self
3017    }
3018}
3019
3020/// Bounded options for one ordered distinct-root page.
3021#[derive(Debug)]
3022pub struct PageOptions<S: Schema> {
3023    limit: u64,
3024    offset: u64,
3025    include_total: bool,
3026    order: Vec<Order<S>>,
3027}
3028
3029impl<S: Schema> Clone for PageOptions<S> {
3030    fn clone(&self) -> Self {
3031        Self {
3032            limit: self.limit,
3033            offset: self.offset,
3034            include_total: self.include_total,
3035            order: self.order.clone(),
3036        }
3037    }
3038}
3039
3040impl<S: Schema> PageOptions<S> {
3041    /// Create resource-bounded page options with a nonzero terminal limit.
3042    #[must_use]
3043    pub fn new(limit: u64) -> Self {
3044        Self {
3045            limit,
3046            offset: 0,
3047            include_total: false,
3048            order: Vec::new(),
3049        }
3050    }
3051
3052    /// Skip the first `offset` distinct roots.
3053    #[must_use]
3054    pub fn offset(mut self, offset: u64) -> Self {
3055        self.offset = offset;
3056        self
3057    }
3058
3059    /// Request a same-snapshot total distinct-root count.
3060    #[must_use]
3061    pub fn include_total(mut self, include_total: bool) -> Self {
3062        self.include_total = include_total;
3063        self
3064    }
3065
3066    /// Append one stable root-ordering term.
3067    #[must_use]
3068    pub fn order_by(mut self, order: Order<S>) -> Self {
3069        self.order.push(order);
3070        self
3071    }
3072}
3073
3074/// One immutable owned distinct-root page.
3075#[derive(Clone, Debug)]
3076pub struct Page<T> {
3077    items: Vec<T>,
3078    offset: u64,
3079    limit: u64,
3080    total: Option<u64>,
3081}
3082
3083impl<T> Page<T> {
3084    /// Borrow page items in stable root order.
3085    #[must_use]
3086    pub fn items(&self) -> &[T] {
3087        &self.items
3088    }
3089
3090    /// Return the requested root offset.
3091    #[must_use]
3092    pub const fn offset(&self) -> u64 {
3093        self.offset
3094    }
3095
3096    /// Return the requested root limit.
3097    #[must_use]
3098    pub const fn limit(&self) -> u64 {
3099        self.limit
3100    }
3101
3102    /// Return the same-snapshot total when it was requested.
3103    #[must_use]
3104    pub const fn total(&self) -> Option<u64> {
3105        self.total
3106    }
3107
3108    /// Consume the page and return its owned items.
3109    #[must_use]
3110    pub fn into_items(self) -> Vec<T> {
3111        self.items
3112    }
3113}
3114
3115/// One persistent, reusable singular-shape query lineage.
3116///
3117/// Each authoring method returns a new lineage and leaves its ancestor
3118/// usable.
3119pub struct Query<'s, 'db, S: Schema, Shape: SelectedShape<S>> {
3120    session: &'s QuerySession<'db, S>,
3121    selection: Shape,
3122    hidden: Vec<BindingKey>,
3123    predicates: Vec<Predicate<S>>,
3124    allowed_cross_joins: Vec<(BindingKey, BindingKey)>,
3125    closed: AtomicBool,
3126}
3127
3128impl<'s, 'db, S: Schema, Shape: SelectedShape<S>> Clone for Query<'s, 'db, S, Shape> {
3129    fn clone(&self) -> Self {
3130        Self {
3131            session: self.session,
3132            selection: self.selection.clone(),
3133            hidden: self.hidden.clone(),
3134            predicates: self.predicates.clone(),
3135            allowed_cross_joins: self.allowed_cross_joins.clone(),
3136            closed: AtomicBool::new(self.closed.load(Ordering::Acquire)),
3137        }
3138    }
3139}
3140
3141impl<'db, S: Schema> QuerySession<'db, S> {
3142    /// Begin one persistent query lineage from a singular selected shape.
3143    pub fn query<Shape: SelectedShape<S>>(
3144        &self,
3145        selection: Shape,
3146    ) -> Result<Query<'_, 'db, S, Shape>> {
3147        selection.__shape_handle(self)?;
3148        Ok(Query {
3149            session: self,
3150            selection,
3151            hidden: Vec::new(),
3152            predicates: Vec::new(),
3153            allowed_cross_joins: Vec::new(),
3154            closed: AtomicBool::new(false),
3155        })
3156    }
3157}
3158
3159impl<'s, 'db, S: Schema, Shape: SelectedShape<S>> Query<'s, 'db, S, Shape> {
3160    /// Explicitly close this immutable query handle.
3161    ///
3162    /// Closing is idempotent and affects only this handle. Clones, ancestors,
3163    /// descendants, siblings, and the authoring session have independent
3164    /// query lifecycles.
3165    pub fn close(&self) {
3166        self.closed.store(true, Ordering::Release);
3167    }
3168
3169    /// Return whether this query handle was explicitly closed.
3170    #[must_use]
3171    pub fn is_closed(&self) -> bool {
3172        self.closed.load(Ordering::Acquire)
3173    }
3174
3175    fn ensure_open(&self, phase: ModelValidationPhase) -> Result<()> {
3176        self.session.ensure_open(phase)?;
3177        if self.closed.load(Ordering::Acquire) {
3178            Err(Error::from_sdk_execution(
3179                type_bridge_orm::query_resource_closed_diagnostic(),
3180                phase,
3181            ))
3182        } else {
3183            Ok(())
3184        }
3185    }
3186
3187    /// Attach one generated binding for predicates without selecting it.
3188    pub fn match_<M: ThingModel<Schema = S>, Mode: SelectionMode>(
3189        &self,
3190        binding: Binding<S, M, Mode>,
3191    ) -> Result<Self> {
3192        self.ensure_open(ModelValidationPhase::Input)?;
3193        self.session.handle_by_key(binding.key())?;
3194        let mut next = self.clone();
3195        if !next.hidden.contains(&binding.key()) {
3196            next.hidden.push(binding.key());
3197        }
3198        Ok(next)
3199    }
3200
3201    /// Attach one predicate; repeated calls form a conjunction in call order.
3202    pub fn where_(&self, predicate: Predicate<S>) -> Result<Self> {
3203        self.ensure_open(ModelValidationPhase::Input)?;
3204        let mut next = self.clone();
3205        next.predicates.push(predicate);
3206        Ok(next)
3207    }
3208
3209    /// Attach predicates as one implicit conjunction in source order.
3210    pub fn where_all(&self, predicates: impl IntoIterator<Item = Predicate<S>>) -> Result<Self> {
3211        self.ensure_open(ModelValidationPhase::Input)?;
3212        let mut next = self.clone();
3213        next.predicates.extend(predicates);
3214        Ok(next)
3215    }
3216
3217    /// Explicitly permit one topology-level cross join between two attached
3218    /// generated bindings. The returned lineage is immutable and reusable.
3219    pub fn allow_cross_join<L: Selectable<S>, R: Selectable<S>>(
3220        &self,
3221        left: L,
3222        right: R,
3223    ) -> Result<Self> {
3224        self.ensure_open(ModelValidationPhase::Input)?;
3225        let left = left.binding_key();
3226        let right = right.binding_key();
3227        self.session.handle_by_key(left)?;
3228        self.session.handle_by_key(right)?;
3229        if left == right {
3230            return Err(Error::model_validation(
3231                ModelValidationPhase::Input,
3232                "self_cross_join",
3233                vec![],
3234                "cross-join permission requires two distinct generated bindings",
3235                None,
3236            ));
3237        }
3238        let pair = if left.index < right.index {
3239            (left, right)
3240        } else {
3241            (right, left)
3242        };
3243        let mut next = self.clone();
3244        if !next.allowed_cross_joins.contains(&pair) {
3245            next.allowed_cross_joins.push(pair);
3246        }
3247        Ok(next)
3248    }
3249
3250    fn lineage(&self) -> Result<OrmQueryHandle> {
3251        self.lineage_with_hidden(&[])
3252    }
3253
3254    fn lineage_with_hidden(&self, hidden: &[BindingKey]) -> Result<OrmQueryHandle> {
3255        self.ensure_open(ModelValidationPhase::Input)?;
3256        let shape = self.selection.__shape_handle(self.session)?;
3257        let mut query = self.session.session.query(shape).map_err(Error::from_orm)?;
3258        let mut hidden_keys = self.hidden.clone();
3259        for key in hidden {
3260            if !hidden_keys.contains(key) {
3261                hidden_keys.push(*key);
3262            }
3263        }
3264        for key in hidden_keys {
3265            let hidden = self.session.handle_by_key(key)?;
3266            query = query.add_hidden(hidden.clone()).map_err(Error::from_orm)?;
3267        }
3268        for (left, right) in &self.allowed_cross_joins {
3269            let left = self.session.handle_by_key(*left)?;
3270            let right = self.session.handle_by_key(*right)?;
3271            query = query
3272                .allow_cross_join(left, right)
3273                .map_err(Error::from_orm)?;
3274        }
3275        for predicate in &self.predicates {
3276            let lowered = self.session.lower_predicate(&predicate.expr)?;
3277            query = query.where_predicate(lowered).map_err(Error::from_orm)?;
3278        }
3279        Ok(query)
3280    }
3281
3282    pub(crate) fn validated_rows(
3283        &self,
3284        order: &[Order<S>],
3285        window: Window,
3286    ) -> Result<ValidatedMatchRequest> {
3287        let lineage = self.lineage()?;
3288        let mut lowered_orders = Vec::with_capacity(order.len());
3289        for term in order {
3290            lowered_orders.push(self.session.lower_order(term)?);
3291        }
3292        lineage
3293            .validate_fetch_rows(&lowered_orders, window, RowCardinality::BoundedMany)
3294            .map_err(Error::from_orm)
3295    }
3296
3297    pub(crate) fn validated_one(&self) -> Result<ValidatedMatchRequest> {
3298        self.lineage()?
3299            .validate_fetch_rows(
3300                &[],
3301                Window {
3302                    offset: 0,
3303                    limit: 1,
3304                },
3305                RowCardinality::ExactlyOne,
3306            )
3307            .map_err(Error::from_orm)
3308    }
3309
3310    pub(crate) fn validated_page<R: Selectable<S>>(
3311        &self,
3312        root: R,
3313        order: &[Order<S>],
3314        window: Window,
3315        include_total: bool,
3316    ) -> Result<ValidatedMatchRequest> {
3317        let root = self.session.handle_by_key(root.binding_key())?;
3318        let lineage = self.lineage()?;
3319        let mut lowered_orders = Vec::with_capacity(order.len());
3320        for term in order {
3321            lowered_orders.push(self.session.lower_order(term)?);
3322        }
3323        lineage
3324            .validate_page_by(root, &lowered_orders, window, include_total)
3325            .map_err(Error::from_orm)
3326    }
3327
3328    pub(crate) fn validated_count_by<R: Selectable<S>>(
3329        &self,
3330        root: R,
3331    ) -> Result<ValidatedMatchRequest> {
3332        let root = self.session.handle_by_key(root.binding_key())?;
3333        self.lineage()?
3334            .validate_count_by(root)
3335            .map_err(Error::from_orm)
3336    }
3337
3338    pub(crate) fn validated_exists_by<R: Selectable<S>>(
3339        &self,
3340        root: R,
3341    ) -> Result<ValidatedMatchRequest> {
3342        let root = self.session.handle_by_key(root.binding_key())?;
3343        self.lineage()?
3344            .validate_exists_by(root)
3345            .map_err(Error::from_orm)
3346    }
3347
3348    fn materialize_rows(
3349        &self,
3350        rows: &[MatchRow],
3351        deadline: QueryExecutionDeadline,
3352    ) -> Result<Vec<Shape::Output>> {
3353        let checkpoint = || {
3354            self.session
3355                .check_invocation(deadline, ModelValidationPhase::Hydration)
3356        };
3357        checkpoint()?;
3358        let mut outputs = Vec::with_capacity(rows.len());
3359        for row in rows {
3360            checkpoint()?;
3361            outputs.push(self.selection.__materialize_row_with_checkpoint(
3362                self.session,
3363                row,
3364                &checkpoint,
3365            )?);
3366        }
3367        checkpoint()?;
3368        Ok(outputs)
3369    }
3370
3371    fn materialize_projected_rows(
3372        &self,
3373        rows: &[ProjectedQueryRow],
3374        deadline: QueryExecutionDeadline,
3375    ) -> Result<Vec<Shape::Output>> {
3376        let checkpoint = || {
3377            self.session
3378                .check_invocation(deadline, ModelValidationPhase::Hydration)
3379        };
3380        checkpoint()?;
3381        let mut outputs = Vec::with_capacity(rows.len());
3382        for row in rows {
3383            checkpoint()?;
3384            outputs.push(self.selection.__materialize_projected_row_with_checkpoint(
3385                self.session,
3386                row,
3387                &checkpoint,
3388            )?);
3389        }
3390        checkpoint()?;
3391        Ok(outputs)
3392    }
3393
3394    pub(crate) fn outputs_from_rows(
3395        &self,
3396        validated: &ValidatedMatchRequest,
3397        result: &ValidatedMatchResult,
3398        deadline: QueryExecutionDeadline,
3399    ) -> Result<Vec<Shape::Output>> {
3400        self.session
3401            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3402        if self.session.uses_successor_projected_materialization() {
3403            let projected = self
3404                .session
3405                .materialize_projected_query_value(validated, result, deadline)?;
3406            let ProjectedQueryValue::Rows { rows } = projected else {
3407                return Err(Error::model_validation(
3408                    ModelValidationPhase::Hydration,
3409                    "wrong_result_shape",
3410                    vec![],
3411                    "provider returned a non-row result for a row fetch",
3412                    None,
3413                ));
3414            };
3415            return self.materialize_projected_rows(&rows, deadline);
3416        }
3417        let rows = match result
3418            .for_request(validated)
3419            .map_err(|error| Error::from_orm_hydration(error.into()))?
3420        {
3421            MatchResult::Rows { rows } => rows,
3422            _ => {
3423                return Err(Error::model_validation(
3424                    ModelValidationPhase::Hydration,
3425                    "wrong_result_shape",
3426                    vec![],
3427                    "provider returned a non-row result for a row fetch",
3428                    None,
3429                ));
3430            }
3431        };
3432        self.materialize_rows(rows, deadline)
3433    }
3434
3435    pub(crate) fn output_page(
3436        &self,
3437        validated: &ValidatedMatchRequest,
3438        result: &ValidatedMatchResult,
3439        deadline: QueryExecutionDeadline,
3440    ) -> Result<Page<Shape::Output>> {
3441        self.session
3442            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3443        if self.session.uses_successor_projected_materialization() {
3444            let projected = self
3445                .session
3446                .materialize_projected_query_value(validated, result, deadline)?;
3447            let ProjectedQueryValue::Page {
3448                entries,
3449                window,
3450                total,
3451                ..
3452            } = projected
3453            else {
3454                return Err(Error::model_validation(
3455                    ModelValidationPhase::Hydration,
3456                    "wrong_result_shape",
3457                    vec![],
3458                    "provider returned a non-page result for a page fetch",
3459                    None,
3460                ));
3461            };
3462            return Ok(Page {
3463                items: self.materialize_projected_rows(&entries, deadline)?,
3464                offset: window.offset,
3465                limit: window.limit,
3466                total,
3467            });
3468        }
3469        let (entries, window, total) = match result
3470            .for_request(validated)
3471            .map_err(|error| Error::from_orm_hydration(error.into()))?
3472        {
3473            MatchResult::Page {
3474                entries,
3475                window,
3476                total,
3477                ..
3478            } => (entries, *window, *total),
3479            _ => {
3480                return Err(Error::model_validation(
3481                    ModelValidationPhase::Hydration,
3482                    "wrong_result_shape",
3483                    vec![],
3484                    "provider returned a non-page result for a page fetch",
3485                    None,
3486                ));
3487            }
3488        };
3489        Ok(Page {
3490            items: self.materialize_rows(entries, deadline)?,
3491            offset: window.offset,
3492            limit: window.limit,
3493            total,
3494        })
3495    }
3496
3497    async fn execute(
3498        &self,
3499        validated: ValidatedMatchRequest,
3500        deadline: QueryExecutionDeadline,
3501    ) -> Result<(ValidatedMatchRequest, ValidatedMatchResult)> {
3502        self.ensure_open(ModelValidationPhase::Input)?;
3503        self.session
3504            .check_invocation(deadline, ModelValidationPhase::Input)?;
3505        let target = match &self.session.execution {
3506            QueryExecution::Borrowed(transaction) => QueryTarget::Transaction(transaction),
3507            QueryExecution::Local(database) => QueryTarget::Database(database.inner_orm()),
3508            QueryExecution::Remote(remote) => {
3509                let result = remote
3510                    .execute_match(
3511                        &self.session.registry,
3512                        validated,
3513                        self.session.resources,
3514                        self.session.cancellation.clone(),
3515                        deadline,
3516                    )
3517                    .await?;
3518                self.ensure_open(ModelValidationPhase::Hydration)?;
3519                return Ok(result);
3520            }
3521        };
3522        let result = target
3523            .execute(
3524                &self.session.registry,
3525                validated,
3526                self.session.resources,
3527                &self.session.cancellation,
3528                deadline,
3529            )
3530            .await;
3531        self.session
3532            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3533        self.ensure_open(ModelValidationPhase::Hydration)?;
3534        result.map_err(crate::remote::target_error)
3535    }
3536}
3537
3538impl<'s, 'db, S, Shape> Query<'s, 'db, S, Shape>
3539where
3540    S: Schema,
3541    Shape: SingularSelectedShape<S>,
3542{
3543    /// Return exactly one distinct selected identity, failing `no_result` on
3544    /// an empty stream and `not_unique` on more than one.
3545    pub async fn one(&self) -> Result<Shape::Output> {
3546        let deadline = self.session.begin_invocation()?;
3547        let validated = self.validated_one()?;
3548        let (validated, result) = self.execute(validated, deadline).await?;
3549        let mut outputs = self.outputs_from_rows(&validated, &result, deadline)?;
3550        match outputs.len() {
3551            0 => Err(Error::model_validation(
3552                ModelValidationPhase::Hydration,
3553                "no_result",
3554                vec![],
3555                "query selected no distinct identity",
3556                None,
3557            )),
3558            1 => Ok(outputs.remove(0)),
3559            _ => Err(Error::model_validation(
3560                ModelValidationPhase::Hydration,
3561                "not_unique",
3562                vec![],
3563                "query selected more than one distinct identity",
3564                None,
3565            )),
3566        }
3567    }
3568
3569    /// Return a resource-bounded ordered sequence of distinct selected
3570    /// identities; the limit must be nonzero.
3571    pub async fn rows(&self, options: RowsOptions<S>) -> Result<Vec<Shape::Output>> {
3572        let deadline = self.session.begin_invocation()?;
3573        if options.limit == 0 {
3574            return Err(Error::model_validation(
3575                ModelValidationPhase::Input,
3576                "zero_limit",
3577                vec![],
3578                "row fetches require a nonzero limit",
3579                None,
3580            ));
3581        }
3582        let validated = self.validated_rows(
3583            &options.order,
3584            Window {
3585                offset: options.offset,
3586                limit: options.limit,
3587            },
3588        )?;
3589        let (validated, result) = self.execute(validated, deadline).await?;
3590        self.outputs_from_rows(&validated, &result, deadline)
3591    }
3592
3593    /// Return the first distinct selected identity under a stable order.
3594    pub async fn first(&self, order: Order<S>) -> Result<Option<Shape::Output>> {
3595        let deadline = self.session.begin_invocation()?;
3596        let validated = self.validated_rows(
3597            &[order],
3598            Window {
3599                offset: 0,
3600                limit: 1,
3601            },
3602        )?;
3603        let (validated, result) = self.execute(validated, deadline).await?;
3604        Ok(self.outputs_from_rows(&validated, &result, deadline)?.pop())
3605    }
3606}
3607
3608impl<'s, 'db, S: Schema, Shape: SelectedShape<S>> Query<'s, 'db, S, Shape> {
3609    /// Return one resource-bounded page grouped by distinct root identity.
3610    pub async fn page_by<R: Selectable<S>>(
3611        &self,
3612        root: R,
3613        options: PageOptions<S>,
3614    ) -> Result<Page<Shape::Output>> {
3615        let deadline = self.session.begin_invocation()?;
3616        if options.limit == 0 {
3617            return Err(Error::model_validation(
3618                ModelValidationPhase::Input,
3619                "zero_limit",
3620                vec![],
3621                "page fetches require a nonzero limit",
3622                None,
3623            ));
3624        }
3625        let validated = self.validated_page(
3626            root,
3627            &options.order,
3628            Window {
3629                offset: options.offset,
3630                limit: options.limit,
3631            },
3632            options.include_total,
3633        )?;
3634        let (validated, result) = self.execute(validated, deadline).await?;
3635        self.output_page(&validated, &result, deadline)
3636    }
3637
3638    /// Count distinct identities of one selected root binding.
3639    pub async fn count_by<R: Selectable<S>>(&self, root: R) -> Result<u64> {
3640        let deadline = self.session.begin_invocation()?;
3641        let validated = self.validated_count_by(root)?;
3642        let (validated, result) = self.execute(validated, deadline).await?;
3643        self.session
3644            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3645        match result
3646            .for_request(&validated)
3647            .map_err(|error| Error::from_orm_hydration(error.into()))?
3648        {
3649            MatchResult::Count { value, .. } => Ok(*value),
3650            _ => Err(Error::model_validation(
3651                ModelValidationPhase::Hydration,
3652                "wrong_result_shape",
3653                vec![],
3654                "provider returned a non-count result for a count",
3655                None,
3656            )),
3657        }
3658    }
3659
3660    /// Test whether any distinct identity of one selected root binding
3661    /// exists.
3662    pub async fn exists_by<R: Selectable<S>>(&self, root: R) -> Result<bool> {
3663        let deadline = self.session.begin_invocation()?;
3664        let validated = self.validated_exists_by(root)?;
3665        let (validated, result) = self.execute(validated, deadline).await?;
3666        self.session
3667            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3668        match result
3669            .for_request(&validated)
3670            .map_err(|error| Error::from_orm_hydration(error.into()))?
3671        {
3672            MatchResult::Exists { value, .. } => Ok(*value),
3673            _ => Err(Error::model_validation(
3674                ModelValidationPhase::Hydration,
3675                "wrong_result_shape",
3676                vec![],
3677                "provider returned a non-existence result for an existence test",
3678                None,
3679            )),
3680        }
3681    }
3682}
3683
3684impl<'s, 'db, S: Schema, B: Selectable<S>> Query<'s, 'db, S, B> {
3685    /// Count distinct selected identities.
3686    pub async fn count(&self) -> Result<u64> {
3687        self.count_by(self.selection).await
3688    }
3689
3690    /// Test whether any distinct selected identity exists.
3691    pub async fn exists(&self) -> Result<bool> {
3692        self.exists_by(self.selection).await
3693    }
3694
3695    fn lowered_reduce_terms(
3696        &self,
3697        terms: &[(
3698            type_bridge_orm::match_request::Reduction,
3699            Option<(BindingKey, &'static str)>,
3700        )],
3701    ) -> Result<Vec<OrmFieldHandle>> {
3702        let mut lowered = Vec::new();
3703        for (_, input) in terms {
3704            if let Some((key, owns_id_json)) = input {
3705                lowered.push(self.session.lower_field(*key, owns_id_json)?);
3706            }
3707        }
3708        Ok(lowered)
3709    }
3710
3711    pub(crate) fn validated_reduce(
3712        &self,
3713        group: Option<BindingKey>,
3714        terms: &[(
3715            type_bridge_orm::match_request::Reduction,
3716            Option<(BindingKey, &'static str)>,
3717        )],
3718    ) -> Result<ValidatedMatchRequest> {
3719        let root = self.session.handle_by_key(self.selection.binding_key())?;
3720        let hidden_groups = group
3721            .filter(|key| *key != self.selection.binding_key())
3722            .into_iter()
3723            .collect::<Vec<_>>();
3724        let lineage = self.lineage_with_hidden(&hidden_groups)?;
3725        let group_handle = group
3726            .map(|key| self.session.handle_by_key(key))
3727            .transpose()?;
3728        let lowered_inputs = self.lowered_reduce_terms(terms)?;
3729        let mut inputs = lowered_inputs.iter();
3730        let mut pairs = Vec::with_capacity(terms.len());
3731        for (reduction, input) in terms {
3732            let handle = if input.is_some() {
3733                Some(inputs.next().expect("one lowered handle per input"))
3734            } else {
3735                None
3736            };
3737            pairs.push((*reduction, handle));
3738        }
3739        lineage
3740            .validate_reduce_by(root, group_handle, &pairs)
3741            .map_err(Error::from_orm)
3742    }
3743
3744    fn validated_reduce_by_field<Owner: Model<Schema = S>, V>(
3745        &self,
3746        group: BoundField<S, Owner, V>,
3747        terms: &[(
3748            type_bridge_orm::match_request::Reduction,
3749            Option<(BindingKey, &'static str)>,
3750        )],
3751    ) -> Result<ValidatedMatchRequest> {
3752        let root = self.session.handle_by_key(self.selection.binding_key())?;
3753        let hidden_groups = (group.key != self.selection.binding_key())
3754            .then_some(group.key)
3755            .into_iter()
3756            .collect::<Vec<_>>();
3757        let lineage = self.lineage_with_hidden(&hidden_groups)?;
3758        let group = self.session.lower_field(group.key, group.owns_id_json)?;
3759        let lowered_inputs = self.lowered_reduce_terms(terms)?;
3760        let mut inputs = lowered_inputs.iter();
3761        let mut pairs = Vec::with_capacity(terms.len());
3762        for (reduction, input) in terms {
3763            let handle = if input.is_some() {
3764                Some(inputs.next().expect("one lowered handle per input"))
3765            } else {
3766                None
3767            };
3768            pairs.push((*reduction, handle));
3769        }
3770        lineage
3771            .validate_reduce_by_field(root, &group, &pairs)
3772            .map_err(Error::from_orm)
3773    }
3774
3775    fn validated_reduce_by_fields(
3776        &self,
3777        groups: &[(BindingKey, &'static str)],
3778        terms: &[(
3779            type_bridge_orm::match_request::Reduction,
3780            Option<(BindingKey, &'static str)>,
3781        )],
3782    ) -> Result<ValidatedMatchRequest> {
3783        let root = self.session.handle_by_key(self.selection.binding_key())?;
3784        let mut hidden_keys = Vec::new();
3785        for (key, _) in groups {
3786            if *key != self.selection.binding_key() && !hidden_keys.contains(key) {
3787                hidden_keys.push(*key);
3788            }
3789        }
3790        let lineage = self.lineage_with_hidden(&hidden_keys)?;
3791        let lowered_groups = groups
3792            .iter()
3793            .map(|(key, owns_id_json)| self.session.lower_field(*key, owns_id_json))
3794            .collect::<Result<Vec<_>>>()?;
3795        let group_refs = lowered_groups.iter().collect::<Vec<_>>();
3796        let lowered_inputs = self.lowered_reduce_terms(terms)?;
3797        let mut inputs = lowered_inputs.iter();
3798        let mut pairs = Vec::with_capacity(terms.len());
3799        for (reduction, input) in terms {
3800            let handle = if input.is_some() {
3801                Some(inputs.next().expect("one lowered handle per input"))
3802            } else {
3803                None
3804            };
3805            pairs.push((*reduction, handle));
3806        }
3807        lineage
3808            .validate_reduce_by_fields(root, &group_refs, &pairs)
3809            .map_err(Error::from_orm)
3810    }
3811
3812    fn decoded_reduction_rows<'result>(
3813        &self,
3814        validated: &ValidatedMatchRequest,
3815        result: &'result ValidatedMatchResult,
3816        deadline: QueryExecutionDeadline,
3817    ) -> Result<&'result [type_bridge_orm::match_request::ReductionRow]> {
3818        self.session
3819            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3820        match result
3821            .for_request(validated)
3822            .map_err(|error| Error::from_orm_hydration(error.into()))?
3823        {
3824            MatchResult::Reduction { rows, .. }
3825            | MatchResult::FieldReduction { rows, .. }
3826            | MatchResult::FieldTupleReduction { rows, .. } => Ok(rows),
3827            _ => Err(Error::model_validation(
3828                ModelValidationPhase::Hydration,
3829                "wrong_result_shape",
3830                vec![],
3831                "provider returned a non-reduction result for an aggregate",
3832                None,
3833            )),
3834        }
3835    }
3836
3837    /// Reduce the distinct selected stream to one typed tuple of aggregate
3838    /// values.
3839    pub async fn aggregate<T: crate::aggregate::AggregateTuple<S>>(
3840        &self,
3841        terms: T,
3842    ) -> Result<T::Output> {
3843        let deadline = self.session.begin_invocation()?;
3844        let term_list = terms.terms();
3845        let validated = self.validated_reduce(None, &term_list)?;
3846        let (validated, result) = self.execute(validated, deadline).await?;
3847        let rows = self.decoded_reduction_rows(&validated, &result, deadline)?;
3848        let [row] = rows else {
3849            return Err(Error::model_validation(
3850                ModelValidationPhase::Hydration,
3851                "wrong_result_shape",
3852                vec![],
3853                "ungrouped aggregates require exactly one reduction row",
3854                None,
3855            ));
3856        };
3857        self.session
3858            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3859        let output = T::decode(row.values())?;
3860        self.session
3861            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3862        Ok(output)
3863    }
3864
3865    /// Group the distinct selected stream by another attached binding's
3866    /// distinct identities before aggregating.
3867    pub fn group_by<G: Selectable<S>>(&self, group: G) -> Result<GroupedQuery<'s, 'db, S, B, G>> {
3868        self.ensure_open(ModelValidationPhase::Input)?;
3869        self.session.handle_by_key(group.binding_key())?;
3870        Ok(GroupedQuery {
3871            query: self.clone(),
3872            group,
3873        })
3874    }
3875
3876    /// Group the distinct selected stream by each witnessed value of one
3877    /// generated owned field before aggregating.
3878    pub fn group_by_field<Owner, V>(
3879        &self,
3880        group: BoundField<S, Owner, V>,
3881    ) -> Result<FieldGroupedQuery<'s, 'db, S, B, Owner, V>>
3882    where
3883        Owner: Model<Schema = S>,
3884        V: GroupedQueryValue,
3885    {
3886        self.ensure_open(ModelValidationPhase::Input)?;
3887        self.session.lower_field(group.key, group.owns_id_json)?;
3888        Ok(FieldGroupedQuery {
3889            query: self.clone(),
3890            group,
3891        })
3892    }
3893
3894    /// Group the distinct selected stream by the Cartesian tuple of multiple
3895    /// generated owned fields' witnessed values before aggregating.
3896    pub fn group_by_fields<G>(&self, groups: G) -> Result<FieldTupleGroupedQuery<'s, 'db, S, B, G>>
3897    where
3898        G: FieldGroupTuple<S>,
3899    {
3900        self.ensure_open(ModelValidationPhase::Input)?;
3901        for (key, owns_id_json) in groups.fields() {
3902            self.session.lower_field(key, owns_id_json)?;
3903        }
3904        Ok(FieldTupleGroupedQuery {
3905            query: self.clone(),
3906            groups,
3907        })
3908    }
3909}
3910
3911/// One query lineage grouped by a second attached binding for aggregation.
3912pub struct GroupedQuery<'s, 'db, S: Schema, B: Selectable<S>, G: Selectable<S>> {
3913    query: Query<'s, 'db, S, B>,
3914    group: G,
3915}
3916
3917impl<'s, 'db, S: Schema, B: Selectable<S>, G: Selectable<S>> GroupedQuery<'s, 'db, S, B, G> {
3918    /// Explicitly close this independently owned grouped-query lineage.
3919    pub fn close(&self) {
3920        self.query.close();
3921    }
3922
3923    /// Return whether this grouped query was explicitly closed.
3924    #[must_use]
3925    pub fn is_closed(&self) -> bool {
3926        self.query.is_closed()
3927    }
3928
3929    /// Reduce each witnessed distinct group identity to one typed tuple,
3930    /// returning materialized group keys with their aggregate values.
3931    pub async fn aggregate<T: crate::aggregate::AggregateTuple<S>>(
3932        &self,
3933        terms: T,
3934    ) -> Result<Vec<(G::Output, T::Output)>> {
3935        let deadline = self.query.session.begin_invocation()?;
3936        let term_list = terms.terms();
3937        let validated = self
3938            .query
3939            .validated_reduce(Some(self.group.binding_key()), &term_list)?;
3940        let (validated, result) = self.query.execute(validated, deadline).await?;
3941        if self
3942            .query
3943            .session
3944            .uses_successor_projected_materialization()
3945        {
3946            let projected = self
3947                .query
3948                .session
3949                .materialize_projected_query_value(&validated, &result, deadline)?;
3950            let ProjectedQueryValue::Reduction { rows, .. } = projected else {
3951                return Err(Error::model_validation(
3952                    ModelValidationPhase::Hydration,
3953                    "wrong_result_shape",
3954                    vec![],
3955                    "provider returned a non-reduction result for an aggregate",
3956                    None,
3957                ));
3958            };
3959            let mut outputs = Vec::with_capacity(rows.len());
3960            for row in rows {
3961                self.query
3962                    .session
3963                    .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3964                let Some(ProjectedReductionGroup::Thing(thing)) = row.group() else {
3965                    return Err(Error::model_validation(
3966                        ModelValidationPhase::Hydration,
3967                        "wrong_result_shape",
3968                        vec![],
3969                        "grouped aggregates require group evidence per row",
3970                        None,
3971                    ));
3972                };
3973                let key = G::__materialize_projected_output(self.query.session, thing)?;
3974                let values = decoded_projected_reduction_values(row.values());
3975                outputs.push((key, T::decode(&values)?));
3976            }
3977            self.query
3978                .session
3979                .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3980            return Ok(outputs);
3981        }
3982        let rows = self
3983            .query
3984            .decoded_reduction_rows(&validated, &result, deadline)?;
3985        let mut outputs = Vec::with_capacity(rows.len());
3986        for row in rows {
3987            self.query
3988                .session
3989                .check_invocation(deadline, ModelValidationPhase::Hydration)?;
3990            let thing = row.group().ok_or_else(|| {
3991                Error::model_validation(
3992                    ModelValidationPhase::Hydration,
3993                    "wrong_result_shape",
3994                    vec![],
3995                    "grouped aggregates require group evidence per row",
3996                    None,
3997                )
3998            })?;
3999            let client_row = self.query.session.client_row_for(thing)?;
4000            let key = G::materialize_output(&client_row).map_err(|error| {
4001                crate::entity_codec::map_validation_error(error, ModelValidationPhase::Hydration)
4002            })?;
4003            outputs.push((key, T::decode(row.values())?));
4004        }
4005        self.query
4006            .session
4007            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
4008        Ok(outputs)
4009    }
4010}
4011
4012/// One query lineage grouped by a generated owned field value for
4013/// aggregation.
4014pub struct FieldGroupedQuery<
4015    's,
4016    'db,
4017    S: Schema,
4018    B: Selectable<S>,
4019    Owner: Model<Schema = S>,
4020    V: GroupedQueryValue,
4021> {
4022    query: Query<'s, 'db, S, B>,
4023    group: BoundField<S, Owner, V>,
4024}
4025
4026impl<'s, 'db, S, B, Owner, V> FieldGroupedQuery<'s, 'db, S, B, Owner, V>
4027where
4028    S: Schema,
4029    B: Selectable<S>,
4030    Owner: Model<Schema = S>,
4031    V: GroupedQueryValue,
4032{
4033    /// Explicitly close this independently owned grouped-query lineage.
4034    pub fn close(&self) {
4035        self.query.close();
4036    }
4037
4038    /// Return whether this grouped query was explicitly closed.
4039    #[must_use]
4040    pub fn is_closed(&self) -> bool {
4041        self.query.is_closed()
4042    }
4043
4044    /// Reduce each witnessed distinct field value to one typed tuple,
4045    /// returning its exact generated attribute wrapper with the aggregates.
4046    pub async fn aggregate<T: crate::aggregate::AggregateTuple<S>>(
4047        &self,
4048        terms: T,
4049    ) -> Result<Vec<(V, T::Output)>> {
4050        let deadline = self.query.session.begin_invocation()?;
4051        let term_list = terms.terms();
4052        let validated = self
4053            .query
4054            .validated_reduce_by_field(self.group, &term_list)?;
4055        let (validated, result) = self.query.execute(validated, deadline).await?;
4056        let rows = self
4057            .query
4058            .decoded_reduction_rows(&validated, &result, deadline)?;
4059        let mut outputs = Vec::with_capacity(rows.len());
4060        for row in rows {
4061            self.query
4062                .session
4063                .check_invocation(deadline, ModelValidationPhase::Hydration)?;
4064            let value = row.field_group().ok_or_else(|| {
4065                Error::model_validation(
4066                    ModelValidationPhase::Hydration,
4067                    "wrong_result_shape",
4068                    vec![],
4069                    "field-grouped aggregates require scalar group evidence per row",
4070                    None,
4071                )
4072            })?;
4073            let key = V::from_group_scalar(encoded_group_scalar(value)?)
4074                .map_err(|error| map_validation_error(error, ModelValidationPhase::Hydration))?;
4075            outputs.push((key, T::decode(row.values())?));
4076        }
4077        self.query
4078            .session
4079            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
4080        Ok(outputs)
4081    }
4082}
4083
4084/// A sealed tuple of two through sixteen generated owned fields used as one
4085/// typed grouped-reduction key.
4086pub trait FieldGroupTuple<S: Schema>: field_group_tuple_sealed::Sealed<S> + Copy {
4087    /// Exact generated attribute-wrapper tuple returned for each group row.
4088    type Output;
4089
4090    #[doc(hidden)]
4091    fn fields(&self) -> Vec<(BindingKey, &'static str)>;
4092
4093    #[doc(hidden)]
4094    fn decode(values: &[AttributeValue]) -> Result<Self::Output>;
4095}
4096
4097mod field_group_tuple_sealed {
4098    pub trait Sealed<S> {}
4099}
4100
4101macro_rules! field_group_tuple {
4102    ($(($owner:ident, $value:ident, $index:tt)),+) => {
4103        impl<S, $($owner, $value),+> field_group_tuple_sealed::Sealed<S>
4104            for ($(BoundField<S, $owner, $value>,)+)
4105        where
4106            S: Schema,
4107            $($owner: Model<Schema = S>, $value: GroupedQueryValue),+
4108        {
4109        }
4110
4111        impl<S, $($owner, $value),+> FieldGroupTuple<S>
4112            for ($(BoundField<S, $owner, $value>,)+)
4113        where
4114            S: Schema,
4115            $($owner: Model<Schema = S>, $value: GroupedQueryValue),+
4116        {
4117            type Output = ($($value,)+);
4118
4119            fn fields(&self) -> Vec<(BindingKey, &'static str)> {
4120                vec![$((self.$index.key, self.$index.owns_id_json)),+]
4121            }
4122
4123            fn decode(values: &[AttributeValue]) -> Result<Self::Output> {
4124                let expected = [$(stringify!($owner)),+].len();
4125                if values.len() != expected {
4126                    return Err(Error::model_validation(
4127                        ModelValidationPhase::Hydration,
4128                        "wrong_result_shape",
4129                        vec![],
4130                        "tuple-field-grouped aggregate key has the wrong arity",
4131                        None,
4132                    ));
4133                }
4134                Ok(($(
4135                    $value::from_group_scalar(encoded_group_scalar(&values[$index])?)
4136                        .map_err(|error| {
4137                            map_validation_error(error, ModelValidationPhase::Hydration)
4138                        })?,
4139                )+))
4140            }
4141        }
4142    };
4143}
4144
4145field_group_tuple!((O1, V1, 0), (O2, V2, 1));
4146field_group_tuple!((O1, V1, 0), (O2, V2, 1), (O3, V3, 2));
4147field_group_tuple!((O1, V1, 0), (O2, V2, 1), (O3, V3, 2), (O4, V4, 3));
4148field_group_tuple!(
4149    (O1, V1, 0),
4150    (O2, V2, 1),
4151    (O3, V3, 2),
4152    (O4, V4, 3),
4153    (O5, V5, 4)
4154);
4155field_group_tuple!(
4156    (O1, V1, 0),
4157    (O2, V2, 1),
4158    (O3, V3, 2),
4159    (O4, V4, 3),
4160    (O5, V5, 4),
4161    (O6, V6, 5)
4162);
4163field_group_tuple!(
4164    (O1, V1, 0),
4165    (O2, V2, 1),
4166    (O3, V3, 2),
4167    (O4, V4, 3),
4168    (O5, V5, 4),
4169    (O6, V6, 5),
4170    (O7, V7, 6)
4171);
4172field_group_tuple!(
4173    (O1, V1, 0),
4174    (O2, V2, 1),
4175    (O3, V3, 2),
4176    (O4, V4, 3),
4177    (O5, V5, 4),
4178    (O6, V6, 5),
4179    (O7, V7, 6),
4180    (O8, V8, 7)
4181);
4182field_group_tuple!(
4183    (O1, V1, 0),
4184    (O2, V2, 1),
4185    (O3, V3, 2),
4186    (O4, V4, 3),
4187    (O5, V5, 4),
4188    (O6, V6, 5),
4189    (O7, V7, 6),
4190    (O8, V8, 7),
4191    (O9, V9, 8)
4192);
4193field_group_tuple!(
4194    (O1, V1, 0),
4195    (O2, V2, 1),
4196    (O3, V3, 2),
4197    (O4, V4, 3),
4198    (O5, V5, 4),
4199    (O6, V6, 5),
4200    (O7, V7, 6),
4201    (O8, V8, 7),
4202    (O9, V9, 8),
4203    (O10, V10, 9)
4204);
4205field_group_tuple!(
4206    (O1, V1, 0),
4207    (O2, V2, 1),
4208    (O3, V3, 2),
4209    (O4, V4, 3),
4210    (O5, V5, 4),
4211    (O6, V6, 5),
4212    (O7, V7, 6),
4213    (O8, V8, 7),
4214    (O9, V9, 8),
4215    (O10, V10, 9),
4216    (O11, V11, 10)
4217);
4218field_group_tuple!(
4219    (O1, V1, 0),
4220    (O2, V2, 1),
4221    (O3, V3, 2),
4222    (O4, V4, 3),
4223    (O5, V5, 4),
4224    (O6, V6, 5),
4225    (O7, V7, 6),
4226    (O8, V8, 7),
4227    (O9, V9, 8),
4228    (O10, V10, 9),
4229    (O11, V11, 10),
4230    (O12, V12, 11)
4231);
4232field_group_tuple!(
4233    (O1, V1, 0),
4234    (O2, V2, 1),
4235    (O3, V3, 2),
4236    (O4, V4, 3),
4237    (O5, V5, 4),
4238    (O6, V6, 5),
4239    (O7, V7, 6),
4240    (O8, V8, 7),
4241    (O9, V9, 8),
4242    (O10, V10, 9),
4243    (O11, V11, 10),
4244    (O12, V12, 11),
4245    (O13, V13, 12)
4246);
4247field_group_tuple!(
4248    (O1, V1, 0),
4249    (O2, V2, 1),
4250    (O3, V3, 2),
4251    (O4, V4, 3),
4252    (O5, V5, 4),
4253    (O6, V6, 5),
4254    (O7, V7, 6),
4255    (O8, V8, 7),
4256    (O9, V9, 8),
4257    (O10, V10, 9),
4258    (O11, V11, 10),
4259    (O12, V12, 11),
4260    (O13, V13, 12),
4261    (O14, V14, 13)
4262);
4263field_group_tuple!(
4264    (O1, V1, 0),
4265    (O2, V2, 1),
4266    (O3, V3, 2),
4267    (O4, V4, 3),
4268    (O5, V5, 4),
4269    (O6, V6, 5),
4270    (O7, V7, 6),
4271    (O8, V8, 7),
4272    (O9, V9, 8),
4273    (O10, V10, 9),
4274    (O11, V11, 10),
4275    (O12, V12, 11),
4276    (O13, V13, 12),
4277    (O14, V14, 13),
4278    (O15, V15, 14)
4279);
4280field_group_tuple!(
4281    (O1, V1, 0),
4282    (O2, V2, 1),
4283    (O3, V3, 2),
4284    (O4, V4, 3),
4285    (O5, V5, 4),
4286    (O6, V6, 5),
4287    (O7, V7, 6),
4288    (O8, V8, 7),
4289    (O9, V9, 8),
4290    (O10, V10, 9),
4291    (O11, V11, 10),
4292    (O12, V12, 11),
4293    (O13, V13, 12),
4294    (O14, V14, 13),
4295    (O15, V15, 14),
4296    (O16, V16, 15)
4297);
4298
4299/// One query lineage grouped by a generated owned-field tuple for
4300/// aggregation.
4301pub struct FieldTupleGroupedQuery<'s, 'db, S: Schema, B: Selectable<S>, G: FieldGroupTuple<S>> {
4302    query: Query<'s, 'db, S, B>,
4303    groups: G,
4304}
4305
4306impl<'s, 'db, S, B, G> FieldTupleGroupedQuery<'s, 'db, S, B, G>
4307where
4308    S: Schema,
4309    B: Selectable<S>,
4310    G: FieldGroupTuple<S>,
4311{
4312    /// Explicitly close this independently owned grouped-query lineage.
4313    pub fn close(&self) {
4314        self.query.close();
4315    }
4316
4317    /// Return whether this grouped query was explicitly closed.
4318    #[must_use]
4319    pub fn is_closed(&self) -> bool {
4320        self.query.is_closed()
4321    }
4322
4323    /// Reduce each witnessed distinct field-value tuple to one typed tuple,
4324    /// returning exact generated attribute wrappers with the aggregates.
4325    pub async fn aggregate<T: crate::aggregate::AggregateTuple<S>>(
4326        &self,
4327        terms: T,
4328    ) -> Result<Vec<(G::Output, T::Output)>> {
4329        let deadline = self.query.session.begin_invocation()?;
4330        let term_list = terms.terms();
4331        let group_fields = self.groups.fields();
4332        let validated = self
4333            .query
4334            .validated_reduce_by_fields(&group_fields, &term_list)?;
4335        let (validated, result) = self.query.execute(validated, deadline).await?;
4336        let rows = self
4337            .query
4338            .decoded_reduction_rows(&validated, &result, deadline)?;
4339        let mut outputs = Vec::with_capacity(rows.len());
4340        for row in rows {
4341            self.query
4342                .session
4343                .check_invocation(deadline, ModelValidationPhase::Hydration)?;
4344            let values = row.field_groups().ok_or_else(|| {
4345                Error::model_validation(
4346                    ModelValidationPhase::Hydration,
4347                    "wrong_result_shape",
4348                    vec![],
4349                    "tuple-field-grouped aggregates require tuple group evidence per row",
4350                    None,
4351                )
4352            })?;
4353            outputs.push((G::decode(values)?, T::decode(row.values())?));
4354        }
4355        self.query
4356            .session
4357            .check_invocation(deadline, ModelValidationPhase::Hydration)?;
4358        Ok(outputs)
4359    }
4360}