Skip to main content

type_bridge/
plan.rs

1#![deny(missing_docs)]
2//! Typed `query-plan/v3` programs built from generated model tokens.
3//!
4//! A [`PlanBuilder`] declares things, field values, inputs and `let`
5//! values, then the writes over them. [`PlanBuilder::build`] validates the
6//! program against the generated schema package and returns a [`Plan`],
7//! which a staged [`Transaction`](crate::staged::Transaction) runs at
8//! commit. The program is one pipeline: a write plan that matches nothing
9//! writes nothing.
10//!
11//! The rules are the same in every SDK, so the same program gives the same
12//! canonical bytes in Rust, Python, TypeScript and C:
13//!
14//! - Handles are numbered in creation order.
15//! - `exact`, `subtypes`, `field`, `links`, `where_` and `let_` add to the
16//!   plan's single leading match, in call order.
17//! - Writes run in call order after the match. Consecutive writes of one
18//!   kind (`update`, `insert`, `put`, `delete`) share one stage.
19//! - Things and fields are named from their labels (`item`, `item_stock`),
20//!   with `_2`, `_3`, ... on collision. `input` and `let_` names must be
21//!   fresh.
22//!
23//! Handles belong to the builder that created them.
24//!
25//! This example is ignored because `Item`, `ItemType` and `models::SCHEMA`
26//! come from an application's generated schema package, which this crate
27//! does not ship.
28//!
29//! ```ignore
30//! let mut plan = Plan::builder();
31//! let item = plan.exact::<Item>();
32//! let stock = plan.field(item, ItemType::stock);
33//! plan.where_(stock.gt(0_i64));
34//! let next = plan.let_("next_stock", stock - 1_i64);
35//! plan.update(item, ItemType::stock, next);
36//! let plan = plan.build(&models::SCHEMA)?;
37//! ```
38
39use std::marker::PhantomData;
40
41use type_bridge_contract::codec::from_canonical_json;
42use type_bridge_contract::id::{AttributeId, RoleId, TypeId};
43use type_bridge_contract::migration_assertion::{BindingId, ValueComparator};
44use type_bridge_contract::query_plan::v3::{
45    ArithOp, Builtin, Expr as PlanExpr, PlanBuilder as CoreBuilder, QueryPlanV3,
46};
47use type_bridge_contract::query_plan::{InputColumnId, QueryOperand};
48use type_bridge_contract::schema::OwnsFactId;
49use type_bridge_contract::value::{CanonicalValue, ValueTypeTag};
50
51use crate::__codegen::{
52    CanonicalDouble, Date, DateTime, DateTimeTz, Decimal, Duration, FieldToken, Model,
53    NominalUpcast, QueryValued, RelationModel, RolePlayerBinding, RoleToken, RoleTokenCompatible,
54    ThingModel, ValidationError, ValidationPath,
55};
56use crate::Result;
57use crate::error::{Error, ModelValidationPhase};
58use crate::query::{Exact, SelectionMode, Subtypes};
59use crate::schema::{Schema, SchemaPackage};
60
61fn identity_error(code: &'static str) -> Error {
62    Error::model_validation(
63        ModelValidationPhase::Input,
64        code,
65        vec![],
66        "generated token identity is not canonical",
67        None,
68    )
69}
70
71fn literal_error(error: ValidationError) -> Error {
72    Error::model_validation(
73        ModelValidationPhase::Input,
74        "plan_literal_invalid",
75        vec![],
76        "a plan literal is not a canonical value",
77        Some(Box::new(error)),
78    )
79}
80
81fn type_id<M: Model>() -> Result<TypeId> {
82    from_canonical_json(M::TYPE_ID_JSON.as_bytes())
83        .map_err(|_| identity_error("invalid_model_identity"))
84}
85
86fn owns_id(owns_id_json: &str) -> Result<OwnsFactId> {
87    let invalid = || identity_error("invalid_field_identity");
88    let value: serde_json::Value = serde_json::from_str(owns_id_json).map_err(|_| invalid())?;
89    let owner: TypeId = value
90        .get("owner")
91        .cloned()
92        .and_then(|owner| serde_json::from_value(owner).ok())
93        .ok_or_else(invalid)?;
94    let attribute = value
95        .get("attribute")
96        .and_then(serde_json::Value::as_str)
97        .and_then(|attribute| AttributeId::new(attribute).ok())
98        .ok_or_else(invalid)?;
99    OwnsFactId::new(owner, attribute).map_err(|_| invalid())
100}
101
102fn role_id(role_id_json: &str) -> Result<RoleId> {
103    from_canonical_json(role_id_json.as_bytes())
104        .map_err(|_| identity_error("invalid_role_identity"))
105}
106
107fn canonical<T: QueryValued>(value: &T) -> std::result::Result<CanonicalValue, ValidationError> {
108    value
109        .into_encoded_scalar()
110        .to_canonical_value(&ValidationPath::root())
111}
112
113mod sealed {
114    pub trait Sealed {
115        const VALUE_TYPE: super::ValueTypeTag;
116    }
117}
118
119/// A scalar domain an input column can carry: the `Domain` of a generated
120/// value wrapper or of a plain Rust scalar.
121pub trait PlanScalar: sealed::Sealed {}
122
123macro_rules! plan_scalar {
124    ($($domain:ty => $tag:ident),* $(,)?) => {$(
125        impl sealed::Sealed for $domain {
126            const VALUE_TYPE: ValueTypeTag = ValueTypeTag::$tag;
127        }
128        impl PlanScalar for $domain {}
129    )*};
130}
131plan_scalar!(
132    String => String,
133    i64 => Long,
134    CanonicalDouble => Double,
135    bool => Boolean,
136    Decimal => Decimal,
137    Date => Date,
138    DateTime => DateTime,
139    DateTimeTz => DateTimeTz,
140    Duration => Duration,
141);
142
143/// A matched or created thing of model `M`.
144pub struct Thing<M: ThingModel, Mode: SelectionMode = Exact> {
145    binding: BindingId,
146    marker: PhantomData<fn() -> (M, Mode)>,
147}
148impl<M: ThingModel, Mode: SelectionMode> Clone for Thing<M, Mode> {
149    fn clone(&self) -> Self {
150        *self
151    }
152}
153impl<M: ThingModel, Mode: SelectionMode> Copy for Thing<M, Mode> {}
154impl<M: ThingModel, Mode: SelectionMode> std::fmt::Debug for Thing<M, Mode> {
155    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        formatter
157            .debug_tuple("Thing")
158            .field(&self.binding.get())
159            .finish()
160    }
161}
162
163/// A scalar value bound by [`PlanBuilder::field`] or [`PlanBuilder::let_`].
164#[derive(Clone, Copy, Debug)]
165pub struct Value {
166    binding: BindingId,
167}
168
169/// A typed input column; rows supply its values through [`Input::value`].
170pub struct Input<V> {
171    column: InputColumnId,
172    marker: PhantomData<fn() -> V>,
173}
174impl<V> Clone for Input<V> {
175    fn clone(&self) -> Self {
176        *self
177    }
178}
179impl<V> Copy for Input<V> {}
180impl<V> std::fmt::Debug for Input<V> {
181    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        formatter
183            .debug_tuple("Input")
184            .field(&self.column.get())
185            .finish()
186    }
187}
188
189impl<V: QueryValued> Input<V> {
190    /// This column's value in one input row.
191    #[must_use]
192    pub fn value(self, value: V) -> InputValue {
193        InputValue {
194            column: self.column,
195            value: canonical(&value).map(Some),
196        }
197    }
198}
199impl<V> Input<V> {
200    /// An absent value for an optional column.
201    #[must_use]
202    pub fn absent(self) -> InputValue {
203        InputValue {
204            column: self.column,
205            value: Ok(None),
206        }
207    }
208}
209
210/// One column's value in an input row; see [`PlanBuilder::row`].
211#[derive(Clone, Debug)]
212pub struct InputValue {
213    column: InputColumnId,
214    value: std::result::Result<Option<CanonicalValue>, ValidationError>,
215}
216
217/// A scalar operand: a [`Value`], an [`Input`], or a literal.
218#[derive(Clone, Debug)]
219pub struct Operand(std::result::Result<QueryOperand, ValidationError>);
220
221impl From<Value> for Operand {
222    fn from(value: Value) -> Self {
223        Self(Ok(QueryOperand::Binding {
224            binding: value.binding,
225        }))
226    }
227}
228impl<V> From<Input<V>> for Operand {
229    fn from(input: Input<V>) -> Self {
230        Self(Ok(QueryOperand::Input {
231            column: input.column,
232        }))
233    }
234}
235impl<T: QueryValued> From<T> for Operand {
236    fn from(value: T) -> Self {
237        Self(canonical(&value).map(|value| QueryOperand::Literal { value }))
238    }
239}
240
241/// A comparison between two operands, added with [`PlanBuilder::where_`].
242#[derive(Clone, Debug)]
243pub struct Condition {
244    left: Operand,
245    comparator: ValueComparator,
246    right: Operand,
247}
248
249macro_rules! comparisons {
250    ($($name:ident => $comparator:ident, $doc:literal;)*) => {$(
251        #[doc = $doc]
252        #[must_use]
253        pub fn $name(self, other: impl Into<Operand>) -> Condition {
254            Condition {
255                left: self.into(),
256                comparator: ValueComparator::$comparator,
257                right: other.into(),
258            }
259        }
260    )*};
261}
262impl Value {
263    comparisons! {
264        eq => Equal, "Require this value to equal `other`.";
265        ne => NotEqual, "Require this value to differ from `other`.";
266        lt => Less, "Require this value to be less than `other`.";
267        le => LessOrEqual, "Require this value to be at most `other`.";
268        gt => Greater, "Require this value to be greater than `other`.";
269        ge => GreaterOrEqual, "Require this value to be at least `other`.";
270    }
271}
272
273/// A value expression for [`PlanBuilder::let_`]. Build it with `+`, `-`,
274/// `*`, `/` and `%` over values, inputs and literals, or with the builtins.
275#[derive(Clone, Debug)]
276pub struct Expr(std::result::Result<PlanExpr, ValidationError>);
277
278impl<T: Into<Operand>> From<T> for Expr {
279    fn from(operand: T) -> Self {
280        Self(operand.into().0.map(PlanExpr::Operand))
281    }
282}
283
284impl Expr {
285    fn arith(op: ArithOp, lhs: Self, rhs: Self) -> Self {
286        Self(lhs.0.and_then(|lhs| {
287            rhs.0.map(|rhs| PlanExpr::Arith {
288                op,
289                lhs: Box::new(lhs),
290                rhs: Box::new(rhs),
291            })
292        }))
293    }
294    fn call(func: Builtin, args: Vec<Self>) -> Self {
295        Self(
296            args.into_iter()
297                .map(|arg| arg.0)
298                .collect::<std::result::Result<Vec<_>, _>>()
299                .map(|args| PlanExpr::Call { func, args }),
300        )
301    }
302    /// `base` to the power `exponent`.
303    #[must_use]
304    pub fn pow(base: impl Into<Self>, exponent: impl Into<Self>) -> Self {
305        Self::arith(ArithOp::Pow, base.into(), exponent.into())
306    }
307    /// Absolute value.
308    #[must_use]
309    pub fn abs(value: impl Into<Self>) -> Self {
310        Self::call(Builtin::Abs, vec![value.into()])
311    }
312    /// Smallest integer not below a decimal or double.
313    #[must_use]
314    pub fn ceil(value: impl Into<Self>) -> Self {
315        Self::call(Builtin::Ceil, vec![value.into()])
316    }
317    /// Largest integer not above a decimal or double.
318    #[must_use]
319    pub fn floor(value: impl Into<Self>) -> Self {
320        Self::call(Builtin::Floor, vec![value.into()])
321    }
322    /// Nearest integer to a decimal or double.
323    #[must_use]
324    pub fn round(value: impl Into<Self>) -> Self {
325        Self::call(Builtin::Round, vec![value.into()])
326    }
327    /// The smaller of two values of one numeric domain.
328    #[must_use]
329    pub fn min(left: impl Into<Self>, right: impl Into<Self>) -> Self {
330        Self::call(Builtin::Min, vec![left.into(), right.into()])
331    }
332    /// The larger of two values of one numeric domain.
333    #[must_use]
334    pub fn max(left: impl Into<Self>, right: impl Into<Self>) -> Self {
335        Self::call(Builtin::Max, vec![left.into(), right.into()])
336    }
337    /// The length of a string.
338    #[must_use]
339    pub fn length(value: impl Into<Self>) -> Self {
340        Self::call(Builtin::Length, vec![value.into()])
341    }
342}
343
344macro_rules! arithmetic {
345    ($($trait:ident :: $method:ident => $op:ident;)*) => {$(
346        impl<R: Into<Expr>> std::ops::$trait<R> for Expr {
347            type Output = Expr;
348            fn $method(self, rhs: R) -> Expr {
349                Expr::arith(ArithOp::$op, self, rhs.into())
350            }
351        }
352        impl<R: Into<Expr>> std::ops::$trait<R> for Value {
353            type Output = Expr;
354            fn $method(self, rhs: R) -> Expr {
355                Expr::arith(ArithOp::$op, self.into(), rhs.into())
356            }
357        }
358        impl<V, R: Into<Expr>> std::ops::$trait<R> for Input<V> {
359            type Output = Expr;
360            fn $method(self, rhs: R) -> Expr {
361                Expr::arith(ArithOp::$op, self.into(), rhs.into())
362            }
363        }
364    )*};
365}
366arithmetic! {
367    Add::add => Add;
368    Sub::sub => Sub;
369    Mul::mul => Mul;
370    Div::div => Div;
371    Rem::rem => Mod;
372}
373
374/// A projected handle for [`PlanBuilder::returning`].
375#[derive(Clone, Copy, Debug)]
376pub struct Column(BindingId);
377impl<M: ThingModel, Mode: SelectionMode> From<Thing<M, Mode>> for Column {
378    fn from(thing: Thing<M, Mode>) -> Self {
379        Self(thing.binding)
380    }
381}
382impl From<Value> for Column {
383    fn from(value: Value) -> Self {
384        Self(value.binding)
385    }
386}
387
388/// A validated `query-plan/v3` program for schema `S`.
389///
390/// Stage it on a [`Transaction`](crate::staged::Transaction) from
391/// [`Database::transaction`](crate::Database::transaction) or
392/// [`ProxyDatabase::transaction`](crate::ProxyDatabase::transaction).
393pub struct Plan<S: Schema> {
394    plan: QueryPlanV3,
395    marker: PhantomData<fn() -> S>,
396}
397impl<S: Schema> Clone for Plan<S> {
398    fn clone(&self) -> Self {
399        Self {
400            plan: self.plan.clone(),
401            marker: PhantomData,
402        }
403    }
404}
405impl<S: Schema> std::fmt::Debug for Plan<S> {
406    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407        formatter
408            .debug_struct("Plan")
409            .field("writes", &self.plan.writes())
410            .finish_non_exhaustive()
411    }
412}
413
414impl<S: Schema> Plan<S> {
415    /// Start an empty program.
416    #[must_use]
417    pub fn builder() -> PlanBuilder<S> {
418        PlanBuilder::new()
419    }
420
421    /// The plan's canonical `query-plan/v3` bytes, identical in every SDK.
422    ///
423    /// # Errors
424    ///
425    /// Returns an error when the plan exceeds the canonical codec limits.
426    pub fn canonical_bytes(&self) -> Result<Vec<u8>> {
427        self.plan
428            .canonical_bytes()
429            .map_err(Error::from_contract_diagnostic)
430    }
431
432    /// Whether the plan writes, which makes an inferred transaction kind
433    /// `Write`.
434    #[must_use]
435    pub fn writes(&self) -> bool {
436        self.plan.writes()
437    }
438
439    pub(crate) fn inner(&self) -> &QueryPlanV3 {
440        &self.plan
441    }
442}
443
444/// Builds one [`Plan`]. See the [module documentation](self) for the rules.
445///
446/// Methods never fail; the first invalid call is returned by
447/// [`Self::build`].
448pub struct PlanBuilder<S: Schema> {
449    core: CoreBuilder,
450    error: Option<Error>,
451    marker: PhantomData<fn() -> S>,
452}
453
454impl<S: Schema> Default for PlanBuilder<S> {
455    fn default() -> Self {
456        Self::new()
457    }
458}
459
460impl<S: Schema> std::fmt::Debug for PlanBuilder<S> {
461    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462        formatter
463            .debug_struct("PlanBuilder")
464            .finish_non_exhaustive()
465    }
466}
467
468impl<S: Schema> PlanBuilder<S> {
469    /// An empty program.
470    #[must_use]
471    pub fn new() -> Self {
472        Self {
473            core: CoreBuilder::new(),
474            error: None,
475            marker: PhantomData,
476        }
477    }
478
479    fn check<T>(&mut self, result: Result<T>) -> Option<T> {
480        match result {
481            Ok(value) => Some(value),
482            Err(error) => {
483                self.error.get_or_insert(error);
484                None
485            }
486        }
487    }
488
489    fn operand(&mut self, operand: impl Into<Operand>) -> QueryOperand {
490        let operand = operand.into().0.map_err(literal_error);
491        self.check(operand).unwrap_or(QueryOperand::Literal {
492            value: CanonicalValue::Boolean(false),
493        })
494    }
495
496    fn thing<M: ThingModel<Schema = S>, Mode: SelectionMode>(
497        &mut self,
498        binding: impl FnOnce(&mut CoreBuilder, TypeId) -> BindingId,
499    ) -> Thing<M, Mode> {
500        let binding = match self.check(type_id::<M>()) {
501            Some(type_id) => binding(&mut self.core, type_id),
502            None => BindingId::new(0).expect("zero is a valid binding"),
503        };
504        Thing {
505            binding,
506            marker: PhantomData,
507        }
508    }
509
510    /// Match things of exactly model `M`.
511    pub fn exact<M: ThingModel<Schema = S>>(&mut self) -> Thing<M, Exact> {
512        self.thing(CoreBuilder::exact)
513    }
514
515    /// Match things of model `M` or any of its subtypes.
516    pub fn subtypes<M: ThingModel<Schema = S>>(&mut self) -> Thing<M, Subtypes> {
517        self.thing(CoreBuilder::subtypes)
518    }
519
520    /// Bind the value of `thing`'s field. Things without the field do not
521    /// match.
522    pub fn field<M, Mode, Owner, V>(
523        &mut self,
524        thing: Thing<M, Mode>,
525        token: FieldToken<Owner, V>,
526    ) -> Value
527    where
528        M: ThingModel<Schema = S> + NominalUpcast<Owner>,
529        Mode: SelectionMode,
530        Owner: Model<Schema = S>,
531    {
532        let binding = match self.check(owns_id(token.owns_id_json())) {
533            Some(field) => self.core.field(thing.binding, field.attribute().clone()),
534            None => BindingId::new(0).expect("zero is a valid binding"),
535        };
536        Value { binding }
537    }
538
539    /// Declare an input column named `name`; each [`Self::row`] supplies a
540    /// value. Many rows run the one plan over all of them.
541    pub fn input<V>(&mut self, name: &str) -> Input<V>
542    where
543        V: QueryValued,
544        V::Domain: PlanScalar,
545    {
546        let column = self
547            .core
548            .input(name, <V::Domain as sealed::Sealed>::VALUE_TYPE, false);
549        Input {
550            column,
551            marker: PhantomData,
552        }
553    }
554
555    /// Declare an optional input column; rows may give it
556    /// [`Input::absent`].
557    pub fn optional_input<V>(&mut self, name: &str) -> Input<V>
558    where
559        V: QueryValued,
560        V::Domain: PlanScalar,
561    {
562        let column = self
563            .core
564            .input(name, <V::Domain as sealed::Sealed>::VALUE_TYPE, true);
565        Input {
566            column,
567            marker: PhantomData,
568        }
569    }
570
571    /// Require `condition` of every matched row.
572    pub fn where_(&mut self, condition: Condition) -> &mut Self {
573        let left = self.operand(condition.left);
574        let right = self.operand(condition.right);
575        self.core.compare(left, condition.comparator, right);
576        self
577    }
578
579    /// Require `relation` to link `player` in `role`.
580    pub fn links<R, RMode, Owner, Players, P, PMode>(
581        &mut self,
582        relation: Thing<R, RMode>,
583        role: RoleToken<Owner, Players>,
584        player: Thing<P, PMode>,
585    ) -> &mut Self
586    where
587        R: ThingModel<Schema = S> + RoleTokenCompatible<Owner, Players>,
588        RMode: SelectionMode,
589        Owner: RelationModel<Schema = S>,
590        Players: RolePlayerBinding<P, PMode>,
591        P: ThingModel<Schema = S>,
592        PMode: SelectionMode,
593    {
594        if let Some(role) = self.check(role_id(role.role_id_json())) {
595            self.core.links(relation.binding, role, player.binding);
596        }
597        self
598    }
599
600    /// Bind `name` to `expr`, evaluated for each matched row.
601    pub fn let_(&mut self, name: &str, expr: impl Into<Expr>) -> Value {
602        let expr = expr.into().0.map_err(literal_error);
603        let expr = self
604            .check(expr)
605            .unwrap_or(PlanExpr::Operand(QueryOperand::Literal {
606                value: CanonicalValue::Boolean(false),
607            }));
608        Value {
609            binding: self.core.let_(name, expr),
610        }
611    }
612
613    /// Replace `thing`'s field value with `value`.
614    pub fn update<M, Mode, Owner, V>(
615        &mut self,
616        thing: Thing<M, Mode>,
617        token: FieldToken<Owner, V>,
618        value: impl Into<Operand>,
619    ) -> &mut Self
620    where
621        M: ThingModel<Schema = S> + NominalUpcast<Owner>,
622        Mode: SelectionMode,
623        Owner: Model<Schema = S>,
624    {
625        let operand = self.operand(value);
626        if let Some(field) = self.check(owns_id(token.owns_id_json())) {
627            self.core.update(thing.binding, field, operand);
628        }
629        self
630    }
631
632    /// Make `player` the `role` player of `relation`.
633    pub fn update_player<R, RMode, Owner, Players, P, PMode>(
634        &mut self,
635        relation: Thing<R, RMode>,
636        role: RoleToken<Owner, Players>,
637        player: Thing<P, PMode>,
638    ) -> &mut Self
639    where
640        R: ThingModel<Schema = S> + RoleTokenCompatible<Owner, Players>,
641        RMode: SelectionMode,
642        Owner: RelationModel<Schema = S>,
643        Players: RolePlayerBinding<P, PMode>,
644        P: ThingModel<Schema = S>,
645        PMode: SelectionMode,
646    {
647        if let Some(role) = self.check(role_id(role.role_id_json())) {
648            self.core
649                .update_player(relation.binding, role, player.binding);
650        }
651        self
652    }
653
654    /// Create a thing of model `M`; give it fields and players on the
655    /// returned [`NewThing`].
656    pub fn insert<M: ThingModel<Schema = S>>(&mut self) -> NewThing<'_, S, M> {
657        let thing = self.thing(CoreBuilder::insert);
658        NewThing {
659            builder: self,
660            thing,
661        }
662    }
663
664    /// Match a thing of model `M` with the fields and players given on the
665    /// returned [`NewThing`], or create it.
666    pub fn put<M: ThingModel<Schema = S>>(&mut self) -> NewThing<'_, S, M> {
667        let thing = self.thing(CoreBuilder::put);
668        NewThing {
669            builder: self,
670            thing,
671        }
672    }
673
674    /// Delete `thing`.
675    pub fn delete<M: ThingModel<Schema = S>, Mode: SelectionMode>(
676        &mut self,
677        thing: Thing<M, Mode>,
678    ) -> &mut Self {
679        self.core.delete(thing.binding);
680        self
681    }
682
683    /// Delete `thing`'s field, keeping the thing.
684    pub fn delete_field<M, Mode, Owner, V>(
685        &mut self,
686        thing: Thing<M, Mode>,
687        token: FieldToken<Owner, V>,
688    ) -> &mut Self
689    where
690        M: ThingModel<Schema = S> + NominalUpcast<Owner>,
691        Mode: SelectionMode,
692        Owner: Model<Schema = S>,
693    {
694        if let Some(field) = self.check(owns_id(token.owns_id_json())) {
695            self.core.delete_field(thing.binding, field);
696        }
697        self
698    }
699
700    /// Remove `player` from `relation`'s `role`.
701    pub fn delete_player<R, RMode, Owner, Players, P, PMode>(
702        &mut self,
703        relation: Thing<R, RMode>,
704        role: RoleToken<Owner, Players>,
705        player: Thing<P, PMode>,
706    ) -> &mut Self
707    where
708        R: ThingModel<Schema = S> + RoleTokenCompatible<Owner, Players>,
709        RMode: SelectionMode,
710        Owner: RelationModel<Schema = S>,
711        Players: RolePlayerBinding<P, PMode>,
712        P: ThingModel<Schema = S>,
713        PMode: SelectionMode,
714    {
715        if let Some(role) = self.check(role_id(role.role_id_json())) {
716            self.core
717                .delete_player(relation.binding, role, player.binding);
718        }
719        self
720    }
721
722    /// Add one input row. Every column appears at most once; a missing
723    /// optional column is absent.
724    pub fn row(&mut self, values: impl IntoIterator<Item = InputValue>) -> &mut Self {
725        let mut row: Vec<Option<CanonicalValue>> = Vec::new();
726        let mut seen = std::collections::BTreeSet::new();
727        for value in values {
728            let index = usize::from(value.column.get());
729            if !seen.insert(index) {
730                self.check::<()>(Err(Error::model_validation(
731                    ModelValidationPhase::Input,
732                    "plan_input_duplicate",
733                    vec![],
734                    "an input row gives one column twice",
735                    None,
736                )));
737                return self;
738            }
739            let Some(value) = self.check(value.value.map_err(literal_error)) else {
740                return self;
741            };
742            if row.len() <= index {
743                row.resize(index + 1, None);
744            }
745            row[index] = value;
746        }
747        self.core.row(row);
748        self
749    }
750
751    /// Project `columns`, in order. A write plan then answers these rows
752    /// from the same pipeline instead of its matched count.
753    pub fn returning(&mut self, columns: impl IntoIterator<Item = impl Into<Column>>) -> &mut Self {
754        self.core
755            .returning(columns.into_iter().map(|column| column.into().0).collect());
756        self
757    }
758
759    /// Answer the number of rows a read plan matches.
760    pub fn count(&mut self) -> &mut Self {
761        self.core.count();
762        self
763    }
764
765    /// Answer whether a read plan matches any row.
766    pub fn exists(&mut self) -> &mut Self {
767        self.core.exists();
768        self
769    }
770
771    /// Validate the program against the generated schema package.
772    ///
773    /// A plan with writes answers its matched row count, or the
774    /// [`Self::returning`] rows. A read answers rows, or
775    /// [`Self::count`] / [`Self::exists`].
776    ///
777    /// # Errors
778    ///
779    /// Returns the first invalid builder call, a package without compiled
780    /// schema authority, or the plan validation failure (for example a
781    /// field the thing does not own, or a key field update).
782    pub fn build(self, schema: &SchemaPackage<S>) -> Result<Plan<S>> {
783        if let Some(error) = self.error {
784            return Err(error);
785        }
786        let authority = schema.plan_authority()?;
787        let plan = self
788            .core
789            .build(
790                authority.declared_schema(),
791                authority.managed_state().managed_semantic_schema().clone(),
792            )
793            .map_err(Error::from_contract_diagnostic)?;
794        Ok(Plan {
795            plan,
796            marker: PhantomData,
797        })
798    }
799}
800
801/// A thing being inserted or put; add its fields and players, then take
802/// its handle with [`Self::thing`].
803pub struct NewThing<'a, S: Schema, M: ThingModel<Schema = S>> {
804    builder: &'a mut PlanBuilder<S>,
805    thing: Thing<M, Exact>,
806}
807
808impl<S: Schema, M: ThingModel<Schema = S>> std::fmt::Debug for NewThing<'_, S, M> {
809    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
810        formatter
811            .debug_tuple("NewThing")
812            .field(&self.thing)
813            .finish()
814    }
815}
816
817impl<S: Schema, M: ThingModel<Schema = S>> NewThing<'_, S, M> {
818    /// Give the new thing a field value.
819    pub fn field<Owner, V>(self, token: FieldToken<Owner, V>, value: impl Into<Operand>) -> Self
820    where
821        M: NominalUpcast<Owner>,
822        Owner: Model<Schema = S>,
823    {
824        let operand = self.builder.operand(value);
825        if let Some(field) = self.builder.check(owns_id(token.owns_id_json())) {
826            self.builder
827                .core
828                .thing_field(self.thing.binding, field, operand);
829        }
830        self
831    }
832
833    /// Give the new relation a role player.
834    pub fn player<Owner, Players, P, PMode>(
835        self,
836        role: RoleToken<Owner, Players>,
837        player: Thing<P, PMode>,
838    ) -> Self
839    where
840        M: RoleTokenCompatible<Owner, Players>,
841        Owner: RelationModel<Schema = S>,
842        Players: RolePlayerBinding<P, PMode>,
843        P: ThingModel<Schema = S>,
844        PMode: SelectionMode,
845    {
846        if let Some(role) = self.builder.check(role_id(role.role_id_json())) {
847            self.builder
848                .core
849                .thing_player(self.thing.binding, role, player.binding);
850        }
851        self
852    }
853
854    /// The new thing's handle.
855    #[must_use]
856    pub fn thing(self) -> Thing<M, Exact> {
857        self.thing
858    }
859}
860
861#[cfg(test)]
862mod tests;