Skip to main content

postrust_graphql/
handler.rs

1//! Axum handler for the /graphql endpoint.
2//!
3//! Provides GraphQL request handling using async-graphql with dynamic schema
4//! generation from the PostgreSQL schema cache.
5
6use crate::context::GraphQLContext;
7use crate::error::GraphQLError;
8use crate::schema::object::TableObjectType;
9use crate::schema::relationship::RelationshipField;
10use crate::schema::{build_schema, FederationEntity, GeneratedSchema, MutationType, SchemaConfig};
11use crate::subscription::{
12    generate_subscription_fields, NotifyBroker, SubscriptionField as SubField,
13};
14use async_graphql::dynamic::*;
15use async_graphql::extensions::{
16    Extension, ExtensionContext, ExtensionFactory, NextResolve, ResolveInfo,
17};
18use async_graphql::parser::types::{FragmentDefinition, Selection, SelectionSet, TypeCondition};
19use async_graphql::{Name, Positioned, SelectionField, ServerResult, Value};
20use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
21use axum::extract::State;
22use axum::response::IntoResponse;
23use postrust_core::schema_cache::SchemaCache;
24use sqlx::{AssertSqlSafe, PgPool};
25use std::collections::{BTreeMap, HashMap, HashSet};
26use std::sync::Arc;
27use tokio::sync::RwLock;
28use tracing::{debug, info, trace};
29
30/// GraphQL execution state shared across requests.
31pub struct GraphQLState {
32    /// Database connection pool
33    pub pool: PgPool,
34    /// Schema cache
35    pub schema_cache: Arc<SchemaCache>,
36    /// Generated GraphQL schema
37    pub generated_schema: GeneratedSchema,
38    /// async-graphql Schema (built dynamically)
39    ///
40    /// The unrestricted one: what an administrator is answered from, and what
41    /// every caller is answered from on a server with no permission document.
42    pub schema: Schema,
43    /// One schema per role the permission document names.
44    ///
45    /// Hasura builds a schema per role because a permission is a statement
46    /// about what exists, not about what is allowed: a role with no `select`
47    /// on a table has no field to name, and naming one is a validation failure
48    /// rather than a denial. Each is built from a schema cache already reduced
49    /// to what that role may see.
50    ///
51    /// Built at startup rather than on first use, so a permission document
52    /// that cannot be built fails while someone is watching rather than on the
53    /// first request from whichever role it broke.
54    ///
55    /// Keyed by the role and by whether the caller asked for what only a
56    /// backend may name -- which is a second schema rather than a check,
57    /// because `backend_only` decides whether a field exists.
58    pub role_schemas: HashMap<(String, bool), Schema>,
59    /// What a role the document never names is answered from.
60    ///
61    /// Not a refusal. To Hasura an unrecognised role is a role with nothing
62    /// granted, so it gets a schema with nothing in it -- and a request is
63    /// answered `field 'user' not found in type: 'query_root'`, or `no
64    /// mutations exist` where there is no mutation root at all, rather than
65    /// with a complaint about the role. `address_permission_error` sends
66    /// `X-Hasura-Role: merchant`, which no permission mentions, and expects
67    /// exactly that.
68    ///
69    /// One schema for every such role rather than one each: they are all the
70    /// same schema, since what they were granted is the same nothing.
71    pub ungranted_schema: Option<Schema>,
72    /// Schema configuration
73    pub config: SchemaConfig,
74    /// Subscription fields
75    pub subscription_fields: Vec<SubField>,
76    /// Notification broker for subscriptions
77    pub broker: Arc<RwLock<Option<NotifyBroker>>>,
78}
79
80/// async-graphql's dynamic resolver requires every union value to carry a
81/// concrete type, including `null`. A typed null is then treated as an object,
82/// though, so its non-null fields fail. Convert only the library's error for a
83/// bare null `_Entity` list member back into the nullable member the schema
84/// declares.
85struct NullableFederationEntity;
86
87impl ExtensionFactory for NullableFederationEntity {
88    fn create(&self) -> Arc<dyn Extension> {
89        Arc::new(Self)
90    }
91}
92
93#[async_graphql::async_trait::async_trait]
94impl Extension for NullableFederationEntity {
95    async fn resolve(
96        &self,
97        ctx: &ExtensionContext<'_>,
98        info: ResolveInfo<'_>,
99        next: NextResolve<'_>,
100    ) -> ServerResult<Option<Value>> {
101        // IMPORTANT: async-graphql 7.0.17 invokes this hook for every field and
102        // every list member, not only `_entities`. That leaves one boxed
103        // extension future per call, so do not copy this pattern for other
104        // field-specific behaviour. Its dynamic API cannot represent a bare
105        // nullable union member: an untyped null is rejected and a typed null
106        // is resolved as an object. Until that changes upstream, keep the
107        // successful path to the one required `next.run`; in particular,
108        // defer all string comparisons until the union error has occurred.
109        let parent_type = info.parent_type;
110        let return_type = info.return_type;
111        match next.run(ctx, info).await {
112            Err(error)
113                if error.message
114                    == "internal: invalid value for union \"_Entity\", expected \"FieldValue::WithType\""
115                    && parent_type == "[_Entity]"
116                    && return_type == "_Entity" =>
117            {
118                Ok(Some(Value::Null))
119            }
120            result => result,
121        }
122    }
123}
124
125/// Build one schema for each role the permission document names.
126///
127/// Each is built from a cache reduced to what that role may see, so nothing in
128/// the builders needs to know a permission exists -- a table this role cannot
129/// read is one the code generating root fields cannot see either. See
130/// [`crate::role`] for why the filtering is done there rather than threaded
131/// through.
132///
133/// Empty when the document carries no permissions, which is what leaves an
134/// unconfigured server building exactly the one schema it always did.
135fn build_role_schemas(
136    schema_cache: &Arc<SchemaCache>,
137    config: &SchemaConfig,
138) -> Result<HashMap<(String, bool), Schema>, GraphQLError> {
139    if !config.names.has_permissions() {
140        return Ok(HashMap::new());
141    }
142
143    let mut schemas = HashMap::new();
144    for role in config.names.roles() {
145        // An administrator is not a role with permissions; it is the caller
146        // the permissions do not apply to. Building it a restricted schema
147        // would take the bypass away.
148        if role == postrust_auth::hasura::ADMIN_ROLE {
149            continue;
150        }
151
152        // A second schema only where the role has something a backend alone
153        // may name. Otherwise the one schema answers both, since there is
154        // nothing for the flag to hide.
155        let variants: &[bool] = match crate::role::has_backend_only(&config.names, role) {
156            true => &[false, true],
157            false => &[false],
158        };
159
160        for &backend in variants {
161            let view = Arc::new(crate::role::cache_for_role(
162                schema_cache,
163                &config.names,
164                role,
165                backend,
166            ));
167            let mut role_config = config.clone();
168            role_config.role = Some(role.to_string());
169
170            let generated = build_schema(&view, &role_config);
171            // Subscriptions are left to the unrestricted schema for now: a live
172            // query is one this server answers from notifications rather than from
173            // the query root, so restricting it is a different piece of work from
174            // restricting a read.
175            let built = build_dynamic_schema(
176                &generated,
177                &view,
178                None,
179                role_config.max_rows,
180                Arc::new(role_config.names.clone()),
181                role_config.subscription_refresh(),
182                Some(role),
183            );
184
185            match built {
186                Ok(schema) => {
187                    schemas.insert((role.to_string(), backend), schema);
188                }
189                // One role's permissions being unbuildable is not a reason for
190                // every other role to lose its API, which is what returning here
191                // would mean -- the caller serves no GraphQL at all on an error.
192                // The role is left without a schema instead, which the request
193                // path already reads as a refusal: it fails closed, loudly, and
194                // alone.
195                Err(e) => tracing::error!(
196                    "GraphQL schema for role \"{}\" could not be built, \
197                 so that role is refused: {}",
198                    role,
199                    e
200                ),
201            }
202        }
203    }
204
205    tracing::info!("GraphQL schemas built for {} roles", schemas.len());
206    Ok(schemas)
207}
208
209/// The schema a role the document never names is answered from.
210///
211/// Built the same way every other role's is, from a cache reduced by a role
212/// nothing was granted to -- which leaves no tables, so it is the same schema
213/// whatever the unrecognised role is called. `None` where there is no
214/// permission document, since then no role is unrecognised.
215fn build_ungranted_schema(
216    schema_cache: &Arc<SchemaCache>,
217    config: &SchemaConfig,
218) -> Option<Schema> {
219    if !config.names.has_permissions() {
220        return None;
221    }
222    // A name no permission can carry: `roles()` reads them out of the
223    // document, and this one is not a role anybody wrote down.
224    const NOBODY: &str = "\u{0}ungranted";
225    let view = Arc::new(crate::role::cache_for_role(
226        schema_cache,
227        &config.names,
228        NOBODY,
229        false,
230    ));
231    let mut role_config = config.clone();
232    role_config.role = Some(NOBODY.to_string());
233    let generated = build_schema(&view, &role_config);
234    build_dynamic_schema(
235        &generated,
236        &view,
237        None,
238        role_config.max_rows,
239        Arc::new(role_config.names.clone()),
240        role_config.subscription_refresh(),
241        Some(NOBODY),
242    )
243    .map_err(|e| {
244        tracing::error!(
245            "the schema for a role with nothing granted could not be built,              so such a role is refused instead: {}",
246            e
247        )
248    })
249    .ok()
250}
251
252impl GraphQLState {
253    /// Create new GraphQL state from schema cache.
254    pub fn new(
255        pool: PgPool,
256        schema_cache: Arc<SchemaCache>,
257        config: SchemaConfig,
258    ) -> Result<Self, GraphQLError> {
259        let generated_schema = build_schema(&schema_cache, &config);
260        let subscription_fields = if config.enable_subscriptions {
261            generate_subscription_fields(&schema_cache, &generated_schema)
262        } else {
263            Vec::new()
264        };
265        let schema = build_dynamic_schema(
266            &generated_schema,
267            &schema_cache,
268            if config.enable_subscriptions {
269                Some(subscription_fields.as_slice())
270            } else {
271                None
272            },
273            config.max_rows,
274            Arc::new(config.names.clone()),
275            config.subscription_refresh(),
276            None,
277        )?;
278
279        let role_schemas = build_role_schemas(&schema_cache, &config)?;
280        let ungranted_schema = build_ungranted_schema(&schema_cache, &config);
281
282        Ok(Self {
283            pool: pool.clone(),
284            schema_cache,
285            generated_schema,
286            schema,
287            role_schemas,
288            ungranted_schema,
289            config,
290            subscription_fields,
291            broker: Arc::new(RwLock::new(None)),
292        })
293    }
294
295    /// Which schema answers for a caller speaking as this role.
296    ///
297    /// A role the document does not name is answered from the schema with
298    /// nothing in it, which is Hasura's reading: an unrecognised role is a
299    /// role that was granted nothing, not an error. Three things are
300    /// deliberately not that: a server with no permission document answers
301    /// everyone from the unrestricted schema, an administrator is answered
302    /// from it too -- permissions are rules for everyone else -- and so is a
303    /// request on a server where the layer is off.
304    ///
305    /// `None` only where the empty schema itself could not be built, which the
306    /// caller still turns into a refusal.
307    pub fn schema_for(&self, role: Option<&str>, backend: bool) -> Option<&Schema> {
308        if !self.config.names.has_permissions() {
309            return Some(&self.schema);
310        }
311        match role {
312            None | Some(postrust_auth::hasura::ADMIN_ROLE) => Some(&self.schema),
313            Some(role) => self
314                .role_schemas
315                .get(&(role.to_string(), backend))
316                // A role with nothing backend-only has one schema, under
317                // `false`, and it answers a backend caller too.
318                .or_else(|| self.role_schemas.get(&(role.to_string(), false)))
319                .or(self.ungranted_schema.as_ref()),
320        }
321    }
322
323    /// Rebuild the schema (e.g., after schema cache refresh).
324    #[allow(clippy::needless_update)]
325    pub fn rebuild(&mut self) -> Result<(), GraphQLError> {
326        self.role_schemas = build_role_schemas(&self.schema_cache, &self.config)?;
327        self.ungranted_schema = build_ungranted_schema(&self.schema_cache, &self.config);
328        self.generated_schema = build_schema(&self.schema_cache, &self.config);
329        self.subscription_fields = if self.config.enable_subscriptions {
330            generate_subscription_fields(&self.schema_cache, &self.generated_schema)
331        } else {
332            Vec::new()
333        };
334        self.schema = build_dynamic_schema(
335            &self.generated_schema,
336            &self.schema_cache,
337            if self.config.enable_subscriptions {
338                Some(self.subscription_fields.as_slice())
339            } else {
340                None
341            },
342            self.config.max_rows,
343            Arc::new(self.config.names.clone()),
344            self.config.subscription_refresh(),
345            None,
346        )?;
347        Ok(())
348    }
349
350    /// Initialize the subscription broker.
351    ///
352    /// This should be called after creating the state to enable subscriptions.
353    pub async fn init_subscriptions(&self) -> Result<(), crate::subscription::BrokerError> {
354        if !self.config.enable_subscriptions {
355            return Ok(());
356        }
357
358        let broker = NotifyBroker::new(self.pool.clone());
359
360        // Collect all channels to listen on
361        let channels: Vec<String> = self
362            .subscription_fields
363            .iter()
364            .map(|f| f.channel_name())
365            .collect();
366
367        if !channels.is_empty() {
368            broker.start(channels).await?;
369            info!(
370                "Subscription broker started with {} channels",
371                self.subscription_fields.len()
372            );
373        }
374
375        // Store the broker
376        let mut broker_guard = self.broker.write().await;
377        *broker_guard = Some(broker);
378
379        Ok(())
380    }
381
382    /// Stop the subscription broker.
383    pub async fn stop_subscriptions(&self) {
384        let broker_guard = self.broker.read().await;
385        if let Some(broker) = broker_guard.as_ref() {
386            broker.stop().await;
387        }
388    }
389
390    /// Serve subscriptions on this state from `previous`'s broker, listening
391    /// on whatever channels this schema adds.
392    ///
393    /// For a schema rebuilt under a running server. The broker carries over
394    /// rather than being replaced, so a subscription opened on the previous
395    /// schema keeps receiving notifications. With no broker yet -- start-up
396    /// could not connect one, or there was no previous state -- one is
397    /// started as `init_subscriptions` would.
398    pub async fn continue_subscriptions(
399        &mut self,
400        previous: Option<&GraphQLState>,
401    ) -> Result<(), crate::subscription::BrokerError> {
402        if let Some(previous) = previous {
403            self.broker = Arc::clone(&previous.broker);
404        }
405        if !self.config.enable_subscriptions {
406            return Ok(());
407        }
408        if let Some(broker) = self.broker.read().await.as_ref() {
409            let channels = self
410                .subscription_fields
411                .iter()
412                .map(|f| f.channel_name())
413                .collect();
414            return broker.listen(channels).await;
415        }
416        self.init_subscriptions().await
417    }
418
419    /// Get the notification broker.
420    pub async fn get_broker(&self) -> Option<Arc<RwLock<Option<NotifyBroker>>>> {
421        Some(Arc::clone(&self.broker))
422    }
423}
424
425/// Handle a GraphQL request.
426pub async fn graphql_handler(
427    State(state): State<Arc<GraphQLState>>,
428    ctx: GraphQLContext,
429    req: GraphQLRequest,
430) -> GraphQLResponse {
431    let request = req
432        .into_inner()
433        .data(ctx)
434        .data(state.pool.clone())
435        .data(Arc::clone(&state.broker));
436    state.schema.execute(request).await.into()
437}
438
439/// Handle GraphQL WebSocket subscription upgrade.
440///
441/// This should be called with a WebSocket upgrade request to enable
442/// GraphQL subscriptions over WebSocket.
443///
444/// It authenticates nothing: no caller identity, session or JWT claims reach
445/// the operations it runs. `postrust-server` serves its WebSocket routes with
446/// its own handler, which settles the identity from `connection_init` exactly
447/// as an HTTP request's is settled; an embedder needing the same must insert a
448/// [`GraphQLContext`](crate::context::GraphQLContext) per operation itself.
449pub async fn graphql_ws_handler(
450    State(state): State<Arc<GraphQLState>>,
451    protocol: async_graphql_axum::GraphQLProtocol,
452    ws: axum::extract::WebSocketUpgrade,
453) -> impl IntoResponse {
454    let schema = state.schema.clone();
455    let pool = state.pool.clone();
456    let broker = Arc::clone(&state.broker);
457
458    ws.protocols(["graphql-transport-ws", "graphql-ws"])
459        .on_upgrade(move |socket| async move {
460            let mut data = async_graphql::Data::default();
461            data.insert(pool);
462            data.insert(broker);
463
464            async_graphql_axum::GraphQLWebSocket::new(socket, schema, protocol)
465                .with_data(data)
466                .serve()
467                .await
468        })
469}
470
471/// Handle GraphQL playground request.
472pub async fn graphql_playground() -> impl axum::response::IntoResponse {
473    axum::response::Html(async_graphql::http::playground_source(
474        async_graphql::http::GraphQLPlaygroundConfig::new("/graphql")
475            .subscription_endpoint("/graphql/ws"),
476    ))
477}
478
479/// The column a field name refers to.
480///
481/// The name itself, unless the table exposes that column under another one.
482/// Every path from a request to SQL goes through here: a renamed column is a
483/// name in the schema and in nothing else, so the translation has to happen at
484/// each boundary rather than once.
485fn column_for<'a>(
486    names: &'a crate::names::NameOverrides,
487    schema: &str,
488    table: &str,
489    field: &'a str,
490) -> &'a str {
491    names.column_source(schema, table, field).unwrap_or(field)
492}
493
494/// The same, given the table itself.
495fn table_column_for<'a>(
496    names: &'a crate::names::NameOverrides,
497    table: &postrust_core::schema_cache::Table,
498    field: &'a str,
499) -> &'a str {
500    column_for(names, &table.schema, &table.name, field)
501}
502
503/// The select list that renames a table's columns to the fields they are
504/// exposed as, or `None` where nothing is renamed.
505///
506/// Applied to a projection over the table rather than to the table itself, so
507/// the row a computed field or a computed relationship is passed stays the
508/// table's own composite -- `cannot cast type record to author` is what
509/// happens when it does not.
510fn rename_projection(
511    table: &postrust_core::schema_cache::Table,
512    alias: &str,
513    names: &crate::names::NameOverrides,
514) -> Option<String> {
515    if !names.renames_columns(&table.schema, &table.name) {
516        return None;
517    }
518    let parts: Vec<String> = table
519        .columns
520        .values()
521        .map(|column| {
522            let exposed = names
523                .column(&table.schema, &table.name, &column.name)
524                .unwrap_or(&column.name);
525            format!(
526                "{}.{} AS {}",
527                postrust_sql::escape_ident(alias),
528                postrust_sql::escape_ident(&column.name),
529                postrust_sql::escape_ident(exposed)
530            )
531        })
532        .collect();
533    match parts.is_empty() {
534        true => None,
535        false => Some(parts.join(", ")),
536    }
537}
538
539/// A table's column types, keyed by the names those columns are exposed under.
540///
541/// [`row_json`] names the shape columns it has to rewrite as GeoJSON, and it
542/// names them in whatever the projection called them. Over a renamed
543/// projection that is the field name, not the column's.
544fn exposed_column_types(
545    table: &postrust_core::schema_cache::Table,
546    names: &crate::names::NameOverrides,
547) -> HashMap<String, String> {
548    table
549        .columns
550        .values()
551        .map(|column| {
552            let exposed = names
553                .column(&table.schema, &table.name, &column.name)
554                .unwrap_or(&column.name);
555            (exposed.to_string(), column.nominal_type.clone())
556        })
557        .collect()
558}
559
560/// The type a value is written as, which keeps the list an array column is.
561///
562/// Not the leaf scalar: `c34_text_array` is a `text[]`, and a client sending
563/// `$textArray: [String]` into it was refused for offering a list where the
564/// input said `String`. Every write is optional, so nothing here is non-null.
565fn write_type_ref(graphql_type: &crate::types::GraphQLType) -> TypeRef {
566    match graphql_type {
567        crate::types::GraphQLType::List(inner) => TypeRef::named_list(leaf_scalar_name(inner)),
568        other => TypeRef::named(leaf_scalar_name(other)),
569    }
570}
571
572/// The scalar at the bottom of a type, past any list wrapping.
573fn leaf_scalar_name(graphql_type: &crate::types::GraphQLType) -> String {
574    match graphql_type {
575        crate::types::GraphQLType::List(inner) => leaf_scalar_name(inner),
576        other => other.to_string(),
577    }
578}
579
580/// Build the dynamic async-graphql schema from our generated schema.
581fn build_dynamic_schema(
582    generated: &GeneratedSchema,
583    _schema_cache: &SchemaCache,
584    subscription_fields: Option<&[SubField]>,
585    max_rows: Option<i64>,
586    names: Arc<crate::names::NameOverrides>,
587    subscription_refresh: std::time::Duration,
588    // Whose schema this is, where it is one role's. What it decides here is
589    // which columns a write may name, which is not the same question as which
590    // columns may be read -- Hasura grants the two separately, and a role that
591    // may set a column it cannot read is ordinary rather than exotic.
592    role: Option<&str>,
593) -> Result<Schema, GraphQLError> {
594    // Create object types for each table
595    let mut object_types: HashMap<String, Object> = HashMap::new();
596
597    // A table with no readable field gets no type at all. That is not an
598    // empty table -- it is one this role may write and not read, and a GraphQL
599    // object type with no fields is not a legal type. Everything that would
600    // have returned it is left out with it.
601    for (type_name, obj) in &generated.object_types {
602        if obj.fields.is_empty() {
603            continue;
604        }
605        let relationships = generated
606            .relationship_fields
607            .get(type_name)
608            .map(|r| r.as_slice())
609            .unwrap_or(&[]);
610        let table_obj = create_object_type(
611            obj,
612            relationships,
613            generated.federation_entities.get(type_name),
614        );
615        object_types.insert(type_name.clone(), table_obj);
616    }
617
618    // Aggregate types: every readable table gets them, because every table has
619    // a count even when it has nothing to sum -- and so does a table a role may
620    // count and not read, which is the whole of what such a role was granted.
621    // Read from the roots that were generated rather than worked out again,
622    // for the reason the write inputs are: two answers to one question drift.
623    let countable: HashSet<&str> = generated
624        .query_fields
625        .iter()
626        .filter(|field| field.aggregates && !field.is_by_pk)
627        .map(|field| field.type_name.as_str())
628        .collect();
629    for (type_name, obj) in &generated.object_types {
630        if obj.fields.is_empty() && !countable.contains(type_name.as_str()) {
631            continue;
632        }
633        for aggregate_type in create_aggregate_types(&obj.local_name, obj) {
634            object_types.insert(aggregate_type.type_name().to_string(), aggregate_type);
635        }
636    }
637
638    // One mutation response per table that has any mutation, and only those:
639    // an unreferenced type is still a type, and a read-only view would
640    // otherwise contribute a response nothing can return.
641    let mutable: HashMap<String, String> = generated
642        .mutation_fields
643        .iter()
644        .filter_map(|f| {
645            // The table's own name. A bulk write already answers with the
646            // response type, and trimming the suffix here is what keeps
647            // `<t>_mutation_response_mutation_response` from being built: the
648            // set used to be carried by `insert_one` and `update_by_pk`
649            // naming the bare type, so a table with only bulk writes -- which
650            // is what a role that cannot read one has -- registered the wrong
651            // name and left the right one missing.
652            let response = f
653                .return_type
654                .trim_matches(|c| c == '[' || c == ']' || c == '!')
655                .strip_suffix("_mutation_response")?;
656            Some((response.to_string(), f.type_name.clone()))
657        })
658        .collect();
659    for (base_name, row_type_name) in mutable {
660        // Whether it has rows to give back. A write to a table this role
661        // cannot read answers with `affected_rows` and nothing else -- there
662        // is no row type for `returning` to be a list of.
663        let returning = generated
664            .object_types
665            .get(&row_type_name)
666            .is_some_and(|object| !object.fields.is_empty());
667        object_types.insert(
668            mutation_response_type_name(&base_name),
669            create_mutation_response_type(&base_name, &row_type_name, returning),
670        );
671    }
672
673    // Non-federated Hasura-compatible schemas use `query_root`, not `Query`.
674    // Federation SDL from async-graphql does not include an operation-root
675    // schema definition, so Apollo composition treats only the conventional
676    // root names as root types.
677    let query_root = if generated.enable_federation {
678        "Query"
679    } else {
680        "query_root"
681    };
682    let mutation_root = if generated.enable_federation {
683        "Mutation"
684    } else {
685        "mutation_root"
686    };
687    let subscription_root = if generated.enable_federation {
688        "Subscription"
689    } else {
690        "subscription_root"
691    };
692
693    // Create query type. Resolvers need the relationship map to embed related
694    // rows, so it is shared into each closure.
695    let relationships = Arc::new(generated.relationship_fields.clone());
696    // (schema, table) -> GraphQL type name. A nested insert is handed a table
697    // by a relationship and has to find that table's relationships in turn,
698    // and the map they live in is keyed by type name -- which is not always
699    // the table's name, since a second schema prefixes it and a name may have
700    // been given.
701    let type_names: Arc<HashMap<(String, String), String>> = Arc::new(
702        generated
703            .object_types
704            .iter()
705            .map(|(type_name, object)| {
706                (
707                    (object.table.schema.clone(), object.table.name.clone()),
708                    type_name.clone(),
709                )
710            })
711            .collect(),
712    );
713    let query = add_function_fields(
714        create_query_type(
715            generated,
716            query_root,
717            max_rows,
718            Arc::clone(&relationships),
719            Arc::clone(&names),
720        ),
721        generated,
722        false,
723        max_rows,
724        Arc::clone(&relationships),
725        Arc::clone(&names),
726    );
727
728    // Create mutation type
729    let mutation = if !generated.mutation_fields.is_empty()
730        || generated.function_fields.iter().any(|f| f.volatile)
731    {
732        Some(add_function_fields(
733            create_mutation_type(
734                generated,
735                mutation_root,
736                Arc::clone(&relationships),
737                Arc::clone(&type_names),
738                Arc::clone(&names),
739                max_rows,
740                role,
741            ),
742            generated,
743            true,
744            max_rows,
745            Arc::clone(&relationships),
746            Arc::clone(&names),
747        ))
748    } else {
749        None
750    };
751
752    // Create subscription type if enabled
753    let subscription = subscription_fields.map(|_| {
754        create_subscription_type(
755            generated,
756            subscription_root,
757            max_rows,
758            Arc::clone(&relationships),
759            Arc::clone(&names),
760            subscription_refresh,
761        )
762    });
763
764    // Build schema
765    let mut builder = Schema::build(
766        query_root,
767        mutation.as_ref().map(|_| mutation_root),
768        subscription.as_ref().map(|_| subscription_root),
769    );
770    if generated.enable_federation {
771        builder = builder
772            .enable_federation()
773            .extension(NullableFederationEntity);
774        let entity_state = Arc::new(EntityResolverState::new(
775            generated,
776            Arc::clone(&relationships),
777            Arc::clone(&names),
778            max_rows,
779        ));
780        builder = builder.entity_resolver(move |ctx| {
781            let state = Arc::clone(&entity_state);
782            FieldFuture::new(async move { resolve_entities(&ctx, state.as_ref()).await })
783        });
784    }
785
786    // Register all object types
787    for (_, obj) in object_types {
788        builder = builder.register(obj);
789    }
790
791    // Register query type
792    builder = builder.register(query);
793
794    // Register mutation type if present
795    if let Some(mutation) = mutation {
796        builder = builder.register(mutation);
797    }
798
799    // Register subscription type if present
800    if let Some(subscription) = subscription {
801        builder = builder.register(subscription);
802    }
803
804    // Register scalar types
805    // Every scalar the generated types actually name, rather than a fixed
806    // list. A `geometry` column, a `raster` column and a database enum each
807    // become a scalar under their own PostgreSQL name, because that is the
808    // name a client's query declares its variables with -- and a scalar the
809    // schema mentions but never registers makes the whole schema unbuildable.
810    let (bool_exp_inputs, bool_exp_scalars) = crate::input::bool_exp::build_inputs(
811        &generated.object_types,
812        &generated.relationship_fields,
813    );
814    for input in bool_exp_inputs {
815        builder = builder.register(input);
816    }
817
818    let mut scalar_names: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
819    for object in generated.object_types.values() {
820        // Both halves. A column a role may set without seeing is named by the
821        // insert input and by nothing a read produces, so collecting only the
822        // readable fields leaves its scalar unregistered -- and a scalar the
823        // schema mentions but never registers makes the whole schema
824        // unbuildable, which costs the role every field it has.
825        for field in object.fields.iter().chain(&object.writable_fields) {
826            scalar_names.insert(leaf_scalar_name(&field.graphql_type));
827        }
828    }
829    // Used as an argument type in its own right, whether or not any column is
830    // one: `objects`, `_set` and the mutation inputs are still JSON.
831    scalar_names.insert("JSON".to_string());
832    // A function's arguments name scalars of their own: a table may have no
833    // geometry column while a function takes one.
834    for function in &generated.function_fields {
835        for (_, pg_type, _) in &function.arguments {
836            scalar_names.insert(leaf_scalar_name(&crate::types::pg_type_to_graphql(pg_type)));
837        }
838    }
839    // The same for the functions behind computed fields, whose arguments are
840    // written where the field is asked for rather than at a root.
841    for object in generated.object_types.values() {
842        for field in &object.fields {
843            for (_, pg_type, _) in &field.arguments {
844                scalar_names.insert(leaf_scalar_name(&crate::types::pg_type_to_graphql(pg_type)));
845            }
846        }
847    }
848    for relationships in generated.relationship_fields.values() {
849        for relationship in relationships {
850            for (_, pg_type, _) in &relationship.arguments {
851                scalar_names.insert(leaf_scalar_name(&crate::types::pg_type_to_graphql(pg_type)));
852            }
853        }
854    }
855
856    // Every scalar the boolean expressions name, which is more than the
857    // scalars the columns are: a cast from a geometry names `geography`, and a
858    // raster comparison names `geometry`. Taken from what was generated rather
859    // than listed here, because a list here is a second place to keep in step
860    // and it fell out of step twice.
861    scalar_names.extend(bool_exp_scalars);
862
863    for name in scalar_names {
864        if matches!(name.as_str(), "Int" | "Float" | "String" | "Boolean" | "ID") {
865            continue;
866        }
867        // An enum table's type is an enum, not a scalar. It reaches this list
868        // because a column typed as one names it, and registering both would
869        // define the same type twice.
870        if generated.enum_types.contains_key(&name) {
871            continue;
872        }
873        builder = builder
874            .register(Scalar::new(&name).description(format!("The PostgreSQL `{}` type.", name)));
875    }
876
877    // Register the boolean expression inputs -- one per table, plus one
878    // comparison input per scalar the tables use.
879
880    // A key as one object, for `update_x_by_pk(pk_columns: {...})`. Only the
881    // by-key update spells its key this way; the by-key query and delete take
882    // the columns as arguments, and both spellings are what a generated client
883    // already sends.
884    let mut key_inputs: HashMap<String, InputObject> = HashMap::new();
885    for field in &generated.mutation_fields {
886        if field.mutation_type != MutationType::UpdateByPk || field.pk_columns.is_empty() {
887            continue;
888        }
889        let base_name = field.local_type_name.as_str();
890        let type_name = format!("{}_pk_columns_input", base_name);
891        let mut input = InputObject::new(&type_name)
892            .description(format!("The primary key of one {} row.", base_name));
893        for (column, pg_type) in &field.pk_columns {
894            input = input.field(InputValue::new(
895                names
896                    .column(&field.schema_name, &field.table_name, column)
897                    .unwrap_or(column),
898                TypeRef::named_nn(exposed_pk_argument_type(
899                    names.as_ref(),
900                    &field.schema_name,
901                    &field.table_name,
902                    column,
903                    pg_type,
904                )),
905            ));
906        }
907        key_inputs.insert(type_name, input);
908    }
909    for (_, input) in key_inputs {
910        builder = builder.register(input);
911    }
912
913    // What a mutation writes. `objects` and `_set` were `JSON`, which accepts
914    // anything and lets a client generate nothing: no completion, no codegen,
915    // and a misspelled column reaching the database instead of being caught
916    // before the request was sent. The same argument that made `where` a real
917    // type applies unchanged.
918    // Which types have an `_insert_input` at all, which is what a nested write
919    // names. Collected first because a relationship may point at a table this
920    // loop has not reached yet -- and because the answer is now a permission
921    // question: a role granted `insert` on `article` and only `select` on
922    // `author` gets an `article_insert_input`, and writing `author` inside it
923    // would name a type nobody registered. async-graphql refuses to build a
924    // schema with a dangling reference, so the whole role would have no schema
925    // over one field it was never allowed to use.
926    // Which types actually got each write input, recorded as they are built
927    // rather than predicted from the object type's fields. The two answers
928    // used to be the same and are not any more: an input is built from the
929    // write permission's columns, so a table whose readable columns include a
930    // number may still have no `_inc_input` -- and an argument naming a type
931    // nobody registered is a schema async-graphql refuses to build, which
932    // costs the role every field it has rather than the one it cannot use.
933    let insertable_types: HashSet<&str> = generated
934        .object_types
935        .iter()
936        .filter(|(_, object)| crate::input::mutation::is_insertable(&object.table))
937        .map(|(type_name, _)| type_name.as_str())
938        .collect();
939
940    for (type_name, object) in &generated.object_types {
941        let local_type_name = object.local_name.as_str();
942        let table = &object.table;
943        // Which columns a write may name, which is the write permission's
944        // answer and not the read permission's. A role granted `columns:
945        // ["age"]` on insert may not name `is_user` even where it can read it,
946        // and the corpus tests exactly that: `field 'is_user' not found in
947        // type: 'resident_insert_input'`.
948        // Only real columns are written. A computed field is a function of the
949        // row and a relationship is handled separately below.
950        let writable_named = |allowed: Option<&crate::names::ColumnSet>| {
951            object
952                .writable_fields
953                .iter()
954                .filter(|field| {
955                    let column = table_column_for(&names, table, &field.name);
956                    table.get_column(column).is_some()
957                        && allowed.is_none_or(|set| set.allows(column))
958                })
959                .collect::<Vec<&crate::schema::object::GraphQLField>>()
960        };
961        let writable = writable_named(None);
962        let insert_fields = write_fields(object, &names, role, crate::role::Verb::Insert);
963        let update_fields = write_fields(object, &names, role, crate::role::Verb::Update);
964        if writable.is_empty() {
965            continue;
966        }
967
968        let relationships = generated
969            .relationship_fields
970            .get(type_name)
971            .map(|r| r.as_slice())
972            .unwrap_or(&[]);
973        let conflict_type = match table.unique_constraints.is_empty() {
974            true => None,
975            false => Some(format!("{}_on_conflict", local_type_name)),
976        };
977
978        if crate::input::mutation::is_insertable(table) {
979            let mut insert = InputObject::new(format!("{}_insert_input", local_type_name))
980                .description(format!("The columns of a new {} row.", local_type_name));
981            let mut taken: HashSet<&str> = HashSet::new();
982            for field in &insert_fields {
983                // Every column optional: which ones the database insists on is
984                // the database's answer, and a column that is NOT NULL with a
985                // default does not have to be given.
986                taken.insert(field.name.as_str());
987                insert = insert.field(InputValue::new(
988                    &field.name,
989                    write_type_ref(&field.graphql_type),
990                ));
991            }
992            // A nested write: the rows to insert beside this one. Only where
993            // the far side is something this schema can write -- see
994            // `insertable_types`.
995            for relationship in relationships {
996                if !insertable_types.contains(relationship.target_type.as_str()) {
997                    continue;
998                }
999                if !taken.insert(relationship.name.as_str()) {
1000                    continue;
1001                }
1002                let suffix = match relationship.is_list {
1003                    true => "arr_rel_insert_input",
1004                    false => "obj_rel_insert_input",
1005                };
1006                insert = insert.field(InputValue::new(
1007                    &relationship.name,
1008                    TypeRef::named(format!("{}_{}", relationship.target_local_name, suffix)),
1009                ));
1010            }
1011            builder = builder.register(insert);
1012
1013            // How this table is written as somebody else's nested row. Both
1014            // shapes carry an `on_conflict`, which is what makes a nested
1015            // upsert expressible.
1016            let data_type = format!("{}_insert_input", local_type_name);
1017            let mut object_rel =
1018                InputObject::new(format!("{}_obj_rel_insert_input", local_type_name))
1019                    .description(format!(
1020                        "One {} row written beside its parent.",
1021                        local_type_name
1022                    ))
1023                    .field(InputValue::new("data", TypeRef::named_nn(&data_type)));
1024            let mut array_rel =
1025                InputObject::new(format!("{}_arr_rel_insert_input", local_type_name))
1026                    .description(format!(
1027                        "{} rows written beside their parent.",
1028                        local_type_name
1029                    ))
1030                    .field(InputValue::new(
1031                        "data",
1032                        TypeRef::named_nn_list_nn(&data_type),
1033                    ));
1034            if let Some(conflict) = &conflict_type {
1035                object_rel =
1036                    object_rel.field(InputValue::new("on_conflict", TypeRef::named(conflict)));
1037                array_rel =
1038                    array_rel.field(InputValue::new("on_conflict", TypeRef::named(conflict)));
1039            }
1040            builder = builder.register(object_rel).register(array_rel);
1041        }
1042
1043        if crate::input::mutation::is_updatable(table) {
1044            let mut set = InputObject::new(format!("{}_set_input", local_type_name))
1045                .description(format!("Columns of {} to replace.", local_type_name));
1046            let mut numeric = InputObject::new(format!("{}_inc_input", local_type_name))
1047                .description(format!("Columns of {} to add to.", local_type_name));
1048            let mut any_numeric = false;
1049            let mut any_jsonb = false;
1050            for field in &update_fields {
1051                if matches!(&field.graphql_type, crate::types::GraphQLType::Json) {
1052                    any_jsonb = true;
1053                }
1054                set = set.field(InputValue::new(
1055                    &field.name,
1056                    write_type_ref(&field.graphql_type),
1057                ));
1058                // Only a number can be added to, and a list of them is not a
1059                // number: `_inc` takes the scalar or nothing.
1060                if crate::schema::aggregate::is_incrementable(&field.graphql_type) {
1061                    any_numeric = true;
1062                    numeric = numeric.field(InputValue::new(
1063                        &field.name,
1064                        TypeRef::named(leaf_scalar_name(&field.graphql_type)),
1065                    ));
1066                }
1067            }
1068            builder = builder.register(set);
1069            // A table with nothing to add to gets no type for adding to it.
1070            if any_numeric {
1071                builder = builder.register(numeric);
1072            }
1073
1074            // One entry of `update_x_many`: a filter and the values to write
1075            // where it matches. The whole list runs in one transaction, in the
1076            // order it was given, which is what makes it different from
1077            // sending the updates one at a time.
1078            let mut updates = InputObject::new(format!("{}_updates", local_type_name))
1079                .description(format!(
1080                    "One update to {}: which rows, and what to write.",
1081                    local_type_name
1082                ))
1083                .field(InputValue::new(
1084                    "where",
1085                    TypeRef::named_nn(crate::input::bool_exp::bool_exp_type_name(local_type_name)),
1086                ))
1087                .field(InputValue::new(
1088                    "_set",
1089                    TypeRef::named(format!("{}_set_input", local_type_name)),
1090                ));
1091            if any_numeric {
1092                updates = updates.field(InputValue::new(
1093                    "_inc",
1094                    TypeRef::named(format!("{}_inc_input", local_type_name)),
1095                ));
1096            }
1097            // What a document column may be told to do, one input per
1098            // operator: each takes a value of a different shape -- a
1099            // document, a key, an index, a path -- and only the columns that
1100            // hold documents may be told any of it. A table with none is not
1101            // given the operators at all, which is what says in the schema
1102            // that `_append` is not a thing to write there.
1103            for (operator, _) in JSONB_OPERATORS {
1104                if !any_jsonb {
1105                    break;
1106                }
1107                updates = updates.field(InputValue::new(
1108                    *operator,
1109                    TypeRef::named(jsonb_operator_input(local_type_name, operator)),
1110                ));
1111            }
1112            builder = builder.register(updates);
1113            if any_jsonb {
1114                for (operator, item) in JSONB_OPERATORS {
1115                    let mut input =
1116                        InputObject::new(jsonb_operator_input(local_type_name, operator))
1117                            .description(format!(
1118                                "Columns of {} to apply `{}` to.",
1119                                local_type_name, operator
1120                            ));
1121                    for field in &update_fields {
1122                        if !matches!(&field.graphql_type, crate::types::GraphQLType::Json) {
1123                            continue;
1124                        }
1125                        input = input.field(InputValue::new(&field.name, item()));
1126                    }
1127                    builder = builder.register(input);
1128                }
1129            }
1130        }
1131    }
1132
1133    // A function's own arguments, under a name of their own so they cannot
1134    // collide with `where` or `limit`.
1135    for function in &generated.function_fields {
1136        if function.arguments.is_empty() {
1137            continue;
1138        }
1139        let mut args = InputObject::new(format!("{}_args", function.name))
1140            .description(format!("Arguments to {}.", function.name));
1141        for (name, pg_type, _) in &function.arguments {
1142            let scalar = crate::types::pg_type_to_graphql(pg_type).to_string();
1143            // Nullable, whether or not the parameter has a default. Every
1144            // PostgreSQL argument accepts a null, and a client passing one
1145            // through a variable declares it as the nullable type -- `query
1146            // ($point: json)` used where `json!` was expected is a query the
1147            // spec's variable rule refuses. Whether a defaulted argument may
1148            // be left out entirely is enforced where the call is written,
1149            // which is the only place that can tell.
1150            args = args.field(InputValue::new(name, TypeRef::named(scalar)));
1151        }
1152        builder = builder.register(args);
1153    }
1154
1155    // The same for a computed relationship's function, which takes its
1156    // arguments where it is embedded rather than at the root. Named after the
1157    // type and the field, since two tables may reach the same function and one
1158    // table may reach two.
1159    for (type_name, relationships) in &generated.relationship_fields {
1160        let local_type_name = generated
1161            .object_types
1162            .get(type_name)
1163            .map(|object| object.local_name.as_str())
1164            .unwrap_or(type_name);
1165        for relationship in relationships {
1166            if relationship.arguments.is_empty() {
1167                continue;
1168            }
1169            let mut args =
1170                InputObject::new(computed_args_type_name(local_type_name, &relationship.name))
1171                    .description(format!(
1172                        "Arguments to {}, beside the row it is asked of.",
1173                        relationship.name
1174                    ));
1175            for (name, pg_type, _) in &relationship.arguments {
1176                let scalar = crate::types::pg_type_to_graphql(pg_type).to_string();
1177                // Nullable, for the reason the function arguments above are.
1178                args = args.field(InputValue::new(name, TypeRef::named(scalar)));
1179            }
1180            builder = builder.register(args);
1181        }
1182    }
1183
1184    // And for a computed *column*'s function, which likewise takes its
1185    // arguments where the field is asked for. `locations { distance(args: {
1186    // from: ... }) }` -- the field is a function of the row and of what the
1187    // caller wants measured against it.
1188    for object in generated.object_types.values() {
1189        let local_type_name = object.local_name.as_str();
1190        for field in &object.fields {
1191            if field.arguments.is_empty() {
1192                continue;
1193            }
1194            let mut args = InputObject::new(computed_args_type_name(local_type_name, &field.name))
1195                .description(format!(
1196                    "Arguments to {}, beside the row it is asked of.",
1197                    field.name
1198                ));
1199            for (name, pg_type, _) in &field.arguments {
1200                let scalar = crate::types::pg_type_to_graphql(pg_type).to_string();
1201                // Nullable, for the reason the function arguments above are.
1202                args = args.field(InputValue::new(name, TypeRef::named(scalar)));
1203            }
1204            builder = builder.register(args);
1205        }
1206    }
1207
1208    // What a predicate over a related set may ask. Registered only for the
1209    // tables something points at with a to-many relationship, which is the
1210    // only place the field naming them exists.
1211    {
1212        use crate::input::bool_exp as be;
1213        let mut targets: BTreeMap<&str, &str> = BTreeMap::new();
1214        for relationships in generated.relationship_fields.values() {
1215            for relationship in relationships {
1216                if relationship.is_list {
1217                    targets.insert(
1218                        relationship.target_local_name.as_str(),
1219                        relationship.target_type.as_str(),
1220                    );
1221                }
1222            }
1223        }
1224        for (target, target_type) in targets {
1225            let Some(object) = generated.object_types.get(target_type) else {
1226                continue;
1227            };
1228            // A boolean column is what `bool_and` and `bool_or` fold, and a
1229            // GraphQL enum may not be empty -- so a table with none gets
1230            // neither the aggregates nor the enum naming their columns.
1231            let booleans: Vec<&str> = object
1232                .fields
1233                .iter()
1234                .filter(|field| {
1235                    object.table.get_column(&field.name).is_some()
1236                        && matches!(field.graphql_type, crate::types::GraphQLType::Boolean)
1237                })
1238                .map(|field| field.name.as_str())
1239                .collect();
1240
1241            let mut over = InputObject::new(be::aggregate_bool_exp_type_name(target)).description(
1242                format!("A question about the whole set of related {} rows.", target),
1243            );
1244            for function in be::AGGREGATE_PREDICATES {
1245                if function != "count" && booleans.is_empty() {
1246                    continue;
1247                }
1248                over = over.field(InputValue::new(
1249                    function,
1250                    TypeRef::named(be::aggregate_bool_exp_function(target, function)),
1251                ));
1252
1253                // `count` may be told which columns to count, as the field
1254                // itself may; `bool_and` folds exactly one.
1255                let (arguments, predicate) = match function {
1256                    "count" => (
1257                        TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
1258                            target,
1259                        )),
1260                        be::comparison_type_name("Int"),
1261                    ),
1262                    _ => (
1263                        TypeRef::named_nn(be::aggregate_bool_exp_columns(target, function)),
1264                        be::comparison_type_name("Boolean"),
1265                    ),
1266                };
1267                let mut input = InputObject::new(be::aggregate_bool_exp_function(target, function))
1268                    .description(format!(
1269                        "`{}` over the related {} rows, and what it has to be.",
1270                        function, target
1271                    ))
1272                    .field(InputValue::new("arguments", arguments))
1273                    .field(InputValue::new("distinct", TypeRef::named("Boolean")))
1274                    .field(InputValue::new(
1275                        "filter",
1276                        TypeRef::named(be::bool_exp_type_name(target)),
1277                    ))
1278                    .field(InputValue::new("predicate", TypeRef::named_nn(predicate)));
1279                if function == "count" {
1280                    input = input.description(format!(
1281                        "How many related {} rows there have to be.",
1282                        target
1283                    ));
1284                }
1285                builder = builder.register(input);
1286
1287                if function != "count" {
1288                    let mut columns = Enum::new(be::aggregate_bool_exp_columns(target, function))
1289                        .description(format!("A boolean column of {}.", target));
1290                    for name in &booleans {
1291                        columns = columns.item(EnumItem::new(*name));
1292                    }
1293                    builder = builder.register(columns);
1294                }
1295            }
1296            builder = builder.register(over);
1297        }
1298    }
1299
1300    // Upserts. A table with no unique constraint has no conflict to resolve,
1301    // and a GraphQL enum may not be empty, so it gets none of these types
1302    // rather than an unusable set of them.
1303    for object in generated.object_types.values() {
1304        let local_type_name = object.local_name.as_str();
1305        // What an upsert may write, which is the update permission's answer
1306        // and not the read permission's: `update_columns` names columns to
1307        // overwrite, so a role that may set a column without seeing it may
1308        // name it here. Where no update permission narrows them these are the
1309        // table's own columns, which is what the enum listed before.
1310        let updatable_columns = write_fields(object, &names, role, crate::role::Verb::Update);
1311        if object.table.unique_constraints.is_empty() {
1312            continue;
1313        }
1314
1315        let mut constraints =
1316            Enum::new(format!("{}_constraint", local_type_name)).description(format!(
1317                "A uniqueness of {} that an insert may conflict with.",
1318                local_type_name
1319            ));
1320        for (name, columns) in &object.table.unique_constraints {
1321            constraints = constraints
1322                .item(EnumItem::new(name).description(format!("unique ({})", columns.join(", "))));
1323        }
1324
1325        let mut updatable = Enum::new(format!("{}_update_column", local_type_name)).description(
1326            format!("A column of {} an upsert may write.", local_type_name),
1327        );
1328        for field in &updatable_columns {
1329            updatable = updatable.item(EnumItem::new(&field.name));
1330        }
1331        // An update permission granting no column leaves the enum with no
1332        // members, which is not a legal type -- and dropping the enum would
1333        // drop `on_conflict` with it, so an insert that names one would fail
1334        // to build rather than be refused. Hasura's answer is a member that
1335        // names no column: the upsert is still expressible, `update_columns:
1336        // []` still means `DO NOTHING`, and naming the placeholder is refused
1337        // where it is used. `article_on_conflict_restricted_role.yaml` tests
1338        // both halves.
1339        if updatable_columns.is_empty() {
1340            updatable = updatable.item(
1341                EnumItem::new(PLACEHOLDER_COLUMN)
1342                    .description("No column may be written by this upsert."),
1343            );
1344        }
1345
1346        let on_conflict = InputObject::new(format!("{}_on_conflict", local_type_name))
1347            .description(format!(
1348                "What to do when an insert into {} conflicts.",
1349                local_type_name
1350            ))
1351            .field(InputValue::new(
1352                "constraint",
1353                TypeRef::named_nn(format!("{}_constraint", local_type_name)),
1354            ))
1355            // An empty list is `DO NOTHING`, which is how Hasura spells "leave
1356            // the row that is already there alone" -- and is the default, so
1357            // `on_conflict: {constraint: article_pkey}` means exactly that
1358            // rather than being refused for saying nothing about columns.
1359            .field(
1360                InputValue::new(
1361                    "update_columns",
1362                    TypeRef::named_nn_list_nn(format!("{}_update_column", local_type_name)),
1363                )
1364                .default_value(Value::List(Vec::new())),
1365            )
1366            .field(InputValue::new(
1367                "where",
1368                TypeRef::named(crate::input::bool_exp::bool_exp_type_name(local_type_name)),
1369            ));
1370
1371        builder = builder
1372            .register(constraints)
1373            .register(updatable)
1374            .register(on_conflict);
1375    }
1376
1377    // The enums generated from enum tables.
1378    for (type_name, members) in &generated.enum_types {
1379        let mut generated_enum =
1380            Enum::new(type_name).description(format!("The values {} allows.", type_name));
1381        for (value, comment) in members {
1382            let item = EnumItem::new(value);
1383            generated_enum = generated_enum.item(match comment {
1384                Some(description) => item.description(description),
1385                None => item,
1386            });
1387        }
1388        builder = builder.register(generated_enum);
1389    }
1390
1391    // Ordering: one input per table, one column enum per table, and the single
1392    // direction enum they all share.
1393    let (order_inputs, order_enums) = crate::input::order_by::build_inputs(
1394        &generated.object_types,
1395        &generated.relationship_fields,
1396    );
1397    for input in order_inputs {
1398        builder = builder.register(input);
1399    }
1400    for enum_type in order_enums {
1401        builder = builder.register(enum_type);
1402    }
1403
1404    builder
1405        .finish()
1406        .map_err(|e| GraphQLError::SchemaError(e.to_string()))
1407}
1408
1409/// Create an object type from a TableObjectType.
1410/// The enum member that stands in for an update permission granting no column.
1411///
1412/// Hasura's spelling, and it is load-bearing: `article_update_column` must be
1413/// a legal enum for `article_on_conflict` to exist, and `on_conflict` must
1414/// exist for an insert that carries one to be refused rather than unbuildable.
1415const PLACEHOLDER_COLUMN: &str = "_PLACEHOLDER";
1416
1417/// The name of a table's mutation response type.
1418pub fn mutation_response_type_name(base_name: &str) -> String {
1419    format!("{}_mutation_response", base_name)
1420}
1421
1422/// Build the `<table>_mutation_response` object.
1423///
1424/// Every bulk mutation answers with this rather than with the rows directly.
1425/// `affected_rows` is the count PostgreSQL reports, which is not the length of
1426/// `returning`: a client may ask for no rows back at all and still need to know
1427/// how many were touched, and that is the usual case for a delete.
1428fn create_mutation_response_type(base_name: &str, row_type: &str, returning: bool) -> Object {
1429    let response_name = mutation_response_type_name(base_name);
1430
1431    let response = Object::new(&response_name)
1432        .description(format!("The rows {} changed, and how many.", base_name))
1433        .field(Field::new(
1434            "affected_rows",
1435            TypeRef::named_nn(TypeRef::INT),
1436            |ctx| {
1437                FieldFuture::new(async move {
1438                    if let Some(Value::Object(map)) = ctx.parent_value.as_value() {
1439                        if let Some(value) = map.get(&async_graphql::Name::new("affected_rows")) {
1440                            return Ok(Some(FieldValue::value(value.clone())));
1441                        }
1442                    }
1443                    Ok(Some(FieldValue::value(Value::from(0))))
1444                })
1445            },
1446        ));
1447    // A table this role may write and not read has no row type, so there is
1448    // nothing for `returning` to be a list of. Hasura answers such a write
1449    // with the count alone, and the corpus asks for nothing else.
1450    if !returning {
1451        return response;
1452    }
1453    response.field(Field::new(
1454        "returning",
1455        TypeRef::named_nn_list_nn(row_type.to_string()),
1456        |ctx| {
1457            FieldFuture::new(async move {
1458                let rows = match ctx.parent_value.as_value() {
1459                    Some(Value::Object(map)) => {
1460                        match map.get(&async_graphql::Name::new("returning")) {
1461                            Some(Value::List(items)) => items.clone(),
1462                            _ => Vec::new(),
1463                        }
1464                    }
1465                    _ => Vec::new(),
1466                };
1467                Ok(Some(FieldValue::list(
1468                    rows.into_iter().map(FieldValue::value),
1469                )))
1470            })
1471        },
1472    ))
1473}
1474
1475/// Build every aggregate type for one table.
1476///
1477/// Four kinds, and they nest: `<t>_aggregate` holds `aggregate` and `nodes`,
1478/// `<t>_aggregate_fields` holds `count` and one field per function, and each
1479/// function has a type of its own holding the columns it applies to.
1480fn create_aggregate_types(base_name: &str, object: &TableObjectType) -> Vec<Object> {
1481    use crate::schema::aggregate as agg;
1482
1483    let mut types = Vec::new();
1484
1485    // `<t>_aggregate`: the rows, and the numbers about them.
1486    let fields_type = agg::aggregate_fields_type_name(base_name);
1487    // Whether there are rows to hand back beside the numbers. A role granted
1488    // "how many" and not "which" has no row type, so `nodes` has nothing to be
1489    // a list of.
1490    let has_rows = !object.fields.is_empty();
1491    let mut over = Object::new(agg::aggregate_type_name(base_name))
1492        .description(match has_rows {
1493            true => format!("Aggregates over {}, with the rows themselves.", base_name),
1494            false => format!("Aggregates over {}.", base_name),
1495        })
1496        .field(Field::new(
1497            "aggregate",
1498            TypeRef::named(&fields_type),
1499            |ctx| FieldFuture::new(async move { Ok(child_of(&ctx, "aggregate")) }),
1500        ));
1501    if has_rows {
1502        over = over.field(Field::new(
1503            "nodes",
1504            TypeRef::named_nn_list_nn(object.name.clone()),
1505            |ctx| {
1506                FieldFuture::new(async move {
1507                    let rows = match child_value(&ctx, "nodes") {
1508                        Some(Value::List(items)) => items,
1509                        _ => Vec::new(),
1510                    };
1511                    Ok(Some(FieldValue::list(
1512                        rows.into_iter().map(FieldValue::value),
1513                    )))
1514                })
1515            },
1516        ));
1517    }
1518    types.push(over);
1519
1520    // `<t>_aggregate_fields`: count, and one field per function.
1521    let mut count = Field::new("count", TypeRef::named_nn(TypeRef::INT), |ctx| {
1522        // Read under the name it was asked for, not under `count`.
1523        // Two counts of different things sit in one selection --
1524        // `count` beside `distinct_authors: count(columns: [author_id],
1525        // distinct: true)` -- and they are different numbers.
1526        let key = ctx.ctx.field().alias().unwrap_or("count").to_string();
1527        FieldFuture::new(async move {
1528            Ok(Some(FieldValue::value(
1529                child_value(&ctx, &key).unwrap_or(Value::from(0)),
1530            )))
1531        })
1532    });
1533    // `count(columns:)` counts the rows where those columns are not null, and
1534    // `distinct` counts distinct values among them. Neither is offered where
1535    // the role may name no column: `count` is then a count of rows and nothing
1536    // else, and the corpus tests exactly that -- `'count' has no argument
1537    // named 'columns'`.
1538    if has_rows {
1539        count = count
1540            .argument(InputValue::new(
1541                "columns",
1542                TypeRef::named_nn_list(agg_select_column(base_name)),
1543            ))
1544            .argument(InputValue::new("distinct", TypeRef::named("Boolean")));
1545    }
1546    let mut aggregate_fields = Object::new(&fields_type)
1547        .description(format!("Aggregate functions over {}.", base_name))
1548        .field(count);
1549
1550    for (function, returns, columns) in agg::functions_for(object) {
1551        let function_type = agg::function_fields_type_name(base_name, function);
1552        let mut per_column = Object::new(&function_type).description(format!(
1553            "`{}` of each {} column it applies to.",
1554            function, base_name
1555        ));
1556        for column in &columns {
1557            let column_name = column.clone();
1558            let type_name = agg::field_type_for(object, column, returns);
1559            per_column =
1560                per_column.field(Field::new(column, TypeRef::named(type_name), move |ctx| {
1561                    let column_name = column_name.clone();
1562                    FieldFuture::new(async move {
1563                        Ok(child_value(&ctx, &column_name).map(FieldValue::value))
1564                    })
1565                }));
1566        }
1567        types.push(per_column);
1568
1569        let owned = function.to_string();
1570        aggregate_fields = aggregate_fields.field(Field::new(
1571            function,
1572            TypeRef::named(&function_type),
1573            move |ctx| {
1574                let owned = owned.clone();
1575                FieldFuture::new(async move { Ok(child_of(&ctx, &owned)) })
1576            },
1577        ));
1578    }
1579
1580    types.push(aggregate_fields);
1581    types
1582}
1583
1584/// The column enum a `count(columns:)` draws from.
1585fn agg_select_column(base_name: &str) -> String {
1586    crate::input::order_by::select_column_type_name(base_name)
1587}
1588
1589/// One key of the parent object, as a value.
1590fn child_value(ctx: &ResolverContext<'_>, key: &str) -> Option<Value> {
1591    match ctx.parent_value.as_value() {
1592        Some(Value::Object(map)) => map.get(&async_graphql::Name::new(key)).cloned(),
1593        _ => None,
1594    }
1595}
1596
1597/// One key of the parent object, as a resolvable child.
1598///
1599/// `None` where the key is absent or null, which is what a client that did not
1600/// ask for that aggregate should see.
1601fn child_of<'a>(ctx: &ResolverContext<'_>, key: &str) -> Option<FieldValue<'a>> {
1602    match child_value(ctx, key) {
1603        None | Some(Value::Null) => None,
1604        Some(value) => Some(FieldValue::value(value)),
1605    }
1606}
1607
1608/// An error carrying the code Hasura would give it.
1609///
1610/// The default coding reads the message, and a refusal written here has no
1611/// word in it that a message from PostgreSQL would not also have -- so it says
1612/// so itself rather than being guessed at.
1613fn coded_error(code: &'static str, message: impl Into<String>) -> async_graphql::Error {
1614    let mut error = async_graphql::Error::new(message);
1615    let mut extensions = async_graphql::ErrorExtensionValues::default();
1616    extensions.set("code", code);
1617    error.extensions = Some(extensions);
1618    error
1619}
1620
1621/// A refusal the client could have avoided by writing the request differently.
1622fn validation_error(message: impl Into<String>) -> async_graphql::Error {
1623    coded_error("validation-failed", message)
1624}
1625
1626/// A database error, classified the way Hasura classifies it.
1627///
1628/// PostgreSQL's own message is the whole of what either server says about
1629/// what went wrong; what Hasura adds is a word for *which kind* of wrong,
1630/// taken from the SQLSTATE rather than from the text: `Uniqueness violation.
1631/// duplicate key value violates unique constraint "author_name_key"`. A client
1632/// reporting that to a user is reporting text it already ships.
1633///
1634/// Read from the code, never from the message. The message is localised, the
1635/// code is not, and every attempt to tell these apart by reading English is
1636/// wrong the first time a server runs in another language.
1637fn database_error(error: sqlx::Error) -> async_graphql::Error {
1638    let sqlx::Error::Database(db) = &error else {
1639        return async_graphql::Error::new(error.to_string());
1640    };
1641    let described = match db.code().as_deref() {
1642        // Class 23, integrity constraint violation: the four PostgreSQL
1643        // raises and Hasura names.
1644        Some("23505") => "Uniqueness violation. ",
1645        Some("23502") => "Not-NULL violation. ",
1646        Some("23503") => "Foreign key violation. ",
1647        Some("23514") => "Check constraint violation. ",
1648        // Everything else is answered with PostgreSQL's own words and no
1649        // heading. Inventing one for a class Hasura says nothing about would
1650        // be a difference rather than a match.
1651        _ => "",
1652    };
1653    let error = async_graphql::Error::new(format!("{}{}", described, db.message()));
1654    // And the code, where the SQLSTATE says which one. Only the codes Hasura's
1655    // corpus pins are set: everything else is left for `code_for` to classify,
1656    // which is a guess from the message text and says so. Replacing that guess
1657    // wholesale would be the same guess with fewer places to notice it.
1658    let coded = match db.code().as_deref() {
1659        Some(code) if code.starts_with("23") => Some("constraint-violation"),
1660        // A `LIKE` pattern that ends mid-escape. Not a data exception to
1661        // Hasura -- the pattern came from the request, so the request is what
1662        // was wrong.
1663        Some("22025") => Some("bad-request"),
1664        // A negative `OFFSET`, and the rest of class 22 with it.
1665        Some(code) if code.starts_with("22") => Some("data-exception"),
1666        _ => None,
1667    };
1668    match coded {
1669        Some(code) => at_code(error, code),
1670        None => error,
1671    }
1672}
1673
1674/// The same error, coded as Hasura codes it.
1675fn at_code(mut error: async_graphql::Error, code: &'static str) -> async_graphql::Error {
1676    let mut extensions = error.extensions.take().unwrap_or_default();
1677    extensions.set("code", code);
1678    error.extensions = Some(extensions);
1679    error
1680}
1681
1682/// The same error, told where in the request it happened.
1683///
1684/// Hasura names the place a write went wrong inside the *arguments* --
1685/// `$.selectionSet.insert_author.args.objects[0].bio` -- and a response path
1686/// cannot say that: it names fields of the answer, and the answer has no
1687/// `objects`. So the path is written where the error is raised, by whoever
1688/// knows which row and which column it is about, and
1689/// [`crate::hasura::path_for`] prefers it over the response path.
1690fn at_path(mut error: async_graphql::Error, path: &str) -> async_graphql::Error {
1691    let mut extensions = error.extensions.take().unwrap_or_default();
1692    extensions.set("path", path);
1693    error.extensions = Some(extensions);
1694    error
1695}
1696
1697fn create_object_type(
1698    obj: &TableObjectType,
1699    relationships: &[RelationshipField],
1700    federation_entity: Option<&FederationEntity>,
1701) -> Object {
1702    let mut object = Object::new(&obj.name);
1703    let entity_is_shared = federation_entity.is_some_and(|entity| entity.shared);
1704    if let Some(entity) = federation_entity {
1705        object = object.key(entity.key_fields_sdl());
1706    }
1707    if entity_is_shared {
1708        object = object.shareable();
1709    }
1710
1711    // A table with no comment still gets a description, because Hasura gives
1712    // one and a client generating documentation from the schema would
1713    // otherwise show a blank where it used to show this.
1714    object = match obj.description() {
1715        // An empty description is one that was given and is empty: metadata
1716        // said the type has none, which is not the same as saying nothing.
1717        Some("") => object,
1718        Some(desc) => object.description(desc),
1719        None => object.description(format!(
1720            "columns and relationships of \"{}\"",
1721            obj.table_name()
1722        )),
1723    };
1724
1725    // A GraphQL object may not have two fields of one name, and a schema that
1726    // tries to build one aborts the process rather than returning an error.
1727    // Relationship names are derived from the table they point at, so a
1728    // foreign key column named after its own target -- `pizza.crust`
1729    // referencing `crust`, which is an ordinary way to write that schema --
1730    // produces exactly that clash.
1731    //
1732    // The column wins. It is the table's own data, it is what a client's
1733    // existing queries select, and dropping it to keep a derived name would
1734    // lose something the schema actually says. The relationship is left out
1735    // and said so, which is what Hasura does with the same clash: the
1736    // metadata is marked inconsistent and the field is simply not there.
1737    let mut taken: HashSet<String> = obj.fields.iter().map(|f| f.name.clone()).collect();
1738
1739    // Collected rather than added as they are built, so they can go on in name
1740    // order -- which is the order Hasura answers introspection in, and does not
1741    // depend on which column the catalogue happened to list first.
1742    let mut fields: Vec<(String, Field)> = Vec::new();
1743
1744    for field in &obj.fields {
1745        let field_name = field.name.clone();
1746        let field_type = graphql_type_ref(&field.type_string());
1747        // A document-valued column can be asked for one part of itself, the
1748        // same way `#>` reads one. It is answered here rather than in SQL
1749        // because the same column may be asked for under several aliases --
1750        // `c32_json(path: "a")` beside `c32_json(path: "arr[0]")` -- and
1751        // one projection cannot carry both.
1752        let takes_path = matches!(&field.graphql_type, crate::types::GraphQLType::Json)
1753            || matches!(
1754                &field.graphql_type,
1755                crate::types::GraphQLType::Custom(name) if name == "json"
1756            );
1757
1758        // Create field with resolver that extracts from parent async_graphql::Value
1759        // The query resolver stores rows as FieldValue::value(Value::Object)
1760        // so we use as_value() to get the Value and extract fields from the Object
1761        let gql_field = Field::new(&field.name, field_type, move |ctx| {
1762            let field_name = field_name.clone();
1763            FieldFuture::new(async move {
1764                // Get the parent value as async_graphql::Value using as_value()
1765                if let Some(Value::Object(map)) = ctx.parent_value.as_value() {
1766                    // Convert field name to async_graphql::Name for lookup
1767                    let key = async_graphql::Name::new(&field_name);
1768                    let path = match takes_path {
1769                        true => ctx.args.get("path").and_then(|v| v.string().ok()),
1770                        false => None,
1771                    };
1772                    match map.get(&key) {
1773                        // A null is the answer, not a value to resolve. An
1774                        // enum-typed column said so with `internal: invalid
1775                        // item for enum` rather than answering null, because a
1776                        // null is not one of its members.
1777                        Some(Value::Null) => return Ok(None),
1778                        Some(val) => {
1779                            let val = match path {
1780                                Some(path) => walk_json_path(val, path)?,
1781                                None => val.clone(),
1782                            };
1783                            return match val {
1784                                Value::Null => Ok(None),
1785                                val => Ok(Some(FieldValue::value(val))),
1786                            };
1787                        }
1788                        None => {}
1789                    }
1790                }
1791
1792                // Field not found or parent not a Value::Object
1793                Ok(None)
1794            })
1795        });
1796
1797        let gql_field = match takes_path {
1798            true => gql_field.argument(
1799                InputValue::new("path", TypeRef::named("String")).description("JSON select path"),
1800            ),
1801            false => gql_field,
1802        };
1803
1804        // A computed field whose function takes more than the row: the
1805        // caller writes those under `args`, for the reason a computed
1806        // relationship's are written there.
1807        let gql_field = match field.arguments.is_empty() {
1808            true => gql_field,
1809            false => gql_field.argument(InputValue::new(
1810                "args",
1811                TypeRef::named_nn(computed_args_type_name(&obj.local_name, &field.name)),
1812            )),
1813        };
1814
1815        let gql_field = if let Some(desc) = &field.description {
1816            gql_field.description(desc)
1817        } else {
1818            gql_field
1819        };
1820        fields.push((field.name.clone(), gql_field));
1821    }
1822
1823    // Relationship fields. The query resolver embeds related rows into the
1824    // parent JSON before returning it, so these read from the parent value the
1825    // same way column fields do.
1826    for rel in relationships {
1827        if !taken.insert(rel.name.clone()) {
1828            tracing::warn!(
1829                "{}: not exposing the relationship to \"{}\" as `{}` -- the table \
1830                 already has a column of that name",
1831                obj.name,
1832                rel.target_type,
1833                rel.name
1834            );
1835            continue;
1836        }
1837        let field_name = rel.name.clone();
1838        let field_type = if rel.is_list {
1839            TypeRef::named_nn_list_nn(&rel.target_type)
1840        } else if always_present(rel, &obj.table) {
1841            TypeRef::named_nn(&rel.target_type)
1842        } else {
1843            TypeRef::named(&rel.target_type)
1844        };
1845
1846        let is_list = rel.is_list;
1847        let mut gql_field = Field::new(&rel.name, field_type, move |ctx| {
1848            let field_name = field_name.clone();
1849            FieldFuture::new(async move {
1850                if let Some(Value::Object(map)) = ctx.parent_value.as_value() {
1851                    let key = async_graphql::Name::new(&field_name);
1852                    match map.get(&key) {
1853                        // A row that points at nothing has no related row, and
1854                        // the answer to that is null -- not an object whose
1855                        // every field is null, which is what handing a null
1856                        // parent value to the field resolvers produced.
1857                        Some(Value::Null) if !is_list => return Ok(None),
1858                        Some(val) => return Ok(Some(FieldValue::value(val.clone()))),
1859                        None => {}
1860                    }
1861                }
1862                Ok(None)
1863            })
1864        });
1865
1866        // The same arguments the root field takes. An embedded list is a list
1867        // like any other: a client showing the five most recent articles of an
1868        // author has nowhere else to say so, and without these the only way to
1869        // narrow one is to fetch all of it and discard the rest in the client.
1870        // A to-one relationship is left alone -- there is nothing to order or
1871        // page through when the answer is one row.
1872        // A computed relationship's function may take more than the row --
1873        // "the articles of this author matching a search" -- and `args` is
1874        // where the caller writes them, so a term called `limit` cannot shadow
1875        // the one that pages the result.
1876        if !rel.arguments.is_empty() {
1877            gql_field = gql_field.argument(InputValue::new(
1878                "args",
1879                TypeRef::named_nn(computed_args_type_name(&obj.local_name, &rel.name)),
1880            ));
1881        }
1882        if rel.is_list {
1883            gql_field = gql_field
1884                .argument(InputValue::new(
1885                    "distinct_on",
1886                    TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
1887                        &rel.target_local_name,
1888                    )),
1889                ))
1890                .argument(InputValue::new(
1891                    "where",
1892                    TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
1893                        &rel.target_local_name,
1894                    )),
1895                ))
1896                .argument(InputValue::new(
1897                    "order_by",
1898                    TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
1899                        &rel.target_local_name,
1900                    )),
1901                ))
1902                .argument(InputValue::new("limit", TypeRef::named("Int")))
1903                .argument(InputValue::new("offset", TypeRef::named("Int")));
1904        }
1905
1906        let gql_field = if let Some(desc) = &rel.description {
1907            gql_field.description(desc)
1908        } else {
1909            gql_field
1910        };
1911        fields.push((rel.name.clone(), gql_field));
1912
1913        // `author { articles_aggregate { aggregate { count } } }` -- the count
1914        // of a row's children without fetching them, which is the query behind
1915        // every "12 comments" beside a post. Only for a relationship to many:
1916        // counting one row is not a question anyone asks.
1917        if rel.is_list {
1918            let aggregate_field = format!("{}_aggregate", rel.name);
1919            if taken.insert(aggregate_field.clone()) {
1920                let key = aggregate_field.clone();
1921                fields.push((
1922                    aggregate_field.clone(),
1923                    Field::new(
1924                        &aggregate_field,
1925                        TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
1926                            &rel.target_local_name,
1927                        )),
1928                        move |ctx| {
1929                            let key = key.clone();
1930                            FieldFuture::new(async move {
1931                                // Absent where the parent has no children at
1932                                // all; the aggregate type's own resolvers read
1933                                // a missing key as zero and an empty list.
1934                                Ok(Some(FieldValue::value(
1935                                    child_value(&ctx, &key).unwrap_or(Value::Null),
1936                                )))
1937                            })
1938                        },
1939                    )
1940                    // The same arguments the list itself takes. "How many of
1941                    // this author's articles were published this year" is the
1942                    // question a count is usually asked as, and without a
1943                    // `where` there is no way to write it.
1944                    .argument(InputValue::new(
1945                        "distinct_on",
1946                        TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
1947                            &rel.target_local_name,
1948                        )),
1949                    ))
1950                    .argument(InputValue::new(
1951                        "where",
1952                        TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
1953                            &rel.target_local_name,
1954                        )),
1955                    ))
1956                    .argument(InputValue::new(
1957                        "order_by",
1958                        TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
1959                            &rel.target_local_name,
1960                        )),
1961                    ))
1962                    .argument(InputValue::new("limit", TypeRef::named("Int")))
1963                    .argument(InputValue::new("offset", TypeRef::named("Int")))
1964                    .description(format!("Aggregates over {}.", rel.name)),
1965                ));
1966                // Counting the rows a function answers with means calling it,
1967                // so the aggregate takes whatever the function takes.
1968                if !rel.arguments.is_empty() {
1969                    let last = fields.len() - 1;
1970                    let (name, field) = fields.remove(last);
1971                    fields.push((
1972                        name,
1973                        field.argument(InputValue::new(
1974                            "args",
1975                            TypeRef::named_nn(computed_args_type_name(&obj.local_name, &rel.name)),
1976                        )),
1977                    ));
1978                }
1979            }
1980        }
1981    }
1982
1983    fields.sort_by(|(a, _), (b, _)| a.cmp(b));
1984    for (_, field) in fields {
1985        object = object.field(field);
1986    }
1987
1988    object
1989}
1990
1991/// A root field, whichever root it is on.
1992///
1993/// A query field and a subscription field take the same arguments and mean the
1994/// same by them -- the difference is only whether the answer is sent once or
1995/// whenever it changes -- and the two builders share no trait of their own, so
1996/// this is what lets the argument list be written once.
1997trait RootField: Sized {
1998    fn with_argument(self, value: InputValue) -> Self;
1999}
2000
2001impl RootField for Field {
2002    fn with_argument(self, value: InputValue) -> Self {
2003        self.argument(value)
2004    }
2005}
2006
2007impl RootField for SubscriptionField {
2008    fn with_argument(self, value: InputValue) -> Self {
2009        self.argument(value)
2010    }
2011}
2012
2013/// The five arguments that narrow a set of rows, in the order Hasura lists
2014/// them.
2015fn with_row_arguments<F: RootField>(field: F, type_name: &str) -> F {
2016    with_row_arguments_named(field, type_name, true)
2017}
2018
2019/// The same, where `columns` says whether the table has any to name.
2020///
2021/// A table a role may count and not read has none: there is no column enum to
2022/// order by and none to be distinct on, so those two arguments are not there
2023/// -- and could not be, since the types they name are not built either. What
2024/// is left still narrows the set being counted, which is the whole of what
2025/// such a root is for.
2026fn with_row_arguments_named<F: RootField>(field: F, type_name: &str, columns: bool) -> F {
2027    let mut field = field;
2028    if columns {
2029        field = field.with_argument(InputValue::new(
2030            "distinct_on",
2031            TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(type_name)),
2032        ));
2033    }
2034    field = field
2035        .with_argument(InputValue::new("limit", TypeRef::named("Int")))
2036        .with_argument(InputValue::new("offset", TypeRef::named("Int")));
2037    if columns {
2038        field = field.with_argument(InputValue::new(
2039            "order_by",
2040            TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(type_name)),
2041        ));
2042    }
2043    field.with_argument(InputValue::new(
2044        "where",
2045        TypeRef::named(crate::input::bool_exp::bool_exp_type_name(type_name)),
2046    ))
2047}
2048
2049/// One argument per primary key column, named and typed after the column
2050/// itself rather than assuming an integer `id`.
2051fn with_key_arguments<F: RootField>(
2052    field: F,
2053    schema_name: &str,
2054    table_name: &str,
2055    pk_columns: &[(String, String)],
2056    names: &crate::names::NameOverrides,
2057) -> F {
2058    let mut field = field;
2059    for (column, pg_type) in pk_columns {
2060        field = field.with_argument(InputValue::new(
2061            names
2062                .column(schema_name, table_name, column)
2063                .unwrap_or(column),
2064            TypeRef::named_nn(exposed_pk_argument_type(
2065                names,
2066                schema_name,
2067                table_name,
2068                column,
2069                pg_type,
2070            )),
2071        ));
2072    }
2073    field
2074}
2075
2076/// Create the Query type with all table query fields.
2077fn create_query_type(
2078    generated: &GeneratedSchema,
2079    root_name: &str,
2080    max_rows: Option<i64>,
2081    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2082    names: Arc<crate::names::NameOverrides>,
2083) -> Object {
2084    // Collected rather than added as they are built, so they can go on in name
2085    // order: that is the order Hasura answers introspection in, and it is the
2086    // order a client diffing two schemas, or a generator writing its types
2087    // out, gets a stable answer from.
2088    let mut roots: Vec<(String, Field)> = Vec::new();
2089
2090    for field in &generated.query_fields {
2091        let table_name = field.table_name.clone();
2092        let schema_name = field.schema_name.clone();
2093        let type_name = field.type_name.clone();
2094        let local_type_name = field.local_type_name.clone();
2095        let is_by_pk = field.is_by_pk;
2096        let pk_columns = field.pk_columns.clone();
2097        let return_type = graphql_type_ref(&field.return_type);
2098
2099        let spec_type_name = local_type_name.clone();
2100        let spec = Arc::new(QueryFieldSpec {
2101            schema_name,
2102            table_name,
2103            type_name,
2104            is_by_pk,
2105            pk_columns: pk_columns.clone(),
2106            max_rows,
2107            relationships: Arc::clone(&relationships),
2108            names: Arc::clone(&names),
2109            call: None,
2110        });
2111
2112        let mut gql_field = Field::new(&field.name, return_type, move |ctx| {
2113            let spec = Arc::clone(&spec);
2114            FieldFuture::new(async move { resolve_query(&ctx, &spec).await })
2115        });
2116
2117        // Add standard query arguments
2118        gql_field = match is_by_pk {
2119            false => with_row_arguments(gql_field, &spec_type_name),
2120            true => with_key_arguments(
2121                gql_field,
2122                &field.schema_name,
2123                &field.table_name,
2124                &pk_columns,
2125                names.as_ref(),
2126            ),
2127        };
2128
2129        if let Some(desc) = &field.description {
2130            gql_field = gql_field.description(desc);
2131        }
2132
2133        // A table this role may count and not read has no row type, so the
2134        // list root that would answer with one is not built. The entry is
2135        // still here for the aggregate root below, which is what such a role
2136        // was granted.
2137        if field.rows {
2138            roots.push((field.name.clone(), gql_field));
2139        }
2140
2141        // The same rows, with numbers about them. Same arguments as the list
2142        // field, because `author_aggregate(where: ...)` counts the set the
2143        // filter describes, not the whole table.
2144        //
2145        // Not built at all for a role whose permission withholds it: counting
2146        // rows is a way of learning about them, so it is granted separately
2147        // from reading them and refused by absence rather than at execution.
2148        if !is_by_pk && field.aggregates {
2149            let agg_spec = Arc::new(AggregateSpec {
2150                schema_name: field.schema_name.clone(),
2151                table_name: field.table_name.clone(),
2152                type_name: field.type_name.clone(),
2153                max_rows,
2154                relationships: Arc::clone(&relationships),
2155                names: Arc::clone(&names),
2156                call: None,
2157            });
2158            let aggregate_field_name = field.aggregate_name.clone().unwrap_or_else(|| {
2159                crate::schema::aggregate::aggregate_type_name(&field.local_type_name)
2160            });
2161            let aggregate_field_name_for_sorting = aggregate_field_name.clone();
2162            let mut agg_field = Field::new(
2163                aggregate_field_name,
2164                TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
2165                    &field.local_type_name,
2166                )),
2167                move |ctx| {
2168                    let agg_spec = Arc::clone(&agg_spec);
2169                    FieldFuture::new(async move { resolve_aggregate(&ctx, &agg_spec).await })
2170                },
2171            );
2172            agg_field = with_row_arguments_named(agg_field, &spec_type_name, field.rows);
2173            agg_field = match field.aggregate_description.as_deref() {
2174                Some("") => agg_field,
2175                Some(given) => agg_field.description(given),
2176                None => agg_field.description(format!(
2177                    "fetch aggregated fields from the table: \"{}\"",
2178                    field.table_name
2179                )),
2180            };
2181            roots.push((aggregate_field_name_for_sorting, agg_field));
2182        }
2183    }
2184
2185    roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2186    let mut query = Object::new(root_name);
2187    // A GraphQL object may not have no fields, so a schema that exposes no
2188    // table needs something on its query root. Hasura puts a placeholder there
2189    // and calls it this; a client that reaches it has nothing to read.
2190    if roots.is_empty() {
2191        return query.field(
2192            Field::new("no_queries_available", TypeRef::named("String"), |_| {
2193                FieldFuture::new(async move { Ok(None::<Value>) })
2194            })
2195            .description("There are no queries available to the current role."),
2196        );
2197    }
2198    for (_, field) in roots {
2199        query = query.field(field);
2200    }
2201
2202    query
2203}
2204
2205/// One document operator: its name, and the type its columns are given.
2206type JsonbOperator = (&'static str, fn() -> TypeRef);
2207
2208/// What a document column may be told to do, and what each is told with.
2209///
2210/// `_append` and `_prepend` take another document; `_delete_key` takes a key;
2211/// `_delete_elem` takes an index into an array; `_delete_at_path` takes the
2212/// path to what is being removed. The shapes are per operator rather than per
2213/// column, which is why one input type per operator says all of it.
2214const JSONB_OPERATORS: &[JsonbOperator] = &[
2215    ("_append", || TypeRef::named("jsonb")),
2216    ("_delete_at_path", || TypeRef::named_nn_list("String")),
2217    ("_delete_elem", || TypeRef::named("Int")),
2218    ("_delete_key", || TypeRef::named("String")),
2219    ("_prepend", || TypeRef::named("jsonb")),
2220];
2221
2222/// The name of the input holding one document operator's columns.
2223fn jsonb_operator_input(type_name: &str, operator: &str) -> String {
2224    format!("{}{}_input", type_name, operator)
2225}
2226
2227/// Add the operators an update may be written with.
2228///
2229/// All optional, and at least one required -- which GraphQL cannot express, so
2230/// the resolver says so instead of the schema. Making `_set` non-null would
2231/// have been expressible and wrong: an update that only increments a counter
2232/// never sends one.
2233fn with_update_operators(
2234    field: Field,
2235    base_name: &str,
2236    has_numeric: bool,
2237    has_jsonb: bool,
2238) -> Field {
2239    let mut field = field;
2240    // A table with no document column is not offered the document operators:
2241    // there is nothing there to append to.
2242    if has_jsonb {
2243        for (operator, _) in JSONB_OPERATORS {
2244            field = field.argument(InputValue::new(
2245                *operator,
2246                TypeRef::named(jsonb_operator_input(base_name, operator)),
2247            ));
2248        }
2249    }
2250    if has_numeric {
2251        field = field.argument(InputValue::new(
2252            "_inc",
2253            TypeRef::named(format!("{}_inc_input", base_name)),
2254        ));
2255    }
2256    field.argument(InputValue::new(
2257        "_set",
2258        TypeRef::named(format!("{}_set_input", base_name)),
2259    ))
2260}
2261
2262/// Create the Mutation type with all mutation fields.
2263/// Which columns a write may name, and so which of its inputs exist.
2264///
2265/// One definition, called both where the inputs are registered and where the
2266/// arguments naming them are declared. They used to agree by coincidence --
2267/// both read the object type's fields -- and stopped the moment a write input
2268/// began following its own permission. An argument naming a type nobody
2269/// registered is a schema async-graphql refuses to build, which costs a role
2270/// every field it has over the one it cannot use.
2271fn write_fields<'a>(
2272    object: &'a crate::schema::object::TableObjectType,
2273    names: &crate::names::NameOverrides,
2274    role: Option<&str>,
2275    verb: crate::role::Verb,
2276) -> Vec<&'a crate::schema::object::GraphQLField> {
2277    let allowed = role.and_then(|role| {
2278        names
2279            .permissions(&object.table.schema, &object.table.name, role)
2280            .and_then(|granted| granted.write_columns(verb))
2281    });
2282    object
2283        .writable_fields
2284        .iter()
2285        .filter(|field| {
2286            let column = table_column_for(names, &object.table, &field.name);
2287            // A column PostgreSQL generates always is not one a write may
2288            // name. Leaving it in the input type moved the refusal to the
2289            // database, which answers `cannot insert a non-DEFAULT value into
2290            // column "id"` and has by then forgotten which argument the value
2291            // came from. Out of the type, the walk over the request says
2292            // `field 'id' not found in type: 'author_insert_input'` and can
2293            // still point at it.
2294            object
2295                .table
2296                .get_column(column)
2297                .is_some_and(|c| !c.always_generated)
2298                && allowed.is_none_or(|set| set.allows(column))
2299        })
2300        .collect()
2301}
2302
2303/// Whether a type has an `_inc_input` and a set of document operator inputs.
2304fn update_inputs(
2305    object: &crate::schema::object::TableObjectType,
2306    names: &crate::names::NameOverrides,
2307    role: Option<&str>,
2308) -> (bool, bool) {
2309    let fields = write_fields(object, names, role, crate::role::Verb::Update);
2310    (
2311        fields
2312            .iter()
2313            .any(|f| crate::schema::aggregate::is_incrementable(&f.graphql_type)),
2314        fields
2315            .iter()
2316            .any(|f| matches!(&f.graphql_type, crate::types::GraphQLType::Json)),
2317    )
2318}
2319
2320fn create_mutation_type(
2321    generated: &GeneratedSchema,
2322    root_name: &str,
2323    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2324    type_names: Arc<HashMap<(String, String), String>>,
2325    names: Arc<crate::names::NameOverrides>,
2326    max_rows: Option<i64>,
2327    role: Option<&str>,
2328) -> Object {
2329    let mut mutation = Object::new(root_name);
2330    // In name order, for the reason the query root is: see there.
2331    let mut roots: Vec<(String, Field)> = Vec::new();
2332
2333    // Only a table with a unique constraint has a conflict to name, and only
2334    // those got the types for it.
2335    // Which tables have something to add to, and which have a document to
2336    // operate on. Read from what was registered above rather than worked out
2337    // again from the object types: the second answer is the one that can
2338    // drift, and drifting means an argument naming a type that is not there.
2339    let mut has_numeric_column: HashSet<String> = HashSet::new();
2340    let mut has_jsonb_column: HashSet<String> = HashSet::new();
2341    for object in generated.object_types.values() {
2342        let (numeric, jsonb) = update_inputs(object, &names, role);
2343        if numeric {
2344            has_numeric_column.insert(object.local_name.clone());
2345        }
2346        if jsonb {
2347            has_jsonb_column.insert(object.local_name.clone());
2348        }
2349    }
2350
2351    let has_conflict_target: HashSet<String> = generated
2352        .object_types
2353        .iter()
2354        .filter(|(_, object)| !object.table.unique_constraints.is_empty())
2355        .map(|(_, object)| object.local_name.clone())
2356        .collect();
2357
2358    for field in &generated.mutation_fields {
2359        let table_name = field.table_name.clone();
2360        let schema_name = field.schema_name.clone();
2361        let mutation_type = field.mutation_type;
2362        let pk_columns = field.pk_columns.clone();
2363        let return_type = graphql_type_ref(&field.return_type);
2364
2365        // The table's own type name, which is what its boolean expression is
2366        // named after. A bulk mutation returns `[author!]!` and a by-key one
2367        // returns `author`; both name the same table.
2368        let where_type = field.local_type_name.clone();
2369
2370        let resolver_pk_columns = pk_columns.clone();
2371        let field_relationships = Arc::clone(&relationships);
2372        let field_type_names = Arc::clone(&type_names);
2373        let field_names = Arc::clone(&names);
2374        let mut gql_field = Field::new(&field.name, return_type, move |ctx| {
2375            let table_name = table_name.clone();
2376            let schema_name = schema_name.clone();
2377            let pk_columns = resolver_pk_columns.clone();
2378            let relationships = Arc::clone(&field_relationships);
2379            let type_names = Arc::clone(&field_type_names);
2380            let names = Arc::clone(&field_names);
2381            FieldFuture::new(async move {
2382                resolve_mutation(
2383                    &ctx,
2384                    &schema_name,
2385                    &table_name,
2386                    mutation_type,
2387                    &pk_columns,
2388                    &relationships,
2389                    &type_names,
2390                    &names,
2391                    max_rows,
2392                )
2393                .await
2394            })
2395        });
2396
2397        // Add mutation-specific arguments.
2398        //
2399        // A by-PK mutation takes the key columns rather than a `where` object:
2400        // it is meant to address exactly one row, and accepting `where` made it
2401        // an ordinary bulk mutation that happened to return the first result.
2402        match mutation_type {
2403            MutationType::Insert | MutationType::InsertOne => {
2404                let insert_input = format!("{}_insert_input", where_type);
2405                gql_field = if mutation_type == MutationType::Insert {
2406                    gql_field.argument(InputValue::new(
2407                        "objects",
2408                        TypeRef::named_nn_list_nn(&insert_input),
2409                    ))
2410                } else {
2411                    // A single insert takes `object`, not a one-element
2412                    // `objects`.
2413                    gql_field.argument(InputValue::new("object", TypeRef::named_nn(&insert_input)))
2414                };
2415                if has_conflict_target.contains(&where_type) {
2416                    gql_field = gql_field.argument(InputValue::new(
2417                        "on_conflict",
2418                        TypeRef::named(format!("{}_on_conflict", where_type)),
2419                    ));
2420                }
2421            }
2422            MutationType::UpdateByPk => {
2423                gql_field = gql_field.argument(InputValue::new(
2424                    "pk_columns",
2425                    TypeRef::named_nn(format!("{}_pk_columns_input", where_type)),
2426                ));
2427                gql_field = with_update_operators(
2428                    gql_field,
2429                    &where_type,
2430                    has_numeric_column.contains(&where_type),
2431                    has_jsonb_column.contains(&where_type),
2432                );
2433            }
2434            MutationType::Update => {
2435                gql_field = gql_field.argument(InputValue::new(
2436                    "where",
2437                    TypeRef::named_nn(crate::input::bool_exp::bool_exp_type_name(&where_type)),
2438                ));
2439                gql_field = with_update_operators(
2440                    gql_field,
2441                    &where_type,
2442                    has_numeric_column.contains(&where_type),
2443                    has_jsonb_column.contains(&where_type),
2444                );
2445            }
2446            MutationType::UpdateMany => {
2447                gql_field = gql_field.argument(InputValue::new(
2448                    "updates",
2449                    TypeRef::named_nn_list_nn(format!("{}_updates", where_type)),
2450                ));
2451            }
2452            MutationType::DeleteByPk => {
2453                for (col_name, pg_type) in &pk_columns {
2454                    gql_field = gql_field.argument(InputValue::new(
2455                        names
2456                            .column(&field.schema_name, &field.table_name, col_name)
2457                            .unwrap_or(col_name),
2458                        TypeRef::named_nn(exposed_pk_argument_type(
2459                            names.as_ref(),
2460                            &field.schema_name,
2461                            &field.table_name,
2462                            col_name,
2463                            pg_type,
2464                        )),
2465                    ));
2466                }
2467            }
2468            MutationType::Delete => {
2469                // Required, as it is on an update: a delete with no predicate
2470                // is a delete of the whole table, and this refused one at
2471                // execution while the schema said it was a query worth
2472                // writing. Saying so in the type is what Hasura does, and it
2473                // is what a client's own tooling can catch before the request
2474                // is sent.
2475                gql_field = gql_field.argument(InputValue::new(
2476                    "where",
2477                    TypeRef::named_nn(crate::input::bool_exp::bool_exp_type_name(&where_type)),
2478                ));
2479            }
2480        }
2481
2482        if let Some(desc) = &field.description {
2483            gql_field = gql_field.description(desc);
2484        }
2485
2486        roots.push((field.name.clone(), gql_field));
2487    }
2488
2489    roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2490    for (_, field) in roots {
2491        mutation = mutation.field(field);
2492    }
2493
2494    mutation
2495}
2496
2497/// Create the Subscription type: the query root, answered again on change.
2498///
2499/// A subscription here is a **live query**. It carries the same fields the
2500/// query root does, takes the same arguments, and answers with the same rows
2501/// -- the difference is that the answer is sent again whenever it stops being
2502/// true. That is the contract a client generated against Hasura expects, and
2503/// the reason its `subscription_root` is a mirror of its `query_root`.
2504///
2505/// What wakes it is this server's own: a trigger publishes on the changed
2506/// table and the query is read again, which costs nothing while nothing is
2507/// written and answers in milliseconds when something is. A trigger cannot
2508/// see everything a query can -- a view has none, an embedded row may live in
2509/// a table that carries none, and `where: {expires_at: {_lt: "now()"}}`
2510/// changes with no write at all -- so a slow refresh runs beside it and
2511/// closes exactly those gaps. Polling alone is what Hasura does, and it pays
2512/// for every subscriber every tick whether or not anything happened.
2513fn create_subscription_type(
2514    generated: &GeneratedSchema,
2515    root_name: &str,
2516    max_rows: Option<i64>,
2517    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2518    names: Arc<crate::names::NameOverrides>,
2519    refresh: std::time::Duration,
2520) -> Subscription {
2521    let mut roots: Vec<(String, SubscriptionField)> = Vec::new();
2522
2523    for field in &generated.query_fields {
2524        let spec_type_name = field.local_type_name.clone();
2525        let pk_columns = field.pk_columns.clone();
2526        let is_by_pk = field.is_by_pk;
2527        let return_type = graphql_type_ref(&field.return_type);
2528        let watched = vec![crate::subscription::table_channel_name(
2529            &field.schema_name,
2530            &field.table_name,
2531        )];
2532
2533        let spec = Arc::new(QueryFieldSpec {
2534            schema_name: field.schema_name.clone(),
2535            table_name: field.table_name.clone(),
2536            type_name: field.type_name.clone(),
2537            is_by_pk,
2538            pk_columns: pk_columns.clone(),
2539            max_rows,
2540            relationships: Arc::clone(&relationships),
2541            names: Arc::clone(&names),
2542            call: None,
2543        });
2544
2545        let mut gql_field = SubscriptionField::new(&field.name, return_type, move |ctx| {
2546            let spec = Arc::clone(&spec);
2547            let watched = watched.clone();
2548            SubscriptionFieldFuture::new(async move {
2549                let wake = wake_on(&ctx, &watched, refresh).await;
2550                Ok(live(ctx, LiveSource::Rows(spec), wake))
2551            })
2552        });
2553
2554        gql_field = match is_by_pk {
2555            false => with_row_arguments(gql_field, &spec_type_name),
2556            true => with_key_arguments(
2557                gql_field,
2558                &field.schema_name,
2559                &field.table_name,
2560                &pk_columns,
2561                names.as_ref(),
2562            ),
2563        };
2564        if let Some(desc) = &field.description {
2565            gql_field = gql_field.description(desc);
2566        }
2567        // No row type, no root that answers with one -- see the query root.
2568        if field.rows {
2569            roots.push((field.name.clone(), gql_field));
2570        }
2571
2572        // A live query mirrors the query root, so an aggregate the role may not
2573        // ask for once is not one it may ask for continuously either.
2574        if is_by_pk || !field.aggregates {
2575            continue;
2576        }
2577
2578        // The same rows, with numbers about them, watched the same way.
2579        let agg_spec = Arc::new(AggregateSpec {
2580            schema_name: field.schema_name.clone(),
2581            table_name: field.table_name.clone(),
2582            type_name: field.type_name.clone(),
2583            max_rows,
2584            relationships: Arc::clone(&relationships),
2585            names: Arc::clone(&names),
2586            call: None,
2587        });
2588        let agg_watched = vec![crate::subscription::table_channel_name(
2589            &field.schema_name,
2590            &field.table_name,
2591        )];
2592        let agg_name = field.aggregate_name.clone().unwrap_or_else(|| {
2593            crate::schema::aggregate::aggregate_type_name(&field.local_type_name)
2594        });
2595        let mut agg_field = SubscriptionField::new(
2596            agg_name.clone(),
2597            TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
2598                &field.local_type_name,
2599            )),
2600            move |ctx| {
2601                let agg_spec = Arc::clone(&agg_spec);
2602                let watched = agg_watched.clone();
2603                SubscriptionFieldFuture::new(async move {
2604                    let wake = wake_on(&ctx, &watched, refresh).await;
2605                    Ok(live(ctx, LiveSource::Aggregate(agg_spec), wake))
2606                })
2607            },
2608        );
2609        agg_field = with_row_arguments_named(agg_field, &spec_type_name, field.rows);
2610        agg_field = match field.aggregate_description.as_deref() {
2611            Some("") => agg_field,
2612            Some(given) => agg_field.description(given),
2613            None => agg_field.description(format!(
2614                "fetch aggregated fields from the table: \"{}\"",
2615                field.table_name
2616            )),
2617        };
2618        roots.push((agg_name, agg_field));
2619    }
2620
2621    roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2622    let mut subscription = Subscription::new(root_name);
2623    // A GraphQL object may not have no fields, and a schema that exposes no
2624    // table still has a subscription root if subscriptions are on.
2625    if roots.is_empty() {
2626        return subscription.field(SubscriptionField::new(
2627            "no_subscriptions_available",
2628            TypeRef::named("String"),
2629            |_| {
2630                SubscriptionFieldFuture::new(async move {
2631                    Ok(futures::stream::empty::<
2632                        Result<FieldValue, async_graphql::Error>,
2633                    >())
2634                })
2635            },
2636        ));
2637    }
2638    for (_, field) in roots {
2639        subscription = subscription.field(field);
2640    }
2641    subscription
2642}
2643
2644/// What tells a live query its answer may have changed.
2645///
2646/// Every notification on the tables it reads, and a slow tick beside them.
2647/// Yields once per wake and never ends -- a subscription lasts as long as the
2648/// client holds it open.
2649async fn wake_on(
2650    ctx: &ResolverContext<'_>,
2651    channels: &[String],
2652    refresh: std::time::Duration,
2653) -> futures::stream::BoxStream<'static, ()> {
2654    use futures::StreamExt;
2655
2656    let mut streams: Vec<futures::stream::BoxStream<'static, ()>> =
2657        Vec::with_capacity(channels.len() + 1);
2658    // A tick even where nothing is listening: a table with no trigger, a view,
2659    // and a predicate that changes with the clock all depend on it.
2660    streams.push(
2661        tokio_stream::wrappers::IntervalStream::new({
2662            let mut interval = tokio::time::interval(refresh);
2663            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
2664            interval
2665        })
2666        .map(|_| ())
2667        .boxed(),
2668    );
2669
2670    if let Ok(broker_arc) = ctx.data::<Arc<RwLock<Option<NotifyBroker>>>>() {
2671        let guard = broker_arc.read().await;
2672        if let Some(broker) = guard.as_ref() {
2673            for channel in channels {
2674                // `subscribe_or_create` rather than `subscribe`: a table whose
2675                // trigger was never installed has no channel, and a live query
2676                // on it is answered by the refresh rather than refused.
2677                streams.push(
2678                    broker
2679                        .subscribe_or_create(channel)
2680                        .await
2681                        .map(|_| ())
2682                        .boxed(),
2683                );
2684            }
2685        }
2686    }
2687
2688    futures::stream::select_all(streams).boxed()
2689}
2690
2691/// What a live query reads each time it is woken.
2692///
2693/// An enum rather than a closure because the answer borrows the context it is
2694/// read from, and a closure returning a future that borrows its argument is
2695/// not something a bound can say.
2696enum LiveSource {
2697    Rows(Arc<QueryFieldSpec>),
2698    Aggregate(Arc<AggregateSpec>),
2699}
2700
2701/// Read one answer, and the value to compare it against the last one by.
2702async fn read_live<'a>(
2703    ctx: &ResolverContext<'a>,
2704    source: &LiveSource,
2705) -> Result<(serde_json::Value, Option<FieldValue<'a>>), async_graphql::Error> {
2706    match source {
2707        LiveSource::Rows(spec) => {
2708            let rows = query_rows(ctx, spec).await?;
2709            Ok((
2710                serde_json::Value::Array(rows.clone()),
2711                rows_as_field_value(rows, spec.is_by_pk),
2712            ))
2713        }
2714        LiveSource::Aggregate(spec) => {
2715            let value = aggregate_value(ctx, spec).await?;
2716            let seen = serde_json::to_value(&value).unwrap_or_default();
2717            Ok((seen, Some(FieldValue::value(value))))
2718        }
2719    }
2720}
2721
2722/// A live query: the answer now, and the answer again each time it changes.
2723///
2724/// The first item is sent as soon as the client subscribes, which is what
2725/// makes this a query rather than a feed -- there is no window in which the
2726/// client knows nothing. After that, `answer` is read again on every wake and
2727/// sent only when what came back is not what was sent last: a write that
2728/// changes a row the subscription does not select is a wake and not a message.
2729fn live<'a>(
2730    ctx: ResolverContext<'a>,
2731    source: LiveSource,
2732    wake: futures::stream::BoxStream<'static, ()>,
2733) -> impl futures::Stream<Item = Result<FieldValue<'a>, async_graphql::Error>> + Send + 'a {
2734    use futures::StreamExt;
2735
2736    struct Live<'a> {
2737        ctx: ResolverContext<'a>,
2738        source: LiveSource,
2739        wake: futures::stream::BoxStream<'static, ()>,
2740        sent: Option<serde_json::Value>,
2741        started: bool,
2742        /// An error has been sent, and the subscription ends after it.
2743        failed: bool,
2744        /// Counts this subscription as open for as long as its stream lives.
2745        _active: crate::subscription::ActiveSubscription,
2746    }
2747
2748    futures::stream::unfold(
2749        Live {
2750            ctx,
2751            source,
2752            wake,
2753            sent: None,
2754            started: false,
2755            failed: false,
2756            _active: crate::subscription::ActiveSubscription::open(),
2757        },
2758        |mut live: Live<'a>| async move {
2759            if live.failed {
2760                return None;
2761            }
2762            loop {
2763                if live.started {
2764                    live.wake.next().await?;
2765                } else {
2766                    live.started = true;
2767                }
2768                let read = read_live(&live.ctx, &live.source).await;
2769                match read {
2770                    // An error ends the subscription: the client asked
2771                    // something that cannot be answered, and answering it
2772                    // again on the next tick would only repeat that. It is
2773                    // sent first, though -- ending on it unsent, as a
2774                    // `take_while(is_ok)` here once did, answers a refused
2775                    // subscription with a bare `complete` that reads exactly
2776                    // like one that finished.
2777                    Err(e) => {
2778                        live.failed = true;
2779                        return Some((Err(e), live));
2780                    }
2781                    Ok((seen, value)) => {
2782                        if live.sent.as_ref() == Some(&seen) {
2783                            continue;
2784                        }
2785                        live.sent = Some(seen);
2786                        let value = value.unwrap_or_else(|| FieldValue::value(Value::Null));
2787                        return Some((Ok(value), live));
2788                    }
2789                }
2790            }
2791        },
2792    )
2793}
2794
2795/// Everything a query field's resolver needs about the field it serves.
2796struct QueryFieldSpec {
2797    schema_name: String,
2798    table_name: String,
2799    type_name: String,
2800    is_by_pk: bool,
2801    pk_columns: Vec<(String, String)>,
2802    max_rows: Option<i64>,
2803    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2804    names: Arc<crate::names::NameOverrides>,
2805    /// Set where the rows come from a function rather than from the table
2806    /// itself. Everything else about reading them is the same.
2807    call: Option<Arc<FunctionCall>>,
2808}
2809
2810/// Everything `_entities` needs to resolve a representation to a table row.
2811#[derive(Clone)]
2812struct EntityLookup {
2813    schema_name: String,
2814    table_name: String,
2815    type_name: String,
2816    key_columns: Vec<EntityKeyColumn>,
2817    row_column_types: HashMap<String, String>,
2818}
2819
2820#[derive(Clone)]
2821struct EntityKeyColumn {
2822    field_name: String,
2823    column_name: String,
2824    pg_type: String,
2825    explicit_id: bool,
2826}
2827
2828/// The federation entity resolver's immutable schema view.
2829struct EntityResolverState {
2830    entities: HashMap<String, EntityLookup>,
2831    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2832    names: Arc<crate::names::NameOverrides>,
2833    max_rows: Option<i64>,
2834}
2835
2836impl EntityResolverState {
2837    fn new(
2838        generated: &GeneratedSchema,
2839        relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2840        names: Arc<crate::names::NameOverrides>,
2841        max_rows: Option<i64>,
2842    ) -> Self {
2843        let mut entities = HashMap::new();
2844        for (type_name, entity) in &generated.federation_entities {
2845            let Some(object) = generated.object_types.get(type_name) else {
2846                continue;
2847            };
2848            let mut key_columns = Vec::with_capacity(entity.key_fields.len());
2849            for field_name in &entity.key_fields {
2850                let column_name = names
2851                    .column_source(&object.table.schema, &object.table.name, field_name)
2852                    .unwrap_or(field_name);
2853                let Some(column) = object.table.get_column(column_name) else {
2854                    continue;
2855                };
2856                key_columns.push(EntityKeyColumn {
2857                    field_name: field_name.clone(),
2858                    column_name: column.name.clone(),
2859                    pg_type: column.nominal_type.clone(),
2860                    explicit_id: matches!(
2861                        names.column_type(&object.table.schema, &object.table.name, &column.name),
2862                        Some(crate::types::GraphQLType::Id)
2863                    ),
2864                });
2865            }
2866            if key_columns.len() != entity.key_fields.len() {
2867                continue;
2868            }
2869            entities.insert(
2870                type_name.clone(),
2871                EntityLookup {
2872                    schema_name: object.table.schema.clone(),
2873                    table_name: object.table.name.clone(),
2874                    type_name: type_name.clone(),
2875                    key_columns,
2876                    row_column_types: exposed_column_types(&object.table, names.as_ref()),
2877                },
2878            );
2879        }
2880        Self {
2881            entities,
2882            relationships,
2883            names,
2884            max_rows,
2885        }
2886    }
2887}
2888
2889struct EntityRepresentation {
2890    index: usize,
2891    type_name: String,
2892    values: serde_json::Map<String, serde_json::Value>,
2893}
2894
2895/// Fields selected for one concrete member of the federation `_Entity` union.
2896///
2897/// `SelectionField::selection_set()` expands every fragment but does not apply
2898/// its type condition. Keep a parallel applicability list while walking the
2899/// raw selection tree, then use it to retain only the fields meant for this
2900/// entity type.
2901fn entity_field_applicability(
2902    selection_set: &SelectionSet,
2903    fragments: &HashMap<Name, Positioned<FragmentDefinition>>,
2904    type_name: &str,
2905) -> Vec<bool> {
2906    fn condition_matches(condition: Option<&Positioned<TypeCondition>>, type_name: &str) -> bool {
2907        condition.is_none_or(|condition| {
2908            let condition = condition.node.on.node.as_str();
2909            condition == type_name || condition == "_Entity"
2910        })
2911    }
2912
2913    fn collect(
2914        selection_set: &SelectionSet,
2915        fragments: &HashMap<Name, Positioned<FragmentDefinition>>,
2916        type_name: &str,
2917        parent_matches: bool,
2918        applicability: &mut Vec<bool>,
2919    ) {
2920        for selection in &selection_set.items {
2921            match &selection.node {
2922                Selection::Field(_) => applicability.push(parent_matches),
2923                Selection::FragmentSpread(spread) => {
2924                    let Some(fragment) = fragments.get(&spread.node.fragment_name.node) else {
2925                        continue;
2926                    };
2927                    collect(
2928                        &fragment.node.selection_set.node,
2929                        fragments,
2930                        type_name,
2931                        parent_matches
2932                            && condition_matches(Some(&fragment.node.type_condition), type_name),
2933                        applicability,
2934                    );
2935                }
2936                Selection::InlineFragment(fragment) => collect(
2937                    &fragment.node.selection_set.node,
2938                    fragments,
2939                    type_name,
2940                    parent_matches
2941                        && condition_matches(fragment.node.type_condition.as_ref(), type_name),
2942                    applicability,
2943                ),
2944            }
2945        }
2946    }
2947
2948    let mut applicability = Vec::new();
2949    collect(
2950        selection_set,
2951        fragments,
2952        type_name,
2953        true,
2954        &mut applicability,
2955    );
2956    applicability
2957}
2958
2959fn entity_selection_fields<'ctx, 'a>(
2960    ctx: &'ctx ResolverContext<'a>,
2961    type_name: &str,
2962) -> Vec<SelectionField<'ctx>> {
2963    let applicability = entity_field_applicability(
2964        &ctx.ctx.item.node.selection_set.node,
2965        &ctx.ctx.query_env.fragments,
2966        type_name,
2967    );
2968    let fields: Vec<_> = ctx.field().selection_set().collect();
2969    debug_assert_eq!(fields.len(), applicability.len());
2970    fields
2971        .into_iter()
2972        .zip(applicability)
2973        .filter_map(|(field, applies)| applies.then_some(field))
2974        .collect()
2975}
2976
2977async fn resolve_entities<'a>(
2978    ctx: &ResolverContext<'a>,
2979    state: &EntityResolverState,
2980) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
2981    let representations = ctx.args.try_get("representations")?.list()?;
2982    let mut grouped: HashMap<String, Vec<EntityRepresentation>> = HashMap::new();
2983    let mut count = 0;
2984    for (index, representation) in representations.iter().enumerate() {
2985        count += 1;
2986        let value = accessor_to_json(&representation);
2987        let serde_json::Value::Object(values) = value else {
2988            return Err(async_graphql::Error::new(
2989                "entity representation must be an object",
2990            ));
2991        };
2992        let type_name = values
2993            .get("__typename")
2994            .and_then(serde_json::Value::as_str)
2995            .ok_or_else(|| {
2996                async_graphql::Error::new("entity representation is missing __typename")
2997            })?
2998            .to_string();
2999        grouped
3000            .entry(type_name.clone())
3001            .or_default()
3002            .push(EntityRepresentation {
3003                index,
3004                type_name,
3005                values,
3006            });
3007    }
3008
3009    let mut resolved: Vec<Option<FieldValue<'a>>> =
3010        std::iter::repeat_with(|| None).take(count).collect();
3011    for (type_name, representations) in grouped {
3012        let lookup = state.entities.get(&type_name).ok_or_else(|| {
3013            async_graphql::Error::new(format!("unknown federation entity \"{}\"", type_name))
3014        })?;
3015        let rows = resolve_entity_group(ctx, lookup, &representations, state).await?;
3016        for (ordinality, representation) in representations.into_iter().enumerate() {
3017            resolved[representation.index] = Some(match &rows[ordinality] {
3018                Some(row) => FieldValue::value(json_to_value(row.clone()))
3019                    .with_type(representation.type_name),
3020                None => FieldValue::NULL,
3021            });
3022        }
3023    }
3024
3025    Ok(Some(FieldValue::list(resolved.into_iter().map(|value| {
3026        value.expect("every representation was resolved or errored")
3027    }))))
3028}
3029
3030async fn resolve_entity_group(
3031    ctx: &ResolverContext<'_>,
3032    lookup: &EntityLookup,
3033    representations: &[EntityRepresentation],
3034    state: &EntityResolverState,
3035) -> Result<Vec<Option<serde_json::Value>>, async_graphql::Error> {
3036    if representations.is_empty() {
3037        return Ok(Vec::new());
3038    }
3039
3040    let pool = ctx.data::<PgPool>()?;
3041    let gql_ctx = ctx.data::<GraphQLContext>()?;
3042    let mut bound_values = Vec::new();
3043    let mut value_rows = Vec::with_capacity(representations.len());
3044    for (ordinality, representation) in representations.iter().enumerate() {
3045        let normalized_values = normalized_entity_key_values(
3046            &representation.values,
3047            &lookup.key_columns,
3048            &lookup.type_name,
3049        )?;
3050        let mut values = Vec::with_capacity(lookup.key_columns.len() + 1);
3051        for (key_column, value) in lookup.key_columns.iter().zip(normalized_values) {
3052            values.push(format!(
3053                "${}::{}",
3054                bound_values.len() + 1,
3055                key_column.pg_type
3056            ));
3057            bound_values.push(value);
3058        }
3059        values.push(ordinality.to_string());
3060        value_rows.push(format!("({})", values.join(", ")));
3061    }
3062
3063    let representation_alias = "pgrst_entity_representation";
3064    let ordinality_column = "pgrst_entity_ordinality";
3065    let key_aliases: Vec<String> = (0..lookup.key_columns.len())
3066        .map(|index| format!("pgrst_entity_key_{index}"))
3067        .collect();
3068    let mut representation_columns: Vec<String> = key_aliases
3069        .iter()
3070        .map(|column| postrust_sql::escape_ident(column))
3071        .collect();
3072    representation_columns.push(postrust_sql::escape_ident(ordinality_column));
3073    let representations_sql = format!(
3074        "(VALUES {}) AS {} ({})",
3075        value_rows.join(", "),
3076        postrust_sql::escape_ident(representation_alias),
3077        representation_columns.join(", ")
3078    );
3079    let key_predicate = lookup
3080        .key_columns
3081        .iter()
3082        .zip(&key_aliases)
3083        .map(|(key_column, key_alias)| {
3084            format!(
3085                "{}.{} = {}.{}",
3086                postrust_sql::escape_ident(READ_ROW),
3087                postrust_sql::escape_ident(&key_column.column_name),
3088                postrust_sql::escape_ident(representation_alias),
3089                postrust_sql::escape_ident(key_alias)
3090            )
3091        })
3092        .collect::<Vec<_>>()
3093        .join(" AND ");
3094    let mut where_sql = format!(" WHERE ({key_predicate})");
3095
3096    let permission = permission_predicate(
3097        &gql_ctx.caller(),
3098        state.names.as_ref(),
3099        &lookup.schema_name,
3100        &lookup.table_name,
3101    )?;
3102    if let Some(predicate) = permission {
3103        let guard = gql_ctx
3104            .schema_cache
3105            .get()
3106            .await
3107            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3108        let cache = guard
3109            .as_ref()
3110            .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3111        let scope = WhereScope::table(
3112            &lookup.schema_name,
3113            &lookup.table_name,
3114            &lookup.type_name,
3115            state.names.as_ref(),
3116        )
3117        .under_alias(READ_ROW)
3118        .with_resolution(cache, state.relationships.as_ref())
3119        .for_caller(gql_ctx.caller());
3120        let (filter_sql, filter_values) =
3121            build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
3122        if !filter_sql.is_empty() {
3123            where_sql = format!(
3124                "{} AND ({})",
3125                where_sql,
3126                filter_sql.trim_start_matches("WHERE ")
3127            );
3128            bound_values.extend(filter_values);
3129        }
3130    }
3131
3132    let source = format!(
3133        "{}.{} AS {}",
3134        postrust_sql::escape_ident(&lookup.schema_name),
3135        postrust_sql::escape_ident(&lookup.table_name),
3136        postrust_sql::escape_ident(READ_ROW)
3137    );
3138    let source_rows = format!(
3139        "SELECT {}.* FROM {}{}",
3140        postrust_sql::escape_ident(READ_ROW),
3141        source,
3142        where_sql
3143    );
3144    let mut projection = {
3145        let guard = gql_ctx
3146            .schema_cache
3147            .get()
3148            .await
3149            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3150        guard
3151            .as_ref()
3152            .and_then(|cache| {
3153                cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
3154                    &lookup.schema_name,
3155                    &lookup.table_name,
3156                ))
3157            })
3158            .and_then(|table| rename_projection(table, "src", state.names.as_ref()))
3159            .unwrap_or_else(|| "src.*".to_string())
3160    };
3161    let projected_rows = {
3162        let guard = gql_ctx
3163            .schema_cache
3164            .get()
3165            .await
3166            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3167        let cache = guard
3168            .as_ref()
3169            .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3170        let table = cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
3171            &lookup.schema_name,
3172            &lookup.table_name,
3173        ));
3174        let selected_fields = entity_selection_fields(ctx, &lookup.type_name);
3175        let mut param_idx = bound_values.len() + 1;
3176        let computed = match table {
3177            Some(table) => computed_projections(
3178                table,
3179                selected_fields.iter().copied(),
3180                "src",
3181                state.names.as_ref(),
3182                cache,
3183                &mut param_idx,
3184                &mut bound_values,
3185            )?,
3186            None => Vec::new(),
3187        };
3188        let embeds = build_embed_expressions(
3189            &gql_ctx.caller(),
3190            cache,
3191            state.relationships.as_ref(),
3192            &lookup.type_name,
3193            "src",
3194            selected_fields,
3195            state.max_rows,
3196            &mut 0,
3197            &mut param_idx,
3198            &mut bound_values,
3199            state.names.as_ref(),
3200        )?;
3201        for expression in &computed {
3202            projection.push_str(", ");
3203            projection.push_str(expression);
3204        }
3205        for (field_name, expression) in &embeds {
3206            projection.push_str(", ");
3207            projection.push_str(expression);
3208            projection.push_str(" AS ");
3209            projection.push_str(&postrust_sql::escape_ident(field_name));
3210        }
3211        format!("SELECT {} FROM ({}) AS src", projection, source_rows)
3212    };
3213    // PostgreSQL decides whether an entity key matches. Carry the input's
3214    // ordinal through that same query instead of reconstructing a key from
3215    // row JSON: PostgreSQL-equivalent spellings (UUID case, citext case and
3216    // timestamptz offsets, for example) need to resolve to the row it found.
3217    let sql = format!(
3218        "SELECT json_build_array({}.{}, {}) FROM {} CROSS JOIN LATERAL ({}) AS t",
3219        postrust_sql::escape_ident(representation_alias),
3220        postrust_sql::escape_ident(ordinality_column),
3221        row_json("t", &lookup.row_column_types),
3222        representations_sql,
3223        projected_rows,
3224    );
3225    let mut tx = begin_with_session(pool, gql_ctx).await?;
3226    let rows = execute_query_on(&mut tx, &sql, &bound_values).await?;
3227    tx.commit().await?;
3228
3229    let mut by_ordinal = std::iter::repeat_with(|| None)
3230        .take(representations.len())
3231        .collect::<Vec<_>>();
3232    for result in rows {
3233        let serde_json::Value::Array(mut pair) = result else {
3234            return Err(async_graphql::Error::new(
3235                "entity query returned an invalid result",
3236            ));
3237        };
3238        if pair.len() != 2 {
3239            return Err(async_graphql::Error::new(
3240                "entity query returned an invalid result",
3241            ));
3242        }
3243        let row = pair.pop().expect("the result pair has two values");
3244        let ordinality = pair
3245            .pop()
3246            .and_then(|value| value.as_u64())
3247            .and_then(|value| usize::try_from(value).ok())
3248            .filter(|value| *value < by_ordinal.len())
3249            .ok_or_else(|| async_graphql::Error::new("entity query returned an invalid ordinal"))?;
3250        by_ordinal[ordinality] = Some(row);
3251    }
3252    Ok(by_ordinal)
3253}
3254
3255/// Validate an entity key and normalize explicit GraphQL `ID` overrides to
3256/// their integer, text or UUID storage type. `_Any` deliberately skips the
3257/// field-level checks ordinary GraphQL arguments receive.
3258fn normalized_entity_key_values(
3259    values: &serde_json::Map<String, serde_json::Value>,
3260    key_columns: &[EntityKeyColumn],
3261    type_name: &str,
3262) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
3263    let mut key = Vec::with_capacity(key_columns.len());
3264    for key_column in key_columns {
3265        let value = values.get(&key_column.field_name).ok_or_else(|| {
3266            async_graphql::Error::new(format!(
3267                "entity representation for \"{}\" is missing key field \"{}\"",
3268                type_name, key_column.field_name
3269            ))
3270        })?;
3271        key.push(normalize_entity_key_value(type_name, key_column, value)?);
3272    }
3273    Ok(key)
3274}
3275
3276fn normalize_entity_key_value(
3277    type_name: &str,
3278    key_column: &EntityKeyColumn,
3279    value: &serde_json::Value,
3280) -> Result<serde_json::Value, async_graphql::Error> {
3281    let invalid = |expected: &str| {
3282        async_graphql::Error::new(format!(
3283            "entity representation for \"{}\" has invalid key field \"{}\": expected {}, found {}",
3284            type_name,
3285            key_column.field_name,
3286            expected,
3287            json_value_kind(value)
3288        ))
3289    };
3290
3291    if key_column.explicit_id {
3292        return normalize_graphql_id(value, &key_column.pg_type).ok_or_else(|| {
3293            invalid(&format!(
3294                "an ID compatible with PostgreSQL type \"{}\"",
3295                key_column.pg_type
3296            ))
3297        });
3298    }
3299
3300    let pg_type = key_column.pg_type.trim().to_ascii_lowercase();
3301    let normalized = if matches!(pg_type.as_str(), "int8" | "bigint") {
3302        match value {
3303            serde_json::Value::Number(number) => number.as_i64(),
3304            serde_json::Value::String(text) => text.parse::<i64>().ok(),
3305            _ => None,
3306        }
3307        .map(serde_json::Value::from)
3308    } else if integer_bounds(&pg_type).is_some() {
3309        value.as_i64().and_then(|integer| {
3310            let (min, max) = integer_bounds(&pg_type)?;
3311            (min..=max)
3312                .contains(&integer)
3313                .then(|| serde_json::Value::from(integer))
3314        })
3315    } else if matches!(
3316        pg_type.as_str(),
3317        "float4" | "float8" | "real" | "double precision"
3318    ) {
3319        value
3320            .as_f64()
3321            .and_then(serde_json::Number::from_f64)
3322            .map(serde_json::Value::Number)
3323    } else if matches!(pg_type.as_str(), "numeric" | "decimal") {
3324        match value {
3325            serde_json::Value::Number(number) => {
3326                Some(serde_json::Value::String(number.to_string()))
3327            }
3328            serde_json::Value::String(text) if text.parse::<sqlx::types::BigDecimal>().is_ok() => {
3329                Some(serde_json::Value::String(text.clone()))
3330            }
3331            _ => None,
3332        }
3333    } else if matches!(pg_type.as_str(), "bool" | "boolean") {
3334        value.as_bool().map(serde_json::Value::Bool)
3335    } else if matches!(pg_type.as_str(), "json" | "jsonb") {
3336        Some(value.clone())
3337    } else if is_array_type(&pg_type) {
3338        value.is_array().then(|| value.clone())
3339    } else {
3340        value
3341            .as_str()
3342            .map(|text| serde_json::Value::String(text.to_string()))
3343    };
3344
3345    normalized.ok_or_else(|| {
3346        invalid(&format!(
3347            "a value compatible with PostgreSQL type \"{}\"",
3348            key_column.pg_type
3349        ))
3350    })
3351}
3352
3353fn normalize_graphql_id(value: &serde_json::Value, pg_type: &str) -> Option<serde_json::Value> {
3354    if integer_bounds(pg_type).is_some() {
3355        let integer = match value {
3356            serde_json::Value::Number(number) => number.as_i64(),
3357            serde_json::Value::String(text) => text.parse::<i64>().ok(),
3358            _ => None,
3359        }?;
3360        let (min, max) = integer_bounds(pg_type)?;
3361        return (min..=max)
3362            .contains(&integer)
3363            .then(|| serde_json::Value::from(integer));
3364    }
3365    if pg_type.eq_ignore_ascii_case("uuid") {
3366        return normalize_uuid(value).map(serde_json::Value::String);
3367    }
3368    if is_text_type(pg_type) {
3369        return match value {
3370            serde_json::Value::String(s) => Some(serde_json::Value::String(s.clone())),
3371            serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => {
3372                Some(serde_json::Value::String(n.to_string()))
3373            }
3374            _ => None,
3375        };
3376    }
3377    None
3378}
3379
3380fn integer_bounds(pg_type: &str) -> Option<(i64, i64)> {
3381    match pg_type.trim().to_ascii_lowercase().as_str() {
3382        "int2" | "smallint" => Some((i16::MIN.into(), i16::MAX.into())),
3383        "int4" | "int" | "integer" => Some((i32::MIN.into(), i32::MAX.into())),
3384        "int8" | "bigint" => Some((i64::MIN, i64::MAX)),
3385        _ => None,
3386    }
3387}
3388
3389fn is_text_type(pg_type: &str) -> bool {
3390    matches!(
3391        pg_type.trim().to_ascii_lowercase().as_str(),
3392        "text" | "varchar" | "character varying" | "char" | "character" | "bpchar" | "citext"
3393    )
3394}
3395
3396fn normalize_uuid(value: &serde_json::Value) -> Option<String> {
3397    sqlx::types::Uuid::parse_str(value.as_str()?)
3398        .ok()
3399        .map(|uuid| uuid.to_string())
3400}
3401
3402fn json_value_kind(value: &serde_json::Value) -> &'static str {
3403    match value {
3404        serde_json::Value::Null => "null",
3405        serde_json::Value::Bool(_) => "a boolean",
3406        serde_json::Value::Number(_) => "a number",
3407        serde_json::Value::String(_) => "a string",
3408        serde_json::Value::Array(_) => "an array",
3409        serde_json::Value::Object(_) => "an object",
3410    }
3411}
3412
3413/// Add the root fields for functions that answer with rows of a table.
3414///
3415/// The same arguments a table's own root field takes, because the rows are the
3416/// same rows: what the function adds is `args`, which is where its own
3417/// arguments go so that a parameter called `limit` cannot shadow the one that
3418/// pages the result.
3419fn add_function_fields(
3420    mut root: Object,
3421    generated: &GeneratedSchema,
3422    volatile: bool,
3423    max_rows: Option<i64>,
3424    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
3425    names: Arc<crate::names::NameOverrides>,
3426) -> Object {
3427    // The names the root already carries, from the tables. A function may be
3428    // named after one -- `create function t() returns setof t` is an ordinary
3429    // way to write a parameterised view -- and `Object::field` *panics* on a
3430    // duplicate, so an unguarded collision is a server that will not start.
3431    let taken: HashSet<&str> = if volatile {
3432        generated
3433            .mutation_fields
3434            .iter()
3435            .map(|f| f.name.as_str())
3436            .collect()
3437    } else {
3438        generated
3439            .query_fields
3440            .iter()
3441            .map(|f| f.name.as_str())
3442            .collect()
3443    };
3444
3445    for function in &generated.function_fields {
3446        if function.volatile != volatile {
3447            continue;
3448        }
3449        if taken.contains(function.name.as_str()) {
3450            tracing::warn!(
3451                "not exposing {}.{}({}) -- a table already has a root field \
3452                 called {}",
3453                function.schema_name,
3454                function.function_name,
3455                function.argument_signature(),
3456                function.name,
3457            );
3458            continue;
3459        }
3460        let spec = Arc::new(QueryFieldSpec {
3461            schema_name: function.returns_table.0.clone(),
3462            table_name: function.returns_table.1.clone(),
3463            type_name: function.returns.clone(),
3464            is_by_pk: false,
3465            pk_columns: Vec::new(),
3466            max_rows,
3467            relationships: Arc::clone(&relationships),
3468            names: Arc::clone(&names),
3469            call: Some(Arc::new(FunctionCall {
3470                schema: function.schema_name.clone(),
3471                name: function.function_name.clone(),
3472                arguments: function.arguments.clone(),
3473                session_argument: function.session_argument.clone(),
3474            })),
3475        });
3476
3477        let mut field = Field::new(
3478            &function.name,
3479            TypeRef::named_nn_list_nn(&function.returns),
3480            move |ctx| {
3481                let spec = Arc::clone(&spec);
3482                FieldFuture::new(async move { resolve_query(&ctx, &spec).await })
3483            },
3484        );
3485        if !function.arguments.is_empty() {
3486            field = field.argument(InputValue::new(
3487                "args",
3488                TypeRef::named_nn(format!("{}_args", function.name)),
3489            ));
3490        }
3491        field = field
3492            .argument(InputValue::new(
3493                "where",
3494                TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
3495                    &function.local_returns,
3496                )),
3497            ))
3498            .argument(InputValue::new(
3499                "order_by",
3500                TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
3501                    &function.local_returns,
3502                )),
3503            ))
3504            .argument(InputValue::new(
3505                "distinct_on",
3506                TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
3507                    &function.local_returns,
3508                )),
3509            ))
3510            .argument(InputValue::new("limit", TypeRef::named("Int")))
3511            .argument(InputValue::new("offset", TypeRef::named("Int")));
3512        if let Some(description) = &function.description {
3513            field = field.description(description);
3514        }
3515        root = root.field(field);
3516
3517        // The same rows, with numbers about them. Every table root has one and
3518        // so does every function root: `search_tracks_aggregate(args: {…})`
3519        // counts what `search_tracks(args: {…})` would have answered with,
3520        // which means calling the function and taking the same arguments.
3521        let agg_spec = Arc::new(AggregateSpec {
3522            schema_name: function.returns_table.0.clone(),
3523            table_name: function.returns_table.1.clone(),
3524            type_name: function.returns.clone(),
3525            max_rows,
3526            relationships: Arc::clone(&relationships),
3527            names: Arc::clone(&names),
3528            call: Some(Arc::new(FunctionCall {
3529                schema: function.schema_name.clone(),
3530                name: function.function_name.clone(),
3531                arguments: function.arguments.clone(),
3532                session_argument: function.session_argument.clone(),
3533            })),
3534        });
3535        let mut aggregate = Field::new(
3536            format!("{}_aggregate", function.name),
3537            TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
3538                &function.local_returns,
3539            )),
3540            move |ctx| {
3541                let agg_spec = Arc::clone(&agg_spec);
3542                FieldFuture::new(async move { resolve_aggregate(&ctx, &agg_spec).await })
3543            },
3544        );
3545        if !function.arguments.is_empty() {
3546            aggregate = aggregate.argument(InputValue::new(
3547                "args",
3548                TypeRef::named_nn(format!("{}_args", function.name)),
3549            ));
3550        }
3551        aggregate = with_row_arguments(aggregate, &function.local_returns).description(format!(
3552            "fetch aggregated fields from the table: \"{}\"",
3553            function.returns_table.1
3554        ));
3555        root = root.field(aggregate);
3556    }
3557    root
3558}
3559
3560/// The FROM entry for a root field that calls a function.
3561///
3562/// Aliased as the table the function answers with rows of, so a filter or an
3563/// ordering written against that table's columns finds them: without it the
3564/// FROM clause names the function and `article.score` is a table nobody
3565/// mentioned. Whatever the caller put under `args` is bound here, which is why
3566/// it takes the parameter list.
3567fn function_source(
3568    ctx: &ResolverContext<'_>,
3569    call: &FunctionCall,
3570    alias: &str,
3571    bound_values: &mut Vec<serde_json::Value>,
3572) -> Result<String, async_graphql::Error> {
3573    let given = ctx
3574        .args
3575        .try_get("args")
3576        .ok()
3577        .map(|v| accessor_to_json(&v))
3578        .unwrap_or_else(|| serde_json::json!({}));
3579    let mut passed = Vec::new();
3580    for (name, _, required) in &call.arguments {
3581        match given.get(name) {
3582            None if *required => {
3583                return Err(async_graphql::Error::new(format!(
3584                    "{} needs the argument \"{}\"",
3585                    call.name, name
3586                )))
3587            }
3588            // An argument left out is left out, so the function's own default
3589            // applies. Passing null instead would override it.
3590            None => continue,
3591            Some(value) => {
3592                // Named notation, so the arguments a client did give land on
3593                // the parameters it meant regardless of order. A GraphQL Int
3594                // binds as a bigint, and `f(article_id => bigint)` is not
3595                // `f(integer)` -- the function is looked up by the types of
3596                // what it was handed, so what it was handed has to be the
3597                // types it declares.
3598                let (_, pg_type, _) = call
3599                    .arguments
3600                    .iter()
3601                    .find(|(argument, _, _)| argument == name)
3602                    .expect("iterating the arguments");
3603                passed.push(format!(
3604                    "{} => ${}::{}",
3605                    postrust_sql::escape_ident(name),
3606                    bound_values.len() + 1,
3607                    pg_type
3608                ));
3609                bound_values.push(value.clone());
3610            }
3611        }
3612    }
3613    // The session argument is not the client's to send: it says who is
3614    // asking, and a caller that could write it could name any identity it
3615    // liked. It is filled here, from the verified token.
3616    if let Some(session) = &call.session_argument {
3617        passed.push(format!(
3618            "{} => {}",
3619            postrust_sql::escape_ident(session),
3620            SESSION_ARGUMENT
3621        ));
3622    }
3623    Ok(format!(
3624        "{}.{}({}) AS {}",
3625        postrust_sql::escape_ident(&call.schema),
3626        postrust_sql::escape_ident(&call.name),
3627        passed.join(", "),
3628        postrust_sql::escape_ident(alias)
3629    ))
3630}
3631
3632/// A function a root field calls instead of reading a table.
3633struct FunctionCall {
3634    schema: String,
3635    name: String,
3636    arguments: Vec<(String, String, bool)>,
3637    /// The parameter filled from the caller's session rather than from the
3638    /// request. See [`crate::schema::FunctionField::session_argument`].
3639    session_argument: Option<String>,
3640}
3641
3642/// Everything an aggregate field's resolver needs.
3643struct AggregateSpec {
3644    schema_name: String,
3645    table_name: String,
3646    type_name: String,
3647    max_rows: Option<i64>,
3648    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
3649    names: Arc<crate::names::NameOverrides>,
3650    /// Set where the rows come from a function rather than from the table
3651    /// itself, exactly as it is on [`QueryFieldSpec`]. Counting the rows a
3652    /// function answers with means calling it.
3653    call: Option<Arc<FunctionCall>>,
3654}
3655
3656/// Resolve an aggregate field.
3657///
3658/// One pass over the selection decides what SQL to write: a client asking only
3659/// for `count` should not pay for the rows, and one asking only for `nodes`
3660/// should not pay for a second scan. Both halves read from the same filtered
3661/// subquery, so `aggregate` describes exactly the set `nodes` came from.
3662async fn resolve_aggregate<'a>(
3663    ctx: &ResolverContext<'a>,
3664    spec: &AggregateSpec,
3665) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
3666    Ok(Some(FieldValue::value(aggregate_value(ctx, spec).await?)))
3667}
3668
3669/// The numbers an aggregate field answers with.
3670///
3671/// Split from the resolver for the reason [`query_rows`] is: a subscription
3672/// reads them over and over and has to tell one answer from the last.
3673async fn aggregate_value(
3674    ctx: &ResolverContext<'_>,
3675    spec: &AggregateSpec,
3676) -> Result<Value, async_graphql::Error> {
3677    use crate::schema::aggregate as agg;
3678
3679    let pool = ctx.data::<PgPool>()?;
3680    let gql_ctx = ctx.data::<GraphQLContext>()?;
3681
3682    let mut bound_values: Vec<serde_json::Value> = Vec::new();
3683    // A function's own arguments are bound before anything else, so a
3684    // predicate written beside them continues the numbering rather than
3685    // colliding with it.
3686    let source = match &spec.call {
3687        None => format!(
3688            "{}.{}",
3689            postrust_sql::escape_ident(&spec.schema_name),
3690            postrust_sql::escape_ident(&spec.table_name)
3691        ),
3692        Some(call) => function_source(ctx, call, &spec.table_name, &mut bound_values)?,
3693    };
3694
3695    let mut where_sql = String::new();
3696    {
3697        // Counting rows is reading them, so the permission applies here in the
3698        // same breath as the request's own filter -- otherwise `count` would
3699        // report a total the same role cannot list.
3700        let requested = ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v));
3701        let permission = permission_predicate(
3702            &gql_ctx.caller(),
3703            spec.names.as_ref(),
3704            &spec.schema_name,
3705            &spec.table_name,
3706        )?;
3707        if let Some(predicate) = and_predicates(requested, permission) {
3708            let guard = gql_ctx
3709                .schema_cache
3710                .get()
3711                .await
3712                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3713            let cache = guard
3714                .as_ref()
3715                .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3716            // A function's rows are read under the table's name as an alias,
3717            // not from the table itself -- the same split the row read makes.
3718            // Counting them under the qualified name answered `invalid
3719            // reference to FROM-clause entry for table "Track"` the moment a
3720            // permission referred to a column, which is any permission that
3721            // follows a relationship.
3722            let scope = match &spec.call {
3723                None => WhereScope::table(
3724                    &spec.schema_name,
3725                    &spec.table_name,
3726                    &spec.type_name,
3727                    spec.names.as_ref(),
3728                )
3729                .with_resolution(cache, spec.relationships.as_ref()),
3730                Some(_) => WhereScope::for_alias(
3731                    &spec.schema_name,
3732                    &spec.table_name,
3733                    &spec.table_name,
3734                    &spec.type_name,
3735                    cache,
3736                    spec.relationships.as_ref(),
3737                    spec.names.as_ref(),
3738                ),
3739            }
3740            .for_caller(gql_ctx.caller());
3741            let (sql, values) =
3742                build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
3743            if !sql.is_empty() {
3744                where_sql = format!(" {}", sql);
3745                bound_values.extend(values);
3746            }
3747        }
3748    }
3749
3750    let order_sql = build_order_by_clause(
3751        ctx,
3752        &gql_ctx.schema_cache,
3753        &spec.schema_name,
3754        &spec.table_name,
3755        &spec.type_name,
3756        spec.relationships.as_ref(),
3757        &format!(
3758            "{}.{}",
3759            postrust_sql::escape_ident(&spec.schema_name),
3760            postrust_sql::escape_ident(&spec.table_name)
3761        ),
3762        spec.names.as_ref(),
3763    )
3764    .await?;
3765
3766    let requested_limit = ctx.args.try_get("limit").ok().and_then(|v| v.i64().ok());
3767    let offset = ctx.args.try_get("offset").ok().and_then(|v| v.i64().ok());
3768    let ceiling = match (
3769        spec.max_rows,
3770        permission_limit(
3771            &gql_ctx.caller(),
3772            spec.names.as_ref(),
3773            &spec.schema_name,
3774            &spec.table_name,
3775        ),
3776    ) {
3777        (Some(configured), Some(granted)) => Some(configured.min(granted)),
3778        (only, None) | (None, only) => only,
3779    };
3780    let limit = match (requested_limit, ceiling) {
3781        (Some(requested), Some(ceiling)) => Some(requested.min(ceiling)),
3782        (Some(requested), None) => Some(requested),
3783        (None, ceiling) => ceiling,
3784    };
3785
3786    let rows = format!("SELECT * FROM {}{}{}", source, where_sql, order_sql);
3787
3788    // What `nodes` reads: the page, bounded by whichever ceiling is lowest.
3789    let mut inner = rows.clone();
3790    if let Some(limit) = limit {
3791        inner.push_str(&format!(" LIMIT {}", limit));
3792    }
3793    if let Some(offset) = offset {
3794        inner.push_str(&format!(" OFFSET {}", offset));
3795    }
3796
3797    // What `aggregate` reads, which is not the same rows. A count is not a
3798    // page: a ceiling exists to bound how many rows travel, and answering
3799    // "how many are there" with "as many as I would have sent you" is not an
3800    // answer to the question. Hasura says so too -- a role limited to one row
3801    // of `article` still counts three of them and still gets `max(id)` over
3802    // all three, which is what `agg_perm` tests.
3803    //
3804    // The request's own `limit` and `offset` do still apply: those were asked
3805    // for, and `article_aggregate(limit: 2)` is a question about two rows. The
3806    // corpus proves this only for the permission's ceiling; the configured one
3807    // is treated the same way because the reason is the same, and because a
3808    // server whose `PGRST_MAX_ROWS` silently became the answer to `count`
3809    // would be wrong in the way that is hardest to notice.
3810    let mut counted = rows;
3811    if let Some(limit) = requested_limit {
3812        counted.push_str(&format!(" LIMIT {}", limit));
3813    }
3814    if let Some(offset) = offset {
3815        counted.push_str(&format!(" OFFSET {}", offset));
3816    }
3817
3818    // What the client actually asked for. Two selections of one aggregate are
3819    // one entry: `sum { id }` beside `totals: sum { views }` reads the same
3820    // object under two names, so the columns are the union of what both named
3821    // and the object is built once.
3822    let mut wants_nodes = false;
3823    let mut wants_aggregate = false;
3824    let mut wanted: BTreeMap<String, Vec<String>> = BTreeMap::new();
3825    // `count` is different: each occurrence may count something else, so each
3826    // is answered under the name it was asked for.
3827    let mut counts: Vec<(String, String)> = Vec::new();
3828    for selection in ctx.field().selection_set() {
3829        match selection.name() {
3830            "nodes" => wants_nodes = true,
3831            "aggregate" => {
3832                wants_aggregate = true;
3833                for function in selection.selection_set() {
3834                    // Answered by the schema, at this level and the one below.
3835                    if function.name() == "__typename" {
3836                        continue;
3837                    }
3838                    if function.name() == "count" {
3839                        counts.push((
3840                            function.alias().unwrap_or("count").to_string(),
3841                            count_expression(
3842                                function,
3843                                (&spec.schema_name, &spec.table_name),
3844                                None,
3845                                spec.names.as_ref(),
3846                            ),
3847                        ));
3848                        continue;
3849                    }
3850                    // Entered even when it names no column: `max { __typename }`
3851                    // is an object with nothing in it, not a null.
3852                    let columns = wanted.entry(function.name().to_string()).or_default();
3853                    for column in function.selection_set() {
3854                        let name = column.name().to_string();
3855                        if name != "__typename" && !columns.contains(&name) {
3856                            columns.push(name);
3857                        }
3858                    }
3859                }
3860            }
3861            _ => {}
3862        }
3863    }
3864
3865    let mut result = async_graphql::indexmap::IndexMap::new();
3866
3867    // Whatever `aggregate` names -- even if that is only `__typename` -- it is
3868    // an object, so it is answered rather than left null.
3869    if wants_aggregate {
3870        // `count` is answered whether or not it was asked for: the aggregate
3871        // type's own resolver reads a missing key as zero, and a client that
3872        // asked for nothing else still gets a number rather than a null.
3873        let mut parts = match counts.iter().any(|(key, _)| key == "count") {
3874            true => Vec::new(),
3875            false => vec!["'count', count(*)".to_string()],
3876        };
3877        for (key, expression) in &counts {
3878            parts.push(format!(
3879                "{}, {}",
3880                postrust_sql::quote_literal(key),
3881                expression
3882            ));
3883        }
3884        for (function, columns) in &wanted {
3885            // The function name comes from the schema, not from the request:
3886            // a selection can only name a field that was generated, so there
3887            // is no path from client text to this identifier.
3888            let sql_function = agg::NUMERIC_AGGREGATES
3889                .iter()
3890                .chain(agg::ORDERED_AGGREGATES.iter())
3891                .find(|(name, _)| name == function)
3892                .map(|(name, _)| *name)
3893                .ok_or_else(|| {
3894                    async_graphql::Error::new(format!("unknown aggregate \"{}\"", function))
3895                })?;
3896            let per_column: Vec<String> = columns
3897                .iter()
3898                .map(|field| {
3899                    let source = spec
3900                        .names
3901                        .column_source(&spec.schema_name, &spec.table_name, field)
3902                        .unwrap_or(field);
3903                    format!(
3904                        "{}, {}({})",
3905                        postrust_sql::quote_literal(field),
3906                        sql_function,
3907                        postrust_sql::escape_ident(source)
3908                    )
3909                })
3910                .collect();
3911            parts.push(format!(
3912                "'{}', json_build_object({})",
3913                sql_function,
3914                per_column.join(", ")
3915            ));
3916        }
3917
3918        let sql = format!(
3919            "SELECT json_build_object({}) FROM ({}) AS pgrst_agg",
3920            parts.join(", "),
3921            counted
3922        );
3923        let mut conn = begin_with_session(pool, gql_ctx).await?;
3924        let rows = execute_query_on(&mut conn, &sql, &bound_values).await?;
3925        conn.commit().await?;
3926        if let Some(first) = rows.into_iter().next() {
3927            if let Value::Object(map) = json_to_value(first) {
3928                result.insert(async_graphql::Name::new("aggregate"), Value::Object(map));
3929            }
3930        }
3931    }
3932
3933    if wants_nodes {
3934        // `nodes` is the same rows selection the plain root field answers, so
3935        // it gets the same projection: computed fields, which are functions of
3936        // the row rather than part of it, and relationships, which are
3937        // correlated subselects. Reading it as columns alone was why a
3938        // relationship asked for beside a count came back null.
3939        let nodes = ctx
3940            .field()
3941            .selection_set()
3942            .find(|selection| selection.name() == "nodes")
3943            .ok_or_else(|| async_graphql::Error::new("nodes was asked for and then was not"))?;
3944
3945        // The aggregate query has already been sent, so its parameters are
3946        // fixed; anything an embed binds continues that numbering in a vector
3947        // of its own.
3948        let mut node_values = bound_values.clone();
3949        let (projection, row_column_types) = {
3950            let guard = gql_ctx
3951                .schema_cache
3952                .get()
3953                .await
3954                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3955            let cache = guard
3956                .as_ref()
3957                .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3958            let qi = postrust_core::api_request::QualifiedIdentifier::new(
3959                &spec.schema_name,
3960                &spec.table_name,
3961            );
3962            let table = cache.get_table(&qi);
3963            let mut param_idx = node_values.len() + 1;
3964            let computed = match table {
3965                Some(table) => computed_projections(
3966                    table,
3967                    nodes.selection_set(),
3968                    "src",
3969                    spec.names.as_ref(),
3970                    cache,
3971                    &mut param_idx,
3972                    &mut node_values,
3973                )?,
3974                None => Vec::new(),
3975            };
3976            let embeds = build_embed_expressions(
3977                &gql_ctx.caller(),
3978                cache,
3979                spec.relationships.as_ref(),
3980                &spec.type_name,
3981                "src",
3982                nodes.selection_set(),
3983                spec.max_rows,
3984                &mut 0,
3985                &mut param_idx,
3986                &mut node_values,
3987                spec.names.as_ref(),
3988            )?;
3989            // A renamed column is renamed here, in the projection over the
3990            // subquery -- not inside it, where `src` has to stay the table's
3991            // own composite for a computed field to be passed the row.
3992            let mut projection = table
3993                .and_then(|table| rename_projection(table, "src", spec.names.as_ref()))
3994                .unwrap_or_else(|| "src.*".to_string());
3995            for expression in &computed {
3996                projection.push_str(", ");
3997                projection.push_str(expression);
3998            }
3999            for (field_name, expression) in &embeds {
4000                projection.push_str(", ");
4001                projection.push_str(expression);
4002                projection.push_str(" AS ");
4003                projection.push_str(&postrust_sql::escape_ident(field_name));
4004            }
4005            (
4006                projection,
4007                table
4008                    .map(|table| exposed_column_types(table, spec.names.as_ref()))
4009                    .unwrap_or_default(),
4010            )
4011        };
4012
4013        let sql = format!(
4014            "SELECT {} FROM (SELECT {} FROM ({}) AS src) AS pgrst_nodes",
4015            row_json("pgrst_nodes", &row_column_types),
4016            projection,
4017            inner
4018        );
4019        let mut conn = begin_with_session(pool, gql_ctx).await?;
4020        let rows = execute_query_on(&mut conn, &sql, &node_values).await?;
4021        conn.commit().await?;
4022        result.insert(
4023            async_graphql::Name::new("nodes"),
4024            Value::List(rows.into_iter().map(json_to_value).collect()),
4025        );
4026    }
4027
4028    let _ = &spec.type_name;
4029    Ok(Value::Object(result))
4030}
4031
4032/// Resolve a query field.
4033async fn resolve_query<'a>(
4034    ctx: &ResolverContext<'a>,
4035    spec: &QueryFieldSpec,
4036) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
4037    Ok(rows_as_field_value(
4038        query_rows(ctx, spec).await?,
4039        spec.is_by_pk,
4040    ))
4041}
4042
4043/// The rows a query field answers with, as JSON.
4044///
4045/// Split from the field's own resolver because a subscription reads the same
4046/// rows over and over and has to tell one answer from the last: a
4047/// `FieldValue` is neither comparable nor readable, and this is.
4048async fn query_rows(
4049    ctx: &ResolverContext<'_>,
4050    spec: &QueryFieldSpec,
4051) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
4052    let schema_name = spec.schema_name.as_str();
4053    let table_name = spec.table_name.as_str();
4054    let type_name = spec.type_name.as_str();
4055    let is_by_pk = spec.is_by_pk;
4056    let pk_columns = spec.pk_columns.as_slice();
4057    let max_rows = spec.max_rows;
4058    let relationships = spec.relationships.as_ref();
4059
4060    let pool = ctx.data::<PgPool>()?;
4061    let gql_ctx = ctx.data::<GraphQLContext>()?;
4062
4063    debug!("Resolving query for table: {}", table_name);
4064
4065    // Extract pagination arguments
4066    let requested_limit: Option<i64> = ctx.args.try_get("limit").ok().and_then(|v| v.i64().ok());
4067
4068    let offset: Option<i64> = ctx.args.try_get("offset").ok().and_then(|v| v.i64().ok());
4069
4070    // A query that names no limit would otherwise select the whole table, so
4071    // the configured ceiling is applied as the limit in that case, and as an
4072    // upper bound when the query asks for more than it. A by-PK query resolves
4073    // to at most one row.
4074    let limit: Option<i64> = if is_by_pk {
4075        Some(1)
4076    } else {
4077        // The permission's ceiling is one more of the same kind, so it folds
4078        // in the same way: whichever of the three is smallest wins, and a
4079        // request naming none takes the lowest that was named.
4080        let ceiling = match (
4081            max_rows,
4082            permission_limit(
4083                &gql_ctx.caller(),
4084                spec.names.as_ref(),
4085                schema_name,
4086                table_name,
4087            ),
4088        ) {
4089            (Some(configured), Some(granted)) => Some(configured.min(granted)),
4090            (only, None) | (None, only) => only,
4091        };
4092        match (requested_limit, ceiling) {
4093            (Some(requested), Some(ceiling)) => Some(requested.min(ceiling)),
4094            (Some(requested), None) => Some(requested),
4095            (None, ceiling) => ceiling,
4096        }
4097    };
4098
4099    // Build the WHERE clause.
4100    //
4101    // A by-PK query filters on the table's key columns; each value is bound as
4102    // a parameter and cast to the column's type, since GraphQL scalars and
4103    // PostgreSQL types do not line up (a `uuid` key arrives as a String). A
4104    // list query filters on the `filter` argument, which takes the same shape
4105    // as a mutation's `where`.
4106    let mut where_sql = String::new();
4107    let mut bound_values: Vec<serde_json::Value> = Vec::new();
4108
4109    // Where the rows come from. A function's own arguments are bound before
4110    // anything else, because they sit in the FROM clause and every other
4111    // parameter is numbered after them.
4112    let source = match &spec.call {
4113        // Aliased rather than named. A whole-row reference -- what a computed
4114        // field is passed -- can only be written as a bare name, and
4115        // `"public"."author"` is not one: PostgreSQL reads it as a column of a
4116        // table called `public`. An alias no column can share is a name that
4117        // works in both positions.
4118        None => format!(
4119            "{}.{} AS {}",
4120            postrust_sql::escape_ident(schema_name),
4121            postrust_sql::escape_ident(table_name),
4122            postrust_sql::escape_ident(READ_ROW)
4123        ),
4124        Some(call) => function_source(ctx, call, table_name, &mut bound_values)?,
4125    };
4126
4127    // How a column of the source is referred to: a table by its qualified
4128    // name, a function's rows by the alias above.
4129    let source_ref = match &spec.call {
4130        None => postrust_sql::escape_ident(READ_ROW),
4131        Some(_) => postrust_sql::escape_ident(table_name),
4132    };
4133
4134    if is_by_pk {
4135        if pk_columns.is_empty() {
4136            return Err(async_graphql::Error::new(format!(
4137                "\"{}\" has no primary key, so it cannot be queried by key",
4138                table_name
4139            )));
4140        }
4141
4142        let mut conditions = Vec::with_capacity(pk_columns.len());
4143        for (idx, (col_name, pg_type)) in pk_columns.iter().enumerate() {
4144            let field = spec
4145                .names
4146                .column(schema_name, table_name, col_name)
4147                .unwrap_or(col_name);
4148            let value = ctx.args.try_get(field).map_err(|_| {
4149                async_graphql::Error::new(format!(
4150                    "missing required primary key argument \"{}\"",
4151                    field
4152                ))
4153            })?;
4154
4155            conditions.push(format!(
4156                "{} = ${}::{}",
4157                postrust_sql::escape_ident(col_name),
4158                idx + 1,
4159                pg_type
4160            ));
4161            bound_values.push(accessor_to_json(&value));
4162        }
4163        where_sql = format!(" WHERE {}", conditions.join(" AND "));
4164    }
4165
4166    // What this role may read, beside what the request asked for. Applied to
4167    // both shapes and to neither: a query naming no `where` at all is still a
4168    // read, and a by-key query that skipped the permission would be the one
4169    // way to fetch a row the filter withholds.
4170    {
4171        let requested = match is_by_pk {
4172            true => None,
4173            false => ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v)),
4174        };
4175        let permission = permission_predicate(
4176            &gql_ctx.caller(),
4177            spec.names.as_ref(),
4178            schema_name,
4179            table_name,
4180        )?;
4181
4182        if let Some(predicate) = and_predicates(requested, permission) {
4183            let guard = gql_ctx
4184                .schema_cache
4185                .get()
4186                .await
4187                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4188            let cache = guard
4189                .as_ref()
4190                .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4191            let scope = match &spec.call {
4192                None => WhereScope::table(schema_name, table_name, type_name, spec.names.as_ref())
4193                    .under_alias(READ_ROW)
4194                    .with_resolution(cache, relationships)
4195                    .for_caller(gql_ctx.caller()),
4196                // A function's rows are the table's rows, so they are renamed
4197                // the same way; only how they are reached differs.
4198                Some(_) => WhereScope::for_alias(
4199                    schema_name,
4200                    table_name,
4201                    table_name,
4202                    type_name,
4203                    cache,
4204                    relationships,
4205                    spec.names.as_ref(),
4206                )
4207                .for_caller(gql_ctx.caller()),
4208            };
4209            let (filter_sql, filter_values) =
4210                build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
4211            if !filter_sql.is_empty() {
4212                // A by-key query already has a `WHERE`, so this joins it
4213                // rather than replacing it.
4214                where_sql = match where_sql.is_empty() {
4215                    true => format!(" {}", filter_sql),
4216                    false => format!(
4217                        "{} AND ({})",
4218                        where_sql,
4219                        filter_sql.trim_start_matches("WHERE ")
4220                    ),
4221                };
4222                bound_values.extend(filter_values);
4223            }
4224        }
4225    }
4226
4227    // A by-key query resolves to one row, so neither ordering nor distinct
4228    // has anything to do.
4229    let (order_sql, distinct_on) = if is_by_pk {
4230        (String::new(), Vec::new())
4231    } else {
4232        (
4233            build_order_by_clause(
4234                ctx,
4235                &gql_ctx.schema_cache,
4236                schema_name,
4237                table_name,
4238                type_name,
4239                relationships,
4240                &source_ref,
4241                spec.names.as_ref(),
4242            )
4243            .await?,
4244            build_distinct_on(
4245                ctx,
4246                &gql_ctx.schema_cache,
4247                schema_name,
4248                table_name,
4249                spec.names.as_ref(),
4250            )
4251            .await?,
4252        )
4253    };
4254
4255    // PostgreSQL keeps the first row of each DISTINCT ON group in the query's
4256    // own order, and picks arbitrarily where the ordering does not begin with
4257    // the distinct columns -- so which row survives would depend on the plan.
4258    // Hasura refuses that query rather than answering it, and so does this:
4259    // prepending the distinct columns instead produced an answer, and a wrong
4260    // one, since `ORDER BY "department", "department" DESC` is decided by its
4261    // first term and sorts ascending.
4262    let (distinct_sql, order_sql) = {
4263        let written = order_sql.strip_prefix(" ORDER BY ");
4264        // Reported against the field's arguments as a whole: the rule is about
4265        // two of them disagreeing, so neither one is where it went wrong.
4266        let (prefix, order) = distinct_on_clause(&distinct_on, written).map_err(|error| {
4267            at_path(
4268                error,
4269                &format!(
4270                    "$.selectionSet.{}.args",
4271                    ctx.ctx.field().alias().unwrap_or(ctx.ctx.field().name())
4272                ),
4273            )
4274        })?;
4275        (
4276            prefix,
4277            match order {
4278                Some(order) => format!(" ORDER BY {}", order),
4279                None => String::new(),
4280            },
4281        )
4282    };
4283
4284    // A computed column is a function of the row rather than part of it, so
4285    // it is not in `*` and is named only when it was asked for.
4286    let (computed, row_column_types) = {
4287        let guard = gql_ctx
4288            .schema_cache
4289            .get()
4290            .await
4291            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4292        match guard.as_ref() {
4293            Some(cache) => {
4294                let qi =
4295                    postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
4296                match cache.get_table(&qi) {
4297                    Some(table) => {
4298                        let mut param_idx = bound_values.len() + 1;
4299                        (
4300                            computed_projections(
4301                                table,
4302                                ctx.field().selection_set(),
4303                                "src",
4304                                spec.names.as_ref(),
4305                                cache,
4306                                &mut param_idx,
4307                                &mut bound_values,
4308                            )?,
4309                            exposed_column_types(table, spec.names.as_ref()),
4310                        )
4311                    }
4312                    None => (Vec::new(), HashMap::new()),
4313                }
4314            }
4315            None => (Vec::new(), HashMap::new()),
4316        }
4317    };
4318    // ORDER BY, LIMIT and OFFSET belong inside the subquery: applying them to
4319    // the outer `row_to_json` projection would leave the ordering of the rows
4320    // that survive the limit unspecified.
4321    let mut inner = format!(
4322        "SELECT {}* FROM {}{}{}",
4323        distinct_sql, source, where_sql, order_sql
4324    );
4325
4326    if let Some(limit) = limit {
4327        inner.push_str(&format!(" LIMIT {}", limit));
4328    }
4329
4330    if let Some(offset) = offset {
4331        inner.push_str(&format!(" OFFSET {}", offset));
4332    }
4333
4334    // Embed the requested relationships in this same query, as correlated
4335    // subselects in the SELECT list, so the whole selection is one round trip.
4336    let embed_expressions = {
4337        let guard = gql_ctx
4338            .schema_cache
4339            .get()
4340            .await
4341            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4342        match guard.as_ref() {
4343            Some(cache) => {
4344                // Parameters bound inside an embed continue the outer query's
4345                // numbering: sqlx binds by position, so the values only have
4346                // to be pushed in the order their placeholders were handed
4347                // out.
4348                let mut param_idx = bound_values.len() + 1;
4349                build_embed_expressions(
4350                    &gql_ctx.caller(),
4351                    cache,
4352                    relationships,
4353                    type_name,
4354                    "src",
4355                    ctx.field().selection_set(),
4356                    max_rows,
4357                    &mut 0,
4358                    &mut param_idx,
4359                    &mut bound_values,
4360                    spec.names.as_ref(),
4361                )?
4362            }
4363            None => Vec::new(),
4364        }
4365    };
4366
4367    // A computed column is a function of the row, and the row it is a function
4368    // of is the table's -- not the subquery's. Projecting it inside the
4369    // subquery gave `src` an extra column, which is what made a computed
4370    // relationship beside it fail with `cannot cast type record to author`: a
4371    // subquery alias is only passable as a composite value while its columns
4372    // are exactly the table's. So both live out here, where `src` still is
4373    // one.
4374    let renamed = {
4375        let guard = gql_ctx
4376            .schema_cache
4377            .get()
4378            .await
4379            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4380        guard
4381            .as_ref()
4382            .and_then(|cache| {
4383                cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
4384                    schema_name,
4385                    table_name,
4386                ))
4387            })
4388            .and_then(|table| rename_projection(table, "src", spec.names.as_ref()))
4389    };
4390    let inner = if embed_expressions.is_empty() && computed.is_empty() && renamed.is_none() {
4391        inner
4392    } else {
4393        let mut projection = renamed.unwrap_or_else(|| "src.*".to_string());
4394        for expression in &computed {
4395            projection.push_str(", ");
4396            projection.push_str(expression);
4397        }
4398        for (field_name, expression) in &embed_expressions {
4399            projection.push_str(", ");
4400            projection.push_str(expression);
4401            projection.push_str(" AS ");
4402            projection.push_str(&postrust_sql::escape_ident(field_name));
4403        }
4404        format!("SELECT {} FROM ({}) AS src", projection, inner)
4405    };
4406
4407    let sql = format!(
4408        "SELECT {} FROM ({}) t",
4409        row_json("t", &row_column_types),
4410        inner
4411    );
4412
4413    // One transaction for the query and any embeds hanging off it, so the role
4414    // applies to all of them and the parent and child rows come from a single
4415    // snapshot.
4416    let mut tx = begin_with_session(pool, gql_ctx).await?;
4417
4418    // Execute query - returns Vec<serde_json::Value>
4419    let mut result = execute_query_on(&mut tx, &sql, &bound_values).await?;
4420
4421    // Anything the single-query form did not cover.
4422    if embed_expressions.is_empty() {
4423        let guard = gql_ctx
4424            .schema_cache
4425            .get()
4426            .await
4427            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4428        let cache = guard
4429            .as_ref()
4430            .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4431
4432        let embed_ctx = EmbedContext {
4433            schema_cache: cache,
4434            relationships,
4435            max_rows,
4436        };
4437
4438        embed_relationships(&mut tx, &embed_ctx, type_name, ctx.field(), &mut result).await?;
4439    }
4440
4441    tx.commit().await?;
4442
4443    Ok(result)
4444}
4445
4446/// The rows a field answers with, in the shape its type says.
4447///
4448/// A by-key field is one row or none; every other is a list, empty where
4449/// nothing matched rather than null.
4450fn rows_as_field_value<'a>(rows: Vec<serde_json::Value>, is_by_pk: bool) -> Option<FieldValue<'a>> {
4451    match is_by_pk {
4452        true => rows
4453            .into_iter()
4454            .next()
4455            .map(|v| FieldValue::value(json_to_value(v))),
4456        false => Some(FieldValue::list(
4457            rows.into_iter()
4458                .map(|v| FieldValue::value(json_to_value(v))),
4459        )),
4460    }
4461}
4462
4463/// Resolve a mutation field.
4464#[allow(clippy::too_many_arguments)]
4465async fn resolve_mutation<'a>(
4466    ctx: &ResolverContext<'a>,
4467    schema_name: &str,
4468    table_name: &str,
4469    mutation_type: MutationType,
4470    pk_columns: &[(String, String)],
4471    relationships: &Arc<HashMap<String, Vec<RelationshipField>>>,
4472    type_names: &Arc<HashMap<(String, String), String>>,
4473    names: &Arc<crate::names::NameOverrides>,
4474    max_rows: Option<i64>,
4475) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
4476    let pool = ctx.data::<PgPool>()?;
4477    let gql_ctx = ctx.data::<GraphQLContext>()?;
4478
4479    debug!(
4480        "Resolving mutation for table: {} type: {:?}",
4481        table_name, mutation_type
4482    );
4483
4484    // A relationship or a computed field asked for beside the written columns
4485    // is not in `RETURNING`, so the rows are read again through the projection
4486    // an ordinary query uses -- and only when the selection asks for something
4487    // that needs it. A delete cannot do that afterwards and builds it into the
4488    // statement instead, which is why this is settled before the statement is.
4489    let type_name = type_names
4490        .get(&(schema_name.to_string(), table_name.to_string()))
4491        .cloned()
4492        .unwrap_or_else(|| table_name.to_string());
4493
4494    let by_key = matches!(
4495        mutation_type,
4496        MutationType::InsertOne | MutationType::UpdateByPk | MutationType::DeleteByPk
4497    );
4498    let returning = if by_key {
4499        Some(ctx.field())
4500    } else {
4501        ctx.field()
4502            .selection_set()
4503            .find(|selection| selection.name() == "returning")
4504    };
4505
4506    // Several updates, each with its own filter, applied in the order given.
4507    // They share the operation's transaction like any other write, which is
4508    // the whole difference from sending them one at a time: either all of them
4509    // happened or none did.
4510    if mutation_type == MutationType::UpdateMany {
4511        let updates = ctx
4512            .args
4513            .try_get("updates")
4514            .ok()
4515            .map(|v| accessor_to_json(&v))
4516            .unwrap_or(serde_json::Value::Null);
4517        let serde_json::Value::Array(entries) = updates else {
4518            return Err(async_graphql::Error::new(
4519                "\"updates\" takes a list of {where, _set, …} objects",
4520            ));
4521        };
4522        let column_types = column_types_of(&gql_ctx.schema_cache, schema_name, table_name).await;
4523        let mut answers: Vec<FieldValue<'_>> = Vec::with_capacity(entries.len());
4524        for entry in entries {
4525            let serde_json::Value::Object(entry) = entry else {
4526                return Err(async_graphql::Error::new(
4527                    "each update is an object of {where, _set, …}",
4528                ));
4529            };
4530            let operators: Vec<(&'static str, serde_json::Value)> = UPDATE_OPERATORS
4531                .iter()
4532                .filter_map(|name| entry.get(*name).map(|value| (*name, value.clone())))
4533                .filter(|(_, value)| !value.is_null())
4534                .collect();
4535            let rows = execute_update(
4536                pool,
4537                gql_ctx,
4538                schema_name,
4539                table_name,
4540                &type_name,
4541                operators,
4542                column_types.clone(),
4543                entry.get("where").cloned(),
4544                relationships.as_ref(),
4545                names.as_ref(),
4546            )
4547            .await?;
4548            let affected = rows.len();
4549            let rows = match returning {
4550                Some(returning) if !rows.is_empty() => {
4551                    reread_returning(
4552                        pool,
4553                        gql_ctx,
4554                        schema_name,
4555                        table_name,
4556                        &type_name,
4557                        rows,
4558                        returning,
4559                        relationships.as_ref(),
4560                        names.as_ref(),
4561                        max_rows,
4562                    )
4563                    .await?
4564                }
4565                _ => rows,
4566            };
4567            answers.extend(mutation_result(rows, affected, false));
4568        }
4569        return Ok(Some(FieldValue::list(answers)));
4570    }
4571
4572    let (result, affected) = match mutation_type {
4573        MutationType::Insert | MutationType::InsertOne => {
4574            let objects = ctx
4575                .args
4576                .try_get("objects")
4577                .ok()
4578                .map(|v| accessor_to_json(&v))
4579                .or_else(|| {
4580                    // `insert_x_one(object: {...})` is one row spelled without
4581                    // the list.
4582                    ctx.args
4583                        .try_get("object")
4584                        .ok()
4585                        .map(|v| serde_json::Value::Array(vec![accessor_to_json(&v)]))
4586                })
4587                .unwrap_or_else(|| serde_json::Value::Array(vec![]));
4588
4589            let guard = gql_ctx
4590                .schema_cache
4591                .get()
4592                .await
4593                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4594            let cache = guard
4595                .as_ref()
4596                .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4597            // Where this write is, in the document the client sent. The
4598            // field as it was written -- an alias if there was one, since that
4599            // is what names this selection.
4600            let here = format!(
4601                "$.selectionSet.{}",
4602                ctx.ctx.field().alias().unwrap_or(ctx.ctx.field().name())
4603            );
4604            // `insert_x(objects: [...])` against `insert_x_one(object: {...})`:
4605            // the same write under two spellings, and the path says which.
4606            let named = match mutation_type {
4607                MutationType::InsertOne => "object",
4608                _ => "objects",
4609            };
4610            let context = InsertContext {
4611                on_conflict: ctx
4612                    .args
4613                    .try_get("on_conflict")
4614                    .ok()
4615                    .map(|v| accessor_to_json(&v))
4616                    .filter(|v| !v.is_null()),
4617                cache,
4618                relationships: relationships.as_ref(),
4619                type_names: type_names.as_ref(),
4620                names: names.as_ref(),
4621                caller: gql_ctx.caller(),
4622                // Filled in per row by `execute_insert`, which is where the
4623                // index is known.
4624                row: String::new(),
4625                objects: format!("{}.args.{}", here, named),
4626                conflict: format!("{}.args.on_conflict", here),
4627            };
4628
4629            execute_insert(
4630                pool,
4631                gql_ctx,
4632                schema_name,
4633                table_name,
4634                objects,
4635                &context,
4636                mutation_type == MutationType::InsertOne,
4637            )
4638            .await?
4639        }
4640        // `UpdateMany` answered above: it is a list of responses rather than
4641        // one, so it does not share this shape.
4642        MutationType::UpdateMany | MutationType::Update | MutationType::UpdateByPk => {
4643            // `_set` replaces, the others read the column they write. A client
4644            // may send more than one, so all of them are collected rather than
4645            // the first that happens to be present.
4646            let operators: Vec<(&'static str, serde_json::Value)> = UPDATE_OPERATORS
4647                .iter()
4648                .filter_map(|name| {
4649                    ctx.args
4650                        .try_get(name)
4651                        .ok()
4652                        .map(|v| (*name, accessor_to_json(&v)))
4653                })
4654                .filter(|(_, value)| !value.is_null())
4655                .collect();
4656
4657            let where_clause = if mutation_type == MutationType::UpdateByPk {
4658                Some(pk_where_from_args(
4659                    ctx,
4660                    schema_name,
4661                    table_name,
4662                    pk_columns,
4663                    names.as_ref(),
4664                )?)
4665            } else {
4666                ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v))
4667            };
4668            // Which rows this role may change, beside which rows the request
4669            // asked to change. A by-key update is narrowed too: naming the key
4670            // of a row the permission withholds must not be a way to reach it.
4671            let where_clause = and_predicates(
4672                where_clause,
4673                permission_filter(
4674                    &gql_ctx.caller(),
4675                    names.as_ref(),
4676                    schema_name,
4677                    table_name,
4678                    crate::role::Verb::Update,
4679                )?,
4680            );
4681
4682            execute_update(
4683                pool,
4684                gql_ctx,
4685                schema_name,
4686                table_name,
4687                &type_name,
4688                operators,
4689                column_types_of(&gql_ctx.schema_cache, schema_name, table_name).await,
4690                where_clause,
4691                relationships.as_ref(),
4692                names.as_ref(),
4693            )
4694            .await
4695            .map(|rows| {
4696                let count = rows.len();
4697                (rows, count)
4698            })?
4699        }
4700        MutationType::Delete | MutationType::DeleteByPk => {
4701            let where_clause = if mutation_type == MutationType::DeleteByPk {
4702                Some(pk_where_from_args(
4703                    ctx,
4704                    schema_name,
4705                    table_name,
4706                    pk_columns,
4707                    names.as_ref(),
4708                )?)
4709            } else {
4710                ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v))
4711            };
4712            let where_clause = and_predicates(
4713                where_clause,
4714                permission_filter(
4715                    &gql_ctx.caller(),
4716                    names.as_ref(),
4717                    schema_name,
4718                    table_name,
4719                    crate::role::Verb::Delete,
4720                )?,
4721            );
4722
4723            execute_delete(
4724                pool,
4725                gql_ctx,
4726                schema_name,
4727                table_name,
4728                &type_name,
4729                where_clause,
4730                returning,
4731                relationships.as_ref(),
4732                names.as_ref(),
4733                max_rows,
4734            )
4735            .await
4736            .map(|rows| {
4737                let count = rows.len();
4738                (rows, count)
4739            })?
4740        }
4741    };
4742
4743    let is_delete = matches!(
4744        mutation_type,
4745        MutationType::Delete | MutationType::DeleteByPk
4746    );
4747    let result = match returning {
4748        Some(returning) if !result.is_empty() && !is_delete => {
4749            reread_returning(
4750                pool,
4751                gql_ctx,
4752                schema_name,
4753                table_name,
4754                &type_name,
4755                result,
4756                returning,
4757                relationships.as_ref(),
4758                names.as_ref(),
4759                max_rows,
4760            )
4761            .await?
4762        }
4763        _ => result,
4764    };
4765
4766    Ok(mutation_result(result, affected, by_key))
4767}
4768
4769/// The transaction this operation's writes share, opening it if this is the
4770/// first one.
4771///
4772/// Held for the length of the write, and settled by whoever answers the
4773/// request -- see [`crate::context::SharedWrite`]. Mutation root fields are
4774/// resolved one after another, so the lock is never contended; it is what
4775/// makes the transaction reachable from a resolver that owns nothing.
4776async fn write_tx<'a>(
4777    gql_ctx: &'a GraphQLContext,
4778    pool: &PgPool,
4779) -> Result<
4780    tokio::sync::MutexGuard<'a, Option<sqlx::Transaction<'static, sqlx::Postgres>>>,
4781    async_graphql::Error,
4782> {
4783    let mut guard = gql_ctx.write.lock().await;
4784    if guard.is_none() {
4785        *guard = Some(begin_with_session(pool, gql_ctx).await?);
4786    }
4787    Ok(guard)
4788}
4789
4790/// Begin a transaction that runs as this request's caller.
4791///
4792/// Every transaction GraphQL opens starts here -- a query's, an aggregate's,
4793/// a federated entity lookup's, a subscription's re-read, and the one a
4794/// mutation's writes share -- and each is set up by the request's
4795/// [`postrust_core::Session`], the same statements REST's transactions start
4796/// with. See [`GraphQLContext::session`] for what goes in and why.
4797///
4798/// This used to be written out here: the settings in one `set_config`, then
4799/// `SET LOCAL ROLE`. It differed from REST in what it left out -- a role's own
4800/// `statement_timeout` and isolation level, `PGRST_DB_TX_ISOLATION`, the
4801/// `search_path`, `app.settings.*` -- and in the order, which put the role
4802/// last. The session sets the role inside the one statement, after the
4803/// settings PostgREST puts before it and before the claims and the `hasura.*`
4804/// variables; every one of those is a setting any role may set on itself, so
4805/// they are set as the caller as readily as they were as the authenticator.
4806async fn begin_with_session(
4807    pool: &PgPool,
4808    gql_ctx: &GraphQLContext,
4809) -> Result<sqlx::Transaction<'static, sqlx::Postgres>, async_graphql::Error> {
4810    let mut tx = pool.begin().await?;
4811    gql_ctx.session().apply_sqlx(&mut tx).await?;
4812    Ok(tx)
4813}
4814
4815/// Render a row as JSON, with any shape column rendered as GeoJSON.
4816///
4817/// PostgreSQL's text form for a geometry is WKB hex --
4818/// `0103000020E6100000…` -- which is what `row_to_json` puts in the response
4819/// and is not what any client can read. Hasura answers GeoJSON, and a client
4820/// migrating from it parses GeoJSON.
4821///
4822/// The shape columns are merged over the row rather than replacing the
4823/// projection, so a table with no shape column produces exactly the SQL it did
4824/// before and one with three needs no list of the others.
4825fn row_json(expr: &str, column_types: &HashMap<String, String>) -> String {
4826    let mut shapes: Vec<(&String, &String)> = column_types
4827        .iter()
4828        .filter(|(_, pg_type)| matches!(pg_type.as_str(), "geometry" | "geography"))
4829        .collect();
4830    if shapes.is_empty() {
4831        return format!("row_to_json({})", expr);
4832    }
4833    shapes.sort();
4834
4835    let overrides: Vec<String> = shapes
4836        .iter()
4837        .map(|(name, _)| {
4838            format!(
4839                // Option 4 asks PostGIS for the long-form CRS member --
4840                // `urn:ogc:def:crs:EPSG::4326` -- which Hasura includes and
4841                // which a client round-tripping a shape needs in order to
4842                // write it back where it came from. PostGIS emits it only
4843                // where the geometry has an SRID to report.
4844                "{}, ST_AsGeoJSON({}.{}, 9, 4)::jsonb",
4845                postrust_sql::quote_literal(name),
4846                expr,
4847                postrust_sql::escape_ident(name)
4848            )
4849        })
4850        .collect();
4851    format!(
4852        "(to_jsonb({}) || jsonb_build_object({}))",
4853        expr,
4854        overrides.join(", ")
4855    )
4856}
4857
4858/// Execute a SQL query and return results as serde_json::Value.
4859/// We keep data as serde_json::Value so field resolvers can use try_downcast_ref.
4860async fn execute_query_on(
4861    conn: &mut sqlx::PgConnection,
4862    sql: &str,
4863    params: &[serde_json::Value],
4864) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
4865    use sqlx::Row;
4866
4867    trace!("Executing SQL: {}", sql);
4868
4869    // Execute query
4870    let mut query = sqlx::query(AssertSqlSafe(sql));
4871    for param in params {
4872        query = bind_json_value(query, param);
4873    }
4874    let rows = query.fetch_all(&mut *conn).await.map_err(database_error)?;
4875
4876    // Return raw JSON values - don't convert to async_graphql::Value
4877    // This allows field resolvers to use try_downcast_ref::<serde_json::Value>()
4878    let results: Vec<serde_json::Value> = rows
4879        .into_iter()
4880        .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
4881        .collect();
4882
4883    Ok(results)
4884}
4885
4886/// Refuse a GeoJSON document PostGIS would accept and should not.
4887///
4888/// `ST_GeomFromGeoJSON` will build a "Polygon" from three points that do not
4889/// meet, and a "LineString" from one point -- neither of which is a shape, and
4890/// both of which are then stored and read back as though they were. Hasura
4891/// checks the document before it reaches the database, refuses with
4892/// `parse-failed`, and says which rule was broken; the messages here are its
4893/// messages, because a client that reports them to a user is reporting text it
4894/// already ships.
4895///
4896/// A value that is not an object is left alone: a string in a geometry column
4897/// is WKT or WKB hex, which is a different thing entirely.
4898fn check_geojson(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4899    fn refuse<T>(message: &str) -> Result<T, async_graphql::Error> {
4900        Err(coded_error("parse-failed", message))
4901    }
4902
4903    fn position(
4904        value: &serde_json::Value,
4905    ) -> Result<&Vec<serde_json::Value>, async_graphql::Error> {
4906        match value.as_array() {
4907            Some(items) if items.len() >= 2 && items.iter().all(|i| i.is_number()) => Ok(items),
4908            _ => refuse("A Position needs at least 2 elements"),
4909        }
4910    }
4911
4912    fn positions(
4913        value: Option<&serde_json::Value>,
4914        least: usize,
4915        what: &str,
4916    ) -> Result<Vec<Vec<serde_json::Value>>, async_graphql::Error> {
4917        let items = match value.and_then(|v| v.as_array()) {
4918            Some(items) => items,
4919            None => return refuse(&format!("A {} needs at least {} Positions", what, least)),
4920        };
4921        if items.len() < least {
4922            return refuse(&format!("A {} needs at least {} Positions", what, least));
4923        }
4924        items.iter().map(|item| position(item).cloned()).collect()
4925    }
4926
4927    fn ring(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4928        let points = positions(Some(value), 4, "LinearRing")?;
4929        match (points.first(), points.last()) {
4930            (Some(first), Some(last)) if first == last => Ok(()),
4931            _ => refuse("the first and last locations have to be equal for a LinearRing"),
4932        }
4933    }
4934
4935    fn polygon(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4936        let Some(rings) = value.as_array() else {
4937            return refuse("A LinearRing needs at least 4 Positions");
4938        };
4939        rings.iter().try_for_each(ring)
4940    }
4941
4942    let serde_json::Value::Object(map) = value else {
4943        return Ok(());
4944    };
4945    let Some(kind) = map.get("type").and_then(|v| v.as_str()) else {
4946        return Ok(());
4947    };
4948    let coordinates = map.get("coordinates");
4949    match kind {
4950        "Point" => {
4951            position(coordinates.unwrap_or(&serde_json::Value::Null))?;
4952        }
4953        "MultiPoint" => {
4954            positions(coordinates, 0, "MultiPoint")?;
4955        }
4956        "LineString" => {
4957            positions(coordinates, 2, "LineString")?;
4958        }
4959        "MultiLineString" => {
4960            for line in coordinates.and_then(|v| v.as_array()).into_iter().flatten() {
4961                positions(Some(line), 2, "LineString")?;
4962            }
4963        }
4964        "Polygon" => polygon(coordinates.unwrap_or(&serde_json::Value::Null))?,
4965        "MultiPolygon" => {
4966            for one in coordinates.and_then(|v| v.as_array()).into_iter().flatten() {
4967                polygon(one)?;
4968            }
4969        }
4970        "GeometryCollection" => {
4971            for geometry in map
4972                .get("geometries")
4973                .and_then(|v| v.as_array())
4974                .into_iter()
4975                .flatten()
4976            {
4977                check_geojson(geometry)?;
4978            }
4979        }
4980        other => return refuse(&format!("unexpected geometry type: {}", other)),
4981    }
4982    Ok(())
4983}
4984
4985/// The call that produces a computed field's value.
4986///
4987/// Two spellings of the same row, because the two calls need different ones.
4988/// A positional call takes `alias.*`, which is what a qualified table can be
4989/// written as; a named call takes the row as one value, which only a bare
4990/// alias is. Named notation is needed exactly where a session argument is,
4991/// since the row is then not the only parameter and may not be the first.
4992fn computed_call(
4993    definition: &postrust_core::schema_cache::ComputedColumn,
4994    row: &str,
4995    row_by_name: &str,
4996) -> String {
4997    let function = format!(
4998        "{}.{}",
4999        postrust_sql::escape_ident(&definition.function.schema),
5000        postrust_sql::escape_ident(&definition.function.name)
5001    );
5002    match (&definition.session_argument, &definition.row_argument) {
5003        (Some(session), Some(row_argument)) => format!(
5004            "{}({} => {}, {} => {})",
5005            function,
5006            postrust_sql::escape_ident(row_argument),
5007            row_by_name,
5008            postrust_sql::escape_ident(session),
5009            SESSION_ARGUMENT
5010        ),
5011        _ => format!("{}({})", function, row),
5012    }
5013}
5014
5015/// What a `hasura_session` argument is given.
5016///
5017/// The session document, read from the setting [`GraphQLContext::session`]
5018/// writes.
5019/// `current_setting`'s second argument makes a missing setting null rather than
5020/// an error, which is the case of a request with no session at all.
5021const SESSION_ARGUMENT: &str = "coalesce(current_setting('hasura.session', true), '{}')::json";
5022
5023/// Everything an update may be told to do, in the order the schema declares
5024/// them. Read by both spellings: one update, and one of many.
5025const UPDATE_OPERATORS: [&str; 7] = [
5026    "_set",
5027    "_inc",
5028    "_append",
5029    "_prepend",
5030    "_delete_key",
5031    "_delete_elem",
5032    "_delete_at_path",
5033];
5034
5035/// What a read table is called inside its own query.
5036///
5037/// See [`WRITTEN_ROW`]: the row a query passes to a computed field has to be
5038/// named, and a table's qualified name is not a name a row can be written
5039/// under.
5040const READ_ROW: &str = "pgrst_src";
5041
5042/// What a written table is called inside its own statement.
5043///
5044/// See [`WhereScope::under_alias`]: the row a statement returns has to be
5045/// named, and a table's own name is read as a column first.
5046const WRITTEN_ROW: &str = "pgrst_row";
5047
5048/// The cast a written value needs to reach a column of this type.
5049///
5050/// A bound parameter arrives as text. PostgreSQL will coerce it to a numeric
5051/// or a date on assignment, but not to `jsonb`, an array, or a user-defined
5052/// type -- `column "details" is of type jsonb but expression is of type text`
5053/// is what an uncast insert answers. Naming the column's own type covers all
5054/// of them and changes nothing where the coercion would have worked anyway.
5055fn write_cast(column_types: &HashMap<String, String>, column: &str) -> String {
5056    match column_types.get(column) {
5057        Some(pg_type) => format!("::{}", pg_type),
5058        None => String::new(),
5059    }
5060}
5061
5062/// The value one column is written with, as it goes over the wire.
5063///
5064/// A `json` column holds a JSON value, and `"[]"` is one -- a string whose
5065/// characters happen to be brackets. Binding the bare text and casting stored
5066/// an empty array instead, so a client that wrote a string read back a list.
5067/// The document a column is given is the document it keeps.
5068fn write_operand(
5069    column_types: &HashMap<String, String>,
5070    column: &str,
5071    value: &serde_json::Value,
5072) -> serde_json::Value {
5073    match column_types.get(column).map(String::as_str) {
5074        Some("json") | Some("jsonb") => match value {
5075            serde_json::Value::String(_)
5076            | serde_json::Value::Number(_)
5077            | serde_json::Value::Bool(_) => serde_json::Value::String(value.to_string()),
5078            other => other.clone(),
5079        },
5080        // An array column takes an array literal. `["a","b"]` is JSON, and
5081        // PostgreSQL reads a text parameter destined for a `text[]` as
5082        // `{a,b}` -- `malformed array literal` is what it says about the
5083        // other spelling.
5084        Some(pg_type) if is_array_type(pg_type) => match value {
5085            serde_json::Value::Array(_) => serde_json::Value::String(array_literal(value)),
5086            other => other.clone(),
5087        },
5088        _ => value.clone(),
5089    }
5090}
5091
5092/// Whether a PostgreSQL type name is an array.
5093///
5094/// Both spellings appear in the catalogue depending on how it was asked:
5095/// `text[]` from `format_type`, `_text` from `typname`.
5096fn is_array_type(pg_type: &str) -> bool {
5097    pg_type.ends_with("[]") || pg_type.starts_with('_')
5098}
5099
5100/// A JSON array as PostgreSQL writes one.
5101///
5102/// `["a","b"]` becomes `{"a","b"}`. Every element is quoted, so a value
5103/// containing a comma, a brace or a backslash survives; a null is the unquoted
5104/// `NULL`, which is the only way to write one.
5105fn array_literal(value: &serde_json::Value) -> String {
5106    fn element(value: &serde_json::Value) -> String {
5107        match value {
5108            serde_json::Value::Null => "NULL".to_string(),
5109            serde_json::Value::Array(_) => array_literal(value),
5110            serde_json::Value::String(text) => {
5111                format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
5112            }
5113            other => format!("\"{}\"", other.to_string().replace('"', "\\\"")),
5114        }
5115    }
5116    let items = match value {
5117        serde_json::Value::Array(items) => items,
5118        other => return element(other),
5119    };
5120    format!(
5121        "{{{}}}",
5122        items.iter().map(element).collect::<Vec<_>>().join(",")
5123    )
5124}
5125
5126/// The expression that writes one bound value into one column.
5127///
5128/// A cast is enough for almost everything. A shape is the exception: a client
5129/// sends GeoJSON, which is what Hasura accepts, and `'{"type":"Point",…}'` is
5130/// not something PostgreSQL will cast to a geometry -- it has a function for
5131/// reading that, and the function is the only way in.
5132///
5133/// Only when the value actually is an object. A string in a geometry column is
5134/// WKT or WKB hex, which the cast does read, and passing that to
5135/// `ST_GeomFromGeoJSON` would refuse a perfectly good value.
5136fn write_expression(
5137    column_types: &HashMap<String, String>,
5138    column: &str,
5139    value: &serde_json::Value,
5140    placeholder: &str,
5141) -> String {
5142    let pg_type = column_types.get(column).map(String::as_str);
5143    if value.is_object() && matches!(pg_type, Some("geometry") | Some("geography")) {
5144        return match pg_type {
5145            Some("geography") => format!("ST_GeomFromGeoJSON({})::geography", placeholder),
5146            _ => format!("ST_GeomFromGeoJSON({})", placeholder),
5147        };
5148    }
5149    // An amount written as a number is reached through one: PostgreSQL has no
5150    // cast from `double precision` to `money`, which is what a bound JSON
5151    // number arrives as, and `numeric` is the type it does take one from. One
5152    // written as text -- `"$12,344.57"` -- is read by `money` directly, and
5153    // going through `numeric` would refuse the currency symbol.
5154    if pg_type == Some("money") && value.is_number() {
5155        return format!("{}::numeric::money", placeholder);
5156    }
5157    format!("{}{}", placeholder, write_cast(column_types, column))
5158}
5159
5160/// Every column of a table with the type it is declared as.
5161async fn column_types_of(
5162    schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
5163    schema_name: &str,
5164    table_name: &str,
5165) -> HashMap<String, String> {
5166    let Ok(guard) = schema_cache.get().await else {
5167        return HashMap::new();
5168    };
5169    let Some(cache) = guard.as_ref() else {
5170        return HashMap::new();
5171    };
5172    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5173    match cache.get_table(&qi) {
5174        Some(table) => table
5175            .columns
5176            .values()
5177            .map(|c| (c.name.clone(), c.nominal_type.clone()))
5178            .collect(),
5179        None => HashMap::new(),
5180    }
5181}
5182
5183/// Insert one row, and any rows nested inside it.
5184///
5185/// Hasura writes a parent and its children in one mutation:
5186///
5187/// ```graphql
5188/// insert_article(objects: [{title: "x", author: {data: {name: "y"}}}])
5189/// ```
5190///
5191/// Which row goes first follows from which side holds the key. A relationship
5192/// to one row is reached through a column of *this* table, so the related row
5193/// is inserted first and its key is what this row's column is set to. A
5194/// relationship to many rows is reached through a column of *theirs*, so this
5195/// row goes first and each child's column is set from it.
5196///
5197/// Everything runs in the transaction the caller opened, so a child that
5198/// cannot be written takes the parent with it -- which is what writing them in
5199/// one mutation means.
5200fn insert_row<'life>(
5201    conn: &'life mut sqlx::PgConnection,
5202    schema_name: &'life str,
5203    table_name: &'life str,
5204    object: serde_json::Map<String, serde_json::Value>,
5205    context: &'life InsertContext<'life>,
5206    written_count: &'life mut usize,
5207) -> std::pin::Pin<
5208    Box<
5209        dyn std::future::Future<Output = Result<serde_json::Value, async_graphql::Error>>
5210            + Send
5211            + 'life,
5212    >,
5213> {
5214    Box::pin(async move {
5215        use sqlx::Row;
5216
5217        let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5218        let table = context.cache.get_table(&qi).ok_or_else(|| {
5219            async_graphql::Error::new(format!("unknown table \"{}\"", table_name))
5220        })?;
5221        let column_types: HashMap<String, String> = table
5222            .columns
5223            .values()
5224            .map(|c| (c.name.clone(), c.nominal_type.clone()))
5225            .collect();
5226
5227        // A key that is a relationship rather than a column is a nested write.
5228        let type_name = context
5229            .type_names
5230            .get(&(schema_name.to_string(), table_name.to_string()));
5231        let relationships: &[RelationshipField] = type_name
5232            .and_then(|name| context.relationships.get(name))
5233            .map(|r| r.as_slice())
5234            .unwrap_or(&[]);
5235
5236        let mut columns = serde_json::Map::new();
5237        type Nested<'r> = (
5238            &'r RelationshipField,
5239            serde_json::Value,
5240            Option<serde_json::Value>,
5241        );
5242        let mut to_one: Vec<Nested> = Vec::new();
5243        let mut to_many: Vec<Nested> = Vec::new();
5244
5245        for (key, value) in object {
5246            match relationships.iter().find(|r| r.name == key) {
5247                None => {
5248                    // A written value is keyed by the field it was sent under;
5249                    // the statement is written in the table's own columns.
5250                    columns.insert(
5251                        table_column_for(context.names, table, &key).to_string(),
5252                        value,
5253                    );
5254                }
5255                Some(_) if value.is_null() => {
5256                    // `author: null` is a row with no author, not a row whose
5257                    // author is a null object. A client writing one insert for
5258                    // both cases sends the relationship either way.
5259                    continue;
5260                }
5261                Some(relationship) => {
5262                    // `{data: {...}}` for one row, `{data: [{...}]}` for many,
5263                    // and an `on_conflict` beside either -- a nested row is
5264                    // upserted the same way a top-level one is.
5265                    let (data, conflict) = match &value {
5266                        serde_json::Value::Object(map) => (
5267                            map.get("data").cloned().unwrap_or(value.clone()),
5268                            map.get("on_conflict").cloned().filter(|v| !v.is_null()),
5269                        ),
5270                        other => (other.clone(), None),
5271                    };
5272                    // Which row goes first follows from which side holds the
5273                    // key, not from how many rows there are. A one-to-one
5274                    // whose child key *is* the parent's -- `author_detail.id`
5275                    // referencing `author.id` -- is one row either way, and
5276                    // the parent still has to be written before there is a key
5277                    // to give it.
5278                    if child_holds_the_key(&relationship.relationship) {
5279                        to_many.push((relationship, data, conflict));
5280                    } else {
5281                        to_one.push((relationship, data, conflict));
5282                    }
5283                }
5284            }
5285        }
5286
5287        // A shape is checked before it is written, since PostGIS would build
5288        // one from a document that is not a shape.
5289        for (column, value) in &columns {
5290            if matches!(
5291                column_types.get(column).map(String::as_str),
5292                Some("geometry") | Some("geography")
5293            ) {
5294                // Under the name the client wrote it under, which is the
5295                // exposed one rather than the column's where they differ.
5296                check_geojson(value).map_err(|error| {
5297                    let field = context
5298                        .names
5299                        .column(schema_name, table_name, column)
5300                        .unwrap_or(column);
5301                    at_path(error, &format!("{}.{}", context.row, field))
5302                })?;
5303            }
5304        }
5305
5306        // The rows this one points at, first: this row's own column carries
5307        // their key.
5308        for (relationship, data, conflict) in to_one {
5309            let plan =
5310                postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, context.cache)
5311                    .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5312            let serde_json::Value::Object(child) = data else {
5313                return Err(async_graphql::Error::new(format!(
5314                    "\"{}\" takes an object to insert",
5315                    relationship.name
5316                )));
5317            };
5318            // Writing the related row is what fills this row's key column in,
5319            // so a value already written there is a second answer to the same
5320            // question and one of them would be silently discarded.
5321            for (local, _) in &plan.columns {
5322                if columns.get(local).is_some_and(|v| !v.is_null()) {
5323                    return Err(at_path(
5324                        validation_error(format!(
5325                            "cannot insert object relationship \"{}\" as \"{}\" column \
5326                             values are already determined",
5327                            relationship.name, local
5328                        )),
5329                        &format!("{}.{}", context.row, relationship.name),
5330                    ));
5331                }
5332            }
5333            // A to-one row is written under the relationship's own name:
5334            // `...objects[0].author.data`, and its `on_conflict` beside it.
5335            let under = format!("{}.{}", context.row, relationship.name);
5336            let nested = InsertContext {
5337                on_conflict: conflict,
5338                cache: context.cache,
5339                relationships: context.relationships,
5340                type_names: context.type_names,
5341                names: context.names,
5342                caller: context.caller,
5343                row: format!("{}.data", under),
5344                objects: format!("{}.data", under),
5345                conflict: format!("{}.on_conflict", under),
5346            };
5347            let written = insert_row(
5348                conn,
5349                &plan.foreign_schema,
5350                &plan.foreign_table,
5351                child,
5352                &nested,
5353                written_count,
5354            )
5355            .await?;
5356            for (local, foreign) in &plan.columns {
5357                if let Some(value) = written.get(foreign) {
5358                    columns.insert(local.clone(), value.clone());
5359                }
5360            }
5361        }
5362
5363        // What the server fills in regardless of what was sent. Applied after
5364        // the nested rows have contributed their keys and before the columns
5365        // are counted, because a preset is a column this statement writes --
5366        // and applied *over* the request, since a preset the client could
5367        // override is not a preset.
5368        for (column, value) in crate::role::presets(
5369            &context.caller,
5370            context.names,
5371            schema_name,
5372            table_name,
5373            crate::role::Verb::Insert,
5374        )
5375        .map_err(|fault| coded_error(fault.code(), fault.to_string()))?
5376        {
5377            columns.insert(column, value);
5378        }
5379
5380        // `ON CONFLICT` says which uniqueness is being resolved against and
5381        // what to do about it. An empty `update_columns` is `DO NOTHING`,
5382        // which is how a client says "leave the row that is already there".
5383        // The columns this statement writes, settled before the conflict
5384        // clause so a predicate on it can number its parameters after theirs.
5385        let column_names: Vec<&str> = columns.keys().map(|k| k.as_str()).collect();
5386        let mut conflict_values: Vec<serde_json::Value> = Vec::new();
5387        let conflict_sql = match &context.on_conflict {
5388            Some(serde_json::Value::Object(spec)) => {
5389                let constraint = spec.get("constraint").and_then(|v| v.as_str());
5390                let Some(constraint) = constraint else {
5391                    return Err(async_graphql::Error::new(
5392                        "on_conflict needs a constraint to resolve against",
5393                    ));
5394                };
5395                if !table
5396                    .unique_constraints
5397                    .iter()
5398                    .any(|(name, _)| name == constraint)
5399                {
5400                    return Err(async_graphql::Error::new(format!(
5401                        "\"{}\" is not a unique constraint of \"{}\"",
5402                        constraint, table_name
5403                    )));
5404                }
5405                let updates: Vec<&str> = spec
5406                    .get("update_columns")
5407                    .and_then(|v| v.as_array())
5408                    .map(|items| items.iter().filter_map(|i| i.as_str()).collect())
5409                    .unwrap_or_default();
5410                // The member that stands for the columns this role has none
5411                // of. It is in the enum so that `on_conflict` exists at all;
5412                // naming it is the one thing it cannot be used for.
5413                if updates.contains(&PLACEHOLDER_COLUMN) {
5414                    return Err(at_path(
5415                        coded_error("validation-failed", "erroneous column name"),
5416                        &context.conflict,
5417                    ));
5418                }
5419
5420                if updates.is_empty() {
5421                    format!(
5422                        " ON CONFLICT ON CONSTRAINT {} DO NOTHING",
5423                        postrust_sql::escape_ident(constraint)
5424                    )
5425                } else {
5426                    // An `ON CONFLICT DO UPDATE` is an update, so the update
5427                    // permission's presets are written here too -- and a
5428                    // column a preset writes does not also take its value from
5429                    // `EXCLUDED`, which is what "a preset overrides the
5430                    // request" means on this side.
5431                    let preset = crate::role::presets(
5432                        &context.caller,
5433                        context.names,
5434                        schema_name,
5435                        table_name,
5436                        crate::role::Verb::Update,
5437                    )
5438                    .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
5439
5440                    // Numbered after the row's own values and before the
5441                    // predicate below, because `SET` is written before `WHERE`
5442                    // and the parameters are bound in the order they appear.
5443                    let mut param_idx = column_names.len() + 1;
5444                    let mut assignments: Vec<String> =
5445                        Vec::with_capacity(preset.len() + updates.len());
5446                    for (column, value) in &preset {
5447                        assignments.push(format!(
5448                            "{} = {}",
5449                            postrust_sql::escape_ident(column),
5450                            write_expression(
5451                                &column_types,
5452                                column,
5453                                value,
5454                                &format!("${}", param_idx)
5455                            )
5456                        ));
5457                        conflict_values.push(write_operand(&column_types, column, value));
5458                        param_idx += 1;
5459                    }
5460                    for field in &updates {
5461                        let column = table_column_for(context.names, table, field);
5462                        if preset.iter().any(|(written, _)| written == column) {
5463                            continue;
5464                        }
5465                        assignments.push(format!(
5466                            "{} = EXCLUDED.{}",
5467                            postrust_sql::escape_ident(column),
5468                            postrust_sql::escape_ident(column)
5469                        ));
5470                    }
5471                    // `where` on an upsert decides whether the row that is
5472                    // already there is overwritten -- "only if what I am
5473                    // writing is newer". It reads the existing row, which is
5474                    // what the statement's alias names.
5475                    //
5476                    // The update permission's own filter is ANDed into it: an
5477                    // upsert that overwrites a row is an update, and a role
5478                    // that may not update a row may not reach it by inserting
5479                    // over it. Compiling that filter is also where a session
5480                    // variable it names and the caller does not carry is
5481                    // noticed -- which is the answer Hasura gives before it
5482                    // writes anything.
5483                    let granted = permission_filter(
5484                        &context.caller,
5485                        context.names,
5486                        schema_name,
5487                        table_name,
5488                        crate::role::Verb::Update,
5489                    )?;
5490                    let requested = spec.get("where").filter(|f| !f.is_null()).cloned();
5491                    let condition = match and_predicates(requested, granted) {
5492                        Some(filter) => {
5493                            let filter = &filter;
5494                            let type_name = context
5495                                .type_names
5496                                .get(&(schema_name.to_string(), table_name.to_string()))
5497                                .map(String::as_str)
5498                                .unwrap_or(table_name);
5499                            let scope = WhereScope::table(
5500                                schema_name,
5501                                table_name,
5502                                type_name,
5503                                context.names,
5504                            )
5505                            .under_alias(WRITTEN_ROW)
5506                            .with_resolution(context.cache, context.relationships);
5507                            let mut alias_counter = 0usize;
5508                            build_condition(
5509                                filter,
5510                                &scope,
5511                                &mut param_idx,
5512                                &mut conflict_values,
5513                                &mut alias_counter,
5514                            )?
5515                            .map(|sql| format!(" WHERE {}", sql))
5516                            .unwrap_or_default()
5517                        }
5518                        None => String::new(),
5519                    };
5520                    format!(
5521                        " ON CONFLICT ON CONSTRAINT {} DO UPDATE SET {}{}",
5522                        postrust_sql::escape_ident(constraint),
5523                        assignments.join(", "),
5524                        condition
5525                    )
5526                }
5527            }
5528            _ => String::new(),
5529        };
5530
5531        // The row this statement writes, as `RETURNING` names it. Not the
5532        // table's own name: qualifying it reads as a column of a table called
5533        // `public`, which is what `missing FROM-clause entry for table
5534        // "public"` means, and leaving it bare reads as a column of the table
5535        // where one shares the name.
5536        let qualified_table = postrust_sql::escape_ident(WRITTEN_ROW);
5537
5538        // What the written row has to satisfy for the write to stand,
5539        // evaluated in `RETURNING` against the row as written. Its parameters
5540        // are numbered after the values and the conflict clause, since
5541        // `RETURNING` is last.
5542        let check_scope = WhereScope::for_alias(
5543            schema_name,
5544            table_name,
5545            WRITTEN_ROW,
5546            context
5547                .type_names
5548                .get(&(schema_name.to_string(), table_name.to_string()))
5549                .map(String::as_str)
5550                .unwrap_or(table_name),
5551            context.cache,
5552            context.relationships,
5553            context.names,
5554        );
5555        let (check_sql, check_values) = {
5556            let check = crate::role::write_check(
5557                &context.caller,
5558                context.names,
5559                schema_name,
5560                table_name,
5561                crate::role::Verb::Insert,
5562            )
5563            .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
5564            match check {
5565                None => (String::new(), Vec::new()),
5566                Some(check) => {
5567                    let mut values = Vec::new();
5568                    let mut param_idx = column_names.len() + conflict_values.len() + 1;
5569                    let mut alias_counter = 0usize;
5570                    match build_condition(
5571                        &check,
5572                        &check_scope,
5573                        &mut param_idx,
5574                        &mut values,
5575                        &mut alias_counter,
5576                    )? {
5577                        None => (String::new(), Vec::new()),
5578                        Some(sql) => (
5579                            format!(
5580                                ", ({}) AS {}",
5581                                sql,
5582                                postrust_sql::escape_ident(CHECK_COLUMN)
5583                            ),
5584                            values,
5585                        ),
5586                    }
5587                }
5588            }
5589        };
5590
5591        let names = column_names;
5592        let written = if names.is_empty() {
5593            // Every column defaulted. `DEFAULT VALUES` is how SQL says that;
5594            // an empty column list is a syntax error.
5595            let sql = format!(
5596                "INSERT INTO {}.{} AS {} DEFAULT VALUES{} RETURNING {}{}",
5597                postrust_sql::escape_ident(schema_name),
5598                postrust_sql::escape_ident(table_name),
5599                qualified_table,
5600                conflict_sql,
5601                row_json(&qualified_table, &column_types),
5602                check_sql
5603            );
5604            let mut query = sqlx::query(AssertSqlSafe(sql));
5605            for value in &conflict_values {
5606                query = bind_json_value(query, value);
5607            }
5608            for value in &check_values {
5609                query = bind_json_value(query, value);
5610            }
5611            query
5612                .fetch_optional(&mut *conn)
5613                .await
5614                // A constraint the write violated is reported against the rows
5615                // the statement was given, which is where Hasura reports it.
5616                .map_err(|error| at_path(database_error(error), &context.objects))?
5617        } else {
5618            let placeholders: Vec<String> = names
5619                .iter()
5620                .enumerate()
5621                .map(|(i, column)| {
5622                    let placeholder = format!("${}", i + 1);
5623                    match columns.get(*column) {
5624                        Some(value) => write_expression(&column_types, column, value, &placeholder),
5625                        None => placeholder,
5626                    }
5627                })
5628                .collect();
5629            let sql = format!(
5630                "INSERT INTO {}.{} AS {} ({}) VALUES ({}){} RETURNING {}{}",
5631                postrust_sql::escape_ident(schema_name),
5632                postrust_sql::escape_ident(table_name),
5633                qualified_table,
5634                names
5635                    .iter()
5636                    .map(|c| postrust_sql::escape_ident(c))
5637                    .collect::<Vec<_>>()
5638                    .join(", "),
5639                placeholders.join(", "),
5640                conflict_sql,
5641                row_json(&qualified_table, &column_types),
5642                check_sql
5643            );
5644            trace!("Executing INSERT SQL: {}", sql);
5645            let mut query = sqlx::query(AssertSqlSafe(sql));
5646            for column in &names {
5647                if let Some(value) = columns.get(*column) {
5648                    query = bind_json_value(query, &write_operand(&column_types, column, value));
5649                }
5650            }
5651            for value in &conflict_values {
5652                query = bind_json_value(query, value);
5653            }
5654            for value in &check_values {
5655                query = bind_json_value(query, value);
5656            }
5657            query
5658                .fetch_optional(&mut *conn)
5659                .await
5660                // A constraint the write violated is reported against the rows
5661                // the statement was given, which is where Hasura reports it.
5662                .map_err(|error| at_path(database_error(error), &context.objects))?
5663        };
5664
5665        // `DO NOTHING` writes nothing and returns nothing, which is the answer
5666        // rather than an error: the row that was already there stays.
5667        let Some(written) = written else {
5668            return Ok(serde_json::Value::Null);
5669        };
5670        refuse_unchecked_rows(std::slice::from_ref(&written), !check_sql.is_empty())
5671            .map_err(|error| at_path(error, &context.objects))?;
5672        let row: serde_json::Value = written.try_get(0).unwrap_or(serde_json::Value::Null);
5673        *written_count += 1;
5674
5675        // Then the rows that point at this one, which need its key.
5676        for (relationship, data, conflict) in to_many {
5677            let plan =
5678                postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, context.cache)
5679                    .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5680            let children = match data {
5681                serde_json::Value::Array(items) => items,
5682                serde_json::Value::Object(map) => vec![serde_json::Value::Object(map)],
5683                serde_json::Value::Null => Vec::new(),
5684                _ => {
5685                    return Err(async_graphql::Error::new(format!(
5686                        "\"{}\" takes objects to insert",
5687                        relationship.name
5688                    )))
5689                }
5690            };
5691            for (child_index, child) in children.into_iter().enumerate() {
5692                let serde_json::Value::Object(mut child) = child else {
5693                    continue;
5694                };
5695                for (local, foreign) in &plan.columns {
5696                    // The parent's key is what makes the child a child, so a
5697                    // child that writes it too is asking for a different
5698                    // parent than the one it is nested inside.
5699                    if child.get(foreign).is_some_and(|v| !v.is_null()) {
5700                        return Err(at_path(
5701                            validation_error(format!(
5702                                "cannot insert \"{}\" columns as their values are already \
5703                                 being determined by parent insert",
5704                                foreign
5705                            )),
5706                            &format!(
5707                                "{}.{}{}",
5708                                context.row,
5709                                relationship.name,
5710                                match relationship.is_list {
5711                                    true => format!(".data[{}]", child_index),
5712                                    false => ".data".to_string(),
5713                                }
5714                            ),
5715                        ));
5716                    }
5717                    if let Some(value) = row.get(local) {
5718                        child.insert(foreign.clone(), value.clone());
5719                    }
5720                }
5721                // `...objects[0].articles.data[0]`, which is the path
5722                // Hasura answers for a child that writes its parent's key.
5723                // One row written after its parent -- a mapped object
5724                // relationship with `after_parent` -- has no index: there is
5725                // no list for it to be an item of.
5726                let at = match relationship.is_list {
5727                    true => format!(".data[{}]", child_index),
5728                    false => ".data".to_string(),
5729                };
5730                let under = format!("{}.{}", context.row, relationship.name);
5731                let nested = InsertContext {
5732                    on_conflict: conflict.clone(),
5733                    cache: context.cache,
5734                    relationships: context.relationships,
5735                    type_names: context.type_names,
5736                    names: context.names,
5737                    caller: context.caller,
5738                    row: format!("{}{}", under, at),
5739                    objects: format!("{}.data", under),
5740                    conflict: format!("{}.on_conflict", under),
5741                };
5742                insert_row(
5743                    conn,
5744                    &plan.foreign_schema,
5745                    &plan.foreign_table,
5746                    child,
5747                    &nested,
5748                    written_count,
5749                )
5750                .await?;
5751            }
5752        }
5753
5754        Ok(row)
5755    })
5756}
5757
5758/// What a nested insert needs to follow a relationship.
5759///
5760/// Cloned per row and per nested row, which costs three strings: the paths are
5761/// the only part that differs between them, and the rest is references and a
5762/// `Caller`.
5763#[derive(Clone)]
5764struct InsertContext<'a> {
5765    /// What to do when this row conflicts. A nested row carries its own, from
5766    /// the `on_conflict` beside its `data`.
5767    on_conflict: Option<serde_json::Value>,
5768    cache: &'a SchemaCache,
5769    relationships: &'a HashMap<String, Vec<RelationshipField>>,
5770    /// (schema, table) -> the GraphQL type name, which keys the relationship
5771    /// map. A table's type is not always its name: a second schema prefixes
5772    /// it, and a name may have been given.
5773    type_names: &'a HashMap<(String, String), String>,
5774    /// The names columns are exposed under, so a written value keyed by a
5775    /// field reaches the column it names.
5776    names: &'a crate::names::NameOverrides,
5777    /// Who is writing, so that a permission's presets and its check reach
5778    /// every row this insert writes -- including the nested ones, which are
5779    /// rows of other tables under other rules.
5780    caller: crate::role::Caller<'a>,
5781    /// Where this row is in the request, as Hasura writes such a place:
5782    /// `$.selectionSet.insert_author.args.objects[0]`, and one level down
5783    /// `$.selectionSet.insert_author.args.objects[0].articles.data[0]`. A
5784    /// column of it is that with the field's name appended.
5785    row: String,
5786    /// Where the rows this statement writes were named. What a refused `check`
5787    /// is reported against -- the argument, not the row inside it, which is
5788    /// what Hasura answers.
5789    objects: String,
5790    /// Where this statement's `on_conflict` was named.
5791    conflict: String,
5792}
5793
5794/// Re-read written rows so that a mutation's `returning` can carry
5795/// relationships and computed fields.
5796///
5797/// `RETURNING row_to_json(t.*)` gives the table's own columns and nothing
5798/// else, so a relationship asked for beside them had no value to resolve --
5799/// and a non-null list field with no value is an error, which meant a mutation
5800/// that had written its rows correctly answered as though it had failed. The
5801/// write is not in doubt; only the shape of the answer is.
5802///
5803/// So the rows are read again by their primary key, through the same
5804/// projection an ordinary query uses. One extra round trip, and only when the
5805/// selection actually asks for something `RETURNING` cannot give.
5806#[allow(clippy::too_many_arguments)]
5807async fn reread_returning(
5808    pool: &PgPool,
5809    gql_ctx: &GraphQLContext,
5810    schema_name: &str,
5811    table_name: &str,
5812    type_name: &str,
5813    rows: Vec<Value>,
5814    returning: async_graphql::SelectionField<'_>,
5815    relationships: &HashMap<String, Vec<RelationshipField>>,
5816    names: &crate::names::NameOverrides,
5817    max_rows: Option<i64>,
5818) -> Result<Vec<Value>, async_graphql::Error> {
5819    let guard = gql_ctx
5820        .schema_cache
5821        .get()
5822        .await
5823        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5824    let Some(cache) = guard.as_ref() else {
5825        return Ok(rows);
5826    };
5827    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5828    let Some(table) = cache.get_table(&qi) else {
5829        return Ok(rows);
5830    };
5831    if table.pk_cols.is_empty() {
5832        // Nothing to identify the rows by. The columns are still right.
5833        return Ok(rows);
5834    }
5835
5836    let mut param_idx = 1usize;
5837    let mut values: Vec<serde_json::Value> = Vec::new();
5838    let mut alias_counter = 0usize;
5839    let embeds = build_embed_expressions(
5840        &gql_ctx.caller(),
5841        cache,
5842        relationships,
5843        type_name,
5844        "src",
5845        returning.selection_set(),
5846        max_rows,
5847        &mut alias_counter,
5848        &mut param_idx,
5849        &mut values,
5850        names,
5851    )?;
5852    let computed = computed_projections(
5853        table,
5854        returning.selection_set(),
5855        "src",
5856        names,
5857        cache,
5858        &mut param_idx,
5859        &mut values,
5860    )?;
5861    // A rename is reason enough to read the rows again: `RETURNING` answers in
5862    // the table's own column names, which are not the names the client asked
5863    // under.
5864    let renames = names.renames_columns(&table.schema, &table.name);
5865    if embeds.is_empty() && computed.is_empty() && !renames {
5866        return Ok(rows);
5867    }
5868
5869    // One row per key written, in the order they were written.
5870    let mut conditions = Vec::with_capacity(rows.len());
5871    for row in &rows {
5872        let mut parts = Vec::with_capacity(table.pk_cols.len());
5873        for column in &table.pk_cols {
5874            let Value::Object(map) = row else {
5875                return Ok(rows);
5876            };
5877            let Some(value) = map.get(&async_graphql::Name::new(column)) else {
5878                return Ok(rows);
5879            };
5880            parts.push(format!(
5881                "{} = ${}",
5882                postrust_sql::escape_ident(column),
5883                param_idx
5884            ));
5885            values.push(value_to_json(value));
5886            param_idx += 1;
5887        }
5888        conditions.push(format!("({})", parts.join(" AND ")));
5889    }
5890    if conditions.is_empty() {
5891        return Ok(rows);
5892    }
5893
5894    let mut projection =
5895        rename_projection(table, "src", names).unwrap_or_else(|| "src.*".to_string());
5896    for expression in &computed {
5897        projection.push_str(", ");
5898        projection.push_str(expression);
5899    }
5900    for (name, expression) in &embeds {
5901        projection.push_str(", ");
5902        projection.push_str(expression);
5903        projection.push_str(" AS ");
5904        projection.push_str(&postrust_sql::escape_ident(name));
5905    }
5906
5907    let sql = format!(
5908        "SELECT {} FROM (SELECT {} FROM (SELECT * FROM {}.{} WHERE {}) AS src) AS pgrst_r",
5909        row_json("pgrst_r", &exposed_column_types(table, names)),
5910        projection,
5911        postrust_sql::escape_ident(schema_name),
5912        postrust_sql::escape_ident(table_name),
5913        conditions.join(" OR ")
5914    );
5915
5916    // The same transaction the write went into: the rows it is reading are the
5917    // rows that write produced, and nothing has committed yet.
5918    let mut guard = write_tx(gql_ctx, pool).await?;
5919    let conn = guard.as_mut().expect("write_tx opens one");
5920    let reread = execute_query_on(conn, &sql, &values).await?;
5921    drop(guard);
5922
5923    if reread.is_empty() {
5924        return Ok(rows);
5925    }
5926    Ok(reread.into_iter().map(json_to_value).collect())
5927}
5928
5929/// Execute an insert mutation.
5930async fn execute_insert(
5931    pool: &PgPool,
5932    gql_ctx: &GraphQLContext,
5933    schema_name: &str,
5934    table_name: &str,
5935    objects: serde_json::Value,
5936    context: &InsertContext<'_>,
5937    // Whether the client wrote one row rather than a list of them. Only the
5938    // error paths care: `insert_x_one(object: {...})` has no row to index, so
5939    // its rows are named `args.object` and not `args.object[0]`.
5940    single: bool,
5941) -> Result<(Vec<Value>, usize), async_graphql::Error> {
5942    trace!("Insert mutation for {}: {:?}", table_name, objects);
5943
5944    // Handle both array and single object
5945    let objects_array = match objects {
5946        serde_json::Value::Array(arr) => arr,
5947        serde_json::Value::Object(obj) => vec![serde_json::Value::Object(obj)],
5948        _ => {
5949            return Err(async_graphql::Error::new(
5950                "objects must be an array or object",
5951            ))
5952        }
5953    };
5954
5955    if objects_array.is_empty() {
5956        return Err(async_graphql::Error::new("objects cannot be empty"));
5957    }
5958
5959    let mut guard = write_tx(gql_ctx, pool).await?;
5960    let conn = guard.as_mut().expect("write_tx opens one");
5961
5962    let mut inserted: Vec<Value> = Vec::new();
5963    let mut written = 0usize;
5964
5965    for (index, object) in objects_array.into_iter().enumerate() {
5966        let serde_json::Value::Object(map) = object else {
5967            return Err(async_graphql::Error::new(
5968                "each object to insert is an object",
5969            ));
5970        };
5971        // This row's own place in the request, which is what an error inside
5972        // it is reported against.
5973        let context = InsertContext {
5974            row: match single {
5975                true => context.objects.clone(),
5976                false => format!("{}[{}]", context.objects, index),
5977            },
5978            ..context.clone()
5979        };
5980        let row = insert_row(conn, schema_name, table_name, map, &context, &mut written).await?;
5981        // A row `DO NOTHING` left alone is not in `returning` and is not in
5982        // `affected_rows` either: nothing was written, and the row that was
5983        // already there is not this mutation's to report.
5984        if !row.is_null() {
5985            inserted.push(json_to_value(row));
5986        }
5987    }
5988
5989    Ok((inserted, written))
5990}
5991
5992/// Shape a mutation's result for the field that asked for it.
5993///
5994/// A by-key mutation answers with the row, or with null where the key matched
5995/// nothing. Every other mutation answers with the table's mutation response,
5996/// which carries `affected_rows` alongside the rows themselves -- a client may
5997/// ask for no rows back and still need the count, which is the usual case for
5998/// a delete.
5999///
6000/// The count is passed in rather than taken from the rows, because a nested
6001/// insert writes more rows than it returns: two articles each carrying a new
6002/// author is four rows written and two returned, and four is the answer.
6003fn mutation_result<'a>(rows: Vec<Value>, affected: usize, by_key: bool) -> Option<FieldValue<'a>> {
6004    if by_key {
6005        return rows.into_iter().next().map(FieldValue::value);
6006    }
6007    let mut response = async_graphql::indexmap::IndexMap::new();
6008    response.insert(
6009        async_graphql::Name::new("affected_rows"),
6010        Value::from(affected),
6011    );
6012    response.insert(async_graphql::Name::new("returning"), Value::List(rows));
6013    Some(FieldValue::value(Value::Object(response)))
6014}
6015
6016/// Bind a JSON value to a sqlx query.
6017///
6018/// Every value a GraphQL request carries reaches the database through here, as
6019/// a bound parameter, and that is what makes the `AssertSqlSafe` around each
6020/// statement in this module true rather than hopeful. sqlx 0.9 takes only a
6021/// `&'static str` as SQL unless told otherwise, and the statements here are
6022/// built at runtime because their shape follows the request -- which columns,
6023/// which tables, how many rows. What is spliced in comes from the schema cache
6024/// or from this module, never from the request: identifiers, each quoted with
6025/// `postrust_sql::escape_ident` first, the catalog's type names, and SQL
6026/// written here.
6027fn bind_json_value<'q>(
6028    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
6029    value: &serde_json::Value,
6030) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
6031    match value {
6032        serde_json::Value::Null => query.bind(None::<String>),
6033        serde_json::Value::Bool(b) => query.bind(*b),
6034        serde_json::Value::Number(n) => {
6035            if let Some(i) = n.as_i64() {
6036                query.bind(i)
6037            } else if let Some(f) = n.as_f64() {
6038                query.bind(f)
6039            } else {
6040                query.bind(n.to_string())
6041            }
6042        }
6043        serde_json::Value::String(s) => query.bind(s.clone()),
6044        _ => query.bind(value.to_string()),
6045    }
6046}
6047
6048/// Execute an update mutation.
6049#[allow(clippy::too_many_arguments)] // the predicate needs the schema it reads
6050async fn execute_update(
6051    pool: &PgPool,
6052    gql_ctx: &GraphQLContext,
6053    schema_name: &str,
6054    table_name: &str,
6055    type_name: &str,
6056    operators: Vec<(&'static str, serde_json::Value)>,
6057    column_types: HashMap<String, String>,
6058    where_clause: Option<serde_json::Value>,
6059    relationships: &HashMap<String, Vec<RelationshipField>>,
6060    names: &crate::names::NameOverrides,
6061) -> Result<Vec<Value>, async_graphql::Error> {
6062    use sqlx::Row;
6063
6064    trace!("Update mutation for {}: {:?}", table_name, operators);
6065
6066    // Build the SET clause. Each operator writes a column in terms of itself
6067    // except `_set`, which replaces it -- `_inc` adds, the jsonb operators
6068    // concatenate or remove, and a client may send several in one mutation as
6069    // long as they name different columns.
6070    let mut set_parts: Vec<String> = Vec::new();
6071    let mut set_values: Vec<serde_json::Value> = Vec::new();
6072    let mut param_idx = 1;
6073    let mut written: HashSet<String> = HashSet::new();
6074
6075    // What the permission writes whatever the request said. A preset overrides
6076    // rather than collides -- one a client could override is not a preset --
6077    // so these go in first and the operators below step around the columns
6078    // they name.
6079    //
6080    // This is also what makes an update with no `_set` at all a real update:
6081    // `update_resident(where: {...})` under a permission whose `set` names
6082    // `city` changes `city`, and answers with the rows it changed rather than
6083    // with nothing.
6084    let preset = crate::role::presets(
6085        &gql_ctx.caller(),
6086        names,
6087        schema_name,
6088        table_name,
6089        crate::role::Verb::Update,
6090    )
6091    .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
6092    let preset_columns: HashSet<&str> = preset.iter().map(|(name, _)| name.as_str()).collect();
6093    for (column, value) in &preset {
6094        let placeholder =
6095            write_expression(&column_types, column, value, &format!("${}", param_idx));
6096        set_parts.push(format!(
6097            "{} = {}",
6098            postrust_sql::escape_ident(column),
6099            placeholder
6100        ));
6101        set_values.push(write_operand(&column_types, column, value));
6102        param_idx += 1;
6103    }
6104
6105    for (operator, payload) in &operators {
6106        let serde_json::Value::Object(map) = payload else {
6107            return Err(async_graphql::Error::new(format!(
6108                "\"{}\" takes an object mapping columns to values",
6109                operator
6110            )));
6111        };
6112        for (field, value) in map {
6113            let column = &names
6114                .column_source(schema_name, table_name, field)
6115                .unwrap_or(field)
6116                .to_string();
6117            // A preset has this column. Not the duplicate-write error below:
6118            // the request is allowed to name it, and the permission wins.
6119            if preset_columns.contains(column.as_str()) {
6120                continue;
6121            }
6122            if !written.insert(column.clone()) {
6123                return Err(async_graphql::Error::new(format!(
6124                    "\"{}\" is written twice in one update; a column may be \
6125                     changed by one operator at a time",
6126                    column
6127                )));
6128            }
6129            let quoted = postrust_sql::escape_ident(column);
6130            // `_set` writes the column and `_inc` adds to it, so both take a
6131            // value of the column's type and are cast to it -- `money + $1`
6132            // is not an operator PostgreSQL has, and neither is `money +
6133            // double precision`, which is what a bound number arrives as. The
6134            // others already say what they need -- `::jsonb` for a
6135            // concatenation, `::text[]` for a path -- and casting twice would
6136            // be wrong for `_delete_elem`, whose operand is an integer rather
6137            // than a value of the column.
6138            let placeholder = match *operator {
6139                "_set" | "_inc" => {
6140                    write_expression(&column_types, column, value, &format!("${}", param_idx))
6141                }
6142                _ => format!("${}", param_idx),
6143            };
6144            // The assignment PostgreSQL needs, which for everything but `_set`
6145            // reads the column's current value.
6146            let assignment = match *operator {
6147                "_set" => format!("{} = {}", quoted, placeholder),
6148                "_inc" => format!("{} = {} + {}", quoted, quoted, placeholder),
6149                "_append" => format!("{} = {} || {}::jsonb", quoted, quoted, placeholder),
6150                "_prepend" => format!("{} = {}::jsonb || {}", quoted, placeholder, quoted),
6151                "_delete_key" => format!("{} = {} - {}::text", quoted, quoted, placeholder),
6152                "_delete_elem" => format!("{} = {} - {}::int", quoted, quoted, placeholder),
6153                // A path is a list of keys, and one parameter carrying
6154                // `["name","last"]` is a JSON array -- which PostgreSQL reads
6155                // as an array literal and refuses, `malformed array literal`.
6156                // The elements are bound one at a time into an `ARRAY[...]`,
6157                // the same way the key-existence comparisons take theirs.
6158                "_delete_at_path" => {
6159                    let Some(steps) = value.as_array() else {
6160                        return Err(async_graphql::Error::new(format!(
6161                            "\"_delete_at_path\" on \"{}\" takes a list of keys",
6162                            column
6163                        )));
6164                    };
6165                    let path = sql_array(steps, "text[]", &mut param_idx, &mut set_values);
6166                    set_parts.push(format!("{} = {} #- {}", quoted, quoted, path));
6167                    continue;
6168                }
6169                other => {
6170                    return Err(async_graphql::Error::new(format!(
6171                        "unsupported update operator \"{}\"",
6172                        other
6173                    )))
6174                }
6175            };
6176            if *operator == "_set"
6177                && matches!(
6178                    column_types.get(column).map(String::as_str),
6179                    Some("geometry") | Some("geography")
6180                )
6181            {
6182                check_geojson(value)?;
6183            }
6184            set_parts.push(assignment);
6185            set_values.push(match *operator {
6186                "_set" => write_operand(&column_types, column, value),
6187                _ => value.clone(),
6188            });
6189            param_idx += 1;
6190        }
6191    }
6192
6193    // An update that changes nothing changes no rows. Refusing it looks like
6194    // the stricter answer and is the wrong one: a client building `_set` from
6195    // a form the user submitted unchanged sends an empty object, and the
6196    // honest report of what happened is that nothing did.
6197    if set_parts.is_empty() {
6198        return Ok(Vec::new());
6199    }
6200
6201    // Build WHERE clause. It can follow a relationship, the same way a query's
6202    // can: `update_article(where: {author: {name: {_eq: "x"}}})` names the
6203    // rows by something they point at rather than by a column of their own.
6204    let guard = gql_ctx
6205        .schema_cache
6206        .get()
6207        .await
6208        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
6209    let cache = guard
6210        .as_ref()
6211        .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
6212    let scope = WhereScope::table(schema_name, table_name, type_name, names)
6213        .under_alias(WRITTEN_ROW)
6214        .with_resolution(cache, relationships);
6215    let (where_sql, where_values) = build_where_clause(where_clause.as_ref(), param_idx, &scope)?;
6216
6217    // An absent or unrecognised `where` argument yields an empty clause, which
6218    // would update every row in the table. Refuse instead.
6219    if where_sql.is_empty() {
6220        return Err(async_graphql::Error::new(format!(
6221            "update on \"{}\" requires a `where` argument with at least one \
6222             recognised condition; refusing to update every row",
6223            table_name
6224        )));
6225    }
6226
6227    // What the changed row has to satisfy for the change to stand. Evaluated
6228    // in the `RETURNING` clause, against the row as written -- which is the
6229    // only place it can honestly be evaluated, and costs neither a re-read nor
6230    // a way to identify the rows afterwards.
6231    let (check_sql, check_values) = permission_check_sql(
6232        gql_ctx,
6233        names,
6234        schema_name,
6235        table_name,
6236        crate::role::Verb::Update,
6237        &scope,
6238        param_idx + where_values.len(),
6239    )?;
6240
6241    let sql = format!(
6242        "UPDATE {}.{} AS {} SET {} {} RETURNING {}{}",
6243        postrust_sql::escape_ident(schema_name),
6244        postrust_sql::escape_ident(table_name),
6245        postrust_sql::escape_ident(WRITTEN_ROW),
6246        set_parts.join(", "),
6247        where_sql,
6248        row_json(&postrust_sql::escape_ident(WRITTEN_ROW), &column_types),
6249        check_sql
6250    );
6251
6252    trace!("Executing UPDATE SQL: {}", sql);
6253
6254    // Build query with parameters
6255    let mut query = sqlx::query(AssertSqlSafe(sql));
6256
6257    // Bind SET values
6258    for val in &set_values {
6259        query = bind_json_value(query, val);
6260    }
6261
6262    // Bind WHERE values
6263    for val in &where_values {
6264        query = bind_json_value(query, val);
6265    }
6266
6267    // And the check's, last, because `RETURNING` is.
6268    for val in &check_values {
6269        query = bind_json_value(query, val);
6270    }
6271
6272    let mut guard = write_tx(gql_ctx, pool).await?;
6273    let conn = guard.as_mut().expect("write_tx opens one");
6274    let rows = query.fetch_all(&mut **conn).await.map_err(database_error)?;
6275
6276    refuse_unchecked_rows(&rows, !check_sql.is_empty())?;
6277
6278    let updated: Vec<Value> = rows
6279        .iter()
6280        .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
6281        .map(json_to_value)
6282        .collect();
6283
6284    Ok(updated)
6285}
6286
6287/// A permission's check, as a column of the write's `RETURNING`.
6288///
6289/// Empty where nothing has to be checked. Otherwise `, (<predicate>) AS ...`,
6290/// evaluated per written row against the row itself -- so a row the permission
6291/// refuses is known before the transaction is settled, and settling it is
6292/// already a rollback once an error is reported.
6293fn permission_check_sql(
6294    gql_ctx: &GraphQLContext,
6295    names: &crate::names::NameOverrides,
6296    schema_name: &str,
6297    table_name: &str,
6298    verb: crate::role::Verb,
6299    scope: &WhereScope<'_>,
6300    start_param_idx: usize,
6301) -> Result<(String, Vec<serde_json::Value>), async_graphql::Error> {
6302    let check = crate::role::write_check(&gql_ctx.caller(), names, schema_name, table_name, verb)
6303        .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
6304    let Some(check) = check else {
6305        return Ok((String::new(), Vec::new()));
6306    };
6307
6308    let mut values = Vec::new();
6309    let mut param_idx = start_param_idx;
6310    let mut alias_counter = 0usize;
6311    let condition = build_condition(
6312        &check,
6313        scope,
6314        &mut param_idx,
6315        &mut values,
6316        &mut alias_counter,
6317    )?;
6318    Ok(match condition {
6319        // A check that compiles to nothing restricts nothing, which is what an
6320        // empty one says.
6321        None => (String::new(), Vec::new()),
6322        Some(sql) => (
6323            format!(
6324                ", ({}) AS {}",
6325                sql,
6326                postrust_sql::escape_ident(CHECK_COLUMN)
6327            ),
6328            values,
6329        ),
6330    })
6331}
6332
6333/// The column a permission's check is returned in.
6334const CHECK_COLUMN: &str = "pgrst_permission_check";
6335
6336/// Refuse the whole write if any row it produced fails the permission's check.
6337///
6338/// Every row, not the first: a mutation is one transaction and a single
6339/// refused row takes the rest with it, which is what makes a check a rule
6340/// about the write rather than about a row. A null counts as a failure -- an
6341/// unknown is not a satisfied condition.
6342fn refuse_unchecked_rows(
6343    rows: &[sqlx::postgres::PgRow],
6344    checked: bool,
6345) -> Result<(), async_graphql::Error> {
6346    if !checked {
6347        return Ok(());
6348    }
6349    use sqlx::Row;
6350    let all_passed = rows
6351        .iter()
6352        .all(|row| row.try_get::<bool, _>(CHECK_COLUMN).unwrap_or(false));
6353    match all_passed {
6354        true => Ok(()),
6355        false => Err(coded_error("permission-error", crate::role::CHECK_FAILED)),
6356    }
6357}
6358
6359/// Execute a delete mutation.
6360#[allow(clippy::too_many_arguments)] // the projection needs the schema it reads
6361async fn execute_delete(
6362    pool: &PgPool,
6363    gql_ctx: &GraphQLContext,
6364    schema_name: &str,
6365    table_name: &str,
6366    type_name: &str,
6367    where_clause: Option<serde_json::Value>,
6368    returning: Option<async_graphql::SelectionField<'_>>,
6369    relationships: &HashMap<String, Vec<RelationshipField>>,
6370    names: &crate::names::NameOverrides,
6371    max_rows: Option<i64>,
6372) -> Result<Vec<Value>, async_graphql::Error> {
6373    use sqlx::Row;
6374
6375    trace!("Delete mutation for {}", table_name);
6376
6377    let guard = gql_ctx
6378        .schema_cache
6379        .get()
6380        .await
6381        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
6382    let cache = guard
6383        .as_ref()
6384        .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
6385    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
6386    let column_types = cache
6387        .get_table(&qi)
6388        .map(|table| exposed_column_types(table, names))
6389        .unwrap_or_default();
6390
6391    // Build WHERE clause. It can follow a relationship -- `delete_article(where:
6392    // {author: {id: {_eq: 2}}})` is the article-by-author delete anyone writes
6393    // -- so the scope is given the schema to resolve one with.
6394    let scope = WhereScope::table(schema_name, table_name, type_name, names)
6395        .under_alias(WRITTEN_ROW)
6396        .with_resolution(cache, relationships);
6397    let (where_sql, mut values) = build_where_clause(where_clause.as_ref(), 1, &scope)?;
6398
6399    // An absent or unrecognised `where` argument yields an empty clause, which
6400    // would delete every row in the table. Refuse instead.
6401    if where_sql.is_empty() {
6402        return Err(async_graphql::Error::new(format!(
6403            "delete on \"{}\" requires a `where` argument with at least one \
6404             recognised condition; refusing to delete every row",
6405            table_name
6406        )));
6407    }
6408
6409    // A relationship or computed field asked for in `returning` cannot be read
6410    // afterwards -- the rows are gone by then, which is why this used to answer
6411    // the plain columns and then fail on a non-null list. Inside one statement
6412    // the deleted rows are still a table: the delete goes in a CTE and the
6413    // projection reads from it, while the rows it points at are still there.
6414    let mut projection = String::new();
6415    let renamed = cache
6416        .get_table(&qi)
6417        .and_then(|table| rename_projection(table, "src", names));
6418    if let Some(returning) = returning {
6419        let mut param_idx = values.len() + 1;
6420        let mut alias_counter = 0usize;
6421        let embeds = build_embed_expressions(
6422            &gql_ctx.caller(),
6423            cache,
6424            relationships,
6425            type_name,
6426            "src",
6427            returning.selection_set(),
6428            max_rows,
6429            &mut alias_counter,
6430            &mut param_idx,
6431            &mut values,
6432            names,
6433        )?;
6434        let computed = match cache.get_table(&qi) {
6435            Some(table) => computed_projections(
6436                table,
6437                returning.selection_set(),
6438                "src",
6439                names,
6440                cache,
6441                &mut param_idx,
6442                &mut values,
6443            )?,
6444            None => Vec::new(),
6445        };
6446        for expression in &computed {
6447            projection.push_str(", ");
6448            projection.push_str(expression);
6449        }
6450        for (name, expression) in &embeds {
6451            projection.push_str(", ");
6452            projection.push_str(expression);
6453            projection.push_str(" AS ");
6454            projection.push_str(&postrust_sql::escape_ident(name));
6455        }
6456    }
6457
6458    let written = postrust_sql::escape_ident(WRITTEN_ROW);
6459    let sql = if projection.is_empty() && renamed.is_none() {
6460        format!(
6461            "DELETE FROM {}.{} AS {} {} RETURNING {}",
6462            postrust_sql::escape_ident(schema_name),
6463            postrust_sql::escape_ident(table_name),
6464            written,
6465            where_sql,
6466            row_json(&written, &column_types)
6467        )
6468    } else {
6469        format!(
6470            "WITH pgrst_deleted AS (DELETE FROM {}.{} AS {} {} RETURNING {}.*) \
6471             SELECT {} FROM (SELECT {}{} FROM pgrst_deleted AS src) AS pgrst_r",
6472            postrust_sql::escape_ident(schema_name),
6473            postrust_sql::escape_ident(table_name),
6474            written,
6475            where_sql,
6476            written,
6477            row_json("pgrst_r", &column_types),
6478            renamed.unwrap_or_else(|| "src.*".to_string()),
6479            projection
6480        )
6481    };
6482
6483    trace!("Executing DELETE SQL: {}", sql);
6484
6485    let mut query = sqlx::query(AssertSqlSafe(sql));
6486    for val in &values {
6487        query = bind_json_value(query, val);
6488    }
6489
6490    let mut guard = write_tx(gql_ctx, pool).await?;
6491    let conn = guard.as_mut().expect("write_tx opens one");
6492    let rows = query.fetch_all(&mut **conn).await.map_err(database_error)?;
6493
6494    let deleted: Vec<Value> = rows
6495        .iter()
6496        .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
6497        .map(json_to_value)
6498        .collect();
6499
6500    Ok(deleted)
6501}
6502
6503/// The predicate a role's permission adds to every read of one table.
6504///
6505/// `None` where nothing restricts the read: no permission document, an
6506/// administrator, or a permission whose filter is `{}`. The value is a
6507/// `<table>_bool_exp` like any other, because [`crate::role::permission_where`]
6508/// rewrites it into one -- which is what lets the same compiler serve both and
6509/// keeps a permission able to say everything a `where` can.
6510fn permission_predicate(
6511    caller: &crate::role::Caller<'_>,
6512    names: &crate::names::NameOverrides,
6513    schema: &str,
6514    table: &str,
6515) -> Result<Option<serde_json::Value>, async_graphql::Error> {
6516    permission_filter(caller, names, schema, table, crate::role::Verb::Select)
6517}
6518
6519/// The same, for whichever grant the operation is asking under.
6520fn permission_filter(
6521    caller: &crate::role::Caller<'_>,
6522    names: &crate::names::NameOverrides,
6523    schema: &str,
6524    table: &str,
6525    verb: crate::role::Verb,
6526) -> Result<Option<serde_json::Value>, async_graphql::Error> {
6527    crate::role::row_filter(caller, names, schema, table, verb)
6528        .map(|filter| filter.map(|predicate| serde_json::json!({ PERMISSION: predicate })))
6529        .map_err(|fault| coded_error(fault.code(), fault.to_string()))
6530}
6531
6532/// The key a permission's own predicate is wrapped in on its way to the
6533/// compiler.
6534///
6535/// The two halves of a `where` are the same language and are compiled by the
6536/// same code, which is what keeps a permission able to say everything a client
6537/// can. They are not evaluated by the same party: a client's half asks what
6538/// *this caller* may see, and a permission's half is the server's own
6539/// predicate, evaluated as the server.
6540///
6541/// The difference shows on a relationship. `{"Artist": {"id":
6542/// "X-Hasura-Artist-Id"}}` on `Track` grants the tracks belonging to the
6543/// caller's artist -- to a role that has no permission on `Artist` at all, and
6544/// is not meant to have one: the predicate consults that table, it does not
6545/// expose it. Compiled as the caller, it needs a permission that does not
6546/// exist and refuses itself; compiled as the server, it says what it was
6547/// written to say. `_exists` has always worked this way and says so where it
6548/// is built; this is the same rule for the relationship a permission follows.
6549///
6550/// The name cannot collide with a column: no boolean expression a client can
6551/// write has this field, because no input type declares it.
6552const PERMISSION: &str = "_permission";
6553
6554/// How many rows a permission lets one read return.
6555///
6556/// A ceiling rather than a default: a request asking for more gets this, one
6557/// asking for fewer gets what it asked for, and one asking for nothing gets
6558/// the ceiling. The same rule `PGRST_MAX_ROWS` follows, folded with it.
6559fn permission_limit(
6560    caller: &crate::role::Caller<'_>,
6561    names: &crate::names::NameOverrides,
6562    schema: &str,
6563    table: &str,
6564) -> Option<i64> {
6565    crate::role::read_limit(caller, names, schema, table)
6566}
6567
6568/// Both predicates, as one.
6569///
6570/// Written as an `_and` rather than as two clauses so that everything
6571/// downstream -- parameter numbering, relationship resolution, the `EXISTS`
6572/// that a relationship predicate becomes -- happens once, in one place, for
6573/// both halves.
6574fn and_predicates(
6575    request: Option<serde_json::Value>,
6576    permission: Option<serde_json::Value>,
6577) -> Option<serde_json::Value> {
6578    match (request, permission) {
6579        (None, None) => None,
6580        (Some(only), None) | (None, Some(only)) => Some(only),
6581        (Some(request), Some(permission)) => {
6582            Some(serde_json::json!({ "_and": [request, permission] }))
6583        }
6584    }
6585}
6586
6587/// Build a WHERE clause from a boolean expression.
6588///
6589/// The expression is the JSON form of a `<table>_bool_exp`: column names
6590/// mapping to comparisons, and `_and`, `_or` and `_not` for structure. It
6591/// nests, so this recurses.
6592///
6593/// Nothing is dropped silently. An operator that is not recognised widens the
6594/// result set if it is ignored -- every row for a query, every row for a
6595/// mutation -- so it is an error instead.
6596fn build_where_clause(
6597    where_value: Option<&serde_json::Value>,
6598    start_param_idx: usize,
6599    scope: &WhereScope<'_>,
6600) -> Result<(String, Vec<serde_json::Value>), async_graphql::Error> {
6601    let mut values: Vec<serde_json::Value> = Vec::new();
6602    let mut param_idx = start_param_idx;
6603    let mut alias_counter = 0usize;
6604
6605    let condition = match where_value {
6606        Some(value) => build_condition(
6607            value,
6608            scope,
6609            &mut param_idx,
6610            &mut values,
6611            &mut alias_counter,
6612        )?,
6613        None => None,
6614    };
6615
6616    Ok(match condition {
6617        Some(sql) => (format!("WHERE {}", sql), values),
6618        None => (String::new(), values),
6619    })
6620}
6621
6622/// The table a boolean expression is being read against.
6623///
6624/// Column references are qualified with `sql_ref` so that a predicate over a
6625/// relationship -- which becomes a correlated `EXISTS` against another table --
6626/// can tell the two apart. Without the qualification a child column sharing a
6627/// parent column's name would silently resolve to whichever PostgreSQL
6628/// preferred.
6629///
6630/// `resolution` is absent where a caller has no schema cache to hand, which is
6631/// how the mutation paths are called. A relationship predicate then reports
6632/// that it cannot be resolved rather than being read as a column.
6633pub struct WhereScope<'a> {
6634    /// The table itself, for the comparisons that need a column's type.
6635    qualified: postrust_core::api_request::QualifiedIdentifier,
6636    /// How to refer to this table's columns in SQL.
6637    sql_ref: String,
6638    /// How to refer to this table's *row*, which is what a function taking the
6639    /// row is passed. A qualified name reads as a column reference there, so
6640    /// this is the bare alias.
6641    row_ref: String,
6642    /// The GraphQL type name, which is the key into the relationship map.
6643    type_name: String,
6644    /// How to refer to the columns of the table the predicate started at, and
6645    /// which table that is.
6646    ///
6647    /// A column comparison written `["$", "name"]` means that table's column,
6648    /// however many relationships the predicate has descended through since --
6649    /// which is what makes the form worth having. Equal to this table's own
6650    /// until an `EXISTS` is entered.
6651    root_ref: String,
6652    root_qualified: postrust_core::api_request::QualifiedIdentifier,
6653    /// The names this table's columns are exposed under, so a predicate
6654    /// written against a field can be written as SQL against a column.
6655    names: &'a crate::names::NameOverrides,
6656    resolution: Option<WhereResolution<'a>>,
6657    /// Who is asking, so that a predicate following a relationship narrows the
6658    /// far side to what that caller may read.
6659    ///
6660    /// Unrestricted unless a scope is told otherwise, which is what leaves
6661    /// every path that has no caller to hand -- the mutation ones -- behaving
6662    /// as it did.
6663    caller: Option<crate::role::Caller<'a>>,
6664}
6665
6666/// What a scope needs to follow a relationship.
6667struct WhereResolution<'a> {
6668    cache: &'a SchemaCache,
6669    relationships: &'a HashMap<String, Vec<RelationshipField>>,
6670}
6671
6672impl<'a> WhereScope<'a> {
6673    /// A scope over a table addressed by its qualified name.
6674    pub fn table(
6675        schema: &str,
6676        table: &str,
6677        type_name: &str,
6678        names: &'a crate::names::NameOverrides,
6679    ) -> Self {
6680        Self {
6681            qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6682            sql_ref: format!(
6683                "{}.{}",
6684                postrust_sql::escape_ident(schema),
6685                postrust_sql::escape_ident(table)
6686            ),
6687            row_ref: postrust_sql::escape_ident(table),
6688            type_name: type_name.to_string(),
6689            root_ref: format!(
6690                "{}.{}",
6691                postrust_sql::escape_ident(schema),
6692                postrust_sql::escape_ident(table)
6693            ),
6694            root_qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6695            names,
6696            resolution: None,
6697            caller: None,
6698        }
6699    }
6700
6701    /// The same, referred to by an alias rather than by its name.
6702    ///
6703    /// A statement that writes a table has to name that table's row in
6704    /// `RETURNING`, and a bare table name there is read as a *column* first --
6705    /// so `area.area`, a geography column in a table of the same name, made
6706    /// `to_jsonb("area")` the shape rather than the row. The alias is a name
6707    /// no column has.
6708    fn under_alias(mut self, alias: &str) -> Self {
6709        // The root moves with it: this is the outermost table being renamed,
6710        // not a step into another one.
6711        if self.root_ref == self.sql_ref {
6712            self.root_ref = postrust_sql::escape_ident(alias);
6713        }
6714        self.sql_ref = postrust_sql::escape_ident(alias);
6715        self.row_ref = postrust_sql::escape_ident(alias);
6716        self
6717    }
6718
6719    /// The same, able to follow relationships.
6720    fn with_resolution(
6721        mut self,
6722        cache: &'a SchemaCache,
6723        relationships: &'a HashMap<String, Vec<RelationshipField>>,
6724    ) -> Self {
6725        self.resolution = Some(WhereResolution {
6726            cache,
6727            relationships,
6728        });
6729        self
6730    }
6731
6732    /// A scope over an aliased table, able to follow relationships.
6733    #[allow(clippy::too_many_arguments)]
6734    fn for_alias(
6735        schema: &str,
6736        table: &str,
6737        alias: &str,
6738        type_name: &str,
6739        cache: &'a SchemaCache,
6740        relationships: &'a HashMap<String, Vec<RelationshipField>>,
6741        names: &'a crate::names::NameOverrides,
6742    ) -> Self {
6743        Self {
6744            qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6745            sql_ref: postrust_sql::escape_ident(alias),
6746            row_ref: postrust_sql::escape_ident(alias),
6747            type_name: type_name.to_string(),
6748            root_ref: postrust_sql::escape_ident(alias),
6749            root_qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6750            names,
6751            resolution: Some(WhereResolution {
6752                cache,
6753                relationships,
6754            }),
6755            caller: None,
6756        }
6757    }
6758
6759    /// A scope over an aliased table, for the inside of an `EXISTS`.
6760    /// A scope over the *other* table of a relationship, under an alias.
6761    ///
6762    /// The child's own qualified name, not the parent's: a comparison inside
6763    /// an `EXISTS` is against the child's columns, so it is the child's types
6764    /// and the child's renames that decide how to write it.
6765    fn aliased(
6766        schema: &str,
6767        table: &str,
6768        alias: &str,
6769        type_name: &str,
6770        from: &WhereScope<'a>,
6771    ) -> Self {
6772        Self {
6773            qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6774            sql_ref: postrust_sql::escape_ident(alias),
6775            row_ref: postrust_sql::escape_ident(alias),
6776            type_name: type_name.to_string(),
6777            // Carried, not replaced: `$` names the table the predicate began
6778            // at, which is the whole point of descending with it.
6779            root_ref: from.root_ref.clone(),
6780            root_qualified: from.root_qualified.clone(),
6781            names: from.names,
6782            resolution: from.resolution.as_ref().map(|r| WhereResolution {
6783                cache: r.cache,
6784                relationships: r.relationships,
6785            }),
6786            // Carried across the relationship: the caller does not change on
6787            // the way into an EXISTS, and the far side has its own permission
6788            // to be narrowed by.
6789            caller: from.caller,
6790        }
6791    }
6792
6793    /// Narrow what this scope's predicates may reach to one caller.
6794    pub fn for_caller(mut self, caller: crate::role::Caller<'a>) -> Self {
6795        self.caller = Some(caller);
6796        self
6797    }
6798
6799    /// The same scope with no caller: what a permission's own predicate is
6800    /// evaluated as. See `PERMISSION`.
6801    fn as_system(&self) -> WhereScope<'a> {
6802        WhereScope {
6803            qualified: self.qualified.clone(),
6804            sql_ref: self.sql_ref.clone(),
6805            row_ref: self.row_ref.clone(),
6806            type_name: self.type_name.clone(),
6807            // The root moves here. `$` in a permission names the table the
6808            // permission is *written on*, which is this one -- not whatever
6809            // table the query happened to start at. Reading `dml_rbp_tasks`
6810            // through a project's `where: {tasks: {...}}` compared the task's
6811            // grant against a column of `dml_rbp_projects` until this, and
6812            // answered with rows the role may not see.
6813            root_ref: self.sql_ref.clone(),
6814            root_qualified: self.qualified.clone(),
6815            names: self.names,
6816            resolution: self.resolution.as_ref().map(|r| WhereResolution {
6817                cache: r.cache,
6818                relationships: r.relationships,
6819            }),
6820            caller: None,
6821        }
6822    }
6823
6824    /// What a field name refers to, as SQL: a column of this table, or the
6825    /// call that produces a computed field.
6826    ///
6827    /// A computed field is in the boolean expression because it is on the type
6828    /// -- `where: {sum_float_offset: {_gt: 5}}` is a question a client can
6829    /// write -- and reading it as a column answered `column
6830    /// float_test.sum_float_offset does not exist`.
6831    fn column(&self, name: &str) -> String {
6832        let column = self.column_name(name);
6833        let plain = format!("{}.{}", self.sql_ref, postrust_sql::escape_ident(column));
6834        let Some(cache) = self.resolution.as_ref().map(|r| r.cache) else {
6835            return plain;
6836        };
6837        let Some(table) = cache.get_table(&self.qualified) else {
6838            return plain;
6839        };
6840        if table.get_column(column).is_some() {
6841            return plain;
6842        }
6843        let function = self
6844            .names
6845            .computed_source(&table.schema, &table.name, name)
6846            .unwrap_or(name);
6847        match table.get_computed_column(function) {
6848            Some(definition) => {
6849                computed_call(definition, &format!("{}.*", self.row_ref), &self.row_ref)
6850            }
6851            None => plain,
6852        }
6853    }
6854
6855    /// The column behind a field name.
6856    fn column_name<'n>(&'n self, name: &'n str) -> &'n str {
6857        self.names
6858            .column_source(&self.qualified.schema, &self.qualified.name, name)
6859            .unwrap_or(name)
6860    }
6861
6862    /// The PostgreSQL type of one of this table's columns, where it can be
6863    /// found. A spatial comparison needs it: the same function takes a
6864    /// geometry or a geography and the operand has to be cast to match.
6865    fn column_type(&self, name: &str) -> Option<String> {
6866        let cache = self.resolution.as_ref()?.cache;
6867        let table = cache.get_table(&self.qualified)?;
6868        table
6869            .get_column(self.column_name(name))
6870            .map(|c| c.nominal_type.clone())
6871    }
6872
6873    /// The other side of a column-to-column comparison, as SQL.
6874    ///
6875    /// Hasura writes the operand two ways. A bare name is a column of *this*
6876    /// table -- `{"bid_price": {"$cgt": "price"}}` compares two columns of one
6877    /// auction. `["$", "name"]` is a column of the table the permission is
6878    /// written on, which is what makes the form useful inside a predicate over
6879    /// a relationship: `{"item": {"item_quantity": {"_cgte": ["$",
6880    /// "order_cart_quantity"]}}}` asks whether the item has as many in stock
6881    /// as the cart is asking for, and the cart is the outer row.
6882    ///
6883    /// Nothing else is accepted. A longer path would walk relationships to
6884    /// reach the column, which Hasura allows and no case here writes -- and
6885    /// reading it wrongly would widen a permission rather than narrow it.
6886    fn other_column(
6887        &self,
6888        operand: &serde_json::Value,
6889        op: &str,
6890    ) -> Result<String, async_graphql::Error> {
6891        use serde_json::Value;
6892
6893        let refused = |what: &str| {
6894            async_graphql::Error::new(format!(
6895                "the \"{}\" comparison takes the name of a column, {}",
6896                op, what
6897            ))
6898        };
6899        let (against, qualified, name) = match operand {
6900            Value::String(name) => (&self.sql_ref, &self.qualified, name.as_str()),
6901            Value::Array(path) => match path.as_slice() {
6902                [Value::String(name)] => (&self.sql_ref, &self.qualified, name.as_str()),
6903                [Value::String(root), Value::String(name)] if root == "$" => {
6904                    (&self.root_ref, &self.root_qualified, name.as_str())
6905                }
6906                _ => return Err(refused("or [\"$\", \"a column\"]")),
6907            },
6908            _ => return Err(refused("written as a string")),
6909        };
6910        // Read against whichever table it belongs to, since a rename is
6911        // per-table and the two are not the same table.
6912        let column = self
6913            .names
6914            .column_source(&qualified.schema, &qualified.name, name)
6915            .unwrap_or(name);
6916        Ok(format!(
6917            "{}.{}",
6918            against,
6919            postrust_sql::escape_ident(column)
6920        ))
6921    }
6922
6923    /// The relationship a predicate is following, where there is one.
6924    ///
6925    /// Looked up in the schema's own map first, which is the answer for every
6926    /// relationship the role can read. A permission may name one it cannot:
6927    /// role `Artist` reads `Track` and filters it by `{"Artist": {"id": ...}}`
6928    /// while having no permission on `Artist` at all, so that relationship is
6929    /// in no schema this role is served. The catalogue still has it -- the
6930    /// cache a scope resolves against is the unreduced one -- and the
6931    /// relationship is derived from it there.
6932    ///
6933    /// Deriving it cannot let a client reach a hidden table: a key that is not
6934    /// a field of the boolean expression is refused before any of this runs,
6935    /// and the only writer of such a key is a permission.
6936    fn relationship(&self, name: &str) -> Option<std::borrow::Cow<'a, RelationshipField>> {
6937        let resolution = self.resolution.as_ref()?;
6938        let published = resolution
6939            .relationships
6940            .get(&self.type_name)
6941            .and_then(|fields| fields.iter().find(|r| r.name == name));
6942        if let Some(found) = published {
6943            return Some(std::borrow::Cow::Borrowed(found));
6944        }
6945
6946        let table = resolution.cache.get_table(&self.qualified)?;
6947
6948        // A relationship metadata declares, which may be a mapped join the
6949        // catalogue has never heard of. `message.members` is one, and a
6950        // permission on `message` is written through it -- so this is not a
6951        // convenience: without it that filter cannot be compiled at all and
6952        // the read is refused rather than narrowed.
6953        if let Some(declared) = self
6954            .names
6955            .declared_relationships(&table.schema, &table.name)
6956        {
6957            if let Some(entry) = declared.iter().find(|entry| entry.name == name) {
6958                // Reached by a mapping, which the catalogue has never heard
6959                // of.
6960                let target = entry
6961                    .target(&table.schema)
6962                    .map(|(_, target)| target)
6963                    .unwrap_or_default();
6964                if let Some(field) = crate::schema::mapped_relationship_field(
6965                    entry,
6966                    table,
6967                    resolution.cache,
6968                    &table.schema,
6969                    &target,
6970                    &target,
6971                    &target,
6972                ) {
6973                    return Some(std::borrow::Cow::Owned(field));
6974                }
6975                // Or by a key, under the name the declaration gives it --
6976                // which is the only place that name is written down now that
6977                // a declaration carries it.
6978                if let Some(key) = entry.using.as_deref() {
6979                    if let Some(found) = resolution
6980                        .cache
6981                        .get_relationships(&self.qualified, &table.schema)
6982                        .into_iter()
6983                        .flatten()
6984                        .find(|rel| {
6985                            crate::schema::relationship_keys(rel)
6986                                .iter()
6987                                .any(|found| found == key)
6988                        })
6989                    {
6990                        return Some(std::borrow::Cow::Owned(
6991                            crate::schema::relationship::RelationshipField::from_relationship_named(
6992                                found,
6993                                &found.foreign_table().name,
6994                                Some(&entry.name),
6995                            ),
6996                        ));
6997                    }
6998                }
6999            }
7000        }
7001
7002        resolution
7003            .cache
7004            .get_relationships(&self.qualified, &table.schema)?
7005            .iter()
7006            .find_map(|rel| {
7007                let given = crate::schema::relationship_keys(rel)
7008                    .iter()
7009                    .find_map(|key| self.names.relationship(&table.schema, &table.name, key));
7010                // The target's own name stands in for its GraphQL type, which
7011                // this role has none of. Nothing reads it but the lookup
7012                // above, and that lookup will land here again.
7013                let field = RelationshipField::from_relationship_named(
7014                    rel,
7015                    &rel.foreign_table().name,
7016                    given,
7017                );
7018                (field.name == name).then_some(std::borrow::Cow::Owned(field))
7019            })
7020    }
7021}
7022
7023/// The SQL operator behind a column-to-column comparison, where this is one.
7024///
7025/// `_ceq`, `_cne`, `_cgt`, `_cgte`, `_clt`, `_clte`: the `c` is for column.
7026/// Only a permission writes these -- no boolean expression a client can write
7027/// has them, because a client has no way to name the row a comparison would be
7028/// against. A permission does: `{"bid_price": {"$cgt": "price"}}` on `auction`
7029/// grants the rows whose bid has passed the reserve, which is a fact about the
7030/// row rather than about the caller.
7031fn column_comparison(op: &str) -> Option<&'static str> {
7032    Some(match op {
7033        "_ceq" => "=",
7034        "_cne" => "<>",
7035        "_cgt" => ">",
7036        "_cgte" => ">=",
7037        "_clt" => "<",
7038        "_clte" => "<=",
7039        _ => return None,
7040    })
7041}
7042
7043/// One boolean expression, as SQL. `None` where it constrains nothing.
7044fn build_condition(
7045    value: &serde_json::Value,
7046    scope: &WhereScope<'_>,
7047    param_idx: &mut usize,
7048    values: &mut Vec<serde_json::Value>,
7049    alias_counter: &mut usize,
7050) -> Result<Option<String>, async_graphql::Error> {
7051    let serde_json::Value::Object(map) = value else {
7052        return Ok(None);
7053    };
7054
7055    let mut conditions: Vec<String> = Vec::new();
7056
7057    for (key, val) in map {
7058        match key.as_str() {
7059            // An empty `_and` is true and an empty `_or` is false, which is
7060            // what SQL's own identities give: nothing to AND constrains
7061            // nothing, nothing to OR matches nothing.
7062            "_and" | "_or" => {
7063                let members = val.as_array().ok_or_else(|| {
7064                    async_graphql::Error::new(format!("\"{}\" takes a list of expressions", key))
7065                })?;
7066                let mut parts = Vec::new();
7067                for member in members {
7068                    if let Some(sql) =
7069                        build_condition(member, scope, param_idx, values, alias_counter)?
7070                    {
7071                        parts.push(sql);
7072                    }
7073                }
7074                if parts.is_empty() {
7075                    if key == "_or" {
7076                        conditions.push("false".to_string());
7077                    }
7078                    continue;
7079                }
7080                let joiner = if key == "_and" { " AND " } else { " OR " };
7081                conditions.push(format!("({})", parts.join(joiner)));
7082            }
7083            "_not" => {
7084                if let Some(sql) = build_condition(val, scope, param_idx, values, alias_counter)? {
7085                    conditions.push(format!("NOT ({})", sql));
7086                }
7087            }
7088            // A permission's own predicate, which is the server's rather
7089            // than the caller's. See `PERMISSION`.
7090            PERMISSION => {
7091                if let Some(sql) =
7092                    build_condition(val, &scope.as_system(), param_idx, values, alias_counter)?
7093                {
7094                    conditions.push(sql);
7095                }
7096            }
7097            // A question about a table nothing relates this one to. Only a
7098            // permission writes it; no client can, because no boolean
7099            // expression has the field.
7100            "_exists" => {
7101                conditions.push(table_exists_sql(
7102                    val,
7103                    scope,
7104                    param_idx,
7105                    values,
7106                    alias_counter,
7107                )?);
7108            }
7109            // A relationship is filtered by filtering the rows at its other
7110            // end. `where: {articles: {title: {_eq: "x"}}}` keeps the authors
7111            // that have such an article -- an `EXISTS` correlated back to the
7112            // parent row, which is also what it means for a to-one
7113            // relationship, where the subquery simply cannot match twice.
7114            name if scope.relationship(name).is_some() => {
7115                let relationship = scope.relationship(name).expect("just checked");
7116                conditions.push(exists_sql(
7117                    &relationship,
7118                    val,
7119                    scope,
7120                    param_idx,
7121                    values,
7122                    alias_counter,
7123                )?);
7124            }
7125            // A question about the whole related set rather than about any
7126            // one row of it. `where: {articles_aggregate: {count: {predicate:
7127            // {_gt: 2}}}}` keeps the authors with more than two articles,
7128            // which no `EXISTS` over one article can say.
7129            name if scope.column_type(name).is_none()
7130                && name
7131                    .strip_suffix("_aggregate")
7132                    .and_then(|rel| scope.relationship(rel))
7133                    .is_some_and(|rel| rel.is_list) =>
7134            {
7135                let relationship = name
7136                    .strip_suffix("_aggregate")
7137                    .and_then(|rel| scope.relationship(rel))
7138                    .expect("just checked");
7139                conditions.push(aggregate_predicate_sql(
7140                    &relationship,
7141                    val,
7142                    scope,
7143                    param_idx,
7144                    values,
7145                    alias_counter,
7146                )?);
7147            }
7148            column => {
7149                let quoted = scope.column(column);
7150                match val {
7151                    serde_json::Value::Object(ops) => {
7152                        let column_type = scope.column_type(column);
7153                        for (op, operand) in ops {
7154                            // A comparison against another column rather than
7155                            // against a value, which only a permission can
7156                            // write. It needs the scope to say *which* column,
7157                            // so it is answered here rather than in
7158                            // `comparison_sql`, which sees one side.
7159                            if let Some(other) = column_comparison(op) {
7160                                conditions.push(format!(
7161                                    "{} {} {}",
7162                                    quoted,
7163                                    other,
7164                                    scope.other_column(operand, op)?
7165                                ));
7166                                continue;
7167                            }
7168                            conditions.push(comparison_sql(
7169                                &quoted,
7170                                column,
7171                                column_type.as_deref(),
7172                                op,
7173                                operand,
7174                                param_idx,
7175                                values,
7176                            )?);
7177                        }
7178                    }
7179                    // `{id: 1}` rather than `{id: {_eq: 1}}`. Not a spelling
7180                    // Hasura accepts, but one that costs nothing to read and
7181                    // that hand-written queries reach for.
7182                    other => {
7183                        conditions.push(format!("{} = ${}", quoted, param_idx));
7184                        values.push(other.clone());
7185                        *param_idx += 1;
7186                    }
7187                }
7188            }
7189        }
7190    }
7191
7192    Ok(if conditions.is_empty() {
7193        None
7194    } else if conditions.len() == 1 {
7195        conditions.pop()
7196    } else {
7197        Some(conditions.join(" AND "))
7198    })
7199}
7200
7201/// A predicate over a relationship, as a correlated `EXISTS`.
7202///
7203/// Only a plain key join is expressible this way. A many-to-many through a
7204/// junction and a computed relationship both need more than a pair of columns
7205/// to correlate on, and saying so is the only honest answer -- reading the
7206/// predicate as though it constrained nothing would return every parent row.
7207fn exists_sql(
7208    relationship: &RelationshipField,
7209    child_expression: &serde_json::Value,
7210    scope: &WhereScope<'_>,
7211    param_idx: &mut usize,
7212    values: &mut Vec<serde_json::Value>,
7213    alias_counter: &mut usize,
7214) -> Result<String, async_graphql::Error> {
7215    let cache = scope.resolution.as_ref().map(|r| r.cache).ok_or_else(|| {
7216        async_graphql::Error::new(format!(
7217            "filtering on the relationship \"{}\" is not available here",
7218            relationship.name
7219        ))
7220    })?;
7221
7222    let plan = postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, cache)
7223        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
7224
7225    if plan.junction.is_some() || (plan.function.is_none() && plan.columns.is_empty()) {
7226        return Err(async_graphql::Error::new(format!(
7227            "filtering on \"{}\" is not supported: it is reached through a junction \
7228             rather than by a key",
7229            relationship.name
7230        )));
7231    }
7232
7233    *alias_counter += 1;
7234    let alias = format!("pgrst_rel_{}", alias_counter);
7235    let child_scope = WhereScope::aliased(
7236        &plan.foreign_schema,
7237        &plan.foreign_table,
7238        &alias,
7239        &relationship.target_type,
7240        scope,
7241    );
7242
7243    // A computed relationship is correlated by argument -- the function takes
7244    // the parent row -- where a key relationship is correlated by columns.
7245    let (source, mut correlation) = match &plan.function {
7246        Some(function) => (
7247            format!(
7248                "{}.{}({})",
7249                postrust_sql::escape_ident(&function.schema),
7250                postrust_sql::escape_ident(&function.name),
7251                scope.row_ref
7252            ),
7253            Vec::new(),
7254        ),
7255        None => {
7256            let mut columns = Vec::with_capacity(plan.columns.len());
7257            for (parent_column, child_column) in &plan.columns {
7258                columns.push(format!(
7259                    "{} = {}",
7260                    scope.column(parent_column),
7261                    child_scope.column(child_column)
7262                ));
7263            }
7264            (
7265                format!(
7266                    "{}.{}",
7267                    postrust_sql::escape_ident(&plan.foreign_schema),
7268                    postrust_sql::escape_ident(&plan.foreign_table)
7269                ),
7270                columns,
7271            )
7272        }
7273    };
7274
7275    let child_condition = build_condition(
7276        child_expression,
7277        &child_scope,
7278        param_idx,
7279        values,
7280        alias_counter,
7281    )?;
7282    if let Some(sql) = child_condition {
7283        correlation.push(format!("({})", sql));
7284    }
7285
7286    // The far side's own permission. `where: {author: {name: {_eq: "Ann"}}}`
7287    // asks whether a related row exists, and a row this caller may not read is
7288    // one it may not learn the existence of either -- so the child's filter
7289    // narrows the EXISTS exactly as it narrows a read of the same table.
7290    if let Some(caller) = &child_scope.caller {
7291        // Through `permission_predicate` rather than `role::read_predicate`,
7292        // so the far side's filter is marked as the server's own -- see
7293        // `PERMISSION`. Without the mark it was compiled as the caller, and a
7294        // filter that follows a relationship of its own then needed a
7295        // permission on *that* table: `dml_rbp_tasks` is filtered through
7296        // `grants`, which the role reading tasks may not read.
7297        let permission = permission_predicate(
7298            caller,
7299            child_scope.names,
7300            &plan.foreign_schema,
7301            &plan.foreign_table,
7302        )?;
7303        if let Some(predicate) = permission {
7304            if let Some(sql) =
7305                build_condition(&predicate, &child_scope, param_idx, values, alias_counter)?
7306            {
7307                correlation.push(format!("({})", sql));
7308            }
7309        }
7310    }
7311    if correlation.is_empty() {
7312        correlation.push("true".to_string());
7313    }
7314
7315    Ok(format!(
7316        "EXISTS (SELECT 1 FROM {} AS {} WHERE {})",
7317        source,
7318        postrust_sql::escape_ident(&alias),
7319        correlation.join(" AND ")
7320    ))
7321}
7322
7323/// `_exists`, the predicate only a permission can write, as SQL.
7324///
7325/// ```json
7326/// {"_exists": {"_table": "user", "_where": {"id": "X-Hasura-User-Id",
7327///                                           "is_admin": true}}}
7328/// ```
7329///
7330/// It asks whether a row exists in *another* table -- one no foreign key
7331/// relates to this one. That is how Hasura writes "the caller is an
7332/// administrator" without asking the caller to say so: the row that decides it
7333/// lives in a table of its own, and whether the account this predicate guards
7334/// is readable does not depend on which account it is.
7335///
7336/// So the subselect is **uncorrelated**, which is the whole difference from
7337/// the `EXISTS` a relationship predicate builds. There are no key columns to
7338/// join on -- if there were, the permission would have been written as a
7339/// relationship -- and the `_where` is read against the named table's columns
7340/// alone.
7341///
7342/// The caller's own permissions are not applied inside it, and that is not an
7343/// oversight. The point of `_exists` is to consult a table the role has no
7344/// access to: in Hasura's corpus the role that reads `account` through this
7345/// predicate may not read `public.user` at all. Narrowing the subselect to
7346/// what the caller may read would make the predicate refuse itself.
7347fn table_exists_sql(
7348    spec: &serde_json::Value,
7349    scope: &WhereScope<'_>,
7350    param_idx: &mut usize,
7351    values: &mut Vec<serde_json::Value>,
7352    alias_counter: &mut usize,
7353) -> Result<String, async_graphql::Error> {
7354    let Some((schema, table)) = crate::role::exists_target(spec, &scope.qualified.schema) else {
7355        return Err(async_graphql::Error::new(
7356            "\"_exists\" needs a \"_table\" to look in",
7357        ));
7358    };
7359
7360    // The name comes from a permission document rather than from a request,
7361    // but it still reaches SQL, and a table that is not there would reach it as
7362    // a syntax error at the far end rather than as an answer here.
7363    let qualified = postrust_core::api_request::QualifiedIdentifier::new(&schema, &table);
7364    if scope
7365        .resolution
7366        .as_ref()
7367        .is_some_and(|r| r.cache.get_table(&qualified).is_none())
7368    {
7369        return Err(async_graphql::Error::new(format!(
7370            "\"_exists\" names a table this server does not have: \"{}.{}\"",
7371            schema, table
7372        )));
7373    }
7374
7375    *alias_counter += 1;
7376    let alias = format!("pgrst_exists_{}", alias_counter);
7377    // The type this table is exposed as, which is the key into the
7378    // relationship map -- so a `_where` may follow the named table's own
7379    // relationships, the way any other predicate over it could.
7380    let type_name = scope
7381        .names
7382        .base_name(&schema, &table)
7383        .unwrap_or(&table)
7384        .to_string();
7385    let mut inner = WhereScope::aliased(&schema, &table, &alias, &type_name, scope);
7386    // See above: the predicate is the permission, so it is not itself
7387    // subject to one.
7388    inner.caller = None;
7389
7390    let condition = match spec.get("_where") {
7391        Some(predicate) => build_condition(predicate, &inner, param_idx, values, alias_counter)?,
7392        None => None,
7393    };
7394
7395    Ok(format!(
7396        "EXISTS (SELECT 1 FROM {}.{} AS {} WHERE {})",
7397        postrust_sql::escape_ident(&schema),
7398        postrust_sql::escape_ident(&table),
7399        postrust_sql::escape_ident(&alias),
7400        condition.unwrap_or_else(|| "true".to_string())
7401    ))
7402}
7403
7404/// A predicate over an aggregate of a related set, as SQL.
7405///
7406/// `{count: {predicate: {_gt: 2}, filter: {...}}}` becomes a scalar subselect
7407/// correlated back to the parent row, compared the way any column is:
7408///
7409/// ```text
7410/// (SELECT count(*) FROM "public"."article" AS pgrst_rel_1
7411///   WHERE "author"."id" = pgrst_rel_1."author_id" AND (...)) > $1
7412/// ```
7413///
7414/// A scalar subselect rather than an `EXISTS`, because the answer is a number
7415/// or a truth value and not whether a row is there -- and because over no rows
7416/// at all `count` is zero and `bool_and` is null, which is what SQL says and
7417/// what a client asking "no articles" is relying on.
7418fn aggregate_predicate_sql(
7419    relationship: &RelationshipField,
7420    expression: &serde_json::Value,
7421    scope: &WhereScope<'_>,
7422    param_idx: &mut usize,
7423    values: &mut Vec<serde_json::Value>,
7424    alias_counter: &mut usize,
7425) -> Result<String, async_graphql::Error> {
7426    let serde_json::Value::Object(over) = expression else {
7427        return Ok("true".to_string());
7428    };
7429
7430    let cache = scope.resolution.as_ref().map(|r| r.cache).ok_or_else(|| {
7431        async_graphql::Error::new(format!(
7432            "filtering on the relationship \"{}\" is not available here",
7433            relationship.name
7434        ))
7435    })?;
7436    let plan = postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, cache)
7437        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
7438    if plan.junction.is_some() || (plan.function.is_none() && plan.columns.is_empty()) {
7439        return Err(async_graphql::Error::new(format!(
7440            "aggregating over \"{}\" is not supported: it is reached through a junction \
7441             rather than by a key",
7442            relationship.name
7443        )));
7444    }
7445
7446    let mut conditions: Vec<String> = Vec::new();
7447    for (function, spec) in over {
7448        if spec.is_null() {
7449            continue;
7450        }
7451        let serde_json::Value::Object(spec) = spec else {
7452            continue;
7453        };
7454        let Some(predicate) = spec.get("predicate").filter(|p| !p.is_null()) else {
7455            return Err(validation_error(format!(
7456                "\"{}\" over \"{}\" needs a predicate",
7457                function, relationship.name
7458            )));
7459        };
7460
7461        *alias_counter += 1;
7462        let alias = format!("pgrst_agg_{}", alias_counter);
7463        let child_scope = WhereScope::aliased(
7464            &plan.foreign_schema,
7465            &plan.foreign_table,
7466            &alias,
7467            &relationship.target_type,
7468            scope,
7469        );
7470
7471        // Correlated the way an `EXISTS` over the same relationship is: by
7472        // the key, or by handing the parent row to the function.
7473        let (source, mut correlation) = match &plan.function {
7474            Some(routine) => (
7475                format!(
7476                    "{}.{}({})",
7477                    postrust_sql::escape_ident(&routine.schema),
7478                    postrust_sql::escape_ident(&routine.name),
7479                    scope.row_ref
7480                ),
7481                Vec::new(),
7482            ),
7483            None => {
7484                let mut columns = Vec::with_capacity(plan.columns.len());
7485                for (parent_column, child_column) in &plan.columns {
7486                    columns.push(format!(
7487                        "{} = {}",
7488                        scope.column(parent_column),
7489                        child_scope.column(child_column)
7490                    ));
7491                }
7492                (
7493                    format!(
7494                        "{}.{}",
7495                        postrust_sql::escape_ident(&plan.foreign_schema),
7496                        postrust_sql::escape_ident(&plan.foreign_table)
7497                    ),
7498                    columns,
7499                )
7500            }
7501        };
7502        // `filter` narrows what is aggregated, and is an ordinary boolean
7503        // expression over the child.
7504        if let Some(filter) = spec.get("filter").filter(|f| !f.is_null()) {
7505            if let Some(sql) =
7506                build_condition(filter, &child_scope, param_idx, values, alias_counter)?
7507            {
7508                correlation.push(format!("({})", sql));
7509            }
7510        }
7511        if correlation.is_empty() {
7512            correlation.push("true".to_string());
7513        }
7514
7515        let arguments = spec.get("arguments").filter(|a| !a.is_null());
7516        let distinct = matches!(spec.get("distinct"), Some(serde_json::Value::Bool(true)));
7517        let (aggregate, operand_type) = match function.as_str() {
7518            "count" => {
7519                let columns: Vec<String> = match arguments {
7520                    Some(serde_json::Value::Array(items)) => items
7521                        .iter()
7522                        .filter_map(|item| item.as_str())
7523                        .map(|column| child_scope.column(column))
7524                        .collect(),
7525                    Some(serde_json::Value::String(one)) => vec![child_scope.column(one)],
7526                    _ => Vec::new(),
7527                };
7528                let counted = match columns.len() {
7529                    0 => "*".to_string(),
7530                    1 => columns.into_iter().next().unwrap_or_default(),
7531                    _ => format!("({})", columns.join(", ")),
7532                };
7533                let counted = match distinct && counted != "*" {
7534                    true => format!("DISTINCT {}", counted),
7535                    false => counted,
7536                };
7537                (format!("count({})", counted), "integer")
7538            }
7539            "bool_and" | "bool_or" => {
7540                let Some(column) = arguments.and_then(|a| a.as_str()) else {
7541                    return Err(validation_error(format!(
7542                        "\"{}\" over \"{}\" needs the column to fold",
7543                        function, relationship.name
7544                    )));
7545                };
7546                (
7547                    format!("{}({})", function, child_scope.column(column)),
7548                    "boolean",
7549                )
7550            }
7551            other => {
7552                return Err(validation_error(format!(
7553                    "\"{}\" is not an aggregate a predicate can be written over",
7554                    other
7555                )))
7556            }
7557        };
7558
7559        let subselect = format!(
7560            "(SELECT {} FROM {} AS {} WHERE {})",
7561            aggregate,
7562            source,
7563            postrust_sql::escape_ident(&alias),
7564            correlation.join(" AND ")
7565        );
7566        let serde_json::Value::Object(operators) = predicate else {
7567            return Err(validation_error(format!(
7568                "the predicate on \"{}\" is not a comparison",
7569                function
7570            )));
7571        };
7572        for (operator, operand) in operators {
7573            conditions.push(comparison_sql(
7574                &subselect,
7575                function,
7576                Some(operand_type),
7577                operator,
7578                operand,
7579                param_idx,
7580                values,
7581            )?);
7582        }
7583    }
7584
7585    Ok(match conditions.is_empty() {
7586        true => "true".to_string(),
7587        false => format!("({})", conditions.join(" AND ")),
7588    })
7589}
7590
7591/// One spatial comparison, as a PostGIS call.
7592///
7593/// The operand arrives as GeoJSON, which is what Hasura accepts and what a
7594/// client sends, so it is parsed by `ST_GeomFromGeoJSON` rather than bound as
7595/// a shape. The cast that follows is the column's own type: the same function
7596/// takes a geometry or a geography and picking the wrong one is not an
7597/// overload PostGIS has.
7598#[allow(clippy::too_many_arguments)]
7599fn postgis_sql(
7600    quoted: &str,
7601    column_type: Option<&str>,
7602    function: &str,
7603    op: &str,
7604    operand: &serde_json::Value,
7605    param_idx: &mut usize,
7606    values: &mut Vec<serde_json::Value>,
7607) -> Result<String, async_graphql::Error> {
7608    let is_geography = column_type == Some("geography");
7609    let mut shape = |value: &serde_json::Value, param_idx: &mut usize| -> String {
7610        let placeholder = format!("${}", param_idx);
7611        *param_idx += 1;
7612        values.push(value.clone());
7613        match is_geography {
7614            true => format!("ST_GeomFromGeoJSON({})::geography", placeholder),
7615            false => format!("ST_GeomFromGeoJSON({})", placeholder),
7616        }
7617    };
7618
7619    match op {
7620        // `{distance, from}`: the shape and how far from it.
7621        "_st_d_within" | "_st_3d_d_within" => {
7622            let serde_json::Value::Object(spec) = operand else {
7623                return Err(async_graphql::Error::new(format!(
7624                    "\"{}\" takes {{distance, from}}",
7625                    op
7626                )));
7627            };
7628            let Some(from) = spec.get("from") else {
7629                return Err(async_graphql::Error::new(format!(
7630                    "\"{}\" needs a shape to measure from",
7631                    op
7632                )));
7633            };
7634            let Some(distance) = spec.get("distance") else {
7635                return Err(async_graphql::Error::new(format!(
7636                    "\"{}\" needs a distance",
7637                    op
7638                )));
7639            };
7640            let from_sql = shape(from, param_idx);
7641            let distance_sql = format!("${}", param_idx);
7642            *param_idx += 1;
7643            values.push(distance.clone());
7644            // On a sphere the answer depends on which sphere: `ST_DWithin`
7645            // over geography measures on the spheroid by default and on a
7646            // perfect sphere when told not to, and the two disagree by enough
7647            // to change which rows come back. Geometry has no such argument.
7648            let spheroid = match (is_geography, spec.get("use_spheroid")) {
7649                (true, Some(use_spheroid)) if !use_spheroid.is_null() => {
7650                    let placeholder = format!("${}", param_idx);
7651                    *param_idx += 1;
7652                    values.push(use_spheroid.clone());
7653                    format!(", {}::boolean", placeholder)
7654                }
7655                _ => String::new(),
7656            };
7657            Ok(format!(
7658                "{}({}, {}, {}::float8{})",
7659                function, quoted, from_sql, distance_sql, spheroid
7660            ))
7661        }
7662        // A raster against another raster, bound as one rather than parsed.
7663        "_st_intersects_rast" => {
7664            let placeholder = format!("${}", param_idx);
7665            *param_idx += 1;
7666            values.push(operand.clone());
7667            Ok(format!("{}({}, {}::raster)", function, quoted, placeholder))
7668        }
7669        // A raster against a shape, in one band or in any.
7670        "_st_intersects_geom_nband" | "_st_intersects_nband_geom" => {
7671            let serde_json::Value::Object(spec) = operand else {
7672                return Err(async_graphql::Error::new(format!(
7673                    "\"{}\" takes an object",
7674                    op
7675                )));
7676            };
7677            let Some(geometry) = spec.get("geommin") else {
7678                return Err(async_graphql::Error::new(format!(
7679                    "\"{}\" needs a shape",
7680                    op
7681                )));
7682            };
7683            let band = spec.get("nband").filter(|v| !v.is_null());
7684            let geometry_sql = shape(geometry, param_idx);
7685            Ok(match band {
7686                None => format!("{}({}, {})", function, quoted, geometry_sql),
7687                Some(band) => {
7688                    let placeholder = format!("${}", param_idx);
7689                    *param_idx += 1;
7690                    values.push(band.clone());
7691                    // `ST_Intersects(raster, nband, geometry)` is the spelling
7692                    // with a band; the argument order is PostGIS's, not the
7693                    // input's.
7694                    format!(
7695                        "{}({}, {}::int, {})",
7696                        function, quoted, placeholder, geometry_sql
7697                    )
7698                }
7699            })
7700        }
7701        // Everything else is the relation between this shape and one other.
7702        _ => {
7703            let other = shape(operand, param_idx);
7704            Ok(format!("{}({}, {})", function, quoted, other))
7705        }
7706    }
7707}
7708
7709/// A list of values as an array PostgreSQL will read.
7710///
7711/// Bound one element at a time rather than as one parameter. A JSON array
7712/// arrives as the text `["a","b"]`, which is not an array literal -- PostgreSQL
7713/// answers `malformed array literal` and means it.
7714fn sql_array(
7715    items: &[serde_json::Value],
7716    cast: &str,
7717    param_idx: &mut usize,
7718    values: &mut Vec<serde_json::Value>,
7719) -> String {
7720    if items.is_empty() {
7721        return format!("ARRAY[]::{}", cast);
7722    }
7723    let placeholders: Vec<String> = items
7724        .iter()
7725        .map(|item| {
7726            let placeholder = format!("${}", param_idx);
7727            *param_idx += 1;
7728            values.push(item.clone());
7729            placeholder
7730        })
7731        .collect();
7732    format!("ARRAY[{}]::{}", placeholders.join(", "), cast)
7733}
7734
7735/// One comparison against one column.
7736#[allow(clippy::too_many_arguments)]
7737fn comparison_sql(
7738    quoted: &str,
7739    column: &str,
7740    column_type: Option<&str>,
7741    op: &str,
7742    operand: &serde_json::Value,
7743    param_idx: &mut usize,
7744    values: &mut Vec<serde_json::Value>,
7745) -> Result<String, async_graphql::Error> {
7746    // `_cast` is not a comparison but a change of what is being compared: the
7747    // column becomes another type and the comparisons inside it apply to that.
7748    // A geometry and a geography answer different questions about the same
7749    // shape -- one on a plane, one on a sphere -- and this is how a client asks
7750    // for the other without the schema carrying two columns.
7751    if op == "_cast" {
7752        let serde_json::Value::Object(casts) = operand else {
7753            return Err(async_graphql::Error::new(
7754                "_cast takes an object naming the type to compare as",
7755            ));
7756        };
7757        let mut conditions = Vec::new();
7758        for (target, comparisons) in casts {
7759            // The GraphQL name of what is being compared as, and the
7760            // PostgreSQL type behind it. `String` is the one that differs:
7761            // a document compared as text is compared as `text`.
7762            let pg_type = match target.as_str() {
7763                "geometry" | "geography" => target.as_str(),
7764                "String" => "text",
7765                _ => {
7766                    return Err(async_graphql::Error::new(format!(
7767                        "cannot compare \"{}\" as \"{}\"",
7768                        column, target
7769                    )))
7770                }
7771            };
7772            let serde_json::Value::Object(ops) = comparisons else {
7773                continue;
7774            };
7775            let cast = format!("{}::{}", quoted, pg_type);
7776            for (nested_op, nested_operand) in ops {
7777                conditions.push(comparison_sql(
7778                    &cast,
7779                    column,
7780                    Some(pg_type),
7781                    nested_op,
7782                    nested_operand,
7783                    param_idx,
7784                    values,
7785                )?);
7786            }
7787        }
7788        return Ok(match conditions.len() {
7789            0 => "true".to_string(),
7790            1 => conditions.pop().expect("just counted"),
7791            _ => format!("({})", conditions.join(" AND ")),
7792        });
7793    }
7794
7795    // A spatial relation is a function of two shapes rather than an operator
7796    // between them, so it is written before the operator table is consulted.
7797    if let Some(function) = crate::input::bool_exp::postgis_function(op) {
7798        return postgis_sql(
7799            quoted,
7800            column_type,
7801            function,
7802            op,
7803            operand,
7804            param_idx,
7805            values,
7806        );
7807    }
7808
7809    // A tree comparison is an operator, but one whose operand has to be cast:
7810    // `?` is "any of these labels" for an ltree and "has this key" for a
7811    // jsonb, and PostgreSQL tells them apart by the operand's type alone.
7812    if let Some((operator, cast)) = crate::input::bool_exp::ltree_operator(op) {
7813        if cast.ends_with("[]") {
7814            let items = operand.as_array().ok_or_else(|| {
7815                async_graphql::Error::new(format!(
7816                    "the \"{}\" comparison on \"{}\" takes a list",
7817                    op, column
7818                ))
7819            })?;
7820            return Ok(format!(
7821                "{} {} {}",
7822                quoted,
7823                operator,
7824                sql_array(items, cast, param_idx, values)
7825            ));
7826        }
7827        let placeholder = format!("${}", param_idx);
7828        *param_idx += 1;
7829        values.push(operand.clone());
7830        return Ok(format!("{} {} {}::{}", quoted, operator, placeholder, cast));
7831    }
7832
7833    // The path language is a query over the document rather than a comparison
7834    // against one, so it is a function of the column and the path: `_exists`
7835    // asks whether the path selects anything, `_match` whether the predicate
7836    // it ends in holds.
7837    if let Some(function) = match op {
7838        "_jsonb_path_exists" => Some("jsonb_path_exists"),
7839        "_jsonb_path_match" => Some("jsonb_path_match"),
7840        _ => None,
7841    } {
7842        let placeholder = format!("${}", param_idx);
7843        *param_idx += 1;
7844        values.push(operand.clone());
7845        return Ok(format!(
7846            "{}({}, {}::jsonpath)",
7847            function, quoted, placeholder
7848        ));
7849    }
7850
7851    // Comparisons binding exactly one parameter, by the SQL they become.
7852    let binary = match op {
7853        "_eq" => Some("="),
7854        "_neq" => Some("<>"),
7855        "_gt" => Some(">"),
7856        "_gte" => Some(">="),
7857        "_lt" => Some("<"),
7858        "_lte" => Some("<="),
7859        "_like" => Some("LIKE"),
7860        "_nlike" => Some("NOT LIKE"),
7861        "_ilike" => Some("ILIKE"),
7862        "_nilike" => Some("NOT ILIKE"),
7863        "_similar" => Some("SIMILAR TO"),
7864        "_nsimilar" => Some("NOT SIMILAR TO"),
7865        "_regex" => Some("~"),
7866        "_nregex" => Some("!~"),
7867        "_iregex" => Some("~*"),
7868        "_niregex" => Some("!~*"),
7869        "_contains" => Some("@>"),
7870        "_contained_in" => Some("<@"),
7871        "_has_key" => Some("?"),
7872        _ => None,
7873    };
7874
7875    if let Some(sql_op) = binary {
7876        let placeholder = format!("${}", param_idx);
7877        *param_idx += 1;
7878        // A containment operand is a whole document, and `"latest"` is one --
7879        // a JSON string, which is not the same text as `latest`. Binding the
7880        // bare string answered `invalid input syntax for type json`, so what
7881        // goes over the wire is the value as it is written in JSON.
7882        values.push(match op {
7883            "_contains" | "_contained_in" => match operand {
7884                serde_json::Value::String(_)
7885                | serde_json::Value::Number(_)
7886                | serde_json::Value::Bool(_) => serde_json::Value::String(operand.to_string()),
7887                other => other.clone(),
7888            },
7889            _ => operand.clone(),
7890        });
7891        // A bound parameter arrives as text and PostgreSQL infers a type for
7892        // it from the operator, which works only while the inference is
7893        // unambiguous. `jsonb @> text` is not an operator at all; and `id =
7894        // $1` against an integer column answers `operator does not exist:
7895        // integer = text` the moment the value is one PostgreSQL cannot read
7896        // as a number -- a null, most obviously, which is how a client asks a
7897        // question it expects an empty answer to.
7898        //
7899        // So the operand says what it is. The containment and key operators
7900        // name the type the operator needs; everything else names the
7901        // column's, which is the type it is being compared against.
7902        let cast = match op {
7903            "_contains" | "_contained_in" => "::jsonb".to_string(),
7904            "_has_key" => "::text".to_string(),
7905            // Only where inference would otherwise pick text and be wrong. A
7906            // cast tells PostgreSQL what the *result* is, and it infers the
7907            // parameter feeding it as text -- so `$1::int4` bound with a
7908            // number sends binary int8 bytes into a text parameter and
7909            // answers `invalid byte sequence for encoding "UTF8"`. A value
7910            // PostgreSQL can read as a number needs no help; a null is the one
7911            // that does, because `id = $1` with nothing to infer from is
7912            // `integer = text`.
7913            _ if operand.is_null() => match column_type {
7914                Some(pg_type) => format!("::{}", pg_type),
7915                None => String::new(),
7916            },
7917            // A parameter arrives as `text`, and PostgreSQL then resolves the
7918            // operator by taking the *column* down to text where it can --
7919            // which is the wrong operator, and sometimes no operator at all.
7920            // `citext = text` compares case-sensitively against a
7921            // case-insensitive column; `uuid = text` does not exist. So a
7922            // written value names the type it is being compared against.
7923            //
7924            // Only a string: a number bound with a cast is sent as binary into
7925            // a parameter PostgreSQL has inferred as text, which is the
7926            // `invalid byte sequence for encoding "UTF8"` this used to answer.
7927            _ if operand.is_string() => match column_type {
7928                Some(pg_type) => format!("::{}", pg_type),
7929                None => String::new(),
7930            },
7931            _ => String::new(),
7932        };
7933        return Ok(format!("{} {} {}{}", quoted, sql_op, placeholder, cast));
7934    }
7935
7936    match op {
7937        "_is_null" => Ok(if operand.as_bool().unwrap_or(false) {
7938            format!("{} IS NULL", quoted)
7939        } else {
7940            format!("{} IS NOT NULL", quoted)
7941        }),
7942        "_in" | "_nin" => {
7943            let items = operand.as_array().ok_or_else(|| {
7944                async_graphql::Error::new(format!(
7945                    "the \"{}\" comparison on \"{}\" requires a list of values",
7946                    op, column
7947                ))
7948            })?;
7949            if items.is_empty() {
7950                // `IN ()` is not valid SQL. An empty `_in` matches nothing and
7951                // an empty `_nin` matches everything.
7952                return Ok(if op == "_in" { "false" } else { "true" }.to_string());
7953            }
7954            let mut placeholders = Vec::with_capacity(items.len());
7955            for item in items {
7956                // Cast only a null, for the reason the binary comparisons
7957                // give: a cast makes PostgreSQL infer the parameter as text.
7958                let cast = match (item.is_null() || item.is_string(), column_type) {
7959                    (true, Some(pg_type)) => format!("::{}", pg_type),
7960                    _ => String::new(),
7961                };
7962                placeholders.push(format!("${}{}", param_idx, cast));
7963                values.push(item.clone());
7964                *param_idx += 1;
7965            }
7966            Ok(format!(
7967                "{} {} ({})",
7968                quoted,
7969                if op == "_in" { "IN" } else { "NOT IN" },
7970                placeholders.join(", ")
7971            ))
7972        }
7973        "_has_keys_any" | "_has_keys_all" => {
7974            let items = operand.as_array().ok_or_else(|| {
7975                async_graphql::Error::new(format!(
7976                    "the \"{}\" comparison on \"{}\" requires a list of keys",
7977                    op, column
7978                ))
7979            })?;
7980            Ok(format!(
7981                "{} {} {}",
7982                quoted,
7983                if op == "_has_keys_any" { "?|" } else { "?&" },
7984                sql_array(items, "text[]", param_idx, values)
7985            ))
7986        }
7987        other => Err(async_graphql::Error::new(format!(
7988            "unsupported comparison \"{}\" on \"{}\"",
7989            other, column
7990        ))),
7991    }
7992}
7993
7994/// Build an `ORDER BY` clause from the `order_by` argument.
7995///
7996/// The argument is a list of single-column objects -- `[{name: asc}, {id:
7997/// desc}]` -- and the list is ordered, which is why it is a list and not one
7998/// object with several keys. Column names are checked against the table in the
7999/// schema cache before being quoted, so a name that is unknown, or crafted to
8000/// inject SQL, is rejected rather than interpolated. Returns an empty string
8001/// when no ordering was requested.
8002#[allow(clippy::too_many_arguments)] // one parameter per SQL clause
8003async fn build_order_by_clause(
8004    ctx: &ResolverContext<'_>,
8005    schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
8006    schema_name: &str,
8007    table_name: &str,
8008    type_name: &str,
8009    relationships: &HashMap<String, Vec<RelationshipField>>,
8010    reference: &str,
8011    names: &crate::names::NameOverrides,
8012) -> Result<String, async_graphql::Error> {
8013    let Ok(order_arg) = ctx.args.try_get("order_by") else {
8014        return Ok(String::new());
8015    };
8016
8017    let value = accessor_to_json(&order_arg);
8018    // A single object is accepted as a one-entry list, which is what a client
8019    // writing `order_by: {name: asc}` means and what Hasura reads it as.
8020    let entries: Vec<&serde_json::Value> = match &value {
8021        serde_json::Value::Array(items) => items.iter().collect(),
8022        serde_json::Value::Object(_) => vec![&value],
8023        serde_json::Value::Null => return Ok(String::new()),
8024        _ => {
8025            return Err(async_graphql::Error::new(
8026                "order_by takes an object or a list of them",
8027            ))
8028        }
8029    };
8030    if entries.is_empty() {
8031        return Ok(String::new());
8032    }
8033
8034    let guard = schema_cache
8035        .get()
8036        .await
8037        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8038    let cache = guard
8039        .as_ref()
8040        .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
8041    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8042    let table = cache
8043        .get_table(&qi)
8044        .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8045
8046    let mut terms = Vec::new();
8047    let mut alias_counter = 0usize;
8048    for entry in entries {
8049        order_terms_into(
8050            entry,
8051            cache,
8052            relationships,
8053            type_name,
8054            table,
8055            reference,
8056            names,
8057            &mut alias_counter,
8058            &mut terms,
8059        )?;
8060    }
8061
8062    if terms.is_empty() {
8063        return Ok(String::new());
8064    }
8065    Ok(format!(" ORDER BY {}", terms.join(", ")))
8066}
8067
8068/// Collect the `ORDER BY` terms one entry contributes.
8069///
8070/// A key whose value is a direction is a column of this table. A key whose
8071/// value is an object is something the row points at, and ordering by it is a
8072/// correlated subselect: one related row contributes its column, and many
8073/// contribute an aggregate. That is the whole difference between the two
8074/// sides, and PostgreSQL will take a scalar subquery anywhere a column goes.
8075#[allow(clippy::too_many_arguments)]
8076fn order_terms_into(
8077    entry: &serde_json::Value,
8078    cache: &SchemaCache,
8079    relationships: &HashMap<String, Vec<RelationshipField>>,
8080    type_name: &str,
8081    table: &postrust_core::schema_cache::Table,
8082    reference: &str,
8083    names: &crate::names::NameOverrides,
8084    alias_counter: &mut usize,
8085    terms: &mut Vec<String>,
8086) -> Result<(), async_graphql::Error> {
8087    let serde_json::Value::Object(map) = entry else {
8088        return Err(async_graphql::Error::new(
8089            "each order_by entry is an object mapping a column to a direction",
8090        ));
8091    };
8092    let available: &[RelationshipField] = relationships
8093        .get(type_name)
8094        .map(|r| r.as_slice())
8095        .unwrap_or(&[]);
8096
8097    for (key, value) in map {
8098        // A direction given as null is no direction. `order_by: {id:
8099        // $direction}` with nothing bound for `$direction` is how a client
8100        // makes an ordering optional without writing the query twice, and the
8101        // same goes for `{author: $author_order_by}`, which is a whole
8102        // ordering left out.
8103        if value.is_null() {
8104            continue;
8105        }
8106
8107        // A direction: this table's own column, or a function of its row.
8108        if let Some(name) = value.as_str() {
8109            let sql = crate::input::order_by::direction_sql(name).ok_or_else(|| {
8110                async_graphql::Error::new(format!(
8111                    "\"{}\" is not a sort direction; expected one of asc, desc, \
8112                     asc_nulls_first, asc_nulls_last, desc_nulls_first, desc_nulls_last",
8113                    name
8114                ))
8115            })?;
8116            let column = table_column_for(names, table, key);
8117            if table.get_column(column).is_some() {
8118                terms.push(format!(
8119                    "{}.{} {}",
8120                    reference,
8121                    postrust_sql::escape_ident(column),
8122                    sql
8123                ));
8124                continue;
8125            }
8126            // A computed field is a column as far as ordering is concerned:
8127            // the row is the argument, and the call is what is sorted on.
8128            let function = names
8129                .computed_source(&table.schema, &table.name, key)
8130                .unwrap_or(key);
8131            if let Some(definition) = table.get_computed_column(function) {
8132                terms.push(format!(
8133                    "{} {}",
8134                    computed_call(definition, &format!("{}.*", reference), reference),
8135                    sql
8136                ));
8137                continue;
8138            }
8139            return Err(async_graphql::Error::new(format!(
8140                "cannot order by unknown column \"{}\" on \"{}\"",
8141                key, table.name
8142            )));
8143        }
8144
8145        // An aggregate of the rows that point here.
8146        if let Some(rel) = key
8147            .strip_suffix("_aggregate")
8148            .and_then(|name| available.iter().find(|r| r.name == name && r.is_list))
8149        {
8150            aggregate_order_terms(value, rel, cache, reference, alias_counter, terms)?;
8151            continue;
8152        }
8153
8154        // A column of the row this one points at.
8155        if let Some(rel) = available.iter().find(|r| r.name == *key && !r.is_list) {
8156            let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, cache)
8157                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8158            if plan.columns.is_empty() {
8159                return Err(async_graphql::Error::new(format!(
8160                    "cannot order by \"{}\": it is not reached by a key",
8161                    key
8162                )));
8163            }
8164            *alias_counter += 1;
8165            let alias = format!("pgrst_ord_{}", alias_counter);
8166            let quoted_alias = postrust_sql::escape_ident(&alias);
8167            let correlation = plan
8168                .columns
8169                .iter()
8170                .map(|(local, foreign)| {
8171                    format!(
8172                        "{} = {}.{}",
8173                        format_args!("{}.{}", reference, postrust_sql::escape_ident(local)),
8174                        quoted_alias,
8175                        postrust_sql::escape_ident(foreign)
8176                    )
8177                })
8178                .collect::<Vec<_>>()
8179                .join(" AND ");
8180
8181            let target_qi = postrust_core::api_request::QualifiedIdentifier::new(
8182                &plan.foreign_schema,
8183                &plan.foreign_table,
8184            );
8185            let Some(target) = cache.get_table(&target_qi) else {
8186                return Err(async_graphql::Error::new(format!(
8187                    "unknown table \"{}\"",
8188                    plan.foreign_table
8189                )));
8190            };
8191
8192            // The related row's own terms, then wrapped one at a time: a
8193            // subquery yields one value, so each term is its own subselect.
8194            let mut nested = Vec::new();
8195            order_terms_into(
8196                value,
8197                cache,
8198                relationships,
8199                &rel.target_type,
8200                target,
8201                &quoted_alias,
8202                names,
8203                alias_counter,
8204                &mut nested,
8205            )?;
8206            for term in nested {
8207                let (expression, direction) = term
8208                    .rsplit_once(' ')
8209                    .map(|(e, d)| (e.to_string(), d.to_string()))
8210                    .unwrap_or((term.clone(), String::new()));
8211                terms.push(format!(
8212                    "(SELECT {} FROM {}.{} AS {} WHERE {}) {}",
8213                    expression,
8214                    postrust_sql::escape_ident(&plan.foreign_schema),
8215                    postrust_sql::escape_ident(&plan.foreign_table),
8216                    quoted_alias,
8217                    correlation,
8218                    direction
8219                ));
8220            }
8221            continue;
8222        }
8223
8224        return Err(async_graphql::Error::new(format!(
8225            "cannot order by \"{}\" on \"{}\"",
8226            key, table.name
8227        )));
8228    }
8229    Ok(())
8230}
8231
8232/// The `ORDER BY` terms for an aggregate of a row's children.
8233fn aggregate_order_terms(
8234    value: &serde_json::Value,
8235    rel: &RelationshipField,
8236    cache: &SchemaCache,
8237    reference: &str,
8238    alias_counter: &mut usize,
8239    terms: &mut Vec<String>,
8240) -> Result<(), async_graphql::Error> {
8241    let serde_json::Value::Object(spec) = value else {
8242        return Err(async_graphql::Error::new(
8243            "ordering by an aggregate takes an object, such as {count: desc}",
8244        ));
8245    };
8246    let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, cache)
8247        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8248    if plan.columns.is_empty() && plan.function.is_none() {
8249        return Err(async_graphql::Error::new(format!(
8250            "cannot order by an aggregate of \"{}\": it is not reached by a key",
8251            rel.name
8252        )));
8253    }
8254    // A computed relationship whose function takes more than the row cannot be
8255    // ordered by here: there is nowhere in `order_by` to write the arguments.
8256    if plan.function.is_some() && !rel.arguments.is_empty() {
8257        return Err(async_graphql::Error::new(format!(
8258            "cannot order by an aggregate of \"{}\": it takes arguments, and an \
8259             ordering has nowhere to write them",
8260            rel.name
8261        )));
8262    }
8263
8264    *alias_counter += 1;
8265    let alias = postrust_sql::escape_ident(&format!("pgrst_ord_{}", alias_counter));
8266    // A computed relationship is correlated by argument -- the function takes
8267    // the parent row -- where a key relationship is correlated by columns.
8268    let (source, correlation) = match &plan.function {
8269        Some(function) => {
8270            let session = plan.row_argument.as_ref().and_then(|row_argument| {
8271                computed_session_argument(cache, function, row_argument)
8272                    .map(|session| (row_argument.clone(), session))
8273            });
8274            let call = match session {
8275                Some((row_argument, session)) => format!(
8276                    "{} => {}, {} => {}",
8277                    postrust_sql::escape_ident(&row_argument),
8278                    reference,
8279                    postrust_sql::escape_ident(&session),
8280                    SESSION_ARGUMENT
8281                ),
8282                None => reference.to_string(),
8283            };
8284            (
8285                format!(
8286                    "{}.{}({})",
8287                    postrust_sql::escape_ident(&function.schema),
8288                    postrust_sql::escape_ident(&function.name),
8289                    call
8290                ),
8291                "true".to_string(),
8292            )
8293        }
8294        None => (
8295            format!(
8296                "{}.{}",
8297                postrust_sql::escape_ident(&plan.foreign_schema),
8298                postrust_sql::escape_ident(&plan.foreign_table)
8299            ),
8300            plan.columns
8301                .iter()
8302                .map(|(local, foreign)| {
8303                    format!(
8304                        "{}.{} = {}.{}",
8305                        reference,
8306                        postrust_sql::escape_ident(local),
8307                        alias,
8308                        postrust_sql::escape_ident(foreign)
8309                    )
8310                })
8311                .collect::<Vec<_>>()
8312                .join(" AND "),
8313        ),
8314    };
8315
8316    // `{count: desc}` is one term; `{max: {id: desc}}` is one per column.
8317    let mut wanted: Vec<(String, String)> = Vec::new();
8318    for (function, argument) in spec {
8319        // A direction given as null is no direction, as everywhere else an
8320        // ordering is read.
8321        if argument.is_null() {
8322            continue;
8323        }
8324        if function == "count" {
8325            let name = argument.as_str().unwrap_or_default();
8326            let Some(direction) = crate::input::order_by::direction_sql(name) else {
8327                return Err(async_graphql::Error::new(format!(
8328                    "\"{}\" is not a sort direction",
8329                    name
8330                )));
8331            };
8332            wanted.push(("count(*)".to_string(), direction.to_string()));
8333            continue;
8334        }
8335        let serde_json::Value::Object(columns) = argument else {
8336            continue;
8337        };
8338        for (column, direction) in columns {
8339            if direction.is_null() {
8340                continue;
8341            }
8342            let name = direction.as_str().unwrap_or_default();
8343            let Some(direction) = crate::input::order_by::direction_sql(name) else {
8344                return Err(async_graphql::Error::new(format!(
8345                    "\"{}\" is not a sort direction",
8346                    name
8347                )));
8348            };
8349            // The function comes from the generated input, not from the
8350            // request: a client can only name one that was offered.
8351            wanted.push((
8352                format!(
8353                    "{}({}.{})",
8354                    function,
8355                    alias,
8356                    postrust_sql::escape_ident(column)
8357                ),
8358                direction.to_string(),
8359            ));
8360        }
8361    }
8362
8363    for (expression, direction) in wanted {
8364        terms.push(format!(
8365            "(SELECT {} FROM {} AS {} WHERE {}) {}",
8366            expression, source, alias, correlation, direction
8367        ));
8368    }
8369    Ok(())
8370}
8371
8372/// The `DISTINCT ON (...)` prefix, and the ordering that has to go with it.
8373///
8374/// PostgreSQL keeps the first row of each DISTINCT ON group in the query's own
8375/// order, and picks arbitrarily where the ordering does not begin with the
8376/// distinct columns -- so which row survives would depend on the plan. Hasura
8377/// refuses that query rather than answering it, and so does this: prepending
8378/// the distinct columns instead produced an answer, and a wrong one, since
8379/// `ORDER BY "department", "department" DESC` is decided by its first term and
8380/// sorts ascending. Where nothing was ordered at all there is nothing to
8381/// disagree with, so the distinct columns become the ordering.
8382///
8383/// `written` is the ordering as its comma-separated terms, without the
8384/// keyword; the answer is in the same spelling.
8385fn distinct_on_clause(
8386    distinct_on: &[String],
8387    written: Option<&str>,
8388) -> Result<(String, Option<String>), async_graphql::Error> {
8389    if distinct_on.is_empty() {
8390        return Ok((String::new(), written.map(str::to_string)));
8391    }
8392    let terms: Vec<&str> = written
8393        .map(|written| written.split(", ").collect())
8394        .unwrap_or_default();
8395    // Terms are qualified and the distinct columns may not be, so they are
8396    // compared by the name itself.
8397    let column_of = |term: &str| {
8398        let expression = term.split_whitespace().next().unwrap_or(term);
8399        expression
8400            .rsplit_once('.')
8401            .map(|(_, name)| name)
8402            .unwrap_or(expression)
8403            .to_string()
8404    };
8405    let leading: Vec<String> = terms
8406        .iter()
8407        .take(distinct_on.len())
8408        .map(|term| column_of(term))
8409        .collect();
8410    if !terms.is_empty()
8411        && (leading.len() != distinct_on.len()
8412            || distinct_on
8413                .iter()
8414                .any(|column| !leading.contains(&column_of(column))))
8415    {
8416        return Err(validation_error(
8417            "\"distinct_on\" columns must match initial \"order_by\" columns",
8418        ));
8419    }
8420    let order = match terms.is_empty() {
8421        true => Some(distinct_on.join(", ")),
8422        false => written.map(str::to_string),
8423    };
8424    Ok((format!("DISTINCT ON ({}) ", distinct_on.join(", ")), order))
8425}
8426
8427/// Build the `DISTINCT ON (...)` prefix from the `distinct_on` argument.
8428///
8429/// PostgreSQL requires the leftmost `ORDER BY` terms to match the distinct
8430/// columns, and picks an arbitrary surviving row otherwise. The caller
8431/// prepends these terms to whatever ordering was asked for rather than
8432/// replacing it, so `distinct_on: [name]` with `order_by: [{id: desc}]` keeps
8433/// the highest id per name instead of an unpredictable one.
8434async fn build_distinct_on(
8435    ctx: &ResolverContext<'_>,
8436    schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
8437    schema_name: &str,
8438    table_name: &str,
8439    names: &crate::names::NameOverrides,
8440) -> Result<Vec<String>, async_graphql::Error> {
8441    let Ok(arg) = ctx.args.try_get("distinct_on") else {
8442        return Ok(Vec::new());
8443    };
8444    let value = accessor_to_json(&arg);
8445    let requested: Vec<String> = match &value {
8446        serde_json::Value::Array(items) => items
8447            .iter()
8448            .filter_map(|i| i.as_str().map(|s| s.to_string()))
8449            .collect(),
8450        serde_json::Value::String(one) => vec![one.clone()],
8451        _ => Vec::new(),
8452    };
8453    if requested.is_empty() {
8454        return Ok(Vec::new());
8455    }
8456
8457    let guard = schema_cache
8458        .get()
8459        .await
8460        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8461    let cache = guard
8462        .as_ref()
8463        .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
8464    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8465    let table = cache
8466        .get_table(&qi)
8467        .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8468
8469    let mut quoted = Vec::with_capacity(requested.len());
8470    for field in requested {
8471        let name = table_column_for(names, table, &field).to_string();
8472        if table.get_column(&name).is_none() {
8473            return Err(async_graphql::Error::new(format!(
8474                "cannot take distinct on unknown column \"{}\" of \"{}\"",
8475                field, table_name
8476            )));
8477        }
8478        quoted.push(postrust_sql::escape_ident(&name));
8479    }
8480    Ok(quoted)
8481}
8482
8483/// Build the SELECT-list expressions that embed relationships in one query.
8484///
8485/// The GraphQL mirror of the REST builder: each requested relationship becomes a
8486/// correlated subselect yielding JSON, so the whole selection comes back from
8487/// the parent query instead of one query per relationship per level.
8488/// The SELECT-list entries for any computed columns the selection asks for.
8489///
8490/// A computed column is a function of one argument of the table's own row
8491/// type, so it is not in `*` and has to be named. PostgreSQL's functional
8492/// notation reads `upper_name(author.*)` and `author.upper_name` as the same
8493/// call; the explicit form is written here because it says which function is
8494/// being called.
8495#[allow(clippy::too_many_arguments)] // the fields, their source, and the binding state
8496fn computed_projections<'a>(
8497    table: &postrust_core::schema_cache::Table,
8498    fields: impl IntoIterator<Item = SelectionField<'a>>,
8499    row_reference: &str,
8500    names: &crate::names::NameOverrides,
8501    schema_cache: &SchemaCache,
8502    param_idx: &mut usize,
8503    values: &mut Vec<serde_json::Value>,
8504) -> Result<Vec<String>, async_graphql::Error> {
8505    let mut projections = Vec::new();
8506    for field in fields {
8507        let name = field.name();
8508        // A real column wins, and the projection already carries it -- under
8509        // this name, whether or not that is the column's own.
8510        if table
8511            .get_column(table_column_for(names, table, name))
8512            .is_some()
8513        {
8514            continue;
8515        }
8516        // The field may be exposed under a name that was given rather than
8517        // the function's own, so the call is looked up from either side.
8518        let function = names
8519            .computed_source(&table.schema, &table.name, name)
8520            .unwrap_or(name);
8521        let Some(computed) = table.get_computed_column(function) else {
8522            continue;
8523        };
8524        let arguments = crate::schema::computed_caller_arguments(computed, schema_cache);
8525        let given = match arguments.is_empty() {
8526            true => None,
8527            false => embed_arguments(field).remove("args"),
8528        };
8529        projections.push(format!(
8530            "{} AS {}",
8531            computed_column_call(
8532                computed,
8533                row_reference,
8534                name,
8535                &arguments,
8536                given.as_ref(),
8537                param_idx,
8538                values,
8539            )?,
8540            postrust_sql::escape_ident(name)
8541        ));
8542    }
8543    Ok(projections)
8544}
8545
8546/// The call behind a computed field, including whatever the caller passed.
8547///
8548/// The ordinary case is a function of the row alone, which is written
8549/// positionally: that is the call REST writes, and the one a client that never
8550/// heard of `args` is asking for. Anything else has to be written by name --
8551/// the row is then not the only parameter and may not be the first -- so the
8552/// row, the session where the function asks for one, and each argument the
8553/// caller gave are all named.
8554fn computed_column_call(
8555    computed: &postrust_core::schema_cache::ComputedColumn,
8556    row: &str,
8557    field_name: &str,
8558    arguments: &[(String, String, bool)],
8559    given: Option<&serde_json::Value>,
8560    param_idx: &mut usize,
8561    values: &mut Vec<serde_json::Value>,
8562) -> Result<String, async_graphql::Error> {
8563    if arguments.is_empty() {
8564        return Ok(computed_call(computed, row, row));
8565    }
8566    let Some(row_argument) = &computed.row_argument else {
8567        return Ok(computed_call(computed, row, row));
8568    };
8569    let function = format!(
8570        "{}.{}",
8571        postrust_sql::escape_ident(&computed.function.schema),
8572        postrust_sql::escape_ident(&computed.function.name)
8573    );
8574    let mut passed = vec![format!(
8575        "{} => {}",
8576        postrust_sql::escape_ident(row_argument),
8577        row
8578    )];
8579    if let Some(session) = &computed.session_argument {
8580        passed.push(format!(
8581            "{} => {}",
8582            postrust_sql::escape_ident(session),
8583            SESSION_ARGUMENT
8584        ));
8585    }
8586    for (name, pg_type, required) in arguments {
8587        match given.and_then(|given| given.get(name)) {
8588            None if *required => {
8589                return Err(async_graphql::Error::new(format!(
8590                    "{} needs the argument \"{}\"",
8591                    field_name, name
8592                )))
8593            }
8594            // Left out is left out, so the function's own default applies.
8595            None => continue,
8596            Some(value) => {
8597                passed.push(format!(
8598                    "{} => ${}::{}",
8599                    postrust_sql::escape_ident(name),
8600                    param_idx,
8601                    pg_type
8602                ));
8603                *param_idx += 1;
8604                values.push(value.clone());
8605            }
8606        }
8607    }
8608    Ok(format!("{}({})", function, passed.join(", ")))
8609}
8610
8611/// The `count(...)` a selection asked for.
8612///
8613/// `count` alone is `count(*)`, which counts rows. `count(columns: [a])` is
8614/// `count("a")`, which counts the rows where `a` is not null -- a different
8615/// number, and the one the client asked for. `distinct: true` counts the
8616/// distinct values among them, and several columns are counted as the row
8617/// they make, which is how PostgreSQL counts more than one thing at once.
8618///
8619/// The column names come from the generated enum, so a selection can only
8620/// name a column the table has; what it may not know is the column's own name
8621/// where the schema exposes it under another.
8622fn count_expression(
8623    field: async_graphql::SelectionField<'_>,
8624    table: (&str, &str),
8625    alias: Option<&str>,
8626    names: &crate::names::NameOverrides,
8627) -> String {
8628    let arguments = embed_arguments(field);
8629    let requested = match arguments.get("columns") {
8630        Some(serde_json::Value::Array(items)) => items
8631            .iter()
8632            .filter_map(|item| item.as_str())
8633            .collect::<Vec<_>>(),
8634        Some(serde_json::Value::String(one)) => vec![one.as_str()],
8635        _ => Vec::new(),
8636    };
8637    if requested.is_empty() {
8638        return "count(*)".to_string();
8639    }
8640    let columns: Vec<String> = requested
8641        .into_iter()
8642        .map(|column| {
8643            let (schema, name) = table;
8644            let source = column_for(names, schema, name, column);
8645            match alias {
8646                Some(alias) => format!(
8647                    "{}.{}",
8648                    postrust_sql::escape_ident(alias),
8649                    postrust_sql::escape_ident(source)
8650                ),
8651                None => postrust_sql::escape_ident(source),
8652            }
8653        })
8654        .collect();
8655    // One column counts itself; several count the row they make, since
8656    // `count(a, b)` is not a call PostgreSQL has.
8657    let counted = match columns.len() {
8658        1 => columns.into_iter().next().unwrap_or_default(),
8659        _ => format!("({})", columns.join(", ")),
8660    };
8661    let distinct = matches!(
8662        arguments.get("distinct"),
8663        Some(serde_json::Value::Bool(true))
8664    );
8665    match distinct {
8666        true => format!("count(DISTINCT {})", counted),
8667        false => format!("count({})", counted),
8668    }
8669}
8670
8671/// The SELECT list for a nested aggregate.
8672///
8673/// `articles_aggregate { aggregate { count } nodes { title } }` becomes one
8674/// row per parent, correlated the way any embed is. Both halves are aggregates
8675/// over the same correlated set, so they go in one select list rather than two
8676/// queries -- `count(*)` and `json_agg(...)` read the same rows.
8677#[allow(clippy::too_many_arguments)] // the recursion carries its whole context
8678fn nested_aggregate_select(
8679    caller: &crate::role::Caller<'_>,
8680    selection: async_graphql::SelectionField<'_>,
8681    child_alias: &str,
8682    schema_cache: &SchemaCache,
8683    relationships: &HashMap<String, Vec<RelationshipField>>,
8684    target_type: &str,
8685    child_table: Option<&postrust_core::schema_cache::Table>,
8686    max_rows: Option<i64>,
8687    alias_counter: &mut usize,
8688    param_idx: &mut usize,
8689    values: &mut Vec<serde_json::Value>,
8690    names: &crate::names::NameOverrides,
8691) -> Result<String, async_graphql::Error> {
8692    use crate::schema::aggregate as agg;
8693
8694    let mut parts: Vec<String> = Vec::new();
8695
8696    for child in selection.selection_set() {
8697        match child.name() {
8698            "aggregate" => {
8699                let of_table = child_table
8700                    .map(|table| (table.schema.as_str(), table.name.as_str()))
8701                    .unwrap_or(("", ""));
8702                // Each `count` is answered under the name it was asked for,
8703                // since two of them may count different things. Every other
8704                // aggregate is one object read under however many names, so
8705                // its columns are the union of what all of them named.
8706                let mut counts: Vec<(String, String)> = Vec::new();
8707                let mut wanted: BTreeMap<&str, Vec<String>> = BTreeMap::new();
8708                for function in child.selection_set() {
8709                    if function.name() == "count" {
8710                        counts.push((
8711                            function.alias().unwrap_or("count").to_string(),
8712                            count_expression(function, of_table, Some(child_alias), names),
8713                        ));
8714                        continue;
8715                    }
8716                    let sql_function = agg::NUMERIC_AGGREGATES
8717                        .iter()
8718                        .chain(agg::ORDERED_AGGREGATES.iter())
8719                        .find(|(name, _)| *name == function.name())
8720                        .map(|(name, _)| *name);
8721                    let Some(sql_function) = sql_function else {
8722                        continue;
8723                    };
8724                    let columns = wanted.entry(sql_function).or_default();
8725                    for column in function.selection_set() {
8726                        let name = column.name().to_string();
8727                        // Answered by the schema, not a column.
8728                        if name != "__typename" && !columns.contains(&name) {
8729                            columns.push(name);
8730                        }
8731                    }
8732                }
8733                // Answered whether or not it was asked for, for the reason
8734                // the root aggregate answers it.
8735                let mut fields = match counts.iter().any(|(key, _)| key == "count") {
8736                    true => Vec::new(),
8737                    false => vec!["'count', count(*)".to_string()],
8738                };
8739                for (key, expression) in &counts {
8740                    fields.push(format!(
8741                        "{}, {}",
8742                        postrust_sql::quote_literal(key),
8743                        expression
8744                    ));
8745                }
8746                for (sql_function, named) in &wanted {
8747                    let columns: Vec<String> = named
8748                        .iter()
8749                        .map(|column| {
8750                            let source = child_table
8751                                .map(|table| table_column_for(names, table, column))
8752                                .unwrap_or(column.as_str());
8753                            format!(
8754                                "{}, {}({}.{})",
8755                                postrust_sql::quote_literal(column),
8756                                sql_function,
8757                                postrust_sql::escape_ident(child_alias),
8758                                postrust_sql::escape_ident(source)
8759                            )
8760                        })
8761                        .collect();
8762                    // Pushed even when empty, as at the root: `max { __typename }`
8763                    // is an object with nothing in it, not a null.
8764                    fields.push(format!(
8765                        "'{}', json_build_object({})",
8766                        sql_function,
8767                        columns.join(", ")
8768                    ));
8769                }
8770                parts.push(format!(
8771                    "json_build_object({}) AS {}",
8772                    fields.join(", "),
8773                    postrust_sql::escape_ident("aggregate")
8774                ));
8775            }
8776            // `nodes` under an aggregate is a rows selection like any other:
8777            // what it names may be a column, a computed field, or a
8778            // relationship of its own, and the last of those is a further
8779            // correlated subselect rather than a column of this one.
8780            "nodes" => {
8781                let embeds = build_embed_expressions(
8782                    caller,
8783                    schema_cache,
8784                    relationships,
8785                    target_type,
8786                    child_alias,
8787                    child.selection_set(),
8788                    max_rows,
8789                    alias_counter,
8790                    param_idx,
8791                    values,
8792                    names,
8793                )?;
8794                let mut columns: Vec<String> = Vec::new();
8795                for column in child.selection_set() {
8796                    let name = column.name();
8797                    if name == "__typename" || embeds.iter().any(|(field, _)| field == name) {
8798                        continue;
8799                    }
8800                    columns.push(format!(
8801                        "{}, {}",
8802                        postrust_sql::quote_literal(name),
8803                        column_expression(child_table, child_alias, name, names)
8804                    ));
8805                }
8806                for (field, expression) in &embeds {
8807                    columns.push(format!(
8808                        "{}, {}",
8809                        postrust_sql::quote_literal(field),
8810                        expression
8811                    ));
8812                }
8813                let row = if columns.is_empty() {
8814                    format!("row_to_json({})", postrust_sql::escape_ident(child_alias))
8815                } else {
8816                    format!("json_build_object({})", columns.join(", "))
8817                };
8818                parts.push(format!(
8819                    "COALESCE(json_agg({}), '[]'::json) AS {}",
8820                    row,
8821                    postrust_sql::escape_ident("nodes")
8822                ));
8823            }
8824            _ => {}
8825        }
8826    }
8827
8828    if parts.is_empty() {
8829        // A selection of nothing but `__typename`. One row, no columns, is not
8830        // valid SQL; a count nobody reads is.
8831        parts.push("count(*) AS pgrst_empty".to_string());
8832    }
8833    Ok(parts.join(", "))
8834}
8835
8836/// How one named field of a row is read, given the alias the row goes by.
8837///
8838/// A column is itself; a computed field is the call that produces it. Which of
8839/// the two a name is depends on the table, so this is the one place that asks.
8840fn column_expression(
8841    table: Option<&postrust_core::schema_cache::Table>,
8842    alias: &str,
8843    name: &str,
8844    names: &crate::names::NameOverrides,
8845) -> String {
8846    let column = table
8847        .map(|t| table_column_for(names, t, name))
8848        .unwrap_or(name);
8849    let plain = format!(
8850        "{}.{}",
8851        postrust_sql::escape_ident(alias),
8852        postrust_sql::escape_ident(column)
8853    );
8854    let computed = table
8855        .filter(|t| t.get_column(column).is_none())
8856        .and_then(|t| {
8857            let function = names
8858                .computed_source(&t.schema, &t.name, name)
8859                .unwrap_or(name);
8860            t.get_computed_column(function)
8861        });
8862    match computed {
8863        Some(definition) => computed_call(
8864            definition,
8865            &format!("{}.*", postrust_sql::escape_ident(alias)),
8866            &postrust_sql::escape_ident(alias),
8867        ),
8868        None => plain,
8869    }
8870}
8871
8872/// Render `order_by` terms against a table, qualified with an alias.
8873///
8874/// The root field's ordering reads its argument from the resolver context and
8875/// needs the schema cache asynchronously; an embed already holds both, so this
8876/// takes the value directly. Columns are checked against the table before they
8877/// are quoted, so an unknown or crafted name is refused rather than
8878/// interpolated.
8879fn order_terms(
8880    order: &serde_json::Value,
8881    schema_cache: &SchemaCache,
8882    schema_name: &str,
8883    table_name: &str,
8884    alias: &str,
8885    names: &crate::names::NameOverrides,
8886) -> Result<Option<String>, async_graphql::Error> {
8887    let entries: Vec<&serde_json::Value> = match order {
8888        serde_json::Value::Array(items) => items.iter().collect(),
8889        serde_json::Value::Object(_) => vec![order],
8890        _ => return Ok(None),
8891    };
8892
8893    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8894    let table = schema_cache
8895        .get_table(&qi)
8896        .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8897
8898    let mut terms = Vec::new();
8899    for entry in entries {
8900        let serde_json::Value::Object(map) = entry else {
8901            continue;
8902        };
8903        for (field, direction) in map {
8904            // A direction given as null is no direction, as at the root.
8905            if direction.is_null() {
8906                continue;
8907            }
8908            let column = table_column_for(names, table, field);
8909            if table.get_column(column).is_none() {
8910                return Err(async_graphql::Error::new(format!(
8911                    "cannot order by unknown column \"{}\" on \"{}\"",
8912                    field, table_name
8913                )));
8914            }
8915            let name = direction.as_str().unwrap_or_default();
8916            let sql = crate::input::order_by::direction_sql(name).ok_or_else(|| {
8917                async_graphql::Error::new(format!("\"{}\" is not a sort direction", name))
8918            })?;
8919            terms.push(format!(
8920                "{}.{} {}",
8921                postrust_sql::escape_ident(alias),
8922                postrust_sql::escape_ident(column),
8923                sql
8924            ));
8925        }
8926    }
8927
8928    Ok(if terms.is_empty() {
8929        None
8930    } else {
8931        Some(terms.join(", "))
8932    })
8933}
8934
8935/// Whether a to-one relationship always has a row at the other end.
8936///
8937/// It does when this row's own key columns cannot be null: a foreign key
8938/// guarantees a matching row for every value, so a `NOT NULL` key is a
8939/// relationship that cannot be absent, and the field is non-null. A client
8940/// generating types then gets `author` rather than `author | null`, which is
8941/// what the schema actually promises.
8942///
8943/// Only where a foreign key says so. A computed relationship is a function
8944/// call, and a one-to-one reached through the *child's* key is a row that may
8945/// simply not exist.
8946fn always_present(rel: &RelationshipField, table: &postrust_core::schema_cache::Table) -> bool {
8947    use postrust_core::schema_cache::{Cardinality, Relationship};
8948    let Relationship::ForeignKey { cardinality, .. } = &rel.relationship else {
8949        return false;
8950    };
8951    match cardinality {
8952        Cardinality::M2O { .. } => {}
8953        Cardinality::O2O {
8954            is_parent: false, ..
8955        } => {}
8956        _ => return false,
8957    }
8958    let columns = cardinality.columns();
8959    !columns.is_empty()
8960        && columns.iter().all(|(local, _)| {
8961            table
8962                .get_column(local)
8963                .is_some_and(|column| !column.nullable)
8964        })
8965}
8966
8967/// Whether the row at the other end of a relationship carries the key.
8968///
8969/// If it does, this row is written first and its key is pushed down; if this
8970/// row's own column carries it, the other row is written first and its key is
8971/// read back. Cardinality alone does not answer it: a one-to-one is one row in
8972/// either direction, and which side holds the foreign key is the whole
8973/// difference between the two orders.
8974fn child_holds_the_key(relationship: &postrust_core::schema_cache::Relationship) -> bool {
8975    use postrust_core::schema_cache::{Cardinality, Relationship};
8976    match relationship {
8977        Relationship::ForeignKey { cardinality, .. } => match cardinality {
8978            Cardinality::M2O { .. } => false,
8979            Cardinality::O2O { is_parent, .. } => *is_parent,
8980            _ => true,
8981        },
8982        Relationship::Computed { .. } => true,
8983    }
8984}
8985
8986/// The name of a function's session parameter, if it has one.
8987fn computed_session_argument(
8988    cache: &SchemaCache,
8989    function: &postrust_core::api_request::QualifiedIdentifier,
8990    row_argument: &str,
8991) -> Option<String> {
8992    let _ = row_argument;
8993    cache
8994        .routines
8995        .get(function)
8996        .into_iter()
8997        .flatten()
8998        .find(|routine| routine.name == function.name)?
8999        .params
9000        .iter()
9001        .find(|param| {
9002            param.name == "hasura_session" && matches!(param.param_type.as_str(), "json" | "jsonb")
9003        })
9004        .map(|param| param.name.clone())
9005}
9006
9007/// The name of the input holding a computed relationship's own arguments.
9008fn computed_args_type_name(type_name: &str, field: &str) -> String {
9009    format!("{}_{}_args", type_name, field)
9010}
9011
9012/// The argument list a computed relationship's function is called with.
9013///
9014/// `None` where the parent row is the only thing it takes -- the ordinary case,
9015/// and the positional call the REST surface writes. Anything else is written by
9016/// name: the row, the session where the function asks for one, and whatever the
9017/// client put under `args`.
9018fn computed_arguments(
9019    relationship: &RelationshipField,
9020    plan: &postrust_core::embed::EmbedPlan,
9021    parent_row: &str,
9022    given: Option<&serde_json::Value>,
9023    param_idx: &mut usize,
9024    values: &mut Vec<serde_json::Value>,
9025    schema_cache: &SchemaCache,
9026) -> Result<Option<String>, async_graphql::Error> {
9027    let (Some(function), Some(row_argument)) = (&plan.function, &plan.row_argument) else {
9028        return Ok(None);
9029    };
9030    let session = schema_cache
9031        .routines
9032        .get(function)
9033        .into_iter()
9034        .flatten()
9035        .find(|routine| routine.name == function.name)
9036        .and_then(|routine| {
9037            routine
9038                .params
9039                .iter()
9040                .find(|param| {
9041                    param.name == "hasura_session"
9042                        && matches!(param.param_type.as_str(), "json" | "jsonb")
9043                })
9044                .map(|param| param.name.clone())
9045        });
9046    if relationship.arguments.is_empty() && session.is_none() {
9047        return Ok(None);
9048    }
9049
9050    let mut passed = vec![format!(
9051        "{} => {}",
9052        postrust_sql::escape_ident(row_argument),
9053        parent_row
9054    )];
9055    if let Some(session) = session {
9056        passed.push(format!(
9057            "{} => {}",
9058            postrust_sql::escape_ident(&session),
9059            SESSION_ARGUMENT
9060        ));
9061    }
9062    for (name, pg_type, required) in &relationship.arguments {
9063        match given.and_then(|given| given.get(name)) {
9064            None if *required => {
9065                return Err(async_graphql::Error::new(format!(
9066                    "{} needs the argument \"{}\"",
9067                    relationship.name, name
9068                )))
9069            }
9070            // Left out is left out, so the function's own default applies.
9071            None => continue,
9072            Some(value) => {
9073                passed.push(format!(
9074                    "{} => ${}::{}",
9075                    postrust_sql::escape_ident(name),
9076                    param_idx,
9077                    pg_type
9078                ));
9079                *param_idx += 1;
9080                values.push(value.clone());
9081            }
9082        }
9083    }
9084    Ok(Some(passed.join(", ")))
9085}
9086
9087/// The arguments written on an embedded field, as JSON.
9088fn embed_arguments(field: async_graphql::SelectionField<'_>) -> HashMap<String, serde_json::Value> {
9089    field
9090        .arguments()
9091        .map(|args| {
9092            args.into_iter()
9093                .map(|(name, value)| {
9094                    (
9095                        name.to_string(),
9096                        plain_numbers(value.into_json().unwrap_or(serde_json::Value::Null)),
9097                    )
9098                })
9099                .collect()
9100        })
9101        .unwrap_or_default()
9102}
9103
9104/// What an embed's arguments narrow its child rows to: a `DISTINCT ON`
9105/// prefix, a predicate, an ordering, a limit and an offset, in the order the
9106/// SQL takes them.
9107type Narrowing = (String, Option<String>, Option<String>, Option<i64>, i64);
9108
9109/// What an embed's arguments narrow its child rows to.
9110///
9111/// A list and an aggregate of that same list take the same four arguments and
9112/// mean the same thing by them; only what is done with the surviving rows
9113/// differs, so the reading of the arguments is shared.
9114#[allow(clippy::too_many_arguments)] // one parameter per SQL clause, plus the binding state
9115fn embed_narrowing(
9116    arguments: &HashMap<String, serde_json::Value>,
9117    plan: &postrust_core::embed::EmbedPlan,
9118    schema_cache: &SchemaCache,
9119    relationships: &HashMap<String, Vec<RelationshipField>>,
9120    target_type: &str,
9121    child_alias: &str,
9122    max_rows: Option<i64>,
9123    param_idx: &mut usize,
9124    values: &mut Vec<serde_json::Value>,
9125    names: &crate::names::NameOverrides,
9126    caller: &crate::role::Caller<'_>,
9127) -> Result<Narrowing, async_graphql::Error> {
9128    // The child's own permission, which is the whole reason an embed is a
9129    // place this has to be applied: `author { articles { ... } }` reads two
9130    // tables, and the rule on the second is not the rule on the first.
9131    let permission =
9132        permission_predicate(caller, names, &plan.foreign_schema, &plan.foreign_table)?;
9133    let requested = arguments.get("where").filter(|v| !v.is_null()).cloned();
9134    let child_where = match and_predicates(requested, permission) {
9135        Some(expression) => {
9136            let child_scope = WhereScope::for_alias(
9137                &plan.foreign_schema,
9138                &plan.foreign_table,
9139                child_alias,
9140                target_type,
9141                schema_cache,
9142                relationships,
9143                names,
9144            )
9145            .for_caller(*caller);
9146            let mut nested_alias = 0usize;
9147            build_condition(
9148                &expression,
9149                &child_scope,
9150                param_idx,
9151                values,
9152                &mut nested_alias,
9153            )?
9154        }
9155        None => None,
9156    };
9157
9158    let child_order = match arguments.get("order_by") {
9159        Some(order) if !order.is_null() => order_terms(
9160            order,
9161            schema_cache,
9162            &plan.foreign_schema,
9163            &plan.foreign_table,
9164            child_alias,
9165            names,
9166        )?,
9167        _ => None,
9168    };
9169
9170    // A limit written on the embed is what the client asked for; the
9171    // configured ceiling still applies as an upper bound, the same way it
9172    // does at the top level -- and so does the child's own permission, which
9173    // bounds rows per parent here rather than per query.
9174    let ceiling = match (
9175        max_rows,
9176        crate::role::read_limit(caller, names, &plan.foreign_schema, &plan.foreign_table),
9177    ) {
9178        (Some(configured), Some(granted)) => Some(configured.min(granted)),
9179        (only, None) | (None, only) => only,
9180    };
9181    let child_limit = match arguments.get("limit").and_then(|v| v.as_i64()) {
9182        Some(requested) => match ceiling {
9183            Some(ceiling) => Some(requested.min(ceiling)),
9184            None => Some(requested),
9185        },
9186        None => ceiling,
9187    };
9188    let child_offset = arguments
9189        .get("offset")
9190        .and_then(|v| v.as_i64())
9191        .unwrap_or(0);
9192
9193    // `author { articles(distinct_on: [title], order_by: {title: asc}) }` --
9194    // one article per title, the same question the root field answers and
9195    // under the same rule about what may be ordered by.
9196    let requested = match arguments.get("distinct_on") {
9197        Some(serde_json::Value::Array(items)) => items
9198            .iter()
9199            .filter_map(|item| item.as_str())
9200            .collect::<Vec<_>>(),
9201        Some(serde_json::Value::String(one)) => vec![one.as_str()],
9202        _ => Vec::new(),
9203    };
9204    let mut distinct_on = Vec::with_capacity(requested.len());
9205    if !requested.is_empty() {
9206        let qi = postrust_core::api_request::QualifiedIdentifier::new(
9207            &plan.foreign_schema,
9208            &plan.foreign_table,
9209        );
9210        let table = schema_cache.get_table(&qi).ok_or_else(|| {
9211            async_graphql::Error::new(format!("unknown table \"{}\"", plan.foreign_table))
9212        })?;
9213        for field in requested {
9214            let column = table_column_for(names, table, field).to_string();
9215            if table.get_column(&column).is_none() {
9216                return Err(async_graphql::Error::new(format!(
9217                    "cannot take distinct on unknown column \"{}\" of \"{}\"",
9218                    field, plan.foreign_table
9219                )));
9220            }
9221            distinct_on.push(format!(
9222                "{}.{}",
9223                postrust_sql::escape_ident(child_alias),
9224                postrust_sql::escape_ident(&column)
9225            ));
9226        }
9227    }
9228    let (distinct, child_order) = distinct_on_clause(&distinct_on, child_order.as_deref())?;
9229
9230    Ok((
9231        distinct,
9232        child_where,
9233        child_order,
9234        child_limit,
9235        child_offset,
9236    ))
9237}
9238
9239#[allow(clippy::too_many_arguments)] // one parameter per SQL clause, plus the binding state
9240fn build_embed_expressions<'a>(
9241    caller: &crate::role::Caller<'_>,
9242    schema_cache: &SchemaCache,
9243    relationships: &HashMap<String, Vec<RelationshipField>>,
9244    type_name: &str,
9245    parent_alias: &str,
9246    fields: impl IntoIterator<Item = SelectionField<'a>>,
9247    max_rows: Option<i64>,
9248    alias_counter: &mut usize,
9249    param_idx: &mut usize,
9250    values: &mut Vec<serde_json::Value>,
9251    names: &crate::names::NameOverrides,
9252) -> Result<Vec<(String, String)>, async_graphql::Error> {
9253    let Some(available) = relationships.get(type_name) else {
9254        return Ok(Vec::new());
9255    };
9256
9257    let mut expressions = Vec::new();
9258
9259    for field in fields {
9260        // `<relationship>_aggregate` is the same embed with an aggregate
9261        // select list, so it is resolved here rather than by a resolver of its
9262        // own -- the correlation is what makes it a per-parent answer.
9263        let aggregate_of = field
9264            .name()
9265            .strip_suffix("_aggregate")
9266            .and_then(|name| available.iter().find(|r| r.name == name && r.is_list));
9267
9268        if let Some(rel) = aggregate_of {
9269            let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, schema_cache)
9270                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9271            *alias_counter += 1;
9272            let child_alias = format!("a{}", alias_counter);
9273
9274            // The same narrowing an embedded list takes. `where` here decides
9275            // which rows are counted, not which are returned, so it goes on the
9276            // set the aggregate reads rather than on the answer.
9277            let arguments = embed_arguments(field);
9278            let (child_distinct, child_where, child_order, child_limit, child_offset) =
9279                embed_narrowing(
9280                    &arguments,
9281                    &plan,
9282                    schema_cache,
9283                    relationships,
9284                    &rel.target_type,
9285                    &child_alias,
9286                    max_rows,
9287                    param_idx,
9288                    values,
9289                    names,
9290                    caller,
9291                )?;
9292
9293            let child_table =
9294                schema_cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
9295                    &plan.foreign_schema,
9296                    &plan.foreign_table,
9297                ));
9298            let select = nested_aggregate_select(
9299                caller,
9300                field,
9301                &child_alias,
9302                schema_cache,
9303                relationships,
9304                &rel.target_type,
9305                child_table,
9306                max_rows,
9307                alias_counter,
9308                param_idx,
9309                values,
9310                names,
9311            )?;
9312
9313            let call = computed_arguments(
9314                rel,
9315                &plan,
9316                &postrust_sql::escape_ident(parent_alias),
9317                arguments.get("args"),
9318                param_idx,
9319                values,
9320                schema_cache,
9321            )?;
9322            let expression = plan
9323                .aggregate_expression(
9324                    parent_alias,
9325                    &postrust_sql::escape_ident(parent_alias),
9326                    &child_alias,
9327                    &select,
9328                    child_limit,
9329                    child_offset,
9330                    child_where.as_deref(),
9331                    child_order.as_deref(),
9332                    call.as_deref(),
9333                    &child_distinct,
9334                    // A GraphQL body is JSON throughout -- nothing here
9335                    // renders a row as text -- and Hasura keeps the order the
9336                    // fields were selected in.
9337                    postrust_core::EmbedRendering::Verbatim,
9338                )
9339                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9340            expressions.push((field.name().to_string(), expression));
9341            continue;
9342        }
9343
9344        let Some(rel) = available.iter().find(|r| r.name == field.name()) else {
9345            continue;
9346        };
9347
9348        let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, schema_cache)
9349            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9350
9351        *alias_counter += 1;
9352        let child_alias = format!("e{}", alias_counter);
9353
9354        let nested = build_embed_expressions(
9355            caller,
9356            schema_cache,
9357            relationships,
9358            &rel.target_type,
9359            &child_alias,
9360            field.selection_set(),
9361            max_rows,
9362            alias_counter,
9363            param_idx,
9364            values,
9365            names,
9366        )?;
9367
9368        // The arguments written on the embed itself.
9369        let arguments = embed_arguments(field);
9370        let (child_distinct, child_where, child_order, child_limit, child_offset) =
9371            embed_narrowing(
9372                &arguments,
9373                &plan,
9374                schema_cache,
9375                relationships,
9376                &rel.target_type,
9377                &child_alias,
9378                max_rows,
9379                param_idx,
9380                values,
9381                names,
9382                caller,
9383            )?;
9384
9385        // Leaf fields are columns; anything that resolved to a relationship is
9386        // an expression instead.
9387        let child_relationships = relationships.get(&rel.target_type);
9388        let child_qi = postrust_core::api_request::QualifiedIdentifier::new(
9389            &plan.foreign_schema,
9390            &plan.foreign_table,
9391        );
9392        let child_table = schema_cache.get_table(&child_qi);
9393        let mut parts: Vec<String> = Vec::new();
9394        for sub in field.selection_set() {
9395            let name = sub.name();
9396            let is_relationship = child_relationships
9397                .map(|rels| {
9398                    rels.iter().any(|r| {
9399                        r.name == name || (r.is_list && format!("{}_aggregate", r.name) == name)
9400                    })
9401                })
9402                .unwrap_or(false);
9403            // `__typename` is answered by the schema, not the row -- and it is
9404            // asked for here constantly: Apollo Client adds it to every
9405            // selection, and a Federation router to every entity reference.
9406            if is_relationship || name == "__typename" {
9407                continue;
9408            }
9409            // A computed column inside an embed is the same call, against the
9410            // child's alias rather than the table.
9411            let column = child_table
9412                .map(|t| table_column_for(names, t, name))
9413                .unwrap_or(name);
9414            let computed = child_table
9415                .filter(|t| t.get_column(column).is_none())
9416                .and_then(|t| {
9417                    let function = names
9418                        .computed_source(&t.schema, &t.name, name)
9419                        .unwrap_or(name);
9420                    t.get_computed_column(function)
9421                });
9422            match computed {
9423                Some(definition) => parts.push(format!(
9424                    "{} AS {}",
9425                    computed_call(
9426                        definition,
9427                        &format!("{}.*", postrust_sql::escape_ident(&child_alias)),
9428                        &postrust_sql::escape_ident(&child_alias),
9429                    ),
9430                    postrust_sql::escape_ident(name)
9431                )),
9432                // A column the child exposes under another name is selected as
9433                // that name, since the row it lands in is the client's.
9434                None if column != name => parts.push(format!(
9435                    "{} AS {}",
9436                    postrust_sql::escape_ident(column),
9437                    postrust_sql::escape_ident(name)
9438                )),
9439                None => parts.push(postrust_sql::escape_ident(name)),
9440            }
9441        }
9442        if parts.is_empty() && nested.is_empty() {
9443            parts.push(
9444                child_table
9445                    .and_then(|table| rename_projection(table, &child_alias, names))
9446                    .unwrap_or_else(|| format!("{}.*", postrust_sql::escape_ident(&child_alias))),
9447            );
9448        }
9449        for (field_name, expression) in nested {
9450            parts.push(format!(
9451                "{} AS {}",
9452                expression,
9453                postrust_sql::escape_ident(&field_name)
9454            ));
9455        }
9456
9457        let computed_call_arguments = computed_arguments(
9458            rel,
9459            &plan,
9460            &postrust_sql::escape_ident(parent_alias),
9461            arguments.get("args"),
9462            param_idx,
9463            values,
9464            schema_cache,
9465        )?;
9466        let expression = plan
9467            .embed_expression(
9468                parent_alias,
9469                // A computed relationship is correlated by argument rather
9470                // than by a key: the function takes the parent row, and an
9471                // alias names that row.
9472                &postrust_sql::escape_ident(parent_alias),
9473                &child_alias,
9474                &format!("{}{}", child_distinct, parts.join(", ")),
9475                child_limit,
9476                child_offset,
9477                child_where.as_deref(),
9478                child_order.as_deref(),
9479                computed_call_arguments.as_deref(),
9480                postrust_core::EmbedRendering::Verbatim,
9481            )
9482            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9483
9484        expressions.push((rel.name.clone(), expression));
9485    }
9486
9487    Ok(expressions)
9488}
9489
9490/// What embedding a relationship needs, independent of the rows involved.
9491///
9492/// The connection is passed alongside rather than held here: embedding runs on
9493/// the request's transaction, and a shared reference to this struct could not
9494/// hand out the mutable borrow the queries need.
9495struct EmbedContext<'c> {
9496    schema_cache: &'c SchemaCache,
9497    relationships: &'c HashMap<String, Vec<RelationshipField>>,
9498    max_rows: Option<i64>,
9499}
9500
9501/// Embed the relationship fields requested on `rows`.
9502///
9503/// One query per relationship per level, not one per row: the parents' join
9504/// keys are collected and passed as a single array. Recurses so a nested
9505/// selection costs one further query per relationship at each depth.
9506fn embed_relationships<'f>(
9507    conn: &'f mut sqlx::PgConnection,
9508    ctx: &'f EmbedContext<'f>,
9509    type_name: &'f str,
9510    selection: async_graphql::SelectionField<'f>,
9511    rows: &'f mut [serde_json::Value],
9512) -> futures::future::BoxFuture<'f, Result<(), async_graphql::Error>> {
9513    Box::pin(async move {
9514        if rows.is_empty() {
9515            return Ok(());
9516        }
9517
9518        let Some(available) = ctx.relationships.get(type_name) else {
9519            return Ok(());
9520        };
9521
9522        for requested in selection.selection_set() {
9523            let Some(rel) = available.iter().find(|r| r.name == requested.name()) else {
9524                continue;
9525            };
9526
9527            let plan =
9528                postrust_core::embed::EmbedPlan::resolve(&rel.relationship, ctx.schema_cache)
9529                    .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9530
9531            let keys = postrust_core::embed::parent_keys(rows, &plan.local_column);
9532
9533            // Project only what the selection asked for. A GraphQL selection
9534            // names its leaf fields, so the columns are known before the query
9535            // and an unrequested column need not be read, serialised, sent and
9536            // parsed just to be dropped.
9537            //
9538            // A nested relationship joins on a column of the child row, so that
9539            // column is added even when it was not selected; it is removed again
9540            // when the response is shaped. A selection whose sub-fields cannot
9541            // all be resolved to columns falls back to every column.
9542            let mut child_columns: Vec<String> = Vec::new();
9543            let mut project_everything = false;
9544            let child_relationships = ctx.relationships.get(&rel.target_type);
9545            for field in requested.selection_set() {
9546                let name = field.name();
9547                match child_relationships.and_then(|rels| rels.iter().find(|r| r.name == name)) {
9548                    Some(nested_rel) => {
9549                        match postrust_core::embed::EmbedPlan::resolve(
9550                            &nested_rel.relationship,
9551                            ctx.schema_cache,
9552                        ) {
9553                            Ok(nested_plan) => child_columns.push(nested_plan.local_column),
9554                            Err(_) => project_everything = true,
9555                        }
9556                    }
9557                    // Answered by the schema, not a column.
9558                    None if name == "__typename" => {}
9559                    None => child_columns.push(name.to_string()),
9560                }
9561            }
9562            if project_everything || child_columns.is_empty() {
9563                child_columns.clear();
9564            }
9565
9566            let mut grouped = if keys.is_empty() {
9567                std::collections::HashMap::new()
9568            } else {
9569                let sql = plan
9570                    .children_grouped_sql(ctx.max_rows, &child_columns)
9571                    .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9572
9573                let fetched = sqlx::query(AssertSqlSafe(sql))
9574                    .bind(&keys)
9575                    .fetch_all(&mut *conn)
9576                    .await
9577                    .map_err(database_error)?;
9578
9579                // The query returns the join key and a JSON array of that key's
9580                // children, grouped by PostgreSQL rather than row by row here.
9581                use sqlx::Row;
9582                let pairs: Vec<(serde_json::Value, serde_json::Value)> = fetched
9583                    .into_iter()
9584                    .filter_map(|row| {
9585                        Some((
9586                            row.try_get::<serde_json::Value, _>(0).ok()?,
9587                            row.try_get::<serde_json::Value, _>(1).ok()?,
9588                        ))
9589                    })
9590                    .collect();
9591
9592                postrust_core::embed::group_from_aggregated(pairs)
9593            };
9594
9595            // Recurse before attaching, so nested embeds land in the values
9596            // copied onto the parents. One query serves every child row at this
9597            // level, so the rows are flattened for the call and put back
9598            // afterwards; skipped when the selection asks for nothing deeper.
9599            let has_deeper_embed = ctx
9600                .relationships
9601                .get(&rel.target_type)
9602                .map(|rels| {
9603                    requested
9604                        .selection_set()
9605                        .any(|field| rels.iter().any(|r| r.name == field.name()))
9606                })
9607                .unwrap_or(false);
9608
9609            if has_deeper_embed {
9610                let mut order: Vec<(String, usize)> = Vec::with_capacity(grouped.len());
9611                let mut flat: Vec<serde_json::Value> = Vec::new();
9612                for (key, children) in grouped.drain() {
9613                    order.push((key, children.len()));
9614                    flat.extend(children);
9615                }
9616
9617                embed_relationships(&mut *conn, ctx, &rel.target_type, requested, &mut flat)
9618                    .await?;
9619
9620                let mut rest = flat.into_iter();
9621                for (key, count) in order {
9622                    grouped.insert(key, rest.by_ref().take(count).collect());
9623                }
9624            }
9625
9626            for row in rows.iter_mut() {
9627                postrust_core::embed::attach_to_parent(row, &rel.name, &plan, &grouped);
9628            }
9629        }
9630
9631        Ok(())
9632    })
9633}
9634
9635/// Build a `where` document that addresses exactly one row by primary key.
9636///
9637/// Used by the by-PK mutations, which take the key columns as arguments instead
9638/// of a free-form `where`.
9639fn pk_where_from_args(
9640    ctx: &ResolverContext<'_>,
9641    schema_name: &str,
9642    table_name: &str,
9643    pk_columns: &[(String, String)],
9644    names: &crate::names::NameOverrides,
9645) -> Result<serde_json::Value, async_graphql::Error> {
9646    if pk_columns.is_empty() {
9647        return Err(async_graphql::Error::new(format!(
9648            "\"{}\" has no primary key, so it cannot be mutated by key",
9649            table_name
9650        )));
9651    }
9652
9653    // `update_x_by_pk` takes its key as one `pk_columns` object; the others
9654    // take the key columns as arguments of their own. Both spellings are what
9655    // a client was generated against, so both are read here.
9656    let from_object = ctx
9657        .args
9658        .try_get("pk_columns")
9659        .ok()
9660        .map(|v| accessor_to_json(&v));
9661
9662    let mut conditions = serde_json::Map::new();
9663    for (col_name, _) in pk_columns {
9664        // Under the name the key column is exposed as, on both sides: the
9665        // argument the client wrote, and the predicate handed on to the same
9666        // builder every other `where` goes through.
9667        let field = names
9668            .column(schema_name, table_name, col_name)
9669            .unwrap_or(col_name);
9670        let value = match &from_object {
9671            Some(serde_json::Value::Object(map)) => map.get(field).cloned().ok_or_else(|| {
9672                async_graphql::Error::new(format!(
9673                    "pk_columns is missing the key column \"{}\"",
9674                    field
9675                ))
9676            })?,
9677            _ => {
9678                let arg = ctx.args.try_get(field).map_err(|_| {
9679                    async_graphql::Error::new(format!(
9680                        "missing required primary key argument \"{}\"",
9681                        field
9682                    ))
9683                })?;
9684                accessor_to_json(&arg)
9685            }
9686        };
9687        conditions.insert(field.to_string(), serde_json::json!({ "_eq": value }));
9688    }
9689
9690    Ok(serde_json::Value::Object(conditions))
9691}
9692
9693/// GraphQL scalar name to use for a primary key argument of the given
9694/// PostgreSQL type.
9695///
9696/// Falls back to `String` for anything that does not map to a plain scalar --
9697/// a composite or array key cannot be expressed as a single named argument, and
9698/// the value is cast to the column's type in SQL anyway.
9699fn pk_argument_type(pg_type: &str) -> String {
9700    let rendered = crate::types::pg_type_to_graphql(pg_type).to_string();
9701    if rendered.starts_with('[') {
9702        "String".to_string()
9703    } else {
9704        rendered
9705    }
9706}
9707
9708/// The public GraphQL type of a primary-key argument.
9709///
9710/// SQL execution still carries the PostgreSQL type beside the key and uses it
9711/// for casts and binding. This is only the schema-facing type.
9712fn exposed_pk_argument_type(
9713    names: &crate::names::NameOverrides,
9714    schema: &str,
9715    table: &str,
9716    column: &str,
9717    pg_type: &str,
9718) -> String {
9719    names
9720        .column_type(schema, table, column)
9721        .map(|given| given.to_string())
9722        .unwrap_or_else(|| pk_argument_type(pg_type))
9723}
9724
9725/// Convert a GraphQL type string to a TypeRef.
9726fn graphql_type_ref(type_str: &str) -> TypeRef {
9727    // Parse type string like "[Users!]!" or "String" or "Int!"
9728    let is_list = type_str.starts_with('[');
9729    let is_nn = type_str.ends_with('!');
9730
9731    // Strip outer modifiers: first the trailing !, then the brackets
9732    let inner = if is_list {
9733        let stripped = type_str
9734            .trim_end_matches('!') // Remove outer !
9735            .trim_start_matches('[') // Remove [
9736            .trim_end_matches(']'); // Remove ]
9737        stripped
9738    } else {
9739        type_str.trim_end_matches('!')
9740    };
9741
9742    let inner_nn = inner.ends_with('!');
9743    let base_type = inner.trim_end_matches('!');
9744
9745    if is_list {
9746        if is_nn {
9747            if inner_nn {
9748                TypeRef::named_nn_list_nn(base_type)
9749            } else {
9750                TypeRef::named_list_nn(base_type)
9751            }
9752        } else if inner_nn {
9753            TypeRef::named_nn_list(base_type)
9754        } else {
9755            TypeRef::named_list(base_type)
9756        }
9757    } else if is_nn {
9758        TypeRef::named_nn(base_type)
9759    } else {
9760        TypeRef::named(base_type)
9761    }
9762}
9763
9764/// The key serde_json wraps a number in when it is keeping its digits.
9765///
9766/// This crate reads `serde_json` with `arbitrary_precision`, so a PostgreSQL
9767/// `numeric` survives a round trip through JSON with every digit it had. The
9768/// cost is on the way in: a fractional number in a *variable* is deserialized
9769/// into async-graphql's own value type as a one-key object holding the text,
9770/// because the generic path cannot know it is looking at a number. Integers
9771/// are unaffected, which is why this went unnoticed until a shape arrived by
9772/// variable and every coordinate in it read as zero.
9773const NUMBER_AS_TEXT: &str = "$serde_json::private::Number";
9774
9775/// The number an arbitrary-precision wrapper is holding, if that is what this
9776/// object is.
9777fn number_kept_as_text(
9778    map: &serde_json::Map<String, serde_json::Value>,
9779) -> Option<serde_json::Value> {
9780    if map.len() != 1 {
9781        return None;
9782    }
9783    let text = map.get(NUMBER_AS_TEXT)?.as_str()?;
9784    serde_json::from_str::<serde_json::Value>(text)
9785        .ok()
9786        .filter(|value| value.is_number())
9787}
9788
9789/// The same, applied to a whole document that came in as one.
9790fn plain_numbers(value: serde_json::Value) -> serde_json::Value {
9791    match value {
9792        serde_json::Value::Object(map) => match number_kept_as_text(&map) {
9793            Some(number) => number,
9794            None => serde_json::Value::Object(
9795                map.into_iter()
9796                    .map(|(k, v)| (k, plain_numbers(v)))
9797                    .collect(),
9798            ),
9799        },
9800        serde_json::Value::Array(items) => {
9801            serde_json::Value::Array(items.into_iter().map(plain_numbers).collect())
9802        }
9803        other => other,
9804    }
9805}
9806
9807/// Convert ValueAccessor to JSON.
9808fn accessor_to_json(accessor: &ValueAccessor<'_>) -> serde_json::Value {
9809    // Use the deserialize method if available, or convert manually
9810    if accessor.is_null() {
9811        serde_json::Value::Null
9812    } else if let Ok(b) = accessor.boolean() {
9813        serde_json::Value::Bool(b)
9814    } else if let Ok(i) = accessor.i64() {
9815        serde_json::Value::Number(i.into())
9816    } else if let Ok(f) = accessor.f64() {
9817        serde_json::Number::from_f64(f)
9818            .map(serde_json::Value::Number)
9819            .unwrap_or(serde_json::Value::Null)
9820    } else if let Ok(s) = accessor.string() {
9821        serde_json::Value::String(s.to_string())
9822    } else if let Ok(name) = accessor.enum_name() {
9823        // An enum value is not a string to `string()`, and falling through to
9824        // null made every `order_by: {name: asc}` read as an empty direction.
9825        serde_json::Value::String(name.to_string())
9826    } else if let Ok(list) = accessor.list() {
9827        serde_json::Value::Array(list.iter().map(|v| accessor_to_json(&v)).collect())
9828    } else if let Ok(obj) = accessor.object() {
9829        let map: serde_json::Map<String, serde_json::Value> = obj
9830            .iter()
9831            .map(|(k, v)| (k.to_string(), accessor_to_json(&v)))
9832            .collect();
9833        match number_kept_as_text(&map) {
9834            Some(number) => number,
9835            None => serde_json::Value::Object(map),
9836        }
9837    } else {
9838        serde_json::Value::Null
9839    }
9840}
9841
9842/// Convert async-graphql Value to JSON.
9843fn value_to_json(value: &Value) -> serde_json::Value {
9844    match value {
9845        Value::Null => serde_json::Value::Null,
9846        Value::Boolean(b) => serde_json::Value::Bool(*b),
9847        Value::Number(n) => {
9848            if let Some(i) = n.as_i64() {
9849                serde_json::Value::Number(i.into())
9850            } else if let Some(f) = n.as_f64() {
9851                serde_json::Value::Number(serde_json::Number::from_f64(f).unwrap())
9852            } else {
9853                serde_json::Value::Null
9854            }
9855        }
9856        Value::String(s) => serde_json::Value::String(s.clone()),
9857        Value::List(arr) => serde_json::Value::Array(arr.iter().map(value_to_json).collect()),
9858        Value::Object(obj) => {
9859            let map: serde_json::Map<String, serde_json::Value> = obj
9860                .iter()
9861                .map(|(k, v)| (k.to_string(), value_to_json(v)))
9862                .collect();
9863            serde_json::Value::Object(map)
9864        }
9865        Value::Binary(b) => serde_json::Value::String(base64::Engine::encode(
9866            &base64::engine::general_purpose::STANDARD,
9867            b,
9868        )),
9869        Value::Enum(e) => serde_json::Value::String(e.to_string()),
9870    }
9871}
9872
9873/// Convert JSON to async-graphql Value.
9874fn json_to_value(json: serde_json::Value) -> Value {
9875    match json {
9876        serde_json::Value::Null => Value::Null,
9877        serde_json::Value::Bool(b) => Value::Boolean(b),
9878        serde_json::Value::Number(n) => {
9879            if let Some(i) = n.as_i64() {
9880                Value::Number(i.into())
9881            } else if let Some(f) = n.as_f64() {
9882                Value::Number(async_graphql::Number::from_f64(f).unwrap())
9883            } else {
9884                Value::Null
9885            }
9886        }
9887        serde_json::Value::String(s) => Value::String(s),
9888        serde_json::Value::Array(arr) => Value::List(arr.into_iter().map(json_to_value).collect()),
9889        serde_json::Value::Object(obj) => {
9890            let map: indexmap::IndexMap<async_graphql::Name, Value> = obj
9891                .into_iter()
9892                .map(|(k, v)| (async_graphql::Name::new(k), json_to_value(v)))
9893                .collect();
9894            Value::Object(map)
9895        }
9896    }
9897}
9898
9899/// Register filter input types.
9900///
9901/// These are currently unreachable: the `filter` and `where` arguments are
9902/// declared as the `JSON` scalar, so no field references these input objects
9903/// and async-graphql prunes them from the published schema (introspecting
9904/// `IntFilterInput` returns null). They are kept as the shape to move to if
9905/// filters become typed per column; until then the operators a filter actually
9906/// supports are the ones `build_where_clause` implements, and it rejects
9907/// anything else rather than ignoring it.
9908#[cfg(test)]
9909mod tests {
9910    use super::*;
9911    use indexmap::IndexMap;
9912    use postrust_core::schema_cache::{Cardinality, Column, Relationship, Table};
9913    use postrust_core::QualifiedIdentifier;
9914    use std::collections::{HashMap, HashSet};
9915
9916    fn entity_key_column(pg_type: &str, explicit_id: bool) -> EntityKeyColumn {
9917        EntityKeyColumn {
9918            field_name: "id".to_string(),
9919            column_name: "id".to_string(),
9920            pg_type: pg_type.to_string(),
9921            explicit_id,
9922        }
9923    }
9924
9925    #[test]
9926    fn federation_integer_keys_reject_strings() {
9927        let column = entity_key_column("int4", false);
9928
9929        assert_eq!(
9930            normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap(),
9931            serde_json::json!(2)
9932        );
9933        let error = normalize_entity_key_value("users", &column, &serde_json::json!("2"))
9934            .expect_err("a GraphQL Int cannot be a string");
9935        assert_eq!(
9936            error.message,
9937            "entity representation for \"users\" has invalid key field \"id\": expected a value compatible with PostgreSQL type \"int4\", found a string"
9938        );
9939    }
9940
9941    #[test]
9942    fn federation_bigint_keys_accept_exact_decimal_strings() {
9943        let column = entity_key_column("int8", false);
9944
9945        assert_eq!(
9946            normalize_entity_key_value("users", &column, &serde_json::json!(7)).unwrap(),
9947            serde_json::json!(7)
9948        );
9949        assert_eq!(
9950            normalize_entity_key_value("users", &column, &serde_json::json!("9007199254740993"))
9951                .unwrap(),
9952            serde_json::json!(9_007_199_254_740_993_i64)
9953        );
9954        assert!(normalize_entity_key_value(
9955            "users",
9956            &column,
9957            &serde_json::json!("9223372036854775808")
9958        )
9959        .is_err());
9960        assert!(normalize_entity_key_value("users", &column, &serde_json::json!("7.5")).is_err());
9961    }
9962
9963    #[test]
9964    fn federation_numeric_keys_accept_exact_decimal_strings() {
9965        let column = entity_key_column("numeric", false);
9966
9967        assert_eq!(
9968            normalize_entity_key_value("users", &column, &serde_json::json!(7.5)).unwrap(),
9969            serde_json::json!("7.5")
9970        );
9971        assert_eq!(
9972            normalize_entity_key_value(
9973                "users",
9974                &column,
9975                &serde_json::json!("9007199254740993.123456789")
9976            )
9977            .unwrap(),
9978            serde_json::json!("9007199254740993.123456789")
9979        );
9980        assert!(
9981            normalize_entity_key_value("users", &column, &serde_json::json!("not-a-number"))
9982                .is_err()
9983        );
9984    }
9985
9986    #[test]
9987    fn federation_integer_backed_ids_have_one_normal_form() {
9988        let column = entity_key_column("int4", true);
9989
9990        let number = normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap();
9991        let string = normalize_entity_key_value("users", &column, &serde_json::json!("2")).unwrap();
9992        assert_eq!(number, serde_json::json!(2));
9993        assert_eq!(string, number);
9994        assert!(normalize_entity_key_value("users", &column, &serde_json::json!("two")).is_err());
9995    }
9996
9997    #[test]
9998    fn federation_text_backed_ids_normalize_integer_input_to_text() {
9999        let column = entity_key_column("text", true);
10000
10001        let number = normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap();
10002        let string = normalize_entity_key_value("users", &column, &serde_json::json!("2")).unwrap();
10003        assert_eq!(number, serde_json::json!("2"));
10004        assert_eq!(string, number);
10005    }
10006
10007    #[test]
10008    fn federation_uuid_backed_ids_are_validated_and_canonicalized() {
10009        let column = entity_key_column("uuid", true);
10010
10011        assert_eq!(
10012            normalize_entity_key_value(
10013                "users",
10014                &column,
10015                &serde_json::json!("550E8400-E29B-41D4-A716-446655440000")
10016            )
10017            .unwrap(),
10018            serde_json::json!("550e8400-e29b-41d4-a716-446655440000")
10019        );
10020        assert!(
10021            normalize_entity_key_value("users", &column, &serde_json::json!("not-a-uuid")).is_err()
10022        );
10023    }
10024
10025    fn create_test_table(name: &str) -> Table {
10026        let mut columns = IndexMap::new();
10027        columns.insert(
10028            "id".into(),
10029            Column {
10030                name: "id".into(),
10031                description: None,
10032                nullable: false,
10033                data_type: "integer".into(),
10034                nominal_type: "int4".into(),
10035                max_len: None,
10036                default: Some("nextval('id_seq')".into()),
10037                enum_values: vec![],
10038                is_pk: true,
10039                position: 1,
10040                always_generated: false,
10041                domain_type: None,
10042            },
10043        );
10044        columns.insert(
10045            "name".into(),
10046            Column {
10047                name: "name".into(),
10048                description: None,
10049                nullable: false,
10050                data_type: "text".into(),
10051                nominal_type: "text".into(),
10052                max_len: None,
10053                default: None,
10054                enum_values: vec![],
10055                is_pk: false,
10056                position: 2,
10057                always_generated: false,
10058                domain_type: None,
10059            },
10060        );
10061
10062        Table {
10063            schema: "public".into(),
10064            name: name.into(),
10065            description: None,
10066            is_view: false,
10067            insertable: true,
10068            updatable: true,
10069            deletable: true,
10070            pk_cols: vec!["id".into()],
10071            unique_constraints: Vec::new(),
10072            columns,
10073            computed_columns: Default::default(),
10074            is_partitioned: false,
10075        }
10076    }
10077
10078    fn create_test_schema_cache() -> SchemaCache {
10079        let mut tables = HashMap::new();
10080        let users = create_test_table("users");
10081        tables.insert(users.qualified_identifier(), users);
10082
10083        SchemaCache {
10084            tables,
10085            relationships: HashMap::new(),
10086            routines: HashMap::new(),
10087            timezones: HashSet::new(),
10088            media_handlers: HashMap::new(),
10089            pg_version: 150000,
10090            representations: Default::default(),
10091        }
10092    }
10093
10094    fn add_test_table(cache: &mut SchemaCache, name: &str) {
10095        let table = create_test_table(name);
10096        cache.tables.insert(table.qualified_identifier(), table);
10097    }
10098
10099    fn add_test_posts_relationship(cache: &mut SchemaCache) {
10100        let users = QualifiedIdentifier::new("public", "users");
10101        cache.relationships.insert(
10102            (users.clone(), "public".into()),
10103            vec![Relationship::ForeignKey {
10104                table: users,
10105                foreign_table: QualifiedIdentifier::new("public", "posts"),
10106                is_self: false,
10107                cardinality: Cardinality::O2M {
10108                    constraint: "posts_user_id_fkey".into(),
10109                    columns: vec![("id".into(), "user_id".into())],
10110                },
10111                table_is_view: false,
10112                foreign_table_is_view: false,
10113                constraint_name: "posts_user_id_fkey".into(),
10114            }],
10115        );
10116    }
10117
10118    // ============================================================================
10119    // Type Reference Tests
10120    // ============================================================================
10121
10122    #[test]
10123    fn test_graphql_type_ref_simple() {
10124        let _type_ref = graphql_type_ref("String");
10125        // TypeRef doesn't implement PartialEq, so we just test it doesn't panic
10126    }
10127
10128    #[test]
10129    fn test_graphql_type_ref_non_null() {
10130        let _type_ref = graphql_type_ref("String!");
10131    }
10132
10133    #[test]
10134    fn test_graphql_type_ref_list() {
10135        let _type_ref = graphql_type_ref("[String]");
10136    }
10137
10138    #[test]
10139    fn test_graphql_type_ref_list_non_null() {
10140        let _type_ref = graphql_type_ref("[String!]!");
10141    }
10142
10143    // ============================================================================
10144    // Value Conversion Tests
10145    // ============================================================================
10146
10147    #[test]
10148    fn test_value_to_json_null() {
10149        let value = Value::Null;
10150        let json = value_to_json(&value);
10151        assert_eq!(json, serde_json::Value::Null);
10152    }
10153
10154    #[test]
10155    fn test_value_to_json_boolean() {
10156        let value = Value::Boolean(true);
10157        let json = value_to_json(&value);
10158        assert_eq!(json, serde_json::Value::Bool(true));
10159    }
10160
10161    #[test]
10162    fn test_value_to_json_number() {
10163        let value = Value::Number(42.into());
10164        let json = value_to_json(&value);
10165        assert_eq!(json, serde_json::json!(42));
10166    }
10167
10168    #[test]
10169    fn test_value_to_json_string() {
10170        let value = Value::String("hello".to_string());
10171        let json = value_to_json(&value);
10172        assert_eq!(json, serde_json::Value::String("hello".to_string()));
10173    }
10174
10175    #[test]
10176    fn test_value_to_json_list() {
10177        let value = Value::List(vec![Value::Number(1.into()), Value::Number(2.into())]);
10178        let json = value_to_json(&value);
10179        assert_eq!(json, serde_json::json!([1, 2]));
10180    }
10181
10182    #[test]
10183    fn test_json_to_value_null() {
10184        let json = serde_json::Value::Null;
10185        let value = json_to_value(json);
10186        assert!(matches!(value, Value::Null));
10187    }
10188
10189    #[test]
10190    fn test_json_to_value_boolean() {
10191        let json = serde_json::Value::Bool(false);
10192        let value = json_to_value(json);
10193        assert!(matches!(value, Value::Boolean(false)));
10194    }
10195
10196    #[test]
10197    fn test_json_to_value_number() {
10198        let json = serde_json::json!(123);
10199        let value = json_to_value(json);
10200        assert!(matches!(value, Value::Number(_)));
10201    }
10202
10203    #[test]
10204    fn test_json_to_value_string() {
10205        let json = serde_json::Value::String("test".to_string());
10206        let value = json_to_value(json);
10207        assert!(matches!(value, Value::String(_)));
10208    }
10209
10210    #[test]
10211    fn test_json_to_value_array() {
10212        let json = serde_json::json!([1, 2, 3]);
10213        let value = json_to_value(json);
10214        assert!(matches!(value, Value::List(_)));
10215    }
10216
10217    #[test]
10218    fn test_json_to_value_object() {
10219        let json = serde_json::json!({"key": "value"});
10220        let value = json_to_value(json);
10221        assert!(matches!(value, Value::Object(_)));
10222    }
10223
10224    // ============================================================================
10225    // Schema Building Tests
10226    // ============================================================================
10227
10228    #[test]
10229    fn test_build_dynamic_schema() {
10230        let cache = create_test_schema_cache();
10231        let config = SchemaConfig::default();
10232        let generated = build_schema(&cache, &config);
10233
10234        let result = build_dynamic_schema(
10235            &generated,
10236            &cache,
10237            None,
10238            None,
10239            Arc::new(Default::default()),
10240            std::time::Duration::from_secs(30),
10241            None,
10242        );
10243        if let Err(ref e) = result {
10244            eprintln!("Schema build error: {:?}", e);
10245        }
10246        assert!(result.is_ok(), "Schema build failed: {:?}", result.err());
10247    }
10248
10249    #[test]
10250    fn a_column_type_override_reaches_fields_and_key_arguments() {
10251        let cache = create_test_schema_cache();
10252        let names = crate::names::NameOverrides::parse(
10253            r#"{"tables": {"public.users": {"column_types": {"id": "ID"}}}}"#,
10254        )
10255        .unwrap();
10256        let config = SchemaConfig {
10257            names: names.clone(),
10258            ..SchemaConfig::default()
10259        };
10260        let generated = build_schema(&cache, &config);
10261        let schema = build_dynamic_schema(
10262            &generated,
10263            &cache,
10264            None,
10265            None,
10266            Arc::new(names),
10267            std::time::Duration::from_secs(30),
10268            None,
10269        )
10270        .expect("schema with an ID override should build");
10271        let sdl = schema.sdl();
10272
10273        let input_body = |name: &str| {
10274            sdl.split_once(&format!("input {name} {{"))
10275                .and_then(|(_, rest)| rest.split_once('}'))
10276                .map(|(body, _)| body.to_string())
10277                .unwrap_or_else(|| panic!("missing input {name}:\n{sdl}"))
10278        };
10279
10280        assert!(sdl.contains("id: ID!"), "object and input fields:\n{sdl}");
10281        assert!(
10282            sdl.contains("users_by_pk(id: ID!): users"),
10283            "query key argument:\n{sdl}"
10284        );
10285        assert!(
10286            sdl.contains("delete_users_by_pk(id: ID!): users"),
10287            "delete key argument:\n{sdl}"
10288        );
10289        assert!(
10290            input_body("users_pk_columns_input").contains("id: ID!"),
10291            "update key input:\n{sdl}"
10292        );
10293        assert!(
10294            input_body("users_bool_exp").contains("id: ID_comparison_exp"),
10295            "comparison input:\n{sdl}"
10296        );
10297        assert!(
10298            input_body("users_insert_input").contains("id: ID"),
10299            "write input:\n{sdl}"
10300        );
10301    }
10302
10303    #[test]
10304    fn a_type_prefix_names_the_complete_dynamic_schema() {
10305        let cache = create_test_schema_cache();
10306        let config = SchemaConfig {
10307            type_prefix: Some("test".into()),
10308            ..SchemaConfig::default()
10309        };
10310        let generated = build_schema(&cache, &config);
10311        let schema = build_dynamic_schema(
10312            &generated,
10313            &cache,
10314            None,
10315            None,
10316            Arc::new(Default::default()),
10317            std::time::Duration::from_secs(30),
10318            None,
10319        )
10320        .expect("a prefixed schema should build");
10321        let sdl = schema.sdl();
10322
10323        assert!(sdl.contains("type test_users "), "object type:\n{sdl}");
10324        assert!(sdl.contains("test_users("), "query root:\n{sdl}");
10325        assert!(sdl.contains("test_users_by_pk("), "by-PK root:\n{sdl}");
10326        assert!(sdl.contains("test_users_bool_exp"), "derived input:\n{sdl}");
10327        assert!(
10328            sdl.contains("test_users_aggregate"),
10329            "aggregate type:\n{sdl}"
10330        );
10331        assert!(sdl.contains("test_insert_users("), "mutation root:\n{sdl}");
10332    }
10333
10334    #[test]
10335    fn federation_is_absent_by_default() {
10336        let cache = create_test_schema_cache();
10337        let generated = build_schema(&cache, &SchemaConfig::default());
10338        let schema = build_dynamic_schema(
10339            &generated,
10340            &cache,
10341            None,
10342            None,
10343            Arc::new(Default::default()),
10344            std::time::Duration::from_secs(30),
10345            None,
10346        )
10347        .expect("a non-federated schema should build");
10348        let sdl = schema.sdl();
10349
10350        assert!(!sdl.contains("_Service"), "service type:\n{sdl}");
10351        assert!(!sdl.contains("_service"), "service field:\n{sdl}");
10352        assert!(!sdl.contains("@key"), "federation key:\n{sdl}");
10353    }
10354
10355    #[test]
10356    fn federation_entity_selections_respect_fragment_type_conditions() {
10357        let document = async_graphql::parser::parse_query(
10358            r#"
10359            query {
10360              _entities(representations: []) {
10361                __typename
10362                ... on authors { id items { title } }
10363                ...ShopFields
10364                ... { common }
10365                ...EntityName
10366              }
10367            }
10368            fragment ShopFields on shops { id items { sku } }
10369            fragment EntityName on _Entity { __typename }
10370            "#,
10371        )
10372        .expect("query parses");
10373        let (_, operation) = document.operations.iter().next().expect("one operation");
10374        let entity = operation
10375            .node
10376            .selection_set
10377            .node
10378            .items
10379            .iter()
10380            .find_map(|selection| match &selection.node {
10381                Selection::Field(field) if field.node.name.node == "_entities" => Some(&field.node),
10382                _ => None,
10383            })
10384            .expect("_entities field");
10385
10386        assert_eq!(
10387            entity_field_applicability(&entity.selection_set.node, &document.fragments, "authors"),
10388            vec![true, true, true, false, false, true, true]
10389        );
10390        assert_eq!(
10391            entity_field_applicability(&entity.selection_set.node, &document.fragments, "shops"),
10392            vec![true, false, false, true, true, true, true]
10393        );
10394    }
10395
10396    #[tokio::test]
10397    async fn federation_entity_lists_allow_null_members() {
10398        let entity =
10399            Object::new("widgets").field(Field::new("id", TypeRef::named_nn(TypeRef::INT), |_| {
10400                FieldFuture::new(async { Ok(Some(Value::from(2))) })
10401            }));
10402        let union = Union::new("_Entity").possible_type("widgets");
10403        let query = Object::new("Query").field(Field::new(
10404            "_entities",
10405            TypeRef::named_list_nn("_Entity"),
10406            |_| {
10407                FieldFuture::new(async {
10408                    Ok(Some(FieldValue::list([
10409                        FieldValue::NULL,
10410                        FieldValue::NULL.with_type("widgets"),
10411                    ])))
10412                })
10413            },
10414        ));
10415        let schema = Schema::build("Query", None, None)
10416            .extension(NullableFederationEntity)
10417            .register(entity)
10418            .register(union)
10419            .register(query)
10420            .finish()
10421            .expect("schema builds");
10422
10423        let response = schema
10424            .execute("{ _entities { ... on widgets { id } } }")
10425            .await;
10426
10427        assert!(response.errors.is_empty(), "{:?}", response.errors);
10428        assert_eq!(
10429            response.data,
10430            async_graphql::value!({ "_entities": [null, { "id": 2 }] })
10431        );
10432    }
10433
10434    #[test]
10435    fn federation_metadata_is_byte_for_byte_inert_when_disabled() {
10436        let cache = create_test_schema_cache();
10437        let sdl_for = |config: SchemaConfig| {
10438            let generated = build_schema(&cache, &config);
10439            build_dynamic_schema(
10440                &generated,
10441                &cache,
10442                None,
10443                None,
10444                Arc::new(config.names.clone()),
10445                std::time::Duration::from_secs(30),
10446                None,
10447            )
10448            .expect("schema should build")
10449            .sdl()
10450        };
10451
10452        let baseline = sdl_for(SchemaConfig {
10453            type_prefix: Some("test".into()),
10454            ..SchemaConfig::default()
10455        });
10456        let with_disabled_federation_metadata = sdl_for(SchemaConfig {
10457            enable_federation: false,
10458            type_prefix: Some("test".into()),
10459            names: crate::names::NameOverrides::parse(
10460                r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10461            )
10462            .expect("metadata"),
10463            ..SchemaConfig::default()
10464        });
10465
10466        assert_eq!(with_disabled_federation_metadata, baseline);
10467        assert!(
10468            with_disabled_federation_metadata.contains("type test_users "),
10469            "prefixed object type remains when federation is disabled:\n{with_disabled_federation_metadata}"
10470        );
10471        assert!(
10472            !with_disabled_federation_metadata.contains("_Service"),
10473            "service type:\n{with_disabled_federation_metadata}"
10474        );
10475        assert!(
10476            !with_disabled_federation_metadata.contains("@key"),
10477            "federation key:\n{with_disabled_federation_metadata}"
10478        );
10479    }
10480
10481    #[test]
10482    fn shared_entities_are_shareable_at_the_type_level() {
10483        let federation_sdl = |shared: bool| {
10484            let mut cache = create_test_schema_cache();
10485            add_test_table(&mut cache, "posts");
10486            add_test_posts_relationship(&mut cache);
10487            let names = match shared {
10488                true => crate::names::NameOverrides::parse(
10489                    r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10490                )
10491                .expect("metadata"),
10492                false => crate::names::NameOverrides::default(),
10493            };
10494            let config = SchemaConfig {
10495                enable_federation: true,
10496                type_prefix: Some("test".into()),
10497                names: names.clone(),
10498                ..SchemaConfig::default()
10499            };
10500            let generated = build_schema(&cache, &config);
10501            build_dynamic_schema(
10502                &generated,
10503                &cache,
10504                None,
10505                None,
10506                Arc::new(names),
10507                std::time::Duration::from_secs(30),
10508                None,
10509            )
10510            .expect("federated schema should build")
10511            .sdl_with_options(async_graphql::SDLExportOptions::new().federation())
10512        };
10513
10514        // `@shareable` on the type covers every field on it, relationships
10515        // and their aggregates included, so it is not repeated per field.
10516        let shared = federation_sdl(true);
10517        assert!(
10518            shared.contains("type users @key(fields: \"id\") @shareable"),
10519            "shared entity type:\n{shared}"
10520        );
10521        assert!(
10522            shared.contains("): [test_posts!]!") && shared.contains("): test_posts_aggregate!"),
10523            "shared relationship fields:\n{shared}"
10524        );
10525        assert!(
10526            !shared.contains("): [test_posts!]! @shareable")
10527                && !shared.contains("): test_posts_aggregate! @shareable"),
10528            "field-level @shareable is redundant under a shareable type:\n{shared}"
10529        );
10530
10531        let not_shared = federation_sdl(false);
10532        assert!(
10533            not_shared.contains("type test_users @key(fields: \"id\") {"),
10534            "non-shared entity type must not be shareable:\n{not_shared}"
10535        );
10536        assert!(
10537            !not_shared.contains(" @shareable"),
10538            "nothing in a schema without shared entities is shareable:\n{not_shared}"
10539        );
10540    }
10541
10542    #[tokio::test]
10543    async fn federation_exposes_service_sdl_and_entity_keys() {
10544        let mut cache = create_test_schema_cache();
10545        add_test_table(&mut cache, "posts");
10546        let config = SchemaConfig {
10547            enable_federation: true,
10548            type_prefix: Some("test".into()),
10549            names: crate::names::NameOverrides::parse(
10550                r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10551            )
10552            .expect("metadata"),
10553            ..SchemaConfig::default()
10554        };
10555        let generated = build_schema(&cache, &config);
10556        let schema = build_dynamic_schema(
10557            &generated,
10558            &cache,
10559            None,
10560            None,
10561            Arc::new(Default::default()),
10562            std::time::Duration::from_secs(30),
10563            None,
10564        )
10565        .expect("a federated schema should build");
10566        let sdl = schema.sdl();
10567        let federation_sdl =
10568            schema.sdl_with_options(async_graphql::SDLExportOptions::new().federation());
10569
10570        assert!(sdl.contains("_Service"), "service type:\n{sdl}");
10571        assert!(sdl.contains("_service"), "service field:\n{sdl}");
10572        assert!(
10573            federation_sdl.contains("type users @key(fields: \"id\") @shareable"),
10574            "users key and type-level @shareable:\n{federation_sdl}"
10575        );
10576        assert!(
10577            federation_sdl.contains("@shareable"),
10578            "shared field directive:\n{federation_sdl}"
10579        );
10580        assert!(sdl.contains("type users "), "shared object type:\n{sdl}");
10581        assert!(
10582            !sdl.contains("type test_users "),
10583            "prefixed shared object type:\n{sdl}"
10584        );
10585        assert!(sdl.contains("test_users("), "query root:\n{sdl}");
10586        assert!(sdl.contains("test_users_by_pk("), "by-PK root:\n{sdl}");
10587        assert!(sdl.contains("test_users_bool_exp"), "derived input:\n{sdl}");
10588        assert!(
10589            !sdl.contains("input users_bool_exp "),
10590            "unprefixed derived input:\n{sdl}"
10591        );
10592        assert!(
10593            sdl.contains("test_users_aggregate"),
10594            "aggregate type:\n{sdl}"
10595        );
10596        assert!(
10597            !sdl.contains("type users_aggregate "),
10598            "unprefixed aggregate type:\n{sdl}"
10599        );
10600        assert!(
10601            sdl.contains("test_users_mutation_response"),
10602            "mutation response type:\n{sdl}"
10603        );
10604        assert!(
10605            !sdl.contains("type users_mutation_response "),
10606            "unprefixed mutation response type:\n{sdl}"
10607        );
10608        assert!(
10609            sdl.contains("type test_posts {"),
10610            "non-shared object type remains prefixed:\n{sdl}"
10611        );
10612        assert!(
10613            !sdl.contains("type posts {"),
10614            "non-shared object type must not become unprefixed:\n{sdl}"
10615        );
10616        assert!(sdl.contains("test_posts("), "prefixed posts root:\n{sdl}");
10617        assert!(
10618            sdl.contains("test_posts_bool_exp"),
10619            "prefixed posts bool_exp:\n{sdl}"
10620        );
10621
10622        let response = schema.execute("{ _service { sdl } }").await;
10623        assert!(
10624            response.errors.is_empty(),
10625            "service query errors: {:?}",
10626            response.errors
10627        );
10628        let service = response.data.into_json().expect("service response JSON");
10629        let service_sdl = service
10630            .get("_service")
10631            .and_then(|value| value.get("sdl"))
10632            .and_then(serde_json::Value::as_str)
10633            .expect("service SDL string");
10634        assert!(
10635            service_sdl.contains("type Query"),
10636            "federation root type:\n{service_sdl}"
10637        );
10638        assert!(
10639            service_sdl.contains("test_users("),
10640            "query fields are on the federation root:\n{service_sdl}"
10641        );
10642        assert!(
10643            service_sdl.contains("test_posts("),
10644            "non-shared query fields are on the federation root:\n{service_sdl}"
10645        );
10646        assert!(
10647            !service_sdl.contains("type query_root"),
10648            "Apollo composition treats query_root as an ordinary object without a schema definition:\n{service_sdl}"
10649        );
10650        assert!(
10651            service_sdl.contains("type users @key(fields: \"id\")"),
10652            "{service_sdl}"
10653        );
10654        assert!(
10655            service_sdl.contains("type test_posts @key(fields: \"id\")"),
10656            "{service_sdl}"
10657        );
10658    }
10659
10660    /// `_exists` becomes a subselect over the table it names, correlated with
10661    /// nothing -- which is the difference between it and a relationship.
10662    #[test]
10663    fn exists_is_a_subselect_over_another_table() {
10664        let cache = create_test_schema_cache();
10665        let names = crate::names::NameOverrides::default();
10666        let relationships: HashMap<String, Vec<RelationshipField>> = HashMap::new();
10667        let scope = WhereScope::table("public", "users", "users", &names)
10668            .with_resolution(&cache, &relationships);
10669
10670        let mut param_idx = 1usize;
10671        let mut values: Vec<serde_json::Value> = Vec::new();
10672        let mut aliases = 0usize;
10673        let sql = build_condition(
10674            &serde_json::json!({
10675                "_exists": {"_table": "users", "_where": {"name": {"_eq": "Ann"}}}
10676            }),
10677            &scope,
10678            &mut param_idx,
10679            &mut values,
10680            &mut aliases,
10681        )
10682        .expect("compiles")
10683        .expect("constrains something");
10684
10685        assert_eq!(
10686            sql,
10687            "EXISTS (SELECT 1 FROM \"public\".\"users\" AS \"pgrst_exists_1\" \
10688             WHERE \"pgrst_exists_1\".\"name\" = $1::text)"
10689        );
10690        assert_eq!(values, vec![serde_json::json!("Ann")]);
10691    }
10692
10693    /// A `_table` nobody has is refused rather than written into the query.
10694    #[test]
10695    fn exists_names_a_table_the_server_has() {
10696        let cache = create_test_schema_cache();
10697        let names = crate::names::NameOverrides::default();
10698        let relationships: HashMap<String, Vec<RelationshipField>> = HashMap::new();
10699        let scope = WhereScope::table("public", "users", "users", &names)
10700            .with_resolution(&cache, &relationships);
10701        let error = build_condition(
10702            &serde_json::json!({"_exists": {"_table": "nowhere", "_where": {}}}),
10703            &scope,
10704            &mut 1,
10705            &mut Vec::new(),
10706            &mut 0,
10707        )
10708        .expect_err("a table that is not there is an error");
10709        assert!(
10710            error.message.contains("public.nowhere"),
10711            "{}",
10712            error.message
10713        );
10714    }
10715
10716    /// A role granted "how many" and not "which" gets the count and no rows.
10717    ///
10718    /// A select permission naming no columns, with `allow_aggregations`, is
10719    /// Hasura's way of writing that. The table has an aggregate root and no
10720    /// row type, so `nodes` is not there to be a list of one -- and `count`
10721    /// takes no `columns`, because there are none to name.
10722    #[test]
10723    fn a_table_a_role_may_count_and_not_read_has_a_count_and_no_rows() {
10724        let cache = create_test_schema_cache();
10725        let names = crate::names::NameOverrides::parse(
10726            r#"{"tables": {"public.users": {"permissions":
10727                 {"counter": {"select": {"columns": [], "filter": {},
10728                                         "allow_aggregations": true}}}}}}"#,
10729        )
10730        .unwrap();
10731        let view = crate::role::cache_for_role(&cache, &names, "counter", false);
10732        assert!(!view.tables.is_empty(), "the table is there to be counted");
10733
10734        let config = SchemaConfig {
10735            names: names.clone(),
10736            role: Some("counter".to_string()),
10737            ..SchemaConfig::default()
10738        };
10739        let generated = build_schema(&view, &config);
10740        let schema = build_dynamic_schema(
10741            &generated,
10742            &view,
10743            None,
10744            None,
10745            Arc::new(names),
10746            std::time::Duration::from_secs(30),
10747            Some("counter"),
10748        )
10749        .expect("a role that may only count still has a buildable schema");
10750        let sdl = schema.sdl();
10751
10752        assert!(
10753            sdl.contains("users_aggregate"),
10754            "the count is there:\n{}",
10755            sdl
10756        );
10757        assert!(sdl.contains("count: Int!"), "and it is a count:\n{}", sdl);
10758        // No row type, so nothing that would answer with one.
10759        assert!(!sdl.contains("type users "), "no row type:\n{}", sdl);
10760        assert!(
10761            !sdl.contains("nodes"),
10762            "and no rows beside the numbers:\n{}",
10763            sdl
10764        );
10765        assert!(
10766            !sdl.contains("users_select_column"),
10767            "no column enum to order by or count over:\n{}",
10768            sdl
10769        );
10770        // The functions that read column data are absent with the columns.
10771        assert!(!sdl.contains("users_max_fields"), "no max:\n{}", sdl);
10772    }
10773
10774    /// A role granted `insert` and no `select` gets the write and no type.
10775    ///
10776    /// Hasura's own corpus does this eight times over. What has to hold is
10777    /// that the schema still builds: `insert_users` is there, `users` is not,
10778    /// and the response the insert answers with has no `returning` to name a
10779    /// type that does not exist.
10780    #[test]
10781    fn a_table_a_role_may_only_write_gets_the_write_and_no_type() {
10782        let cache = create_test_schema_cache();
10783        let names = crate::names::NameOverrides::parse(
10784            r#"{"tables": {"public.users": {"permissions":
10785                 {"writer": {"insert": {"columns": "*", "check": {}}}}}}}"#,
10786        )
10787        .unwrap();
10788        let view = crate::role::cache_for_role(&cache, &names, "writer", false);
10789        let config = SchemaConfig {
10790            names: names.clone(),
10791            role: Some("writer".to_string()),
10792            ..SchemaConfig::default()
10793        };
10794        let generated = build_schema(&view, &config);
10795
10796        let schema = build_dynamic_schema(
10797            &generated,
10798            &view,
10799            None,
10800            None,
10801            Arc::new(names),
10802            std::time::Duration::from_secs(30),
10803            Some("writer"),
10804        )
10805        .expect("a role that may only write still has a buildable schema");
10806        let sdl = schema.sdl();
10807
10808        assert!(
10809            sdl.contains("insert_users("),
10810            "the write is there:\n{}",
10811            sdl
10812        );
10813        assert!(
10814            sdl.contains("users_insert_input"),
10815            "and its input:\n{}",
10816            sdl
10817        );
10818        // No row type, and so none of the three fields that answer with one.
10819        assert!(!sdl.contains("type users "), "no row type:\n{}", sdl);
10820        assert!(!sdl.contains("insert_users_one"), "no insert_one:\n{}", sdl);
10821        assert!(
10822            !sdl.contains("returning"),
10823            "and nothing to return:\n{}",
10824            sdl
10825        );
10826        assert!(
10827            sdl.contains("users_mutation_response"),
10828            "the count is still answered:\n{}",
10829            sdl
10830        );
10831        assert!(
10832            !sdl.contains("_mutation_response_mutation_response"),
10833            "and no type is named twice over:\n{}",
10834            sdl
10835        );
10836    }
10837
10838    /// A cache with one VOLATILE function returning rows of `users`, which is
10839    /// the shape `add_to_score` has in Hasura's corpus.
10840    fn cache_with_a_mutation_function() -> SchemaCache {
10841        use postrust_core::schema_cache::{FuncVolatility, RetType, Routine};
10842
10843        let mut cache = create_test_schema_cache();
10844        let routine = Routine {
10845            schema: "public".into(),
10846            name: "add_to_score".into(),
10847            description: None,
10848            params: Vec::new(),
10849            return_type: RetType::SetOf("users".into()),
10850            returns_composite: true,
10851            volatility: FuncVolatility::Volatile,
10852            has_variadic: false,
10853            isolation_level: None,
10854            settings: Vec::new(),
10855            is_procedure: false,
10856            media_type: None,
10857            media_base_type: None,
10858            output_columns: Vec::new(),
10859        };
10860        cache
10861            .routines
10862            .insert(routine.qualified_identifier(), vec![routine]);
10863        cache
10864    }
10865
10866    /// A function with side effects is not granted by permission to read the
10867    /// table it returns. Hasura infers a query function's permission from
10868    /// that select and infers nothing for a mutation, so a role never named
10869    /// by a function permission has no mutation root at all.
10870    #[test]
10871    fn a_mutation_function_needs_the_role_to_be_named() {
10872        let cache = cache_with_a_mutation_function();
10873        let withheld = crate::names::NameOverrides::parse(
10874            r#"{"tables": {"public.users": {"permissions":
10875                 {"reader": {"select": {"columns": "*", "filter": {}}}}}},
10876                "functions": {"public.add_to_score": {"exposed_as": "mutation"}}}"#,
10877        )
10878        .unwrap();
10879        let granted = crate::names::NameOverrides::parse(
10880            r#"{"tables": {"public.users": {"permissions":
10881                 {"reader": {"select": {"columns": "*", "filter": {}}}}}},
10882                "functions": {"public.add_to_score":
10883                  {"exposed_as": "mutation", "roles": ["reader"]}}}"#,
10884        )
10885        .unwrap();
10886
10887        let sdl_for = |names: &crate::names::NameOverrides| {
10888            let view = crate::role::cache_for_role(&cache, names, "reader", false);
10889            let config = SchemaConfig {
10890                names: names.clone(),
10891                role: Some("reader".to_string()),
10892                ..SchemaConfig::default()
10893            };
10894            let generated = build_schema(&view, &config);
10895            build_dynamic_schema(
10896                &generated,
10897                &view,
10898                None,
10899                None,
10900                Arc::new(names.clone()),
10901                std::time::Duration::from_secs(30),
10902                Some("reader"),
10903            )
10904            .expect("schema builds")
10905            .sdl()
10906        };
10907
10908        let without = sdl_for(&withheld);
10909        assert!(
10910            !without.contains("add_to_score"),
10911            "not granted, so not there:\n{}",
10912            without
10913        );
10914        // And with no mutation of any kind left, there is no mutation root --
10915        // which is what `no mutations exist` is answered from.
10916        assert!(
10917            !without.contains("mutation: mutation_root"),
10918            "and no mutation root at all:\n{}",
10919            without
10920        );
10921
10922        let with = sdl_for(&granted);
10923        assert!(
10924            with.contains("add_to_score"),
10925            "named by a function permission, so it is:\n{}",
10926            with
10927        );
10928    }
10929
10930    /// An unrecognised role is a role that was granted nothing, not an error.
10931    #[test]
10932    fn a_role_the_document_never_names_is_granted_nothing() {
10933        let cache = Arc::new(create_test_schema_cache());
10934        let config = SchemaConfig {
10935            names: crate::names::NameOverrides::parse(
10936                r#"{"tables": {"public.users": {"permissions":
10937                     {"reader": {"select": {"columns": "*", "filter": {}}}}}}}"#,
10938            )
10939            .unwrap(),
10940            ..SchemaConfig::default()
10941        };
10942        let empty = build_ungranted_schema(&cache, &config).expect("it builds");
10943        let sdl = empty.sdl();
10944        assert!(
10945            sdl.contains("no_queries_available"),
10946            "nothing to read:\n{}",
10947            sdl
10948        );
10949        assert!(!sdl.contains("type users "), "and no table:\n{}", sdl);
10950        // A document with no permissions at all has no unrecognised roles.
10951        assert!(build_ungranted_schema(&cache, &SchemaConfig::default()).is_none());
10952    }
10953
10954    /// A column the role may write and not read is in the input and not in the
10955    /// type. The two column sets are the point: one schema cache, two answers.
10956    #[test]
10957    fn a_column_a_role_may_set_without_seeing_is_in_the_input_alone() {
10958        let cache = create_test_schema_cache();
10959        let names = crate::names::NameOverrides::parse(
10960            r#"{"tables": {"public.users": {"permissions":
10961                 {"user": {"select": {"columns": ["id"], "filter": {}},
10962                           "insert": {"columns": "*", "check": {}}}}}}}"#,
10963        )
10964        .unwrap();
10965        let view = crate::role::cache_for_role(&cache, &names, "user", false);
10966        let config = SchemaConfig {
10967            names: names.clone(),
10968            role: Some("user".to_string()),
10969            ..SchemaConfig::default()
10970        };
10971        let generated = build_schema(&view, &config);
10972        let object = &generated.object_types["users"];
10973        assert_eq!(
10974            object
10975                .fields
10976                .iter()
10977                .map(|f| f.name.as_str())
10978                .collect::<Vec<_>>(),
10979            vec!["id"],
10980            "the type shows what may be read"
10981        );
10982        assert!(
10983            object.writable_fields.iter().any(|f| f.name == "name"),
10984            "and the input keeps what may be written"
10985        );
10986
10987        let schema = build_dynamic_schema(
10988            &generated,
10989            &view,
10990            None,
10991            None,
10992            Arc::new(names),
10993            std::time::Duration::from_secs(30),
10994            Some("user"),
10995        )
10996        .expect("schema builds");
10997        let sdl = schema.sdl();
10998        let input = sdl
10999            .split("input users_insert_input")
11000            .nth(1)
11001            .and_then(|rest| rest.split('}').next())
11002            .expect("the insert input is registered");
11003        assert!(input.contains("name:"), "settable without being readable");
11004    }
11005
11006    /// A column PostgreSQL generates always is in the row type and in no
11007    /// write input. It is not a permission -- no role may name it -- so the
11008    /// refusal belongs to the schema rather than to the database.
11009    #[test]
11010    fn a_generated_column_is_readable_and_not_writable() {
11011        let mut cache = create_test_schema_cache();
11012        cache
11013            .tables
11014            .get_mut(&postrust_core::api_request::QualifiedIdentifier::new(
11015                "public", "users",
11016            ))
11017            .expect("the fixture has users")
11018            .columns
11019            .get_mut("id")
11020            .expect("with an id")
11021            .always_generated = true;
11022
11023        let names = crate::names::NameOverrides::default();
11024        let config = SchemaConfig {
11025            names: names.clone(),
11026            ..SchemaConfig::default()
11027        };
11028        let generated = build_schema(&cache, &config);
11029        let schema = build_dynamic_schema(
11030            &generated,
11031            &cache,
11032            None,
11033            None,
11034            Arc::new(names),
11035            std::time::Duration::from_secs(30),
11036            None,
11037        )
11038        .expect("schema builds");
11039        let sdl = schema.sdl();
11040
11041        let block = |header: &str| {
11042            sdl.split(header)
11043                .nth(1)
11044                .and_then(|rest| rest.split('}').next())
11045                .unwrap_or_else(|| panic!("{} is registered:\n{}", header, sdl))
11046                .to_string()
11047        };
11048        assert!(
11049            block("type users ").contains("id:"),
11050            "still readable:\n{}",
11051            sdl
11052        );
11053        for header in ["input users_insert_input", "input users_set_input"] {
11054            assert!(
11055                !block(header).contains("id:"),
11056                "{} may not name it:\n{}",
11057                header,
11058                block(header)
11059            );
11060        }
11061        // The table's only number was the generated column, so there is
11062        // nothing left to add to and no type for adding to it.
11063        assert!(
11064            !sdl.contains("users_inc_input"),
11065            "and nothing is left to increment:\n{}",
11066            sdl
11067        );
11068        assert!(
11069            block("input users_insert_input").contains("name:"),
11070            "and the rest of the table is untouched",
11071        );
11072    }
11073
11074    #[test]
11075    fn test_create_object_type() {
11076        let table = create_test_table("users");
11077        let obj = TableObjectType::from_table(&table);
11078        let _gql_obj = create_object_type(&obj, &[], None);
11079    }
11080
11081    #[test]
11082    fn test_create_query_type() {
11083        let cache = create_test_schema_cache();
11084        let config = SchemaConfig::default();
11085        let generated = build_schema(&cache, &config);
11086
11087        let _query = create_query_type(
11088            &generated,
11089            "query_root",
11090            None,
11091            Arc::new(HashMap::new()),
11092            Arc::new(Default::default()),
11093        );
11094    }
11095
11096    #[test]
11097    fn test_create_mutation_type() {
11098        let cache = create_test_schema_cache();
11099        let config = SchemaConfig::default();
11100        let generated = build_schema(&cache, &config);
11101
11102        let _mutation = create_mutation_type(
11103            &generated,
11104            "mutation_root",
11105            Arc::new(HashMap::new()),
11106            Arc::new(HashMap::new()),
11107            Arc::new(Default::default()),
11108            None,
11109            None,
11110        );
11111    }
11112
11113    // ============================================================================
11114    // Scalar Tests
11115    // ============================================================================
11116
11117    #[test]
11118    fn a_scalar_is_named_the_way_a_client_declares_it() {
11119        use crate::types::{pg_type_to_graphql, GraphQLType};
11120
11121        // These names appear in the client's own queries -- `query ($x:
11122        // jsonb!)` names a type that has to exist under exactly that
11123        // spelling -- so they are asserted rather than left to the Display
11124        // impl.
11125        assert_eq!(pg_type_to_graphql("jsonb").to_string(), "jsonb");
11126        assert_eq!(pg_type_to_graphql("json").to_string(), "json");
11127        assert_eq!(pg_type_to_graphql("int8").to_string(), "bigint");
11128        assert_eq!(pg_type_to_graphql("numeric").to_string(), "numeric");
11129        assert_eq!(pg_type_to_graphql("timestamptz").to_string(), "timestamptz");
11130        assert_eq!(pg_type_to_graphql("timestamp").to_string(), "timestamp");
11131        assert_eq!(pg_type_to_graphql("uuid").to_string(), "uuid");
11132
11133        // A type this server knows nothing about keeps its own name, which is
11134        // how a PostGIS column and a database enum both become usable.
11135        assert_eq!(pg_type_to_graphql("geometry").to_string(), "geometry");
11136        assert_eq!(
11137            pg_type_to_graphql("colors_enum"),
11138            GraphQLType::Custom("colors_enum".to_string())
11139        );
11140
11141        // And the leaf of an array is what gets registered, not the array.
11142        assert_eq!(
11143            leaf_scalar_name(&pg_type_to_graphql("_text")),
11144            "String".to_string()
11145        );
11146    }
11147
11148    // ============================================================================
11149    // Filter Input Type Tests
11150    // ============================================================================
11151
11152    #[test]
11153    fn every_table_gets_a_boolean_expression() {
11154        let cache = create_test_schema_cache();
11155        let config = SchemaConfig::default();
11156        let generated = build_schema(&cache, &config);
11157
11158        let (inputs, _) = crate::input::bool_exp::build_inputs(
11159            &generated.object_types,
11160            &generated.relationship_fields,
11161        );
11162        let names: HashSet<String> = inputs.iter().map(|i| i.type_name().to_string()).collect();
11163
11164        for table in generated.object_types.keys() {
11165            let expected = format!("{}_bool_exp", table);
11166            assert!(
11167                names.contains(&expected),
11168                "no {} among {:?}",
11169                expected,
11170                names
11171            );
11172        }
11173        // The scalars the fixture's columns use.
11174        assert!(names.contains("String_comparison_exp"));
11175        assert!(names.contains("Int_comparison_exp"));
11176    }
11177
11178    #[test]
11179    fn a_schema_carrying_the_boolean_expressions_still_builds() {
11180        let cache = create_test_schema_cache();
11181        let config = SchemaConfig::default();
11182        let generated = build_schema(&cache, &config);
11183
11184        let schema = build_dynamic_schema(
11185            &generated,
11186            &cache,
11187            None,
11188            None,
11189            Arc::new(Default::default()),
11190            std::time::Duration::from_secs(30),
11191            None,
11192        );
11193        assert!(schema.is_ok(), "{:?}", schema.err());
11194
11195        let sdl = schema.unwrap().sdl();
11196        assert!(
11197            sdl.contains("_bool_exp"),
11198            "no boolean expressions in:\n{}",
11199            sdl
11200        );
11201        assert!(sdl.contains("_and"), "no _and in the generated expressions");
11202    }
11203
11204    // ============================================================================
11205    // Subscription Tests
11206    // ============================================================================
11207
11208    #[test]
11209    fn test_build_schema_with_subscriptions() {
11210        let cache = create_test_schema_cache();
11211        let config = SchemaConfig {
11212            enable_subscriptions: true,
11213            ..SchemaConfig::default()
11214        };
11215        let generated = build_schema(&cache, &config);
11216
11217        // Generate subscription fields
11218        let sub_fields = generate_subscription_fields(&cache, &generated);
11219        assert!(!sub_fields.is_empty(), "Should have subscription fields");
11220
11221        // Build schema with subscriptions
11222        let result = build_dynamic_schema(
11223            &generated,
11224            &cache,
11225            Some(&sub_fields),
11226            None,
11227            Arc::new(Default::default()),
11228            std::time::Duration::from_secs(30),
11229            None,
11230        );
11231        assert!(result.is_ok(), "Schema with subscriptions should build");
11232    }
11233
11234    #[test]
11235    fn test_subscription_field_generation() {
11236        let cache = create_test_schema_cache();
11237        let config = SchemaConfig::default();
11238        let generated = build_schema(&cache, &config);
11239
11240        let fields = generate_subscription_fields(&cache, &generated);
11241
11242        // Should have one subscription field for the users table
11243        assert_eq!(fields.len(), 1);
11244        assert_eq!(fields[0].name, "users");
11245        assert_eq!(fields[0].table_name, "users");
11246        assert_eq!(fields[0].channel_name(), "postrust_public_users");
11247    }
11248
11249    #[test]
11250    fn test_create_subscription_type() {
11251        let cache = create_test_schema_cache();
11252        let config = SchemaConfig::default();
11253        let generated = build_schema(&cache, &config);
11254        // A live query per queryable root: the subscription root mirrors the
11255        // query root, which is the whole contract.
11256        let _subscription = create_subscription_type(
11257            &generated,
11258            "subscription_root",
11259            None,
11260            Arc::new(Default::default()),
11261            Arc::new(Default::default()),
11262            std::time::Duration::from_secs(30),
11263        );
11264    }
11265}
11266
11267/// One step of a JSON path: a key of an object or an index of an array.
11268#[derive(Debug, PartialEq, Eq)]
11269enum PathStep {
11270    Key(String),
11271    Index(usize),
11272}
11273
11274/// Read one part of a document, by the path spelling Hasura accepts.
11275///
11276/// `column(path: "objs[0]['你好']")` -- an optional leading `$`, then keys
11277/// written bare or after a dot, and indices or quoted keys written in
11278/// brackets. A step that names something the document does not have is null,
11279/// which is what `#>` answers to the same path.
11280fn walk_json_path(value: &Value, path: &str) -> Result<Value, async_graphql::Error> {
11281    let mut at = value;
11282    for step in parse_json_path(path)? {
11283        let next = match (&step, at) {
11284            (PathStep::Key(key), Value::Object(map)) => map.get(key.as_str()),
11285            (PathStep::Index(index), Value::List(items)) => items.get(*index),
11286            // An index of an object or a key of an array reads nothing, and so
11287            // does anything asked of a scalar.
11288            _ => None,
11289        };
11290        match next {
11291            Some(next) => at = next,
11292            None => return Ok(Value::Null),
11293        }
11294    }
11295    Ok(at.clone())
11296}
11297
11298/// A path whose bracket never closes: written wrong rather than written oddly.
11299fn unclosed_bracket(path: &str) -> async_graphql::Error {
11300    let message = format!("\"{}\" is not a JSON path: a bracket is never closed", path);
11301    validation_error(&message)
11302}
11303
11304/// Parse the path spelling Hasura accepts into its steps.
11305///
11306/// Deliberately tolerant about separators, because the corpus writes the same
11307/// path four ways: `objs[0]["x"]`, `objs[0].["x"]`, `objs.[0].["x"]` and
11308/// `.objs[0]['x']` all name one thing. What is not tolerated is a bracket that
11309/// never closes, which is a path the client got wrong rather than a spelling.
11310fn parse_json_path(path: &str) -> Result<Vec<PathStep>, async_graphql::Error> {
11311    let mut steps = Vec::new();
11312    let mut chars = path.chars().peekable();
11313    // `$` is the document itself, and naming it is optional.
11314    if chars.peek() == Some(&'$') {
11315        chars.next();
11316    }
11317    while let Some(&c) = chars.peek() {
11318        match c {
11319            // A separator carries no step of its own.
11320            '.' => {
11321                chars.next();
11322            }
11323            '[' => {
11324                chars.next();
11325                let quote = match chars.peek() {
11326                    Some(&q @ ('\'' | '"')) => {
11327                        chars.next();
11328                        Some(q)
11329                    }
11330                    _ => None,
11331                };
11332                let mut inner = String::new();
11333                loop {
11334                    let Some(c) = chars.next() else {
11335                        return Err(unclosed_bracket(path));
11336                    };
11337                    match (quote, c) {
11338                        (Some(quote), c) if c == quote => break,
11339                        (None, ']') => break,
11340                        _ => inner.push(c),
11341                    }
11342                }
11343                // A quoted key's closing bracket, which the quote ended before.
11344                if quote.is_some() {
11345                    match chars.next() {
11346                        Some(']') => {}
11347                        _ => return Err(unclosed_bracket(path)),
11348                    }
11349                }
11350                // An unquoted number is an index; anything else is a key,
11351                // since an object may be keyed by a word as well as a digit.
11352                match (quote, inner.parse::<usize>()) {
11353                    (None, Ok(index)) => steps.push(PathStep::Index(index)),
11354                    _ => steps.push(PathStep::Key(inner)),
11355                }
11356            }
11357            _ => {
11358                let mut key = String::new();
11359                while let Some(&c) = chars.peek() {
11360                    if matches!(c, '.' | '[') {
11361                        break;
11362                    }
11363                    key.push(c);
11364                    chars.next();
11365                }
11366                steps.push(PathStep::Key(key));
11367            }
11368        }
11369    }
11370    Ok(steps)
11371}
11372
11373#[cfg(test)]
11374mod json_path_tests {
11375    use super::*;
11376
11377    fn steps(path: &str) -> Vec<PathStep> {
11378        parse_json_path(path).expect("the path parses")
11379    }
11380
11381    fn key(name: &str) -> PathStep {
11382        PathStep::Key(name.to_string())
11383    }
11384
11385    #[test]
11386    fn the_document_itself_has_no_steps() {
11387        assert_eq!(steps("$"), vec![]);
11388        assert_eq!(steps(""), vec![]);
11389    }
11390
11391    #[test]
11392    fn a_key_is_written_bare_or_after_a_dot() {
11393        assert_eq!(steps("a"), vec![key("a")]);
11394        assert_eq!(steps(".obj.c1"), vec![key("obj"), key("c1")]);
11395        assert_eq!(steps("._underscore"), vec![key("_underscore")]);
11396    }
11397
11398    #[test]
11399    fn a_bracket_holds_an_index_or_a_quoted_key() {
11400        assert_eq!(steps("arr[0]"), vec![key("arr"), PathStep::Index(0)]);
11401        assert_eq!(steps("['!@#$%^']"), vec![key("!@#$%^")]);
11402        assert_eq!(
11403            steps("translations['hello world!']"),
11404            vec![key("translations"), key("hello world!")]
11405        );
11406    }
11407
11408    /// The corpus writes one path four ways, and Hasura reads them all alike.
11409    #[test]
11410    fn a_dot_before_a_bracket_changes_nothing() {
11411        let expected = vec![key("objs"), PathStep::Index(0), key("\u{4f60}\u{597d}")];
11412        for spelling in [
11413            "objs[0]['\u{4f60}\u{597d}']",
11414            "objs[0][\"\u{4f60}\u{597d}\"]",
11415            "objs[0].[\"\u{4f60}\u{597d}\"]",
11416            "objs.[0].[\"\u{4f60}\u{597d}\"]",
11417        ] {
11418            assert_eq!(steps(spelling), expected, "{}", spelling);
11419        }
11420    }
11421
11422    #[test]
11423    fn a_bracket_that_never_closes_is_refused() {
11424        assert!(parse_json_path("arr[0").is_err());
11425        assert!(parse_json_path("['key'").is_err());
11426    }
11427
11428    #[test]
11429    fn a_step_the_document_does_not_have_reads_null() {
11430        let document = Value::from_json(serde_json::json!({
11431            "obj": {"c1": "c2"},
11432            "arr": [1, 2, 3],
11433        }))
11434        .expect("a document");
11435        let at = |path| walk_json_path(&document, path).expect("the path parses");
11436        assert_eq!(at(".obj.c1"), Value::String("c2".to_string()));
11437        assert_eq!(at("arr[1]"), Value::Number(2.into()));
11438        assert_eq!(at("arr[9]"), Value::Null);
11439        assert_eq!(at(".obj.nothing"), Value::Null);
11440        // An index of an object, and a key of an array: neither reads
11441        // anything, which is what `#>` answers.
11442        assert_eq!(at("obj[0]"), Value::Null);
11443        assert_eq!(at("arr.first"), Value::Null);
11444    }
11445}