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        let gql_field = if entity_is_shared && !field.is_pk {
1821            gql_field.shareable()
1822        } else {
1823            gql_field
1824        };
1825
1826        fields.push((field.name.clone(), gql_field));
1827    }
1828
1829    // Relationship fields. The query resolver embeds related rows into the
1830    // parent JSON before returning it, so these read from the parent value the
1831    // same way column fields do.
1832    for rel in relationships {
1833        if !taken.insert(rel.name.clone()) {
1834            tracing::warn!(
1835                "{}: not exposing the relationship to \"{}\" as `{}` -- the table \
1836                 already has a column of that name",
1837                obj.name,
1838                rel.target_type,
1839                rel.name
1840            );
1841            continue;
1842        }
1843        let field_name = rel.name.clone();
1844        let field_type = if rel.is_list {
1845            TypeRef::named_nn_list_nn(&rel.target_type)
1846        } else if always_present(rel, &obj.table) {
1847            TypeRef::named_nn(&rel.target_type)
1848        } else {
1849            TypeRef::named(&rel.target_type)
1850        };
1851
1852        let is_list = rel.is_list;
1853        let mut gql_field = Field::new(&rel.name, field_type, move |ctx| {
1854            let field_name = field_name.clone();
1855            FieldFuture::new(async move {
1856                if let Some(Value::Object(map)) = ctx.parent_value.as_value() {
1857                    let key = async_graphql::Name::new(&field_name);
1858                    match map.get(&key) {
1859                        // A row that points at nothing has no related row, and
1860                        // the answer to that is null -- not an object whose
1861                        // every field is null, which is what handing a null
1862                        // parent value to the field resolvers produced.
1863                        Some(Value::Null) if !is_list => return Ok(None),
1864                        Some(val) => return Ok(Some(FieldValue::value(val.clone()))),
1865                        None => {}
1866                    }
1867                }
1868                Ok(None)
1869            })
1870        });
1871
1872        // The same arguments the root field takes. An embedded list is a list
1873        // like any other: a client showing the five most recent articles of an
1874        // author has nowhere else to say so, and without these the only way to
1875        // narrow one is to fetch all of it and discard the rest in the client.
1876        // A to-one relationship is left alone -- there is nothing to order or
1877        // page through when the answer is one row.
1878        // A computed relationship's function may take more than the row --
1879        // "the articles of this author matching a search" -- and `args` is
1880        // where the caller writes them, so a term called `limit` cannot shadow
1881        // the one that pages the result.
1882        if !rel.arguments.is_empty() {
1883            gql_field = gql_field.argument(InputValue::new(
1884                "args",
1885                TypeRef::named_nn(computed_args_type_name(&obj.local_name, &rel.name)),
1886            ));
1887        }
1888        if rel.is_list {
1889            gql_field = gql_field
1890                .argument(InputValue::new(
1891                    "distinct_on",
1892                    TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
1893                        &rel.target_local_name,
1894                    )),
1895                ))
1896                .argument(InputValue::new(
1897                    "where",
1898                    TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
1899                        &rel.target_local_name,
1900                    )),
1901                ))
1902                .argument(InputValue::new(
1903                    "order_by",
1904                    TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
1905                        &rel.target_local_name,
1906                    )),
1907                ))
1908                .argument(InputValue::new("limit", TypeRef::named("Int")))
1909                .argument(InputValue::new("offset", TypeRef::named("Int")));
1910        }
1911
1912        let gql_field = if let Some(desc) = &rel.description {
1913            gql_field.description(desc)
1914        } else {
1915            gql_field
1916        };
1917        let gql_field = if entity_is_shared {
1918            gql_field.shareable()
1919        } else {
1920            gql_field
1921        };
1922
1923        fields.push((rel.name.clone(), gql_field));
1924
1925        // `author { articles_aggregate { aggregate { count } } }` -- the count
1926        // of a row's children without fetching them, which is the query behind
1927        // every "12 comments" beside a post. Only for a relationship to many:
1928        // counting one row is not a question anyone asks.
1929        if rel.is_list {
1930            let aggregate_field = format!("{}_aggregate", rel.name);
1931            if taken.insert(aggregate_field.clone()) {
1932                let key = aggregate_field.clone();
1933                fields.push((
1934                    aggregate_field.clone(),
1935                    Field::new(
1936                        &aggregate_field,
1937                        TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
1938                            &rel.target_local_name,
1939                        )),
1940                        move |ctx| {
1941                            let key = key.clone();
1942                            FieldFuture::new(async move {
1943                                // Absent where the parent has no children at
1944                                // all; the aggregate type's own resolvers read
1945                                // a missing key as zero and an empty list.
1946                                Ok(Some(FieldValue::value(
1947                                    child_value(&ctx, &key).unwrap_or(Value::Null),
1948                                )))
1949                            })
1950                        },
1951                    )
1952                    // The same arguments the list itself takes. "How many of
1953                    // this author's articles were published this year" is the
1954                    // question a count is usually asked as, and without a
1955                    // `where` there is no way to write it.
1956                    .argument(InputValue::new(
1957                        "distinct_on",
1958                        TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
1959                            &rel.target_local_name,
1960                        )),
1961                    ))
1962                    .argument(InputValue::new(
1963                        "where",
1964                        TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
1965                            &rel.target_local_name,
1966                        )),
1967                    ))
1968                    .argument(InputValue::new(
1969                        "order_by",
1970                        TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
1971                            &rel.target_local_name,
1972                        )),
1973                    ))
1974                    .argument(InputValue::new("limit", TypeRef::named("Int")))
1975                    .argument(InputValue::new("offset", TypeRef::named("Int")))
1976                    .description(format!("Aggregates over {}.", rel.name)),
1977                ));
1978                // Counting the rows a function answers with means calling it,
1979                // so the aggregate takes whatever the function takes.
1980                if !rel.arguments.is_empty() {
1981                    let last = fields.len() - 1;
1982                    let (name, field) = fields.remove(last);
1983                    fields.push((
1984                        name,
1985                        field.argument(InputValue::new(
1986                            "args",
1987                            TypeRef::named_nn(computed_args_type_name(&obj.local_name, &rel.name)),
1988                        )),
1989                    ));
1990                }
1991                if entity_is_shared {
1992                    let last = fields.len() - 1;
1993                    let (name, field) = fields.remove(last);
1994                    fields.push((name, field.shareable()));
1995                }
1996            }
1997        }
1998    }
1999
2000    fields.sort_by(|(a, _), (b, _)| a.cmp(b));
2001    for (_, field) in fields {
2002        object = object.field(field);
2003    }
2004
2005    object
2006}
2007
2008/// A root field, whichever root it is on.
2009///
2010/// A query field and a subscription field take the same arguments and mean the
2011/// same by them -- the difference is only whether the answer is sent once or
2012/// whenever it changes -- and the two builders share no trait of their own, so
2013/// this is what lets the argument list be written once.
2014trait RootField: Sized {
2015    fn with_argument(self, value: InputValue) -> Self;
2016}
2017
2018impl RootField for Field {
2019    fn with_argument(self, value: InputValue) -> Self {
2020        self.argument(value)
2021    }
2022}
2023
2024impl RootField for SubscriptionField {
2025    fn with_argument(self, value: InputValue) -> Self {
2026        self.argument(value)
2027    }
2028}
2029
2030/// The five arguments that narrow a set of rows, in the order Hasura lists
2031/// them.
2032fn with_row_arguments<F: RootField>(field: F, type_name: &str) -> F {
2033    with_row_arguments_named(field, type_name, true)
2034}
2035
2036/// The same, where `columns` says whether the table has any to name.
2037///
2038/// A table a role may count and not read has none: there is no column enum to
2039/// order by and none to be distinct on, so those two arguments are not there
2040/// -- and could not be, since the types they name are not built either. What
2041/// is left still narrows the set being counted, which is the whole of what
2042/// such a root is for.
2043fn with_row_arguments_named<F: RootField>(field: F, type_name: &str, columns: bool) -> F {
2044    let mut field = field;
2045    if columns {
2046        field = field.with_argument(InputValue::new(
2047            "distinct_on",
2048            TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(type_name)),
2049        ));
2050    }
2051    field = field
2052        .with_argument(InputValue::new("limit", TypeRef::named("Int")))
2053        .with_argument(InputValue::new("offset", TypeRef::named("Int")));
2054    if columns {
2055        field = field.with_argument(InputValue::new(
2056            "order_by",
2057            TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(type_name)),
2058        ));
2059    }
2060    field.with_argument(InputValue::new(
2061        "where",
2062        TypeRef::named(crate::input::bool_exp::bool_exp_type_name(type_name)),
2063    ))
2064}
2065
2066/// One argument per primary key column, named and typed after the column
2067/// itself rather than assuming an integer `id`.
2068fn with_key_arguments<F: RootField>(
2069    field: F,
2070    schema_name: &str,
2071    table_name: &str,
2072    pk_columns: &[(String, String)],
2073    names: &crate::names::NameOverrides,
2074) -> F {
2075    let mut field = field;
2076    for (column, pg_type) in pk_columns {
2077        field = field.with_argument(InputValue::new(
2078            names
2079                .column(schema_name, table_name, column)
2080                .unwrap_or(column),
2081            TypeRef::named_nn(exposed_pk_argument_type(
2082                names,
2083                schema_name,
2084                table_name,
2085                column,
2086                pg_type,
2087            )),
2088        ));
2089    }
2090    field
2091}
2092
2093/// Create the Query type with all table query fields.
2094fn create_query_type(
2095    generated: &GeneratedSchema,
2096    root_name: &str,
2097    max_rows: Option<i64>,
2098    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2099    names: Arc<crate::names::NameOverrides>,
2100) -> Object {
2101    // Collected rather than added as they are built, so they can go on in name
2102    // order: that is the order Hasura answers introspection in, and it is the
2103    // order a client diffing two schemas, or a generator writing its types
2104    // out, gets a stable answer from.
2105    let mut roots: Vec<(String, Field)> = Vec::new();
2106
2107    for field in &generated.query_fields {
2108        let table_name = field.table_name.clone();
2109        let schema_name = field.schema_name.clone();
2110        let type_name = field.type_name.clone();
2111        let local_type_name = field.local_type_name.clone();
2112        let is_by_pk = field.is_by_pk;
2113        let pk_columns = field.pk_columns.clone();
2114        let return_type = graphql_type_ref(&field.return_type);
2115
2116        let spec_type_name = local_type_name.clone();
2117        let spec = Arc::new(QueryFieldSpec {
2118            schema_name,
2119            table_name,
2120            type_name,
2121            is_by_pk,
2122            pk_columns: pk_columns.clone(),
2123            max_rows,
2124            relationships: Arc::clone(&relationships),
2125            names: Arc::clone(&names),
2126            call: None,
2127        });
2128
2129        let mut gql_field = Field::new(&field.name, return_type, move |ctx| {
2130            let spec = Arc::clone(&spec);
2131            FieldFuture::new(async move { resolve_query(&ctx, &spec).await })
2132        });
2133
2134        // Add standard query arguments
2135        gql_field = match is_by_pk {
2136            false => with_row_arguments(gql_field, &spec_type_name),
2137            true => with_key_arguments(
2138                gql_field,
2139                &field.schema_name,
2140                &field.table_name,
2141                &pk_columns,
2142                names.as_ref(),
2143            ),
2144        };
2145
2146        if let Some(desc) = &field.description {
2147            gql_field = gql_field.description(desc);
2148        }
2149
2150        // A table this role may count and not read has no row type, so the
2151        // list root that would answer with one is not built. The entry is
2152        // still here for the aggregate root below, which is what such a role
2153        // was granted.
2154        if field.rows {
2155            roots.push((field.name.clone(), gql_field));
2156        }
2157
2158        // The same rows, with numbers about them. Same arguments as the list
2159        // field, because `author_aggregate(where: ...)` counts the set the
2160        // filter describes, not the whole table.
2161        //
2162        // Not built at all for a role whose permission withholds it: counting
2163        // rows is a way of learning about them, so it is granted separately
2164        // from reading them and refused by absence rather than at execution.
2165        if !is_by_pk && field.aggregates {
2166            let agg_spec = Arc::new(AggregateSpec {
2167                schema_name: field.schema_name.clone(),
2168                table_name: field.table_name.clone(),
2169                type_name: field.type_name.clone(),
2170                max_rows,
2171                relationships: Arc::clone(&relationships),
2172                names: Arc::clone(&names),
2173                call: None,
2174            });
2175            let aggregate_field_name = field.aggregate_name.clone().unwrap_or_else(|| {
2176                crate::schema::aggregate::aggregate_type_name(&field.local_type_name)
2177            });
2178            let aggregate_field_name_for_sorting = aggregate_field_name.clone();
2179            let mut agg_field = Field::new(
2180                aggregate_field_name,
2181                TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
2182                    &field.local_type_name,
2183                )),
2184                move |ctx| {
2185                    let agg_spec = Arc::clone(&agg_spec);
2186                    FieldFuture::new(async move { resolve_aggregate(&ctx, &agg_spec).await })
2187                },
2188            );
2189            agg_field = with_row_arguments_named(agg_field, &spec_type_name, field.rows);
2190            agg_field = match field.aggregate_description.as_deref() {
2191                Some("") => agg_field,
2192                Some(given) => agg_field.description(given),
2193                None => agg_field.description(format!(
2194                    "fetch aggregated fields from the table: \"{}\"",
2195                    field.table_name
2196                )),
2197            };
2198            roots.push((aggregate_field_name_for_sorting, agg_field));
2199        }
2200    }
2201
2202    roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2203    let mut query = Object::new(root_name);
2204    // A GraphQL object may not have no fields, so a schema that exposes no
2205    // table needs something on its query root. Hasura puts a placeholder there
2206    // and calls it this; a client that reaches it has nothing to read.
2207    if roots.is_empty() {
2208        return query.field(
2209            Field::new("no_queries_available", TypeRef::named("String"), |_| {
2210                FieldFuture::new(async move { Ok(None::<Value>) })
2211            })
2212            .description("There are no queries available to the current role."),
2213        );
2214    }
2215    for (_, field) in roots {
2216        query = query.field(field);
2217    }
2218
2219    query
2220}
2221
2222/// One document operator: its name, and the type its columns are given.
2223type JsonbOperator = (&'static str, fn() -> TypeRef);
2224
2225/// What a document column may be told to do, and what each is told with.
2226///
2227/// `_append` and `_prepend` take another document; `_delete_key` takes a key;
2228/// `_delete_elem` takes an index into an array; `_delete_at_path` takes the
2229/// path to what is being removed. The shapes are per operator rather than per
2230/// column, which is why one input type per operator says all of it.
2231const JSONB_OPERATORS: &[JsonbOperator] = &[
2232    ("_append", || TypeRef::named("jsonb")),
2233    ("_delete_at_path", || TypeRef::named_nn_list("String")),
2234    ("_delete_elem", || TypeRef::named("Int")),
2235    ("_delete_key", || TypeRef::named("String")),
2236    ("_prepend", || TypeRef::named("jsonb")),
2237];
2238
2239/// The name of the input holding one document operator's columns.
2240fn jsonb_operator_input(type_name: &str, operator: &str) -> String {
2241    format!("{}{}_input", type_name, operator)
2242}
2243
2244/// Add the operators an update may be written with.
2245///
2246/// All optional, and at least one required -- which GraphQL cannot express, so
2247/// the resolver says so instead of the schema. Making `_set` non-null would
2248/// have been expressible and wrong: an update that only increments a counter
2249/// never sends one.
2250fn with_update_operators(
2251    field: Field,
2252    base_name: &str,
2253    has_numeric: bool,
2254    has_jsonb: bool,
2255) -> Field {
2256    let mut field = field;
2257    // A table with no document column is not offered the document operators:
2258    // there is nothing there to append to.
2259    if has_jsonb {
2260        for (operator, _) in JSONB_OPERATORS {
2261            field = field.argument(InputValue::new(
2262                *operator,
2263                TypeRef::named(jsonb_operator_input(base_name, operator)),
2264            ));
2265        }
2266    }
2267    if has_numeric {
2268        field = field.argument(InputValue::new(
2269            "_inc",
2270            TypeRef::named(format!("{}_inc_input", base_name)),
2271        ));
2272    }
2273    field.argument(InputValue::new(
2274        "_set",
2275        TypeRef::named(format!("{}_set_input", base_name)),
2276    ))
2277}
2278
2279/// Create the Mutation type with all mutation fields.
2280/// Which columns a write may name, and so which of its inputs exist.
2281///
2282/// One definition, called both where the inputs are registered and where the
2283/// arguments naming them are declared. They used to agree by coincidence --
2284/// both read the object type's fields -- and stopped the moment a write input
2285/// began following its own permission. An argument naming a type nobody
2286/// registered is a schema async-graphql refuses to build, which costs a role
2287/// every field it has over the one it cannot use.
2288fn write_fields<'a>(
2289    object: &'a crate::schema::object::TableObjectType,
2290    names: &crate::names::NameOverrides,
2291    role: Option<&str>,
2292    verb: crate::role::Verb,
2293) -> Vec<&'a crate::schema::object::GraphQLField> {
2294    let allowed = role.and_then(|role| {
2295        names
2296            .permissions(&object.table.schema, &object.table.name, role)
2297            .and_then(|granted| granted.write_columns(verb))
2298    });
2299    object
2300        .writable_fields
2301        .iter()
2302        .filter(|field| {
2303            let column = table_column_for(names, &object.table, &field.name);
2304            // A column PostgreSQL generates always is not one a write may
2305            // name. Leaving it in the input type moved the refusal to the
2306            // database, which answers `cannot insert a non-DEFAULT value into
2307            // column "id"` and has by then forgotten which argument the value
2308            // came from. Out of the type, the walk over the request says
2309            // `field 'id' not found in type: 'author_insert_input'` and can
2310            // still point at it.
2311            object
2312                .table
2313                .get_column(column)
2314                .is_some_and(|c| !c.always_generated)
2315                && allowed.is_none_or(|set| set.allows(column))
2316        })
2317        .collect()
2318}
2319
2320/// Whether a type has an `_inc_input` and a set of document operator inputs.
2321fn update_inputs(
2322    object: &crate::schema::object::TableObjectType,
2323    names: &crate::names::NameOverrides,
2324    role: Option<&str>,
2325) -> (bool, bool) {
2326    let fields = write_fields(object, names, role, crate::role::Verb::Update);
2327    (
2328        fields
2329            .iter()
2330            .any(|f| crate::schema::aggregate::is_incrementable(&f.graphql_type)),
2331        fields
2332            .iter()
2333            .any(|f| matches!(&f.graphql_type, crate::types::GraphQLType::Json)),
2334    )
2335}
2336
2337fn create_mutation_type(
2338    generated: &GeneratedSchema,
2339    root_name: &str,
2340    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2341    type_names: Arc<HashMap<(String, String), String>>,
2342    names: Arc<crate::names::NameOverrides>,
2343    max_rows: Option<i64>,
2344    role: Option<&str>,
2345) -> Object {
2346    let mut mutation = Object::new(root_name);
2347    // In name order, for the reason the query root is: see there.
2348    let mut roots: Vec<(String, Field)> = Vec::new();
2349
2350    // Only a table with a unique constraint has a conflict to name, and only
2351    // those got the types for it.
2352    // Which tables have something to add to, and which have a document to
2353    // operate on. Read from what was registered above rather than worked out
2354    // again from the object types: the second answer is the one that can
2355    // drift, and drifting means an argument naming a type that is not there.
2356    let mut has_numeric_column: HashSet<String> = HashSet::new();
2357    let mut has_jsonb_column: HashSet<String> = HashSet::new();
2358    for object in generated.object_types.values() {
2359        let (numeric, jsonb) = update_inputs(object, &names, role);
2360        if numeric {
2361            has_numeric_column.insert(object.local_name.clone());
2362        }
2363        if jsonb {
2364            has_jsonb_column.insert(object.local_name.clone());
2365        }
2366    }
2367
2368    let has_conflict_target: HashSet<String> = generated
2369        .object_types
2370        .iter()
2371        .filter(|(_, object)| !object.table.unique_constraints.is_empty())
2372        .map(|(_, object)| object.local_name.clone())
2373        .collect();
2374
2375    for field in &generated.mutation_fields {
2376        let table_name = field.table_name.clone();
2377        let schema_name = field.schema_name.clone();
2378        let mutation_type = field.mutation_type;
2379        let pk_columns = field.pk_columns.clone();
2380        let return_type = graphql_type_ref(&field.return_type);
2381
2382        // The table's own type name, which is what its boolean expression is
2383        // named after. A bulk mutation returns `[author!]!` and a by-key one
2384        // returns `author`; both name the same table.
2385        let where_type = field.local_type_name.clone();
2386
2387        let resolver_pk_columns = pk_columns.clone();
2388        let field_relationships = Arc::clone(&relationships);
2389        let field_type_names = Arc::clone(&type_names);
2390        let field_names = Arc::clone(&names);
2391        let mut gql_field = Field::new(&field.name, return_type, move |ctx| {
2392            let table_name = table_name.clone();
2393            let schema_name = schema_name.clone();
2394            let pk_columns = resolver_pk_columns.clone();
2395            let relationships = Arc::clone(&field_relationships);
2396            let type_names = Arc::clone(&field_type_names);
2397            let names = Arc::clone(&field_names);
2398            FieldFuture::new(async move {
2399                resolve_mutation(
2400                    &ctx,
2401                    &schema_name,
2402                    &table_name,
2403                    mutation_type,
2404                    &pk_columns,
2405                    &relationships,
2406                    &type_names,
2407                    &names,
2408                    max_rows,
2409                )
2410                .await
2411            })
2412        });
2413
2414        // Add mutation-specific arguments.
2415        //
2416        // A by-PK mutation takes the key columns rather than a `where` object:
2417        // it is meant to address exactly one row, and accepting `where` made it
2418        // an ordinary bulk mutation that happened to return the first result.
2419        match mutation_type {
2420            MutationType::Insert | MutationType::InsertOne => {
2421                let insert_input = format!("{}_insert_input", where_type);
2422                gql_field = if mutation_type == MutationType::Insert {
2423                    gql_field.argument(InputValue::new(
2424                        "objects",
2425                        TypeRef::named_nn_list_nn(&insert_input),
2426                    ))
2427                } else {
2428                    // A single insert takes `object`, not a one-element
2429                    // `objects`.
2430                    gql_field.argument(InputValue::new("object", TypeRef::named_nn(&insert_input)))
2431                };
2432                if has_conflict_target.contains(&where_type) {
2433                    gql_field = gql_field.argument(InputValue::new(
2434                        "on_conflict",
2435                        TypeRef::named(format!("{}_on_conflict", where_type)),
2436                    ));
2437                }
2438            }
2439            MutationType::UpdateByPk => {
2440                gql_field = gql_field.argument(InputValue::new(
2441                    "pk_columns",
2442                    TypeRef::named_nn(format!("{}_pk_columns_input", where_type)),
2443                ));
2444                gql_field = with_update_operators(
2445                    gql_field,
2446                    &where_type,
2447                    has_numeric_column.contains(&where_type),
2448                    has_jsonb_column.contains(&where_type),
2449                );
2450            }
2451            MutationType::Update => {
2452                gql_field = gql_field.argument(InputValue::new(
2453                    "where",
2454                    TypeRef::named_nn(crate::input::bool_exp::bool_exp_type_name(&where_type)),
2455                ));
2456                gql_field = with_update_operators(
2457                    gql_field,
2458                    &where_type,
2459                    has_numeric_column.contains(&where_type),
2460                    has_jsonb_column.contains(&where_type),
2461                );
2462            }
2463            MutationType::UpdateMany => {
2464                gql_field = gql_field.argument(InputValue::new(
2465                    "updates",
2466                    TypeRef::named_nn_list_nn(format!("{}_updates", where_type)),
2467                ));
2468            }
2469            MutationType::DeleteByPk => {
2470                for (col_name, pg_type) in &pk_columns {
2471                    gql_field = gql_field.argument(InputValue::new(
2472                        names
2473                            .column(&field.schema_name, &field.table_name, col_name)
2474                            .unwrap_or(col_name),
2475                        TypeRef::named_nn(exposed_pk_argument_type(
2476                            names.as_ref(),
2477                            &field.schema_name,
2478                            &field.table_name,
2479                            col_name,
2480                            pg_type,
2481                        )),
2482                    ));
2483                }
2484            }
2485            MutationType::Delete => {
2486                // Required, as it is on an update: a delete with no predicate
2487                // is a delete of the whole table, and this refused one at
2488                // execution while the schema said it was a query worth
2489                // writing. Saying so in the type is what Hasura does, and it
2490                // is what a client's own tooling can catch before the request
2491                // is sent.
2492                gql_field = gql_field.argument(InputValue::new(
2493                    "where",
2494                    TypeRef::named_nn(crate::input::bool_exp::bool_exp_type_name(&where_type)),
2495                ));
2496            }
2497        }
2498
2499        if let Some(desc) = &field.description {
2500            gql_field = gql_field.description(desc);
2501        }
2502
2503        roots.push((field.name.clone(), gql_field));
2504    }
2505
2506    roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2507    for (_, field) in roots {
2508        mutation = mutation.field(field);
2509    }
2510
2511    mutation
2512}
2513
2514/// Create the Subscription type: the query root, answered again on change.
2515///
2516/// A subscription here is a **live query**. It carries the same fields the
2517/// query root does, takes the same arguments, and answers with the same rows
2518/// -- the difference is that the answer is sent again whenever it stops being
2519/// true. That is the contract a client generated against Hasura expects, and
2520/// the reason its `subscription_root` is a mirror of its `query_root`.
2521///
2522/// What wakes it is this server's own: a trigger publishes on the changed
2523/// table and the query is read again, which costs nothing while nothing is
2524/// written and answers in milliseconds when something is. A trigger cannot
2525/// see everything a query can -- a view has none, an embedded row may live in
2526/// a table that carries none, and `where: {expires_at: {_lt: "now()"}}`
2527/// changes with no write at all -- so a slow refresh runs beside it and
2528/// closes exactly those gaps. Polling alone is what Hasura does, and it pays
2529/// for every subscriber every tick whether or not anything happened.
2530fn create_subscription_type(
2531    generated: &GeneratedSchema,
2532    root_name: &str,
2533    max_rows: Option<i64>,
2534    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2535    names: Arc<crate::names::NameOverrides>,
2536    refresh: std::time::Duration,
2537) -> Subscription {
2538    let mut roots: Vec<(String, SubscriptionField)> = Vec::new();
2539
2540    for field in &generated.query_fields {
2541        let spec_type_name = field.local_type_name.clone();
2542        let pk_columns = field.pk_columns.clone();
2543        let is_by_pk = field.is_by_pk;
2544        let return_type = graphql_type_ref(&field.return_type);
2545        let watched = vec![crate::subscription::table_channel_name(
2546            &field.schema_name,
2547            &field.table_name,
2548        )];
2549
2550        let spec = Arc::new(QueryFieldSpec {
2551            schema_name: field.schema_name.clone(),
2552            table_name: field.table_name.clone(),
2553            type_name: field.type_name.clone(),
2554            is_by_pk,
2555            pk_columns: pk_columns.clone(),
2556            max_rows,
2557            relationships: Arc::clone(&relationships),
2558            names: Arc::clone(&names),
2559            call: None,
2560        });
2561
2562        let mut gql_field = SubscriptionField::new(&field.name, return_type, move |ctx| {
2563            let spec = Arc::clone(&spec);
2564            let watched = watched.clone();
2565            SubscriptionFieldFuture::new(async move {
2566                let wake = wake_on(&ctx, &watched, refresh).await;
2567                Ok(live(ctx, LiveSource::Rows(spec), wake))
2568            })
2569        });
2570
2571        gql_field = match is_by_pk {
2572            false => with_row_arguments(gql_field, &spec_type_name),
2573            true => with_key_arguments(
2574                gql_field,
2575                &field.schema_name,
2576                &field.table_name,
2577                &pk_columns,
2578                names.as_ref(),
2579            ),
2580        };
2581        if let Some(desc) = &field.description {
2582            gql_field = gql_field.description(desc);
2583        }
2584        // No row type, no root that answers with one -- see the query root.
2585        if field.rows {
2586            roots.push((field.name.clone(), gql_field));
2587        }
2588
2589        // A live query mirrors the query root, so an aggregate the role may not
2590        // ask for once is not one it may ask for continuously either.
2591        if is_by_pk || !field.aggregates {
2592            continue;
2593        }
2594
2595        // The same rows, with numbers about them, watched the same way.
2596        let agg_spec = Arc::new(AggregateSpec {
2597            schema_name: field.schema_name.clone(),
2598            table_name: field.table_name.clone(),
2599            type_name: field.type_name.clone(),
2600            max_rows,
2601            relationships: Arc::clone(&relationships),
2602            names: Arc::clone(&names),
2603            call: None,
2604        });
2605        let agg_watched = vec![crate::subscription::table_channel_name(
2606            &field.schema_name,
2607            &field.table_name,
2608        )];
2609        let agg_name = field.aggregate_name.clone().unwrap_or_else(|| {
2610            crate::schema::aggregate::aggregate_type_name(&field.local_type_name)
2611        });
2612        let mut agg_field = SubscriptionField::new(
2613            agg_name.clone(),
2614            TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
2615                &field.local_type_name,
2616            )),
2617            move |ctx| {
2618                let agg_spec = Arc::clone(&agg_spec);
2619                let watched = agg_watched.clone();
2620                SubscriptionFieldFuture::new(async move {
2621                    let wake = wake_on(&ctx, &watched, refresh).await;
2622                    Ok(live(ctx, LiveSource::Aggregate(agg_spec), wake))
2623                })
2624            },
2625        );
2626        agg_field = with_row_arguments_named(agg_field, &spec_type_name, field.rows);
2627        agg_field = match field.aggregate_description.as_deref() {
2628            Some("") => agg_field,
2629            Some(given) => agg_field.description(given),
2630            None => agg_field.description(format!(
2631                "fetch aggregated fields from the table: \"{}\"",
2632                field.table_name
2633            )),
2634        };
2635        roots.push((agg_name, agg_field));
2636    }
2637
2638    roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2639    let mut subscription = Subscription::new(root_name);
2640    // A GraphQL object may not have no fields, and a schema that exposes no
2641    // table still has a subscription root if subscriptions are on.
2642    if roots.is_empty() {
2643        return subscription.field(SubscriptionField::new(
2644            "no_subscriptions_available",
2645            TypeRef::named("String"),
2646            |_| {
2647                SubscriptionFieldFuture::new(async move {
2648                    Ok(futures::stream::empty::<
2649                        Result<FieldValue, async_graphql::Error>,
2650                    >())
2651                })
2652            },
2653        ));
2654    }
2655    for (_, field) in roots {
2656        subscription = subscription.field(field);
2657    }
2658    subscription
2659}
2660
2661/// What tells a live query its answer may have changed.
2662///
2663/// Every notification on the tables it reads, and a slow tick beside them.
2664/// Yields once per wake and never ends -- a subscription lasts as long as the
2665/// client holds it open.
2666async fn wake_on(
2667    ctx: &ResolverContext<'_>,
2668    channels: &[String],
2669    refresh: std::time::Duration,
2670) -> futures::stream::BoxStream<'static, ()> {
2671    use futures::StreamExt;
2672
2673    let mut streams: Vec<futures::stream::BoxStream<'static, ()>> =
2674        Vec::with_capacity(channels.len() + 1);
2675    // A tick even where nothing is listening: a table with no trigger, a view,
2676    // and a predicate that changes with the clock all depend on it.
2677    streams.push(
2678        tokio_stream::wrappers::IntervalStream::new({
2679            let mut interval = tokio::time::interval(refresh);
2680            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
2681            interval
2682        })
2683        .map(|_| ())
2684        .boxed(),
2685    );
2686
2687    if let Ok(broker_arc) = ctx.data::<Arc<RwLock<Option<NotifyBroker>>>>() {
2688        let guard = broker_arc.read().await;
2689        if let Some(broker) = guard.as_ref() {
2690            for channel in channels {
2691                // `subscribe_or_create` rather than `subscribe`: a table whose
2692                // trigger was never installed has no channel, and a live query
2693                // on it is answered by the refresh rather than refused.
2694                streams.push(
2695                    broker
2696                        .subscribe_or_create(channel)
2697                        .await
2698                        .map(|_| ())
2699                        .boxed(),
2700                );
2701            }
2702        }
2703    }
2704
2705    futures::stream::select_all(streams).boxed()
2706}
2707
2708/// What a live query reads each time it is woken.
2709///
2710/// An enum rather than a closure because the answer borrows the context it is
2711/// read from, and a closure returning a future that borrows its argument is
2712/// not something a bound can say.
2713enum LiveSource {
2714    Rows(Arc<QueryFieldSpec>),
2715    Aggregate(Arc<AggregateSpec>),
2716}
2717
2718/// Read one answer, and the value to compare it against the last one by.
2719async fn read_live<'a>(
2720    ctx: &ResolverContext<'a>,
2721    source: &LiveSource,
2722) -> Result<(serde_json::Value, Option<FieldValue<'a>>), async_graphql::Error> {
2723    match source {
2724        LiveSource::Rows(spec) => {
2725            let rows = query_rows(ctx, spec).await?;
2726            Ok((
2727                serde_json::Value::Array(rows.clone()),
2728                rows_as_field_value(rows, spec.is_by_pk),
2729            ))
2730        }
2731        LiveSource::Aggregate(spec) => {
2732            let value = aggregate_value(ctx, spec).await?;
2733            let seen = serde_json::to_value(&value).unwrap_or_default();
2734            Ok((seen, Some(FieldValue::value(value))))
2735        }
2736    }
2737}
2738
2739/// A live query: the answer now, and the answer again each time it changes.
2740///
2741/// The first item is sent as soon as the client subscribes, which is what
2742/// makes this a query rather than a feed -- there is no window in which the
2743/// client knows nothing. After that, `answer` is read again on every wake and
2744/// sent only when what came back is not what was sent last: a write that
2745/// changes a row the subscription does not select is a wake and not a message.
2746fn live<'a>(
2747    ctx: ResolverContext<'a>,
2748    source: LiveSource,
2749    wake: futures::stream::BoxStream<'static, ()>,
2750) -> impl futures::Stream<Item = Result<FieldValue<'a>, async_graphql::Error>> + Send + 'a {
2751    use futures::StreamExt;
2752
2753    struct Live<'a> {
2754        ctx: ResolverContext<'a>,
2755        source: LiveSource,
2756        wake: futures::stream::BoxStream<'static, ()>,
2757        sent: Option<serde_json::Value>,
2758        started: bool,
2759        /// An error has been sent, and the subscription ends after it.
2760        failed: bool,
2761        /// Counts this subscription as open for as long as its stream lives.
2762        _active: crate::subscription::ActiveSubscription,
2763    }
2764
2765    futures::stream::unfold(
2766        Live {
2767            ctx,
2768            source,
2769            wake,
2770            sent: None,
2771            started: false,
2772            failed: false,
2773            _active: crate::subscription::ActiveSubscription::open(),
2774        },
2775        |mut live: Live<'a>| async move {
2776            if live.failed {
2777                return None;
2778            }
2779            loop {
2780                if live.started {
2781                    live.wake.next().await?;
2782                } else {
2783                    live.started = true;
2784                }
2785                let read = read_live(&live.ctx, &live.source).await;
2786                match read {
2787                    // An error ends the subscription: the client asked
2788                    // something that cannot be answered, and answering it
2789                    // again on the next tick would only repeat that. It is
2790                    // sent first, though -- ending on it unsent, as a
2791                    // `take_while(is_ok)` here once did, answers a refused
2792                    // subscription with a bare `complete` that reads exactly
2793                    // like one that finished.
2794                    Err(e) => {
2795                        live.failed = true;
2796                        return Some((Err(e), live));
2797                    }
2798                    Ok((seen, value)) => {
2799                        if live.sent.as_ref() == Some(&seen) {
2800                            continue;
2801                        }
2802                        live.sent = Some(seen);
2803                        let value = value.unwrap_or_else(|| FieldValue::value(Value::Null));
2804                        return Some((Ok(value), live));
2805                    }
2806                }
2807            }
2808        },
2809    )
2810}
2811
2812/// Everything a query field's resolver needs about the field it serves.
2813struct QueryFieldSpec {
2814    schema_name: String,
2815    table_name: String,
2816    type_name: String,
2817    is_by_pk: bool,
2818    pk_columns: Vec<(String, String)>,
2819    max_rows: Option<i64>,
2820    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2821    names: Arc<crate::names::NameOverrides>,
2822    /// Set where the rows come from a function rather than from the table
2823    /// itself. Everything else about reading them is the same.
2824    call: Option<Arc<FunctionCall>>,
2825}
2826
2827/// Everything `_entities` needs to resolve a representation to a table row.
2828#[derive(Clone)]
2829struct EntityLookup {
2830    schema_name: String,
2831    table_name: String,
2832    type_name: String,
2833    key_columns: Vec<EntityKeyColumn>,
2834    row_column_types: HashMap<String, String>,
2835}
2836
2837#[derive(Clone)]
2838struct EntityKeyColumn {
2839    field_name: String,
2840    column_name: String,
2841    pg_type: String,
2842    explicit_id: bool,
2843}
2844
2845/// The federation entity resolver's immutable schema view.
2846struct EntityResolverState {
2847    entities: HashMap<String, EntityLookup>,
2848    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2849    names: Arc<crate::names::NameOverrides>,
2850    max_rows: Option<i64>,
2851}
2852
2853impl EntityResolverState {
2854    fn new(
2855        generated: &GeneratedSchema,
2856        relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2857        names: Arc<crate::names::NameOverrides>,
2858        max_rows: Option<i64>,
2859    ) -> Self {
2860        let mut entities = HashMap::new();
2861        for (type_name, entity) in &generated.federation_entities {
2862            let Some(object) = generated.object_types.get(type_name) else {
2863                continue;
2864            };
2865            let mut key_columns = Vec::with_capacity(entity.key_fields.len());
2866            for field_name in &entity.key_fields {
2867                let column_name = names
2868                    .column_source(&object.table.schema, &object.table.name, field_name)
2869                    .unwrap_or(field_name);
2870                let Some(column) = object.table.get_column(column_name) else {
2871                    continue;
2872                };
2873                key_columns.push(EntityKeyColumn {
2874                    field_name: field_name.clone(),
2875                    column_name: column.name.clone(),
2876                    pg_type: column.nominal_type.clone(),
2877                    explicit_id: matches!(
2878                        names.column_type(&object.table.schema, &object.table.name, &column.name),
2879                        Some(crate::types::GraphQLType::Id)
2880                    ),
2881                });
2882            }
2883            if key_columns.len() != entity.key_fields.len() {
2884                continue;
2885            }
2886            entities.insert(
2887                type_name.clone(),
2888                EntityLookup {
2889                    schema_name: object.table.schema.clone(),
2890                    table_name: object.table.name.clone(),
2891                    type_name: type_name.clone(),
2892                    key_columns,
2893                    row_column_types: exposed_column_types(&object.table, names.as_ref()),
2894                },
2895            );
2896        }
2897        Self {
2898            entities,
2899            relationships,
2900            names,
2901            max_rows,
2902        }
2903    }
2904}
2905
2906struct EntityRepresentation {
2907    index: usize,
2908    type_name: String,
2909    values: serde_json::Map<String, serde_json::Value>,
2910}
2911
2912/// Fields selected for one concrete member of the federation `_Entity` union.
2913///
2914/// `SelectionField::selection_set()` expands every fragment but does not apply
2915/// its type condition. Keep a parallel applicability list while walking the
2916/// raw selection tree, then use it to retain only the fields meant for this
2917/// entity type.
2918fn entity_field_applicability(
2919    selection_set: &SelectionSet,
2920    fragments: &HashMap<Name, Positioned<FragmentDefinition>>,
2921    type_name: &str,
2922) -> Vec<bool> {
2923    fn condition_matches(condition: Option<&Positioned<TypeCondition>>, type_name: &str) -> bool {
2924        condition.is_none_or(|condition| {
2925            let condition = condition.node.on.node.as_str();
2926            condition == type_name || condition == "_Entity"
2927        })
2928    }
2929
2930    fn collect(
2931        selection_set: &SelectionSet,
2932        fragments: &HashMap<Name, Positioned<FragmentDefinition>>,
2933        type_name: &str,
2934        parent_matches: bool,
2935        applicability: &mut Vec<bool>,
2936    ) {
2937        for selection in &selection_set.items {
2938            match &selection.node {
2939                Selection::Field(_) => applicability.push(parent_matches),
2940                Selection::FragmentSpread(spread) => {
2941                    let Some(fragment) = fragments.get(&spread.node.fragment_name.node) else {
2942                        continue;
2943                    };
2944                    collect(
2945                        &fragment.node.selection_set.node,
2946                        fragments,
2947                        type_name,
2948                        parent_matches
2949                            && condition_matches(Some(&fragment.node.type_condition), type_name),
2950                        applicability,
2951                    );
2952                }
2953                Selection::InlineFragment(fragment) => collect(
2954                    &fragment.node.selection_set.node,
2955                    fragments,
2956                    type_name,
2957                    parent_matches
2958                        && condition_matches(fragment.node.type_condition.as_ref(), type_name),
2959                    applicability,
2960                ),
2961            }
2962        }
2963    }
2964
2965    let mut applicability = Vec::new();
2966    collect(
2967        selection_set,
2968        fragments,
2969        type_name,
2970        true,
2971        &mut applicability,
2972    );
2973    applicability
2974}
2975
2976fn entity_selection_fields<'ctx, 'a>(
2977    ctx: &'ctx ResolverContext<'a>,
2978    type_name: &str,
2979) -> Vec<SelectionField<'ctx>> {
2980    let applicability = entity_field_applicability(
2981        &ctx.ctx.item.node.selection_set.node,
2982        &ctx.ctx.query_env.fragments,
2983        type_name,
2984    );
2985    let fields: Vec<_> = ctx.field().selection_set().collect();
2986    debug_assert_eq!(fields.len(), applicability.len());
2987    fields
2988        .into_iter()
2989        .zip(applicability)
2990        .filter_map(|(field, applies)| applies.then_some(field))
2991        .collect()
2992}
2993
2994async fn resolve_entities<'a>(
2995    ctx: &ResolverContext<'a>,
2996    state: &EntityResolverState,
2997) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
2998    let representations = ctx.args.try_get("representations")?.list()?;
2999    let mut grouped: HashMap<String, Vec<EntityRepresentation>> = HashMap::new();
3000    let mut count = 0;
3001    for (index, representation) in representations.iter().enumerate() {
3002        count += 1;
3003        let value = accessor_to_json(&representation);
3004        let serde_json::Value::Object(values) = value else {
3005            return Err(async_graphql::Error::new(
3006                "entity representation must be an object",
3007            ));
3008        };
3009        let type_name = values
3010            .get("__typename")
3011            .and_then(serde_json::Value::as_str)
3012            .ok_or_else(|| {
3013                async_graphql::Error::new("entity representation is missing __typename")
3014            })?
3015            .to_string();
3016        grouped
3017            .entry(type_name.clone())
3018            .or_default()
3019            .push(EntityRepresentation {
3020                index,
3021                type_name,
3022                values,
3023            });
3024    }
3025
3026    let mut resolved: Vec<Option<FieldValue<'a>>> =
3027        std::iter::repeat_with(|| None).take(count).collect();
3028    for (type_name, representations) in grouped {
3029        let lookup = state.entities.get(&type_name).ok_or_else(|| {
3030            async_graphql::Error::new(format!("unknown federation entity \"{}\"", type_name))
3031        })?;
3032        let rows = resolve_entity_group(ctx, lookup, &representations, state).await?;
3033        for (ordinality, representation) in representations.into_iter().enumerate() {
3034            resolved[representation.index] = Some(match &rows[ordinality] {
3035                Some(row) => FieldValue::value(json_to_value(row.clone()))
3036                    .with_type(representation.type_name),
3037                None => FieldValue::NULL,
3038            });
3039        }
3040    }
3041
3042    Ok(Some(FieldValue::list(resolved.into_iter().map(|value| {
3043        value.expect("every representation was resolved or errored")
3044    }))))
3045}
3046
3047async fn resolve_entity_group(
3048    ctx: &ResolverContext<'_>,
3049    lookup: &EntityLookup,
3050    representations: &[EntityRepresentation],
3051    state: &EntityResolverState,
3052) -> Result<Vec<Option<serde_json::Value>>, async_graphql::Error> {
3053    if representations.is_empty() {
3054        return Ok(Vec::new());
3055    }
3056
3057    let pool = ctx.data::<PgPool>()?;
3058    let gql_ctx = ctx.data::<GraphQLContext>()?;
3059    let mut bound_values = Vec::new();
3060    let mut value_rows = Vec::with_capacity(representations.len());
3061    for (ordinality, representation) in representations.iter().enumerate() {
3062        let normalized_values = normalized_entity_key_values(
3063            &representation.values,
3064            &lookup.key_columns,
3065            &lookup.type_name,
3066        )?;
3067        let mut values = Vec::with_capacity(lookup.key_columns.len() + 1);
3068        for (key_column, value) in lookup.key_columns.iter().zip(normalized_values) {
3069            values.push(format!(
3070                "${}::{}",
3071                bound_values.len() + 1,
3072                key_column.pg_type
3073            ));
3074            bound_values.push(value);
3075        }
3076        values.push(ordinality.to_string());
3077        value_rows.push(format!("({})", values.join(", ")));
3078    }
3079
3080    let representation_alias = "pgrst_entity_representation";
3081    let ordinality_column = "pgrst_entity_ordinality";
3082    let key_aliases: Vec<String> = (0..lookup.key_columns.len())
3083        .map(|index| format!("pgrst_entity_key_{index}"))
3084        .collect();
3085    let mut representation_columns: Vec<String> = key_aliases
3086        .iter()
3087        .map(|column| postrust_sql::escape_ident(column))
3088        .collect();
3089    representation_columns.push(postrust_sql::escape_ident(ordinality_column));
3090    let representations_sql = format!(
3091        "(VALUES {}) AS {} ({})",
3092        value_rows.join(", "),
3093        postrust_sql::escape_ident(representation_alias),
3094        representation_columns.join(", ")
3095    );
3096    let key_predicate = lookup
3097        .key_columns
3098        .iter()
3099        .zip(&key_aliases)
3100        .map(|(key_column, key_alias)| {
3101            format!(
3102                "{}.{} = {}.{}",
3103                postrust_sql::escape_ident(READ_ROW),
3104                postrust_sql::escape_ident(&key_column.column_name),
3105                postrust_sql::escape_ident(representation_alias),
3106                postrust_sql::escape_ident(key_alias)
3107            )
3108        })
3109        .collect::<Vec<_>>()
3110        .join(" AND ");
3111    let mut where_sql = format!(" WHERE ({key_predicate})");
3112
3113    let permission = permission_predicate(
3114        &gql_ctx.caller(),
3115        state.names.as_ref(),
3116        &lookup.schema_name,
3117        &lookup.table_name,
3118    )?;
3119    if let Some(predicate) = permission {
3120        let guard = gql_ctx
3121            .schema_cache
3122            .get()
3123            .await
3124            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3125        let cache = guard
3126            .as_ref()
3127            .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3128        let scope = WhereScope::table(
3129            &lookup.schema_name,
3130            &lookup.table_name,
3131            &lookup.type_name,
3132            state.names.as_ref(),
3133        )
3134        .under_alias(READ_ROW)
3135        .with_resolution(cache, state.relationships.as_ref())
3136        .for_caller(gql_ctx.caller());
3137        let (filter_sql, filter_values) =
3138            build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
3139        if !filter_sql.is_empty() {
3140            where_sql = format!(
3141                "{} AND ({})",
3142                where_sql,
3143                filter_sql.trim_start_matches("WHERE ")
3144            );
3145            bound_values.extend(filter_values);
3146        }
3147    }
3148
3149    let source = format!(
3150        "{}.{} AS {}",
3151        postrust_sql::escape_ident(&lookup.schema_name),
3152        postrust_sql::escape_ident(&lookup.table_name),
3153        postrust_sql::escape_ident(READ_ROW)
3154    );
3155    let source_rows = format!(
3156        "SELECT {}.* FROM {}{}",
3157        postrust_sql::escape_ident(READ_ROW),
3158        source,
3159        where_sql
3160    );
3161    let mut projection = {
3162        let guard = gql_ctx
3163            .schema_cache
3164            .get()
3165            .await
3166            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3167        guard
3168            .as_ref()
3169            .and_then(|cache| {
3170                cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
3171                    &lookup.schema_name,
3172                    &lookup.table_name,
3173                ))
3174            })
3175            .and_then(|table| rename_projection(table, "src", state.names.as_ref()))
3176            .unwrap_or_else(|| "src.*".to_string())
3177    };
3178    let projected_rows = {
3179        let guard = gql_ctx
3180            .schema_cache
3181            .get()
3182            .await
3183            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3184        let cache = guard
3185            .as_ref()
3186            .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3187        let table = cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
3188            &lookup.schema_name,
3189            &lookup.table_name,
3190        ));
3191        let selected_fields = entity_selection_fields(ctx, &lookup.type_name);
3192        let mut param_idx = bound_values.len() + 1;
3193        let computed = match table {
3194            Some(table) => computed_projections(
3195                table,
3196                selected_fields.iter().copied(),
3197                "src",
3198                state.names.as_ref(),
3199                cache,
3200                &mut param_idx,
3201                &mut bound_values,
3202            )?,
3203            None => Vec::new(),
3204        };
3205        let embeds = build_embed_expressions(
3206            &gql_ctx.caller(),
3207            cache,
3208            state.relationships.as_ref(),
3209            &lookup.type_name,
3210            "src",
3211            selected_fields,
3212            state.max_rows,
3213            &mut 0,
3214            &mut param_idx,
3215            &mut bound_values,
3216            state.names.as_ref(),
3217        )?;
3218        for expression in &computed {
3219            projection.push_str(", ");
3220            projection.push_str(expression);
3221        }
3222        for (field_name, expression) in &embeds {
3223            projection.push_str(", ");
3224            projection.push_str(expression);
3225            projection.push_str(" AS ");
3226            projection.push_str(&postrust_sql::escape_ident(field_name));
3227        }
3228        format!("SELECT {} FROM ({}) AS src", projection, source_rows)
3229    };
3230    // PostgreSQL decides whether an entity key matches. Carry the input's
3231    // ordinal through that same query instead of reconstructing a key from
3232    // row JSON: PostgreSQL-equivalent spellings (UUID case, citext case and
3233    // timestamptz offsets, for example) need to resolve to the row it found.
3234    let sql = format!(
3235        "SELECT json_build_array({}.{}, {}) FROM {} CROSS JOIN LATERAL ({}) AS t",
3236        postrust_sql::escape_ident(representation_alias),
3237        postrust_sql::escape_ident(ordinality_column),
3238        row_json("t", &lookup.row_column_types),
3239        representations_sql,
3240        projected_rows,
3241    );
3242    let mut tx = begin_with_session(pool, gql_ctx).await?;
3243    let rows = execute_query_on(&mut tx, &sql, &bound_values).await?;
3244    tx.commit().await?;
3245
3246    let mut by_ordinal = std::iter::repeat_with(|| None)
3247        .take(representations.len())
3248        .collect::<Vec<_>>();
3249    for result in rows {
3250        let serde_json::Value::Array(mut pair) = result else {
3251            return Err(async_graphql::Error::new(
3252                "entity query returned an invalid result",
3253            ));
3254        };
3255        if pair.len() != 2 {
3256            return Err(async_graphql::Error::new(
3257                "entity query returned an invalid result",
3258            ));
3259        }
3260        let row = pair.pop().expect("the result pair has two values");
3261        let ordinality = pair
3262            .pop()
3263            .and_then(|value| value.as_u64())
3264            .and_then(|value| usize::try_from(value).ok())
3265            .filter(|value| *value < by_ordinal.len())
3266            .ok_or_else(|| async_graphql::Error::new("entity query returned an invalid ordinal"))?;
3267        by_ordinal[ordinality] = Some(row);
3268    }
3269    Ok(by_ordinal)
3270}
3271
3272/// Validate an entity key and normalize explicit GraphQL `ID` overrides to
3273/// their integer, text or UUID storage type. `_Any` deliberately skips the
3274/// field-level checks ordinary GraphQL arguments receive.
3275fn normalized_entity_key_values(
3276    values: &serde_json::Map<String, serde_json::Value>,
3277    key_columns: &[EntityKeyColumn],
3278    type_name: &str,
3279) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
3280    let mut key = Vec::with_capacity(key_columns.len());
3281    for key_column in key_columns {
3282        let value = values.get(&key_column.field_name).ok_or_else(|| {
3283            async_graphql::Error::new(format!(
3284                "entity representation for \"{}\" is missing key field \"{}\"",
3285                type_name, key_column.field_name
3286            ))
3287        })?;
3288        key.push(normalize_entity_key_value(type_name, key_column, value)?);
3289    }
3290    Ok(key)
3291}
3292
3293fn normalize_entity_key_value(
3294    type_name: &str,
3295    key_column: &EntityKeyColumn,
3296    value: &serde_json::Value,
3297) -> Result<serde_json::Value, async_graphql::Error> {
3298    let invalid = |expected: &str| {
3299        async_graphql::Error::new(format!(
3300            "entity representation for \"{}\" has invalid key field \"{}\": expected {}, found {}",
3301            type_name,
3302            key_column.field_name,
3303            expected,
3304            json_value_kind(value)
3305        ))
3306    };
3307
3308    if key_column.explicit_id {
3309        return normalize_graphql_id(value, &key_column.pg_type).ok_or_else(|| {
3310            invalid(&format!(
3311                "an ID compatible with PostgreSQL type \"{}\"",
3312                key_column.pg_type
3313            ))
3314        });
3315    }
3316
3317    let pg_type = key_column.pg_type.trim().to_ascii_lowercase();
3318    let normalized = if matches!(pg_type.as_str(), "int8" | "bigint") {
3319        match value {
3320            serde_json::Value::Number(number) => number.as_i64(),
3321            serde_json::Value::String(text) => text.parse::<i64>().ok(),
3322            _ => None,
3323        }
3324        .map(serde_json::Value::from)
3325    } else if integer_bounds(&pg_type).is_some() {
3326        value.as_i64().and_then(|integer| {
3327            let (min, max) = integer_bounds(&pg_type)?;
3328            (min..=max)
3329                .contains(&integer)
3330                .then(|| serde_json::Value::from(integer))
3331        })
3332    } else if matches!(
3333        pg_type.as_str(),
3334        "float4" | "float8" | "real" | "double precision"
3335    ) {
3336        value
3337            .as_f64()
3338            .and_then(serde_json::Number::from_f64)
3339            .map(serde_json::Value::Number)
3340    } else if matches!(pg_type.as_str(), "numeric" | "decimal") {
3341        match value {
3342            serde_json::Value::Number(number) => {
3343                Some(serde_json::Value::String(number.to_string()))
3344            }
3345            serde_json::Value::String(text) if text.parse::<sqlx::types::BigDecimal>().is_ok() => {
3346                Some(serde_json::Value::String(text.clone()))
3347            }
3348            _ => None,
3349        }
3350    } else if matches!(pg_type.as_str(), "bool" | "boolean") {
3351        value.as_bool().map(serde_json::Value::Bool)
3352    } else if matches!(pg_type.as_str(), "json" | "jsonb") {
3353        Some(value.clone())
3354    } else if is_array_type(&pg_type) {
3355        value.is_array().then(|| value.clone())
3356    } else {
3357        value
3358            .as_str()
3359            .map(|text| serde_json::Value::String(text.to_string()))
3360    };
3361
3362    normalized.ok_or_else(|| {
3363        invalid(&format!(
3364            "a value compatible with PostgreSQL type \"{}\"",
3365            key_column.pg_type
3366        ))
3367    })
3368}
3369
3370fn normalize_graphql_id(value: &serde_json::Value, pg_type: &str) -> Option<serde_json::Value> {
3371    if integer_bounds(pg_type).is_some() {
3372        let integer = match value {
3373            serde_json::Value::Number(number) => number.as_i64(),
3374            serde_json::Value::String(text) => text.parse::<i64>().ok(),
3375            _ => None,
3376        }?;
3377        let (min, max) = integer_bounds(pg_type)?;
3378        return (min..=max)
3379            .contains(&integer)
3380            .then(|| serde_json::Value::from(integer));
3381    }
3382    if pg_type.eq_ignore_ascii_case("uuid") {
3383        return normalize_uuid(value).map(serde_json::Value::String);
3384    }
3385    if is_text_type(pg_type) {
3386        return match value {
3387            serde_json::Value::String(s) => Some(serde_json::Value::String(s.clone())),
3388            serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => {
3389                Some(serde_json::Value::String(n.to_string()))
3390            }
3391            _ => None,
3392        };
3393    }
3394    None
3395}
3396
3397fn integer_bounds(pg_type: &str) -> Option<(i64, i64)> {
3398    match pg_type.trim().to_ascii_lowercase().as_str() {
3399        "int2" | "smallint" => Some((i16::MIN.into(), i16::MAX.into())),
3400        "int4" | "int" | "integer" => Some((i32::MIN.into(), i32::MAX.into())),
3401        "int8" | "bigint" => Some((i64::MIN, i64::MAX)),
3402        _ => None,
3403    }
3404}
3405
3406fn is_text_type(pg_type: &str) -> bool {
3407    matches!(
3408        pg_type.trim().to_ascii_lowercase().as_str(),
3409        "text" | "varchar" | "character varying" | "char" | "character" | "bpchar" | "citext"
3410    )
3411}
3412
3413fn normalize_uuid(value: &serde_json::Value) -> Option<String> {
3414    sqlx::types::Uuid::parse_str(value.as_str()?)
3415        .ok()
3416        .map(|uuid| uuid.to_string())
3417}
3418
3419fn json_value_kind(value: &serde_json::Value) -> &'static str {
3420    match value {
3421        serde_json::Value::Null => "null",
3422        serde_json::Value::Bool(_) => "a boolean",
3423        serde_json::Value::Number(_) => "a number",
3424        serde_json::Value::String(_) => "a string",
3425        serde_json::Value::Array(_) => "an array",
3426        serde_json::Value::Object(_) => "an object",
3427    }
3428}
3429
3430/// Add the root fields for functions that answer with rows of a table.
3431///
3432/// The same arguments a table's own root field takes, because the rows are the
3433/// same rows: what the function adds is `args`, which is where its own
3434/// arguments go so that a parameter called `limit` cannot shadow the one that
3435/// pages the result.
3436fn add_function_fields(
3437    mut root: Object,
3438    generated: &GeneratedSchema,
3439    volatile: bool,
3440    max_rows: Option<i64>,
3441    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
3442    names: Arc<crate::names::NameOverrides>,
3443) -> Object {
3444    // The names the root already carries, from the tables. A function may be
3445    // named after one -- `create function t() returns setof t` is an ordinary
3446    // way to write a parameterised view -- and `Object::field` *panics* on a
3447    // duplicate, so an unguarded collision is a server that will not start.
3448    let taken: HashSet<&str> = if volatile {
3449        generated
3450            .mutation_fields
3451            .iter()
3452            .map(|f| f.name.as_str())
3453            .collect()
3454    } else {
3455        generated
3456            .query_fields
3457            .iter()
3458            .map(|f| f.name.as_str())
3459            .collect()
3460    };
3461
3462    for function in &generated.function_fields {
3463        if function.volatile != volatile {
3464            continue;
3465        }
3466        if taken.contains(function.name.as_str()) {
3467            tracing::warn!(
3468                "not exposing {}.{}({}) -- a table already has a root field \
3469                 called {}",
3470                function.schema_name,
3471                function.function_name,
3472                function.argument_signature(),
3473                function.name,
3474            );
3475            continue;
3476        }
3477        let spec = Arc::new(QueryFieldSpec {
3478            schema_name: function.returns_table.0.clone(),
3479            table_name: function.returns_table.1.clone(),
3480            type_name: function.returns.clone(),
3481            is_by_pk: false,
3482            pk_columns: Vec::new(),
3483            max_rows,
3484            relationships: Arc::clone(&relationships),
3485            names: Arc::clone(&names),
3486            call: Some(Arc::new(FunctionCall {
3487                schema: function.schema_name.clone(),
3488                name: function.function_name.clone(),
3489                arguments: function.arguments.clone(),
3490                session_argument: function.session_argument.clone(),
3491            })),
3492        });
3493
3494        let mut field = Field::new(
3495            &function.name,
3496            TypeRef::named_nn_list_nn(&function.returns),
3497            move |ctx| {
3498                let spec = Arc::clone(&spec);
3499                FieldFuture::new(async move { resolve_query(&ctx, &spec).await })
3500            },
3501        );
3502        if !function.arguments.is_empty() {
3503            field = field.argument(InputValue::new(
3504                "args",
3505                TypeRef::named_nn(format!("{}_args", function.name)),
3506            ));
3507        }
3508        field = field
3509            .argument(InputValue::new(
3510                "where",
3511                TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
3512                    &function.local_returns,
3513                )),
3514            ))
3515            .argument(InputValue::new(
3516                "order_by",
3517                TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
3518                    &function.local_returns,
3519                )),
3520            ))
3521            .argument(InputValue::new(
3522                "distinct_on",
3523                TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
3524                    &function.local_returns,
3525                )),
3526            ))
3527            .argument(InputValue::new("limit", TypeRef::named("Int")))
3528            .argument(InputValue::new("offset", TypeRef::named("Int")));
3529        if let Some(description) = &function.description {
3530            field = field.description(description);
3531        }
3532        root = root.field(field);
3533
3534        // The same rows, with numbers about them. Every table root has one and
3535        // so does every function root: `search_tracks_aggregate(args: {…})`
3536        // counts what `search_tracks(args: {…})` would have answered with,
3537        // which means calling the function and taking the same arguments.
3538        let agg_spec = Arc::new(AggregateSpec {
3539            schema_name: function.returns_table.0.clone(),
3540            table_name: function.returns_table.1.clone(),
3541            type_name: function.returns.clone(),
3542            max_rows,
3543            relationships: Arc::clone(&relationships),
3544            names: Arc::clone(&names),
3545            call: Some(Arc::new(FunctionCall {
3546                schema: function.schema_name.clone(),
3547                name: function.function_name.clone(),
3548                arguments: function.arguments.clone(),
3549                session_argument: function.session_argument.clone(),
3550            })),
3551        });
3552        let mut aggregate = Field::new(
3553            format!("{}_aggregate", function.name),
3554            TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
3555                &function.local_returns,
3556            )),
3557            move |ctx| {
3558                let agg_spec = Arc::clone(&agg_spec);
3559                FieldFuture::new(async move { resolve_aggregate(&ctx, &agg_spec).await })
3560            },
3561        );
3562        if !function.arguments.is_empty() {
3563            aggregate = aggregate.argument(InputValue::new(
3564                "args",
3565                TypeRef::named_nn(format!("{}_args", function.name)),
3566            ));
3567        }
3568        aggregate = with_row_arguments(aggregate, &function.local_returns).description(format!(
3569            "fetch aggregated fields from the table: \"{}\"",
3570            function.returns_table.1
3571        ));
3572        root = root.field(aggregate);
3573    }
3574    root
3575}
3576
3577/// The FROM entry for a root field that calls a function.
3578///
3579/// Aliased as the table the function answers with rows of, so a filter or an
3580/// ordering written against that table's columns finds them: without it the
3581/// FROM clause names the function and `article.score` is a table nobody
3582/// mentioned. Whatever the caller put under `args` is bound here, which is why
3583/// it takes the parameter list.
3584fn function_source(
3585    ctx: &ResolverContext<'_>,
3586    call: &FunctionCall,
3587    alias: &str,
3588    bound_values: &mut Vec<serde_json::Value>,
3589) -> Result<String, async_graphql::Error> {
3590    let given = ctx
3591        .args
3592        .try_get("args")
3593        .ok()
3594        .map(|v| accessor_to_json(&v))
3595        .unwrap_or_else(|| serde_json::json!({}));
3596    let mut passed = Vec::new();
3597    for (name, _, required) in &call.arguments {
3598        match given.get(name) {
3599            None if *required => {
3600                return Err(async_graphql::Error::new(format!(
3601                    "{} needs the argument \"{}\"",
3602                    call.name, name
3603                )))
3604            }
3605            // An argument left out is left out, so the function's own default
3606            // applies. Passing null instead would override it.
3607            None => continue,
3608            Some(value) => {
3609                // Named notation, so the arguments a client did give land on
3610                // the parameters it meant regardless of order. A GraphQL Int
3611                // binds as a bigint, and `f(article_id => bigint)` is not
3612                // `f(integer)` -- the function is looked up by the types of
3613                // what it was handed, so what it was handed has to be the
3614                // types it declares.
3615                let (_, pg_type, _) = call
3616                    .arguments
3617                    .iter()
3618                    .find(|(argument, _, _)| argument == name)
3619                    .expect("iterating the arguments");
3620                passed.push(format!(
3621                    "{} => ${}::{}",
3622                    postrust_sql::escape_ident(name),
3623                    bound_values.len() + 1,
3624                    pg_type
3625                ));
3626                bound_values.push(value.clone());
3627            }
3628        }
3629    }
3630    // The session argument is not the client's to send: it says who is
3631    // asking, and a caller that could write it could name any identity it
3632    // liked. It is filled here, from the verified token.
3633    if let Some(session) = &call.session_argument {
3634        passed.push(format!(
3635            "{} => {}",
3636            postrust_sql::escape_ident(session),
3637            SESSION_ARGUMENT
3638        ));
3639    }
3640    Ok(format!(
3641        "{}.{}({}) AS {}",
3642        postrust_sql::escape_ident(&call.schema),
3643        postrust_sql::escape_ident(&call.name),
3644        passed.join(", "),
3645        postrust_sql::escape_ident(alias)
3646    ))
3647}
3648
3649/// A function a root field calls instead of reading a table.
3650struct FunctionCall {
3651    schema: String,
3652    name: String,
3653    arguments: Vec<(String, String, bool)>,
3654    /// The parameter filled from the caller's session rather than from the
3655    /// request. See [`crate::schema::FunctionField::session_argument`].
3656    session_argument: Option<String>,
3657}
3658
3659/// Everything an aggregate field's resolver needs.
3660struct AggregateSpec {
3661    schema_name: String,
3662    table_name: String,
3663    type_name: String,
3664    max_rows: Option<i64>,
3665    relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
3666    names: Arc<crate::names::NameOverrides>,
3667    /// Set where the rows come from a function rather than from the table
3668    /// itself, exactly as it is on [`QueryFieldSpec`]. Counting the rows a
3669    /// function answers with means calling it.
3670    call: Option<Arc<FunctionCall>>,
3671}
3672
3673/// Resolve an aggregate field.
3674///
3675/// One pass over the selection decides what SQL to write: a client asking only
3676/// for `count` should not pay for the rows, and one asking only for `nodes`
3677/// should not pay for a second scan. Both halves read from the same filtered
3678/// subquery, so `aggregate` describes exactly the set `nodes` came from.
3679async fn resolve_aggregate<'a>(
3680    ctx: &ResolverContext<'a>,
3681    spec: &AggregateSpec,
3682) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
3683    Ok(Some(FieldValue::value(aggregate_value(ctx, spec).await?)))
3684}
3685
3686/// The numbers an aggregate field answers with.
3687///
3688/// Split from the resolver for the reason [`query_rows`] is: a subscription
3689/// reads them over and over and has to tell one answer from the last.
3690async fn aggregate_value(
3691    ctx: &ResolverContext<'_>,
3692    spec: &AggregateSpec,
3693) -> Result<Value, async_graphql::Error> {
3694    use crate::schema::aggregate as agg;
3695
3696    let pool = ctx.data::<PgPool>()?;
3697    let gql_ctx = ctx.data::<GraphQLContext>()?;
3698
3699    let mut bound_values: Vec<serde_json::Value> = Vec::new();
3700    // A function's own arguments are bound before anything else, so a
3701    // predicate written beside them continues the numbering rather than
3702    // colliding with it.
3703    let source = match &spec.call {
3704        None => format!(
3705            "{}.{}",
3706            postrust_sql::escape_ident(&spec.schema_name),
3707            postrust_sql::escape_ident(&spec.table_name)
3708        ),
3709        Some(call) => function_source(ctx, call, &spec.table_name, &mut bound_values)?,
3710    };
3711
3712    let mut where_sql = String::new();
3713    {
3714        // Counting rows is reading them, so the permission applies here in the
3715        // same breath as the request's own filter -- otherwise `count` would
3716        // report a total the same role cannot list.
3717        let requested = ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v));
3718        let permission = permission_predicate(
3719            &gql_ctx.caller(),
3720            spec.names.as_ref(),
3721            &spec.schema_name,
3722            &spec.table_name,
3723        )?;
3724        if let Some(predicate) = and_predicates(requested, permission) {
3725            let guard = gql_ctx
3726                .schema_cache
3727                .get()
3728                .await
3729                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3730            let cache = guard
3731                .as_ref()
3732                .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3733            // A function's rows are read under the table's name as an alias,
3734            // not from the table itself -- the same split the row read makes.
3735            // Counting them under the qualified name answered `invalid
3736            // reference to FROM-clause entry for table "Track"` the moment a
3737            // permission referred to a column, which is any permission that
3738            // follows a relationship.
3739            let scope = match &spec.call {
3740                None => WhereScope::table(
3741                    &spec.schema_name,
3742                    &spec.table_name,
3743                    &spec.type_name,
3744                    spec.names.as_ref(),
3745                )
3746                .with_resolution(cache, spec.relationships.as_ref()),
3747                Some(_) => WhereScope::for_alias(
3748                    &spec.schema_name,
3749                    &spec.table_name,
3750                    &spec.table_name,
3751                    &spec.type_name,
3752                    cache,
3753                    spec.relationships.as_ref(),
3754                    spec.names.as_ref(),
3755                ),
3756            }
3757            .for_caller(gql_ctx.caller());
3758            let (sql, values) =
3759                build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
3760            if !sql.is_empty() {
3761                where_sql = format!(" {}", sql);
3762                bound_values.extend(values);
3763            }
3764        }
3765    }
3766
3767    let order_sql = build_order_by_clause(
3768        ctx,
3769        &gql_ctx.schema_cache,
3770        &spec.schema_name,
3771        &spec.table_name,
3772        &spec.type_name,
3773        spec.relationships.as_ref(),
3774        &format!(
3775            "{}.{}",
3776            postrust_sql::escape_ident(&spec.schema_name),
3777            postrust_sql::escape_ident(&spec.table_name)
3778        ),
3779        spec.names.as_ref(),
3780    )
3781    .await?;
3782
3783    let requested_limit = ctx.args.try_get("limit").ok().and_then(|v| v.i64().ok());
3784    let offset = ctx.args.try_get("offset").ok().and_then(|v| v.i64().ok());
3785    let ceiling = match (
3786        spec.max_rows,
3787        permission_limit(
3788            &gql_ctx.caller(),
3789            spec.names.as_ref(),
3790            &spec.schema_name,
3791            &spec.table_name,
3792        ),
3793    ) {
3794        (Some(configured), Some(granted)) => Some(configured.min(granted)),
3795        (only, None) | (None, only) => only,
3796    };
3797    let limit = match (requested_limit, ceiling) {
3798        (Some(requested), Some(ceiling)) => Some(requested.min(ceiling)),
3799        (Some(requested), None) => Some(requested),
3800        (None, ceiling) => ceiling,
3801    };
3802
3803    let rows = format!("SELECT * FROM {}{}{}", source, where_sql, order_sql);
3804
3805    // What `nodes` reads: the page, bounded by whichever ceiling is lowest.
3806    let mut inner = rows.clone();
3807    if let Some(limit) = limit {
3808        inner.push_str(&format!(" LIMIT {}", limit));
3809    }
3810    if let Some(offset) = offset {
3811        inner.push_str(&format!(" OFFSET {}", offset));
3812    }
3813
3814    // What `aggregate` reads, which is not the same rows. A count is not a
3815    // page: a ceiling exists to bound how many rows travel, and answering
3816    // "how many are there" with "as many as I would have sent you" is not an
3817    // answer to the question. Hasura says so too -- a role limited to one row
3818    // of `article` still counts three of them and still gets `max(id)` over
3819    // all three, which is what `agg_perm` tests.
3820    //
3821    // The request's own `limit` and `offset` do still apply: those were asked
3822    // for, and `article_aggregate(limit: 2)` is a question about two rows. The
3823    // corpus proves this only for the permission's ceiling; the configured one
3824    // is treated the same way because the reason is the same, and because a
3825    // server whose `PGRST_MAX_ROWS` silently became the answer to `count`
3826    // would be wrong in the way that is hardest to notice.
3827    let mut counted = rows;
3828    if let Some(limit) = requested_limit {
3829        counted.push_str(&format!(" LIMIT {}", limit));
3830    }
3831    if let Some(offset) = offset {
3832        counted.push_str(&format!(" OFFSET {}", offset));
3833    }
3834
3835    // What the client actually asked for. Two selections of one aggregate are
3836    // one entry: `sum { id }` beside `totals: sum { views }` reads the same
3837    // object under two names, so the columns are the union of what both named
3838    // and the object is built once.
3839    let mut wants_nodes = false;
3840    let mut wants_aggregate = false;
3841    let mut wanted: BTreeMap<String, Vec<String>> = BTreeMap::new();
3842    // `count` is different: each occurrence may count something else, so each
3843    // is answered under the name it was asked for.
3844    let mut counts: Vec<(String, String)> = Vec::new();
3845    for selection in ctx.field().selection_set() {
3846        match selection.name() {
3847            "nodes" => wants_nodes = true,
3848            "aggregate" => {
3849                wants_aggregate = true;
3850                for function in selection.selection_set() {
3851                    // Answered by the schema, at this level and the one below.
3852                    if function.name() == "__typename" {
3853                        continue;
3854                    }
3855                    if function.name() == "count" {
3856                        counts.push((
3857                            function.alias().unwrap_or("count").to_string(),
3858                            count_expression(
3859                                function,
3860                                (&spec.schema_name, &spec.table_name),
3861                                None,
3862                                spec.names.as_ref(),
3863                            ),
3864                        ));
3865                        continue;
3866                    }
3867                    // Entered even when it names no column: `max { __typename }`
3868                    // is an object with nothing in it, not a null.
3869                    let columns = wanted.entry(function.name().to_string()).or_default();
3870                    for column in function.selection_set() {
3871                        let name = column.name().to_string();
3872                        if name != "__typename" && !columns.contains(&name) {
3873                            columns.push(name);
3874                        }
3875                    }
3876                }
3877            }
3878            _ => {}
3879        }
3880    }
3881
3882    let mut result = async_graphql::indexmap::IndexMap::new();
3883
3884    // Whatever `aggregate` names -- even if that is only `__typename` -- it is
3885    // an object, so it is answered rather than left null.
3886    if wants_aggregate {
3887        // `count` is answered whether or not it was asked for: the aggregate
3888        // type's own resolver reads a missing key as zero, and a client that
3889        // asked for nothing else still gets a number rather than a null.
3890        let mut parts = match counts.iter().any(|(key, _)| key == "count") {
3891            true => Vec::new(),
3892            false => vec!["'count', count(*)".to_string()],
3893        };
3894        for (key, expression) in &counts {
3895            parts.push(format!(
3896                "{}, {}",
3897                postrust_sql::quote_literal(key),
3898                expression
3899            ));
3900        }
3901        for (function, columns) in &wanted {
3902            // The function name comes from the schema, not from the request:
3903            // a selection can only name a field that was generated, so there
3904            // is no path from client text to this identifier.
3905            let sql_function = agg::NUMERIC_AGGREGATES
3906                .iter()
3907                .chain(agg::ORDERED_AGGREGATES.iter())
3908                .find(|(name, _)| name == function)
3909                .map(|(name, _)| *name)
3910                .ok_or_else(|| {
3911                    async_graphql::Error::new(format!("unknown aggregate \"{}\"", function))
3912                })?;
3913            let per_column: Vec<String> = columns
3914                .iter()
3915                .map(|field| {
3916                    let source = spec
3917                        .names
3918                        .column_source(&spec.schema_name, &spec.table_name, field)
3919                        .unwrap_or(field);
3920                    format!(
3921                        "{}, {}({})",
3922                        postrust_sql::quote_literal(field),
3923                        sql_function,
3924                        postrust_sql::escape_ident(source)
3925                    )
3926                })
3927                .collect();
3928            parts.push(format!(
3929                "'{}', json_build_object({})",
3930                sql_function,
3931                per_column.join(", ")
3932            ));
3933        }
3934
3935        let sql = format!(
3936            "SELECT json_build_object({}) FROM ({}) AS pgrst_agg",
3937            parts.join(", "),
3938            counted
3939        );
3940        let mut conn = begin_with_session(pool, gql_ctx).await?;
3941        let rows = execute_query_on(&mut conn, &sql, &bound_values).await?;
3942        conn.commit().await?;
3943        if let Some(first) = rows.into_iter().next() {
3944            if let Value::Object(map) = json_to_value(first) {
3945                result.insert(async_graphql::Name::new("aggregate"), Value::Object(map));
3946            }
3947        }
3948    }
3949
3950    if wants_nodes {
3951        // `nodes` is the same rows selection the plain root field answers, so
3952        // it gets the same projection: computed fields, which are functions of
3953        // the row rather than part of it, and relationships, which are
3954        // correlated subselects. Reading it as columns alone was why a
3955        // relationship asked for beside a count came back null.
3956        let nodes = ctx
3957            .field()
3958            .selection_set()
3959            .find(|selection| selection.name() == "nodes")
3960            .ok_or_else(|| async_graphql::Error::new("nodes was asked for and then was not"))?;
3961
3962        // The aggregate query has already been sent, so its parameters are
3963        // fixed; anything an embed binds continues that numbering in a vector
3964        // of its own.
3965        let mut node_values = bound_values.clone();
3966        let (projection, row_column_types) = {
3967            let guard = gql_ctx
3968                .schema_cache
3969                .get()
3970                .await
3971                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3972            let cache = guard
3973                .as_ref()
3974                .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3975            let qi = postrust_core::api_request::QualifiedIdentifier::new(
3976                &spec.schema_name,
3977                &spec.table_name,
3978            );
3979            let table = cache.get_table(&qi);
3980            let mut param_idx = node_values.len() + 1;
3981            let computed = match table {
3982                Some(table) => computed_projections(
3983                    table,
3984                    nodes.selection_set(),
3985                    "src",
3986                    spec.names.as_ref(),
3987                    cache,
3988                    &mut param_idx,
3989                    &mut node_values,
3990                )?,
3991                None => Vec::new(),
3992            };
3993            let embeds = build_embed_expressions(
3994                &gql_ctx.caller(),
3995                cache,
3996                spec.relationships.as_ref(),
3997                &spec.type_name,
3998                "src",
3999                nodes.selection_set(),
4000                spec.max_rows,
4001                &mut 0,
4002                &mut param_idx,
4003                &mut node_values,
4004                spec.names.as_ref(),
4005            )?;
4006            // A renamed column is renamed here, in the projection over the
4007            // subquery -- not inside it, where `src` has to stay the table's
4008            // own composite for a computed field to be passed the row.
4009            let mut projection = table
4010                .and_then(|table| rename_projection(table, "src", spec.names.as_ref()))
4011                .unwrap_or_else(|| "src.*".to_string());
4012            for expression in &computed {
4013                projection.push_str(", ");
4014                projection.push_str(expression);
4015            }
4016            for (field_name, expression) in &embeds {
4017                projection.push_str(", ");
4018                projection.push_str(expression);
4019                projection.push_str(" AS ");
4020                projection.push_str(&postrust_sql::escape_ident(field_name));
4021            }
4022            (
4023                projection,
4024                table
4025                    .map(|table| exposed_column_types(table, spec.names.as_ref()))
4026                    .unwrap_or_default(),
4027            )
4028        };
4029
4030        let sql = format!(
4031            "SELECT {} FROM (SELECT {} FROM ({}) AS src) AS pgrst_nodes",
4032            row_json("pgrst_nodes", &row_column_types),
4033            projection,
4034            inner
4035        );
4036        let mut conn = begin_with_session(pool, gql_ctx).await?;
4037        let rows = execute_query_on(&mut conn, &sql, &node_values).await?;
4038        conn.commit().await?;
4039        result.insert(
4040            async_graphql::Name::new("nodes"),
4041            Value::List(rows.into_iter().map(json_to_value).collect()),
4042        );
4043    }
4044
4045    let _ = &spec.type_name;
4046    Ok(Value::Object(result))
4047}
4048
4049/// Resolve a query field.
4050async fn resolve_query<'a>(
4051    ctx: &ResolverContext<'a>,
4052    spec: &QueryFieldSpec,
4053) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
4054    Ok(rows_as_field_value(
4055        query_rows(ctx, spec).await?,
4056        spec.is_by_pk,
4057    ))
4058}
4059
4060/// The rows a query field answers with, as JSON.
4061///
4062/// Split from the field's own resolver because a subscription reads the same
4063/// rows over and over and has to tell one answer from the last: a
4064/// `FieldValue` is neither comparable nor readable, and this is.
4065async fn query_rows(
4066    ctx: &ResolverContext<'_>,
4067    spec: &QueryFieldSpec,
4068) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
4069    let schema_name = spec.schema_name.as_str();
4070    let table_name = spec.table_name.as_str();
4071    let type_name = spec.type_name.as_str();
4072    let is_by_pk = spec.is_by_pk;
4073    let pk_columns = spec.pk_columns.as_slice();
4074    let max_rows = spec.max_rows;
4075    let relationships = spec.relationships.as_ref();
4076
4077    let pool = ctx.data::<PgPool>()?;
4078    let gql_ctx = ctx.data::<GraphQLContext>()?;
4079
4080    debug!("Resolving query for table: {}", table_name);
4081
4082    // Extract pagination arguments
4083    let requested_limit: Option<i64> = ctx.args.try_get("limit").ok().and_then(|v| v.i64().ok());
4084
4085    let offset: Option<i64> = ctx.args.try_get("offset").ok().and_then(|v| v.i64().ok());
4086
4087    // A query that names no limit would otherwise select the whole table, so
4088    // the configured ceiling is applied as the limit in that case, and as an
4089    // upper bound when the query asks for more than it. A by-PK query resolves
4090    // to at most one row.
4091    let limit: Option<i64> = if is_by_pk {
4092        Some(1)
4093    } else {
4094        // The permission's ceiling is one more of the same kind, so it folds
4095        // in the same way: whichever of the three is smallest wins, and a
4096        // request naming none takes the lowest that was named.
4097        let ceiling = match (
4098            max_rows,
4099            permission_limit(
4100                &gql_ctx.caller(),
4101                spec.names.as_ref(),
4102                schema_name,
4103                table_name,
4104            ),
4105        ) {
4106            (Some(configured), Some(granted)) => Some(configured.min(granted)),
4107            (only, None) | (None, only) => only,
4108        };
4109        match (requested_limit, ceiling) {
4110            (Some(requested), Some(ceiling)) => Some(requested.min(ceiling)),
4111            (Some(requested), None) => Some(requested),
4112            (None, ceiling) => ceiling,
4113        }
4114    };
4115
4116    // Build the WHERE clause.
4117    //
4118    // A by-PK query filters on the table's key columns; each value is bound as
4119    // a parameter and cast to the column's type, since GraphQL scalars and
4120    // PostgreSQL types do not line up (a `uuid` key arrives as a String). A
4121    // list query filters on the `filter` argument, which takes the same shape
4122    // as a mutation's `where`.
4123    let mut where_sql = String::new();
4124    let mut bound_values: Vec<serde_json::Value> = Vec::new();
4125
4126    // Where the rows come from. A function's own arguments are bound before
4127    // anything else, because they sit in the FROM clause and every other
4128    // parameter is numbered after them.
4129    let source = match &spec.call {
4130        // Aliased rather than named. A whole-row reference -- what a computed
4131        // field is passed -- can only be written as a bare name, and
4132        // `"public"."author"` is not one: PostgreSQL reads it as a column of a
4133        // table called `public`. An alias no column can share is a name that
4134        // works in both positions.
4135        None => format!(
4136            "{}.{} AS {}",
4137            postrust_sql::escape_ident(schema_name),
4138            postrust_sql::escape_ident(table_name),
4139            postrust_sql::escape_ident(READ_ROW)
4140        ),
4141        Some(call) => function_source(ctx, call, table_name, &mut bound_values)?,
4142    };
4143
4144    // How a column of the source is referred to: a table by its qualified
4145    // name, a function's rows by the alias above.
4146    let source_ref = match &spec.call {
4147        None => postrust_sql::escape_ident(READ_ROW),
4148        Some(_) => postrust_sql::escape_ident(table_name),
4149    };
4150
4151    if is_by_pk {
4152        if pk_columns.is_empty() {
4153            return Err(async_graphql::Error::new(format!(
4154                "\"{}\" has no primary key, so it cannot be queried by key",
4155                table_name
4156            )));
4157        }
4158
4159        let mut conditions = Vec::with_capacity(pk_columns.len());
4160        for (idx, (col_name, pg_type)) in pk_columns.iter().enumerate() {
4161            let field = spec
4162                .names
4163                .column(schema_name, table_name, col_name)
4164                .unwrap_or(col_name);
4165            let value = ctx.args.try_get(field).map_err(|_| {
4166                async_graphql::Error::new(format!(
4167                    "missing required primary key argument \"{}\"",
4168                    field
4169                ))
4170            })?;
4171
4172            conditions.push(format!(
4173                "{} = ${}::{}",
4174                postrust_sql::escape_ident(col_name),
4175                idx + 1,
4176                pg_type
4177            ));
4178            bound_values.push(accessor_to_json(&value));
4179        }
4180        where_sql = format!(" WHERE {}", conditions.join(" AND "));
4181    }
4182
4183    // What this role may read, beside what the request asked for. Applied to
4184    // both shapes and to neither: a query naming no `where` at all is still a
4185    // read, and a by-key query that skipped the permission would be the one
4186    // way to fetch a row the filter withholds.
4187    {
4188        let requested = match is_by_pk {
4189            true => None,
4190            false => ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v)),
4191        };
4192        let permission = permission_predicate(
4193            &gql_ctx.caller(),
4194            spec.names.as_ref(),
4195            schema_name,
4196            table_name,
4197        )?;
4198
4199        if let Some(predicate) = and_predicates(requested, permission) {
4200            let guard = gql_ctx
4201                .schema_cache
4202                .get()
4203                .await
4204                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4205            let cache = guard
4206                .as_ref()
4207                .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4208            let scope = match &spec.call {
4209                None => WhereScope::table(schema_name, table_name, type_name, spec.names.as_ref())
4210                    .under_alias(READ_ROW)
4211                    .with_resolution(cache, relationships)
4212                    .for_caller(gql_ctx.caller()),
4213                // A function's rows are the table's rows, so they are renamed
4214                // the same way; only how they are reached differs.
4215                Some(_) => WhereScope::for_alias(
4216                    schema_name,
4217                    table_name,
4218                    table_name,
4219                    type_name,
4220                    cache,
4221                    relationships,
4222                    spec.names.as_ref(),
4223                )
4224                .for_caller(gql_ctx.caller()),
4225            };
4226            let (filter_sql, filter_values) =
4227                build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
4228            if !filter_sql.is_empty() {
4229                // A by-key query already has a `WHERE`, so this joins it
4230                // rather than replacing it.
4231                where_sql = match where_sql.is_empty() {
4232                    true => format!(" {}", filter_sql),
4233                    false => format!(
4234                        "{} AND ({})",
4235                        where_sql,
4236                        filter_sql.trim_start_matches("WHERE ")
4237                    ),
4238                };
4239                bound_values.extend(filter_values);
4240            }
4241        }
4242    }
4243
4244    // A by-key query resolves to one row, so neither ordering nor distinct
4245    // has anything to do.
4246    let (order_sql, distinct_on) = if is_by_pk {
4247        (String::new(), Vec::new())
4248    } else {
4249        (
4250            build_order_by_clause(
4251                ctx,
4252                &gql_ctx.schema_cache,
4253                schema_name,
4254                table_name,
4255                type_name,
4256                relationships,
4257                &source_ref,
4258                spec.names.as_ref(),
4259            )
4260            .await?,
4261            build_distinct_on(
4262                ctx,
4263                &gql_ctx.schema_cache,
4264                schema_name,
4265                table_name,
4266                spec.names.as_ref(),
4267            )
4268            .await?,
4269        )
4270    };
4271
4272    // PostgreSQL keeps the first row of each DISTINCT ON group in the query's
4273    // own order, and picks arbitrarily where the ordering does not begin with
4274    // the distinct columns -- so which row survives would depend on the plan.
4275    // Hasura refuses that query rather than answering it, and so does this:
4276    // prepending the distinct columns instead produced an answer, and a wrong
4277    // one, since `ORDER BY "department", "department" DESC` is decided by its
4278    // first term and sorts ascending.
4279    let (distinct_sql, order_sql) = {
4280        let written = order_sql.strip_prefix(" ORDER BY ");
4281        // Reported against the field's arguments as a whole: the rule is about
4282        // two of them disagreeing, so neither one is where it went wrong.
4283        let (prefix, order) = distinct_on_clause(&distinct_on, written).map_err(|error| {
4284            at_path(
4285                error,
4286                &format!(
4287                    "$.selectionSet.{}.args",
4288                    ctx.ctx.field().alias().unwrap_or(ctx.ctx.field().name())
4289                ),
4290            )
4291        })?;
4292        (
4293            prefix,
4294            match order {
4295                Some(order) => format!(" ORDER BY {}", order),
4296                None => String::new(),
4297            },
4298        )
4299    };
4300
4301    // A computed column is a function of the row rather than part of it, so
4302    // it is not in `*` and is named only when it was asked for.
4303    let (computed, row_column_types) = {
4304        let guard = gql_ctx
4305            .schema_cache
4306            .get()
4307            .await
4308            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4309        match guard.as_ref() {
4310            Some(cache) => {
4311                let qi =
4312                    postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
4313                match cache.get_table(&qi) {
4314                    Some(table) => {
4315                        let mut param_idx = bound_values.len() + 1;
4316                        (
4317                            computed_projections(
4318                                table,
4319                                ctx.field().selection_set(),
4320                                "src",
4321                                spec.names.as_ref(),
4322                                cache,
4323                                &mut param_idx,
4324                                &mut bound_values,
4325                            )?,
4326                            exposed_column_types(table, spec.names.as_ref()),
4327                        )
4328                    }
4329                    None => (Vec::new(), HashMap::new()),
4330                }
4331            }
4332            None => (Vec::new(), HashMap::new()),
4333        }
4334    };
4335    // ORDER BY, LIMIT and OFFSET belong inside the subquery: applying them to
4336    // the outer `row_to_json` projection would leave the ordering of the rows
4337    // that survive the limit unspecified.
4338    let mut inner = format!(
4339        "SELECT {}* FROM {}{}{}",
4340        distinct_sql, source, where_sql, order_sql
4341    );
4342
4343    if let Some(limit) = limit {
4344        inner.push_str(&format!(" LIMIT {}", limit));
4345    }
4346
4347    if let Some(offset) = offset {
4348        inner.push_str(&format!(" OFFSET {}", offset));
4349    }
4350
4351    // Embed the requested relationships in this same query, as correlated
4352    // subselects in the SELECT list, so the whole selection is one round trip.
4353    let embed_expressions = {
4354        let guard = gql_ctx
4355            .schema_cache
4356            .get()
4357            .await
4358            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4359        match guard.as_ref() {
4360            Some(cache) => {
4361                // Parameters bound inside an embed continue the outer query's
4362                // numbering: sqlx binds by position, so the values only have
4363                // to be pushed in the order their placeholders were handed
4364                // out.
4365                let mut param_idx = bound_values.len() + 1;
4366                build_embed_expressions(
4367                    &gql_ctx.caller(),
4368                    cache,
4369                    relationships,
4370                    type_name,
4371                    "src",
4372                    ctx.field().selection_set(),
4373                    max_rows,
4374                    &mut 0,
4375                    &mut param_idx,
4376                    &mut bound_values,
4377                    spec.names.as_ref(),
4378                )?
4379            }
4380            None => Vec::new(),
4381        }
4382    };
4383
4384    // A computed column is a function of the row, and the row it is a function
4385    // of is the table's -- not the subquery's. Projecting it inside the
4386    // subquery gave `src` an extra column, which is what made a computed
4387    // relationship beside it fail with `cannot cast type record to author`: a
4388    // subquery alias is only passable as a composite value while its columns
4389    // are exactly the table's. So both live out here, where `src` still is
4390    // one.
4391    let renamed = {
4392        let guard = gql_ctx
4393            .schema_cache
4394            .get()
4395            .await
4396            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4397        guard
4398            .as_ref()
4399            .and_then(|cache| {
4400                cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
4401                    schema_name,
4402                    table_name,
4403                ))
4404            })
4405            .and_then(|table| rename_projection(table, "src", spec.names.as_ref()))
4406    };
4407    let inner = if embed_expressions.is_empty() && computed.is_empty() && renamed.is_none() {
4408        inner
4409    } else {
4410        let mut projection = renamed.unwrap_or_else(|| "src.*".to_string());
4411        for expression in &computed {
4412            projection.push_str(", ");
4413            projection.push_str(expression);
4414        }
4415        for (field_name, expression) in &embed_expressions {
4416            projection.push_str(", ");
4417            projection.push_str(expression);
4418            projection.push_str(" AS ");
4419            projection.push_str(&postrust_sql::escape_ident(field_name));
4420        }
4421        format!("SELECT {} FROM ({}) AS src", projection, inner)
4422    };
4423
4424    let sql = format!(
4425        "SELECT {} FROM ({}) t",
4426        row_json("t", &row_column_types),
4427        inner
4428    );
4429
4430    // One transaction for the query and any embeds hanging off it, so the role
4431    // applies to all of them and the parent and child rows come from a single
4432    // snapshot.
4433    let mut tx = begin_with_session(pool, gql_ctx).await?;
4434
4435    // Execute query - returns Vec<serde_json::Value>
4436    let mut result = execute_query_on(&mut tx, &sql, &bound_values).await?;
4437
4438    // Anything the single-query form did not cover.
4439    if embed_expressions.is_empty() {
4440        let guard = gql_ctx
4441            .schema_cache
4442            .get()
4443            .await
4444            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4445        let cache = guard
4446            .as_ref()
4447            .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4448
4449        let embed_ctx = EmbedContext {
4450            schema_cache: cache,
4451            relationships,
4452            max_rows,
4453        };
4454
4455        embed_relationships(&mut tx, &embed_ctx, type_name, ctx.field(), &mut result).await?;
4456    }
4457
4458    tx.commit().await?;
4459
4460    Ok(result)
4461}
4462
4463/// The rows a field answers with, in the shape its type says.
4464///
4465/// A by-key field is one row or none; every other is a list, empty where
4466/// nothing matched rather than null.
4467fn rows_as_field_value<'a>(rows: Vec<serde_json::Value>, is_by_pk: bool) -> Option<FieldValue<'a>> {
4468    match is_by_pk {
4469        true => rows
4470            .into_iter()
4471            .next()
4472            .map(|v| FieldValue::value(json_to_value(v))),
4473        false => Some(FieldValue::list(
4474            rows.into_iter()
4475                .map(|v| FieldValue::value(json_to_value(v))),
4476        )),
4477    }
4478}
4479
4480/// Resolve a mutation field.
4481#[allow(clippy::too_many_arguments)]
4482async fn resolve_mutation<'a>(
4483    ctx: &ResolverContext<'a>,
4484    schema_name: &str,
4485    table_name: &str,
4486    mutation_type: MutationType,
4487    pk_columns: &[(String, String)],
4488    relationships: &Arc<HashMap<String, Vec<RelationshipField>>>,
4489    type_names: &Arc<HashMap<(String, String), String>>,
4490    names: &Arc<crate::names::NameOverrides>,
4491    max_rows: Option<i64>,
4492) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
4493    let pool = ctx.data::<PgPool>()?;
4494    let gql_ctx = ctx.data::<GraphQLContext>()?;
4495
4496    debug!(
4497        "Resolving mutation for table: {} type: {:?}",
4498        table_name, mutation_type
4499    );
4500
4501    // A relationship or a computed field asked for beside the written columns
4502    // is not in `RETURNING`, so the rows are read again through the projection
4503    // an ordinary query uses -- and only when the selection asks for something
4504    // that needs it. A delete cannot do that afterwards and builds it into the
4505    // statement instead, which is why this is settled before the statement is.
4506    let type_name = type_names
4507        .get(&(schema_name.to_string(), table_name.to_string()))
4508        .cloned()
4509        .unwrap_or_else(|| table_name.to_string());
4510
4511    let by_key = matches!(
4512        mutation_type,
4513        MutationType::InsertOne | MutationType::UpdateByPk | MutationType::DeleteByPk
4514    );
4515    let returning = if by_key {
4516        Some(ctx.field())
4517    } else {
4518        ctx.field()
4519            .selection_set()
4520            .find(|selection| selection.name() == "returning")
4521    };
4522
4523    // Several updates, each with its own filter, applied in the order given.
4524    // They share the operation's transaction like any other write, which is
4525    // the whole difference from sending them one at a time: either all of them
4526    // happened or none did.
4527    if mutation_type == MutationType::UpdateMany {
4528        let updates = ctx
4529            .args
4530            .try_get("updates")
4531            .ok()
4532            .map(|v| accessor_to_json(&v))
4533            .unwrap_or(serde_json::Value::Null);
4534        let serde_json::Value::Array(entries) = updates else {
4535            return Err(async_graphql::Error::new(
4536                "\"updates\" takes a list of {where, _set, …} objects",
4537            ));
4538        };
4539        let column_types = column_types_of(&gql_ctx.schema_cache, schema_name, table_name).await;
4540        let mut answers: Vec<FieldValue<'_>> = Vec::with_capacity(entries.len());
4541        for entry in entries {
4542            let serde_json::Value::Object(entry) = entry else {
4543                return Err(async_graphql::Error::new(
4544                    "each update is an object of {where, _set, …}",
4545                ));
4546            };
4547            let operators: Vec<(&'static str, serde_json::Value)> = UPDATE_OPERATORS
4548                .iter()
4549                .filter_map(|name| entry.get(*name).map(|value| (*name, value.clone())))
4550                .filter(|(_, value)| !value.is_null())
4551                .collect();
4552            let rows = execute_update(
4553                pool,
4554                gql_ctx,
4555                schema_name,
4556                table_name,
4557                &type_name,
4558                operators,
4559                column_types.clone(),
4560                entry.get("where").cloned(),
4561                relationships.as_ref(),
4562                names.as_ref(),
4563            )
4564            .await?;
4565            let affected = rows.len();
4566            let rows = match returning {
4567                Some(returning) if !rows.is_empty() => {
4568                    reread_returning(
4569                        pool,
4570                        gql_ctx,
4571                        schema_name,
4572                        table_name,
4573                        &type_name,
4574                        rows,
4575                        returning,
4576                        relationships.as_ref(),
4577                        names.as_ref(),
4578                        max_rows,
4579                    )
4580                    .await?
4581                }
4582                _ => rows,
4583            };
4584            answers.extend(mutation_result(rows, affected, false));
4585        }
4586        return Ok(Some(FieldValue::list(answers)));
4587    }
4588
4589    let (result, affected) = match mutation_type {
4590        MutationType::Insert | MutationType::InsertOne => {
4591            let objects = ctx
4592                .args
4593                .try_get("objects")
4594                .ok()
4595                .map(|v| accessor_to_json(&v))
4596                .or_else(|| {
4597                    // `insert_x_one(object: {...})` is one row spelled without
4598                    // the list.
4599                    ctx.args
4600                        .try_get("object")
4601                        .ok()
4602                        .map(|v| serde_json::Value::Array(vec![accessor_to_json(&v)]))
4603                })
4604                .unwrap_or_else(|| serde_json::Value::Array(vec![]));
4605
4606            let guard = gql_ctx
4607                .schema_cache
4608                .get()
4609                .await
4610                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4611            let cache = guard
4612                .as_ref()
4613                .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4614            // Where this write is, in the document the client sent. The
4615            // field as it was written -- an alias if there was one, since that
4616            // is what names this selection.
4617            let here = format!(
4618                "$.selectionSet.{}",
4619                ctx.ctx.field().alias().unwrap_or(ctx.ctx.field().name())
4620            );
4621            // `insert_x(objects: [...])` against `insert_x_one(object: {...})`:
4622            // the same write under two spellings, and the path says which.
4623            let named = match mutation_type {
4624                MutationType::InsertOne => "object",
4625                _ => "objects",
4626            };
4627            let context = InsertContext {
4628                on_conflict: ctx
4629                    .args
4630                    .try_get("on_conflict")
4631                    .ok()
4632                    .map(|v| accessor_to_json(&v))
4633                    .filter(|v| !v.is_null()),
4634                cache,
4635                relationships: relationships.as_ref(),
4636                type_names: type_names.as_ref(),
4637                names: names.as_ref(),
4638                caller: gql_ctx.caller(),
4639                // Filled in per row by `execute_insert`, which is where the
4640                // index is known.
4641                row: String::new(),
4642                objects: format!("{}.args.{}", here, named),
4643                conflict: format!("{}.args.on_conflict", here),
4644            };
4645
4646            execute_insert(
4647                pool,
4648                gql_ctx,
4649                schema_name,
4650                table_name,
4651                objects,
4652                &context,
4653                mutation_type == MutationType::InsertOne,
4654            )
4655            .await?
4656        }
4657        // `UpdateMany` answered above: it is a list of responses rather than
4658        // one, so it does not share this shape.
4659        MutationType::UpdateMany | MutationType::Update | MutationType::UpdateByPk => {
4660            // `_set` replaces, the others read the column they write. A client
4661            // may send more than one, so all of them are collected rather than
4662            // the first that happens to be present.
4663            let operators: Vec<(&'static str, serde_json::Value)> = UPDATE_OPERATORS
4664                .iter()
4665                .filter_map(|name| {
4666                    ctx.args
4667                        .try_get(name)
4668                        .ok()
4669                        .map(|v| (*name, accessor_to_json(&v)))
4670                })
4671                .filter(|(_, value)| !value.is_null())
4672                .collect();
4673
4674            let where_clause = if mutation_type == MutationType::UpdateByPk {
4675                Some(pk_where_from_args(
4676                    ctx,
4677                    schema_name,
4678                    table_name,
4679                    pk_columns,
4680                    names.as_ref(),
4681                )?)
4682            } else {
4683                ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v))
4684            };
4685            // Which rows this role may change, beside which rows the request
4686            // asked to change. A by-key update is narrowed too: naming the key
4687            // of a row the permission withholds must not be a way to reach it.
4688            let where_clause = and_predicates(
4689                where_clause,
4690                permission_filter(
4691                    &gql_ctx.caller(),
4692                    names.as_ref(),
4693                    schema_name,
4694                    table_name,
4695                    crate::role::Verb::Update,
4696                )?,
4697            );
4698
4699            execute_update(
4700                pool,
4701                gql_ctx,
4702                schema_name,
4703                table_name,
4704                &type_name,
4705                operators,
4706                column_types_of(&gql_ctx.schema_cache, schema_name, table_name).await,
4707                where_clause,
4708                relationships.as_ref(),
4709                names.as_ref(),
4710            )
4711            .await
4712            .map(|rows| {
4713                let count = rows.len();
4714                (rows, count)
4715            })?
4716        }
4717        MutationType::Delete | MutationType::DeleteByPk => {
4718            let where_clause = if mutation_type == MutationType::DeleteByPk {
4719                Some(pk_where_from_args(
4720                    ctx,
4721                    schema_name,
4722                    table_name,
4723                    pk_columns,
4724                    names.as_ref(),
4725                )?)
4726            } else {
4727                ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v))
4728            };
4729            let where_clause = and_predicates(
4730                where_clause,
4731                permission_filter(
4732                    &gql_ctx.caller(),
4733                    names.as_ref(),
4734                    schema_name,
4735                    table_name,
4736                    crate::role::Verb::Delete,
4737                )?,
4738            );
4739
4740            execute_delete(
4741                pool,
4742                gql_ctx,
4743                schema_name,
4744                table_name,
4745                &type_name,
4746                where_clause,
4747                returning,
4748                relationships.as_ref(),
4749                names.as_ref(),
4750                max_rows,
4751            )
4752            .await
4753            .map(|rows| {
4754                let count = rows.len();
4755                (rows, count)
4756            })?
4757        }
4758    };
4759
4760    let is_delete = matches!(
4761        mutation_type,
4762        MutationType::Delete | MutationType::DeleteByPk
4763    );
4764    let result = match returning {
4765        Some(returning) if !result.is_empty() && !is_delete => {
4766            reread_returning(
4767                pool,
4768                gql_ctx,
4769                schema_name,
4770                table_name,
4771                &type_name,
4772                result,
4773                returning,
4774                relationships.as_ref(),
4775                names.as_ref(),
4776                max_rows,
4777            )
4778            .await?
4779        }
4780        _ => result,
4781    };
4782
4783    Ok(mutation_result(result, affected, by_key))
4784}
4785
4786/// The transaction this operation's writes share, opening it if this is the
4787/// first one.
4788///
4789/// Held for the length of the write, and settled by whoever answers the
4790/// request -- see [`crate::context::SharedWrite`]. Mutation root fields are
4791/// resolved one after another, so the lock is never contended; it is what
4792/// makes the transaction reachable from a resolver that owns nothing.
4793async fn write_tx<'a>(
4794    gql_ctx: &'a GraphQLContext,
4795    pool: &PgPool,
4796) -> Result<
4797    tokio::sync::MutexGuard<'a, Option<sqlx::Transaction<'static, sqlx::Postgres>>>,
4798    async_graphql::Error,
4799> {
4800    let mut guard = gql_ctx.write.lock().await;
4801    if guard.is_none() {
4802        *guard = Some(begin_with_session(pool, gql_ctx).await?);
4803    }
4804    Ok(guard)
4805}
4806
4807/// Begin a transaction that runs as this request's caller.
4808///
4809/// Every transaction GraphQL opens starts here -- a query's, an aggregate's,
4810/// a federated entity lookup's, a subscription's re-read, and the one a
4811/// mutation's writes share -- and each is set up by the request's
4812/// [`postrust_core::Session`], the same statements REST's transactions start
4813/// with. See [`GraphQLContext::session`] for what goes in and why.
4814///
4815/// This used to be written out here: the settings in one `set_config`, then
4816/// `SET LOCAL ROLE`. It differed from REST in what it left out -- a role's own
4817/// `statement_timeout` and isolation level, `PGRST_DB_TX_ISOLATION`, the
4818/// `search_path`, `app.settings.*` -- and in the order, which put the role
4819/// last. The session sets the role inside the one statement, after the
4820/// settings PostgREST puts before it and before the claims and the `hasura.*`
4821/// variables; every one of those is a setting any role may set on itself, so
4822/// they are set as the caller as readily as they were as the authenticator.
4823async fn begin_with_session(
4824    pool: &PgPool,
4825    gql_ctx: &GraphQLContext,
4826) -> Result<sqlx::Transaction<'static, sqlx::Postgres>, async_graphql::Error> {
4827    let mut tx = pool.begin().await?;
4828    gql_ctx.session().apply_sqlx(&mut tx).await?;
4829    Ok(tx)
4830}
4831
4832/// Render a row as JSON, with any shape column rendered as GeoJSON.
4833///
4834/// PostgreSQL's text form for a geometry is WKB hex --
4835/// `0103000020E6100000…` -- which is what `row_to_json` puts in the response
4836/// and is not what any client can read. Hasura answers GeoJSON, and a client
4837/// migrating from it parses GeoJSON.
4838///
4839/// The shape columns are merged over the row rather than replacing the
4840/// projection, so a table with no shape column produces exactly the SQL it did
4841/// before and one with three needs no list of the others.
4842fn row_json(expr: &str, column_types: &HashMap<String, String>) -> String {
4843    let mut shapes: Vec<(&String, &String)> = column_types
4844        .iter()
4845        .filter(|(_, pg_type)| matches!(pg_type.as_str(), "geometry" | "geography"))
4846        .collect();
4847    if shapes.is_empty() {
4848        return format!("row_to_json({})", expr);
4849    }
4850    shapes.sort();
4851
4852    let overrides: Vec<String> = shapes
4853        .iter()
4854        .map(|(name, _)| {
4855            format!(
4856                // Option 4 asks PostGIS for the long-form CRS member --
4857                // `urn:ogc:def:crs:EPSG::4326` -- which Hasura includes and
4858                // which a client round-tripping a shape needs in order to
4859                // write it back where it came from. PostGIS emits it only
4860                // where the geometry has an SRID to report.
4861                "{}, ST_AsGeoJSON({}.{}, 9, 4)::jsonb",
4862                postrust_sql::quote_literal(name),
4863                expr,
4864                postrust_sql::escape_ident(name)
4865            )
4866        })
4867        .collect();
4868    format!(
4869        "(to_jsonb({}) || jsonb_build_object({}))",
4870        expr,
4871        overrides.join(", ")
4872    )
4873}
4874
4875/// Execute a SQL query and return results as serde_json::Value.
4876/// We keep data as serde_json::Value so field resolvers can use try_downcast_ref.
4877async fn execute_query_on(
4878    conn: &mut sqlx::PgConnection,
4879    sql: &str,
4880    params: &[serde_json::Value],
4881) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
4882    use sqlx::Row;
4883
4884    trace!("Executing SQL: {}", sql);
4885
4886    // Execute query
4887    let mut query = sqlx::query(AssertSqlSafe(sql));
4888    for param in params {
4889        query = bind_json_value(query, param);
4890    }
4891    let rows = query.fetch_all(&mut *conn).await.map_err(database_error)?;
4892
4893    // Return raw JSON values - don't convert to async_graphql::Value
4894    // This allows field resolvers to use try_downcast_ref::<serde_json::Value>()
4895    let results: Vec<serde_json::Value> = rows
4896        .into_iter()
4897        .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
4898        .collect();
4899
4900    Ok(results)
4901}
4902
4903/// Refuse a GeoJSON document PostGIS would accept and should not.
4904///
4905/// `ST_GeomFromGeoJSON` will build a "Polygon" from three points that do not
4906/// meet, and a "LineString" from one point -- neither of which is a shape, and
4907/// both of which are then stored and read back as though they were. Hasura
4908/// checks the document before it reaches the database, refuses with
4909/// `parse-failed`, and says which rule was broken; the messages here are its
4910/// messages, because a client that reports them to a user is reporting text it
4911/// already ships.
4912///
4913/// A value that is not an object is left alone: a string in a geometry column
4914/// is WKT or WKB hex, which is a different thing entirely.
4915fn check_geojson(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4916    fn refuse<T>(message: &str) -> Result<T, async_graphql::Error> {
4917        Err(coded_error("parse-failed", message))
4918    }
4919
4920    fn position(
4921        value: &serde_json::Value,
4922    ) -> Result<&Vec<serde_json::Value>, async_graphql::Error> {
4923        match value.as_array() {
4924            Some(items) if items.len() >= 2 && items.iter().all(|i| i.is_number()) => Ok(items),
4925            _ => refuse("A Position needs at least 2 elements"),
4926        }
4927    }
4928
4929    fn positions(
4930        value: Option<&serde_json::Value>,
4931        least: usize,
4932        what: &str,
4933    ) -> Result<Vec<Vec<serde_json::Value>>, async_graphql::Error> {
4934        let items = match value.and_then(|v| v.as_array()) {
4935            Some(items) => items,
4936            None => return refuse(&format!("A {} needs at least {} Positions", what, least)),
4937        };
4938        if items.len() < least {
4939            return refuse(&format!("A {} needs at least {} Positions", what, least));
4940        }
4941        items.iter().map(|item| position(item).cloned()).collect()
4942    }
4943
4944    fn ring(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4945        let points = positions(Some(value), 4, "LinearRing")?;
4946        match (points.first(), points.last()) {
4947            (Some(first), Some(last)) if first == last => Ok(()),
4948            _ => refuse("the first and last locations have to be equal for a LinearRing"),
4949        }
4950    }
4951
4952    fn polygon(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4953        let Some(rings) = value.as_array() else {
4954            return refuse("A LinearRing needs at least 4 Positions");
4955        };
4956        rings.iter().try_for_each(ring)
4957    }
4958
4959    let serde_json::Value::Object(map) = value else {
4960        return Ok(());
4961    };
4962    let Some(kind) = map.get("type").and_then(|v| v.as_str()) else {
4963        return Ok(());
4964    };
4965    let coordinates = map.get("coordinates");
4966    match kind {
4967        "Point" => {
4968            position(coordinates.unwrap_or(&serde_json::Value::Null))?;
4969        }
4970        "MultiPoint" => {
4971            positions(coordinates, 0, "MultiPoint")?;
4972        }
4973        "LineString" => {
4974            positions(coordinates, 2, "LineString")?;
4975        }
4976        "MultiLineString" => {
4977            for line in coordinates.and_then(|v| v.as_array()).into_iter().flatten() {
4978                positions(Some(line), 2, "LineString")?;
4979            }
4980        }
4981        "Polygon" => polygon(coordinates.unwrap_or(&serde_json::Value::Null))?,
4982        "MultiPolygon" => {
4983            for one in coordinates.and_then(|v| v.as_array()).into_iter().flatten() {
4984                polygon(one)?;
4985            }
4986        }
4987        "GeometryCollection" => {
4988            for geometry in map
4989                .get("geometries")
4990                .and_then(|v| v.as_array())
4991                .into_iter()
4992                .flatten()
4993            {
4994                check_geojson(geometry)?;
4995            }
4996        }
4997        other => return refuse(&format!("unexpected geometry type: {}", other)),
4998    }
4999    Ok(())
5000}
5001
5002/// The call that produces a computed field's value.
5003///
5004/// Two spellings of the same row, because the two calls need different ones.
5005/// A positional call takes `alias.*`, which is what a qualified table can be
5006/// written as; a named call takes the row as one value, which only a bare
5007/// alias is. Named notation is needed exactly where a session argument is,
5008/// since the row is then not the only parameter and may not be the first.
5009fn computed_call(
5010    definition: &postrust_core::schema_cache::ComputedColumn,
5011    row: &str,
5012    row_by_name: &str,
5013) -> String {
5014    let function = format!(
5015        "{}.{}",
5016        postrust_sql::escape_ident(&definition.function.schema),
5017        postrust_sql::escape_ident(&definition.function.name)
5018    );
5019    match (&definition.session_argument, &definition.row_argument) {
5020        (Some(session), Some(row_argument)) => format!(
5021            "{}({} => {}, {} => {})",
5022            function,
5023            postrust_sql::escape_ident(row_argument),
5024            row_by_name,
5025            postrust_sql::escape_ident(session),
5026            SESSION_ARGUMENT
5027        ),
5028        _ => format!("{}({})", function, row),
5029    }
5030}
5031
5032/// What a `hasura_session` argument is given.
5033///
5034/// The session document, read from the setting [`GraphQLContext::session`]
5035/// writes.
5036/// `current_setting`'s second argument makes a missing setting null rather than
5037/// an error, which is the case of a request with no session at all.
5038const SESSION_ARGUMENT: &str = "coalesce(current_setting('hasura.session', true), '{}')::json";
5039
5040/// Everything an update may be told to do, in the order the schema declares
5041/// them. Read by both spellings: one update, and one of many.
5042const UPDATE_OPERATORS: [&str; 7] = [
5043    "_set",
5044    "_inc",
5045    "_append",
5046    "_prepend",
5047    "_delete_key",
5048    "_delete_elem",
5049    "_delete_at_path",
5050];
5051
5052/// What a read table is called inside its own query.
5053///
5054/// See [`WRITTEN_ROW`]: the row a query passes to a computed field has to be
5055/// named, and a table's qualified name is not a name a row can be written
5056/// under.
5057const READ_ROW: &str = "pgrst_src";
5058
5059/// What a written table is called inside its own statement.
5060///
5061/// See [`WhereScope::under_alias`]: the row a statement returns has to be
5062/// named, and a table's own name is read as a column first.
5063const WRITTEN_ROW: &str = "pgrst_row";
5064
5065/// The cast a written value needs to reach a column of this type.
5066///
5067/// A bound parameter arrives as text. PostgreSQL will coerce it to a numeric
5068/// or a date on assignment, but not to `jsonb`, an array, or a user-defined
5069/// type -- `column "details" is of type jsonb but expression is of type text`
5070/// is what an uncast insert answers. Naming the column's own type covers all
5071/// of them and changes nothing where the coercion would have worked anyway.
5072fn write_cast(column_types: &HashMap<String, String>, column: &str) -> String {
5073    match column_types.get(column) {
5074        Some(pg_type) => format!("::{}", pg_type),
5075        None => String::new(),
5076    }
5077}
5078
5079/// The value one column is written with, as it goes over the wire.
5080///
5081/// A `json` column holds a JSON value, and `"[]"` is one -- a string whose
5082/// characters happen to be brackets. Binding the bare text and casting stored
5083/// an empty array instead, so a client that wrote a string read back a list.
5084/// The document a column is given is the document it keeps.
5085fn write_operand(
5086    column_types: &HashMap<String, String>,
5087    column: &str,
5088    value: &serde_json::Value,
5089) -> serde_json::Value {
5090    match column_types.get(column).map(String::as_str) {
5091        Some("json") | Some("jsonb") => match value {
5092            serde_json::Value::String(_)
5093            | serde_json::Value::Number(_)
5094            | serde_json::Value::Bool(_) => serde_json::Value::String(value.to_string()),
5095            other => other.clone(),
5096        },
5097        // An array column takes an array literal. `["a","b"]` is JSON, and
5098        // PostgreSQL reads a text parameter destined for a `text[]` as
5099        // `{a,b}` -- `malformed array literal` is what it says about the
5100        // other spelling.
5101        Some(pg_type) if is_array_type(pg_type) => match value {
5102            serde_json::Value::Array(_) => serde_json::Value::String(array_literal(value)),
5103            other => other.clone(),
5104        },
5105        _ => value.clone(),
5106    }
5107}
5108
5109/// Whether a PostgreSQL type name is an array.
5110///
5111/// Both spellings appear in the catalogue depending on how it was asked:
5112/// `text[]` from `format_type`, `_text` from `typname`.
5113fn is_array_type(pg_type: &str) -> bool {
5114    pg_type.ends_with("[]") || pg_type.starts_with('_')
5115}
5116
5117/// A JSON array as PostgreSQL writes one.
5118///
5119/// `["a","b"]` becomes `{"a","b"}`. Every element is quoted, so a value
5120/// containing a comma, a brace or a backslash survives; a null is the unquoted
5121/// `NULL`, which is the only way to write one.
5122fn array_literal(value: &serde_json::Value) -> String {
5123    fn element(value: &serde_json::Value) -> String {
5124        match value {
5125            serde_json::Value::Null => "NULL".to_string(),
5126            serde_json::Value::Array(_) => array_literal(value),
5127            serde_json::Value::String(text) => {
5128                format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
5129            }
5130            other => format!("\"{}\"", other.to_string().replace('"', "\\\"")),
5131        }
5132    }
5133    let items = match value {
5134        serde_json::Value::Array(items) => items,
5135        other => return element(other),
5136    };
5137    format!(
5138        "{{{}}}",
5139        items.iter().map(element).collect::<Vec<_>>().join(",")
5140    )
5141}
5142
5143/// The expression that writes one bound value into one column.
5144///
5145/// A cast is enough for almost everything. A shape is the exception: a client
5146/// sends GeoJSON, which is what Hasura accepts, and `'{"type":"Point",…}'` is
5147/// not something PostgreSQL will cast to a geometry -- it has a function for
5148/// reading that, and the function is the only way in.
5149///
5150/// Only when the value actually is an object. A string in a geometry column is
5151/// WKT or WKB hex, which the cast does read, and passing that to
5152/// `ST_GeomFromGeoJSON` would refuse a perfectly good value.
5153fn write_expression(
5154    column_types: &HashMap<String, String>,
5155    column: &str,
5156    value: &serde_json::Value,
5157    placeholder: &str,
5158) -> String {
5159    let pg_type = column_types.get(column).map(String::as_str);
5160    if value.is_object() && matches!(pg_type, Some("geometry") | Some("geography")) {
5161        return match pg_type {
5162            Some("geography") => format!("ST_GeomFromGeoJSON({})::geography", placeholder),
5163            _ => format!("ST_GeomFromGeoJSON({})", placeholder),
5164        };
5165    }
5166    // An amount written as a number is reached through one: PostgreSQL has no
5167    // cast from `double precision` to `money`, which is what a bound JSON
5168    // number arrives as, and `numeric` is the type it does take one from. One
5169    // written as text -- `"$12,344.57"` -- is read by `money` directly, and
5170    // going through `numeric` would refuse the currency symbol.
5171    if pg_type == Some("money") && value.is_number() {
5172        return format!("{}::numeric::money", placeholder);
5173    }
5174    format!("{}{}", placeholder, write_cast(column_types, column))
5175}
5176
5177/// Every column of a table with the type it is declared as.
5178async fn column_types_of(
5179    schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
5180    schema_name: &str,
5181    table_name: &str,
5182) -> HashMap<String, String> {
5183    let Ok(guard) = schema_cache.get().await else {
5184        return HashMap::new();
5185    };
5186    let Some(cache) = guard.as_ref() else {
5187        return HashMap::new();
5188    };
5189    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5190    match cache.get_table(&qi) {
5191        Some(table) => table
5192            .columns
5193            .values()
5194            .map(|c| (c.name.clone(), c.nominal_type.clone()))
5195            .collect(),
5196        None => HashMap::new(),
5197    }
5198}
5199
5200/// Insert one row, and any rows nested inside it.
5201///
5202/// Hasura writes a parent and its children in one mutation:
5203///
5204/// ```graphql
5205/// insert_article(objects: [{title: "x", author: {data: {name: "y"}}}])
5206/// ```
5207///
5208/// Which row goes first follows from which side holds the key. A relationship
5209/// to one row is reached through a column of *this* table, so the related row
5210/// is inserted first and its key is what this row's column is set to. A
5211/// relationship to many rows is reached through a column of *theirs*, so this
5212/// row goes first and each child's column is set from it.
5213///
5214/// Everything runs in the transaction the caller opened, so a child that
5215/// cannot be written takes the parent with it -- which is what writing them in
5216/// one mutation means.
5217fn insert_row<'life>(
5218    conn: &'life mut sqlx::PgConnection,
5219    schema_name: &'life str,
5220    table_name: &'life str,
5221    object: serde_json::Map<String, serde_json::Value>,
5222    context: &'life InsertContext<'life>,
5223    written_count: &'life mut usize,
5224) -> std::pin::Pin<
5225    Box<
5226        dyn std::future::Future<Output = Result<serde_json::Value, async_graphql::Error>>
5227            + Send
5228            + 'life,
5229    >,
5230> {
5231    Box::pin(async move {
5232        use sqlx::Row;
5233
5234        let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5235        let table = context.cache.get_table(&qi).ok_or_else(|| {
5236            async_graphql::Error::new(format!("unknown table \"{}\"", table_name))
5237        })?;
5238        let column_types: HashMap<String, String> = table
5239            .columns
5240            .values()
5241            .map(|c| (c.name.clone(), c.nominal_type.clone()))
5242            .collect();
5243
5244        // A key that is a relationship rather than a column is a nested write.
5245        let type_name = context
5246            .type_names
5247            .get(&(schema_name.to_string(), table_name.to_string()));
5248        let relationships: &[RelationshipField] = type_name
5249            .and_then(|name| context.relationships.get(name))
5250            .map(|r| r.as_slice())
5251            .unwrap_or(&[]);
5252
5253        let mut columns = serde_json::Map::new();
5254        type Nested<'r> = (
5255            &'r RelationshipField,
5256            serde_json::Value,
5257            Option<serde_json::Value>,
5258        );
5259        let mut to_one: Vec<Nested> = Vec::new();
5260        let mut to_many: Vec<Nested> = Vec::new();
5261
5262        for (key, value) in object {
5263            match relationships.iter().find(|r| r.name == key) {
5264                None => {
5265                    // A written value is keyed by the field it was sent under;
5266                    // the statement is written in the table's own columns.
5267                    columns.insert(
5268                        table_column_for(context.names, table, &key).to_string(),
5269                        value,
5270                    );
5271                }
5272                Some(_) if value.is_null() => {
5273                    // `author: null` is a row with no author, not a row whose
5274                    // author is a null object. A client writing one insert for
5275                    // both cases sends the relationship either way.
5276                    continue;
5277                }
5278                Some(relationship) => {
5279                    // `{data: {...}}` for one row, `{data: [{...}]}` for many,
5280                    // and an `on_conflict` beside either -- a nested row is
5281                    // upserted the same way a top-level one is.
5282                    let (data, conflict) = match &value {
5283                        serde_json::Value::Object(map) => (
5284                            map.get("data").cloned().unwrap_or(value.clone()),
5285                            map.get("on_conflict").cloned().filter(|v| !v.is_null()),
5286                        ),
5287                        other => (other.clone(), None),
5288                    };
5289                    // Which row goes first follows from which side holds the
5290                    // key, not from how many rows there are. A one-to-one
5291                    // whose child key *is* the parent's -- `author_detail.id`
5292                    // referencing `author.id` -- is one row either way, and
5293                    // the parent still has to be written before there is a key
5294                    // to give it.
5295                    if child_holds_the_key(&relationship.relationship) {
5296                        to_many.push((relationship, data, conflict));
5297                    } else {
5298                        to_one.push((relationship, data, conflict));
5299                    }
5300                }
5301            }
5302        }
5303
5304        // A shape is checked before it is written, since PostGIS would build
5305        // one from a document that is not a shape.
5306        for (column, value) in &columns {
5307            if matches!(
5308                column_types.get(column).map(String::as_str),
5309                Some("geometry") | Some("geography")
5310            ) {
5311                // Under the name the client wrote it under, which is the
5312                // exposed one rather than the column's where they differ.
5313                check_geojson(value).map_err(|error| {
5314                    let field = context
5315                        .names
5316                        .column(schema_name, table_name, column)
5317                        .unwrap_or(column);
5318                    at_path(error, &format!("{}.{}", context.row, field))
5319                })?;
5320            }
5321        }
5322
5323        // The rows this one points at, first: this row's own column carries
5324        // their key.
5325        for (relationship, data, conflict) in to_one {
5326            let plan =
5327                postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, context.cache)
5328                    .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5329            let serde_json::Value::Object(child) = data else {
5330                return Err(async_graphql::Error::new(format!(
5331                    "\"{}\" takes an object to insert",
5332                    relationship.name
5333                )));
5334            };
5335            // Writing the related row is what fills this row's key column in,
5336            // so a value already written there is a second answer to the same
5337            // question and one of them would be silently discarded.
5338            for (local, _) in &plan.columns {
5339                if columns.get(local).is_some_and(|v| !v.is_null()) {
5340                    return Err(at_path(
5341                        validation_error(format!(
5342                            "cannot insert object relationship \"{}\" as \"{}\" column \
5343                             values are already determined",
5344                            relationship.name, local
5345                        )),
5346                        &format!("{}.{}", context.row, relationship.name),
5347                    ));
5348                }
5349            }
5350            // A to-one row is written under the relationship's own name:
5351            // `...objects[0].author.data`, and its `on_conflict` beside it.
5352            let under = format!("{}.{}", context.row, relationship.name);
5353            let nested = InsertContext {
5354                on_conflict: conflict,
5355                cache: context.cache,
5356                relationships: context.relationships,
5357                type_names: context.type_names,
5358                names: context.names,
5359                caller: context.caller,
5360                row: format!("{}.data", under),
5361                objects: format!("{}.data", under),
5362                conflict: format!("{}.on_conflict", under),
5363            };
5364            let written = insert_row(
5365                conn,
5366                &plan.foreign_schema,
5367                &plan.foreign_table,
5368                child,
5369                &nested,
5370                written_count,
5371            )
5372            .await?;
5373            for (local, foreign) in &plan.columns {
5374                if let Some(value) = written.get(foreign) {
5375                    columns.insert(local.clone(), value.clone());
5376                }
5377            }
5378        }
5379
5380        // What the server fills in regardless of what was sent. Applied after
5381        // the nested rows have contributed their keys and before the columns
5382        // are counted, because a preset is a column this statement writes --
5383        // and applied *over* the request, since a preset the client could
5384        // override is not a preset.
5385        for (column, value) in crate::role::presets(
5386            &context.caller,
5387            context.names,
5388            schema_name,
5389            table_name,
5390            crate::role::Verb::Insert,
5391        )
5392        .map_err(|fault| coded_error(fault.code(), fault.to_string()))?
5393        {
5394            columns.insert(column, value);
5395        }
5396
5397        // `ON CONFLICT` says which uniqueness is being resolved against and
5398        // what to do about it. An empty `update_columns` is `DO NOTHING`,
5399        // which is how a client says "leave the row that is already there".
5400        // The columns this statement writes, settled before the conflict
5401        // clause so a predicate on it can number its parameters after theirs.
5402        let column_names: Vec<&str> = columns.keys().map(|k| k.as_str()).collect();
5403        let mut conflict_values: Vec<serde_json::Value> = Vec::new();
5404        let conflict_sql = match &context.on_conflict {
5405            Some(serde_json::Value::Object(spec)) => {
5406                let constraint = spec.get("constraint").and_then(|v| v.as_str());
5407                let Some(constraint) = constraint else {
5408                    return Err(async_graphql::Error::new(
5409                        "on_conflict needs a constraint to resolve against",
5410                    ));
5411                };
5412                if !table
5413                    .unique_constraints
5414                    .iter()
5415                    .any(|(name, _)| name == constraint)
5416                {
5417                    return Err(async_graphql::Error::new(format!(
5418                        "\"{}\" is not a unique constraint of \"{}\"",
5419                        constraint, table_name
5420                    )));
5421                }
5422                let updates: Vec<&str> = spec
5423                    .get("update_columns")
5424                    .and_then(|v| v.as_array())
5425                    .map(|items| items.iter().filter_map(|i| i.as_str()).collect())
5426                    .unwrap_or_default();
5427                // The member that stands for the columns this role has none
5428                // of. It is in the enum so that `on_conflict` exists at all;
5429                // naming it is the one thing it cannot be used for.
5430                if updates.contains(&PLACEHOLDER_COLUMN) {
5431                    return Err(at_path(
5432                        coded_error("validation-failed", "erroneous column name"),
5433                        &context.conflict,
5434                    ));
5435                }
5436
5437                if updates.is_empty() {
5438                    format!(
5439                        " ON CONFLICT ON CONSTRAINT {} DO NOTHING",
5440                        postrust_sql::escape_ident(constraint)
5441                    )
5442                } else {
5443                    // An `ON CONFLICT DO UPDATE` is an update, so the update
5444                    // permission's presets are written here too -- and a
5445                    // column a preset writes does not also take its value from
5446                    // `EXCLUDED`, which is what "a preset overrides the
5447                    // request" means on this side.
5448                    let preset = crate::role::presets(
5449                        &context.caller,
5450                        context.names,
5451                        schema_name,
5452                        table_name,
5453                        crate::role::Verb::Update,
5454                    )
5455                    .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
5456
5457                    // Numbered after the row's own values and before the
5458                    // predicate below, because `SET` is written before `WHERE`
5459                    // and the parameters are bound in the order they appear.
5460                    let mut param_idx = column_names.len() + 1;
5461                    let mut assignments: Vec<String> =
5462                        Vec::with_capacity(preset.len() + updates.len());
5463                    for (column, value) in &preset {
5464                        assignments.push(format!(
5465                            "{} = {}",
5466                            postrust_sql::escape_ident(column),
5467                            write_expression(
5468                                &column_types,
5469                                column,
5470                                value,
5471                                &format!("${}", param_idx)
5472                            )
5473                        ));
5474                        conflict_values.push(write_operand(&column_types, column, value));
5475                        param_idx += 1;
5476                    }
5477                    for field in &updates {
5478                        let column = table_column_for(context.names, table, field);
5479                        if preset.iter().any(|(written, _)| written == column) {
5480                            continue;
5481                        }
5482                        assignments.push(format!(
5483                            "{} = EXCLUDED.{}",
5484                            postrust_sql::escape_ident(column),
5485                            postrust_sql::escape_ident(column)
5486                        ));
5487                    }
5488                    // `where` on an upsert decides whether the row that is
5489                    // already there is overwritten -- "only if what I am
5490                    // writing is newer". It reads the existing row, which is
5491                    // what the statement's alias names.
5492                    //
5493                    // The update permission's own filter is ANDed into it: an
5494                    // upsert that overwrites a row is an update, and a role
5495                    // that may not update a row may not reach it by inserting
5496                    // over it. Compiling that filter is also where a session
5497                    // variable it names and the caller does not carry is
5498                    // noticed -- which is the answer Hasura gives before it
5499                    // writes anything.
5500                    let granted = permission_filter(
5501                        &context.caller,
5502                        context.names,
5503                        schema_name,
5504                        table_name,
5505                        crate::role::Verb::Update,
5506                    )?;
5507                    let requested = spec.get("where").filter(|f| !f.is_null()).cloned();
5508                    let condition = match and_predicates(requested, granted) {
5509                        Some(filter) => {
5510                            let filter = &filter;
5511                            let type_name = context
5512                                .type_names
5513                                .get(&(schema_name.to_string(), table_name.to_string()))
5514                                .map(String::as_str)
5515                                .unwrap_or(table_name);
5516                            let scope = WhereScope::table(
5517                                schema_name,
5518                                table_name,
5519                                type_name,
5520                                context.names,
5521                            )
5522                            .under_alias(WRITTEN_ROW)
5523                            .with_resolution(context.cache, context.relationships);
5524                            let mut alias_counter = 0usize;
5525                            build_condition(
5526                                filter,
5527                                &scope,
5528                                &mut param_idx,
5529                                &mut conflict_values,
5530                                &mut alias_counter,
5531                            )?
5532                            .map(|sql| format!(" WHERE {}", sql))
5533                            .unwrap_or_default()
5534                        }
5535                        None => String::new(),
5536                    };
5537                    format!(
5538                        " ON CONFLICT ON CONSTRAINT {} DO UPDATE SET {}{}",
5539                        postrust_sql::escape_ident(constraint),
5540                        assignments.join(", "),
5541                        condition
5542                    )
5543                }
5544            }
5545            _ => String::new(),
5546        };
5547
5548        // The row this statement writes, as `RETURNING` names it. Not the
5549        // table's own name: qualifying it reads as a column of a table called
5550        // `public`, which is what `missing FROM-clause entry for table
5551        // "public"` means, and leaving it bare reads as a column of the table
5552        // where one shares the name.
5553        let qualified_table = postrust_sql::escape_ident(WRITTEN_ROW);
5554
5555        // What the written row has to satisfy for the write to stand,
5556        // evaluated in `RETURNING` against the row as written. Its parameters
5557        // are numbered after the values and the conflict clause, since
5558        // `RETURNING` is last.
5559        let check_scope = WhereScope::for_alias(
5560            schema_name,
5561            table_name,
5562            WRITTEN_ROW,
5563            context
5564                .type_names
5565                .get(&(schema_name.to_string(), table_name.to_string()))
5566                .map(String::as_str)
5567                .unwrap_or(table_name),
5568            context.cache,
5569            context.relationships,
5570            context.names,
5571        );
5572        let (check_sql, check_values) = {
5573            let check = crate::role::write_check(
5574                &context.caller,
5575                context.names,
5576                schema_name,
5577                table_name,
5578                crate::role::Verb::Insert,
5579            )
5580            .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
5581            match check {
5582                None => (String::new(), Vec::new()),
5583                Some(check) => {
5584                    let mut values = Vec::new();
5585                    let mut param_idx = column_names.len() + conflict_values.len() + 1;
5586                    let mut alias_counter = 0usize;
5587                    match build_condition(
5588                        &check,
5589                        &check_scope,
5590                        &mut param_idx,
5591                        &mut values,
5592                        &mut alias_counter,
5593                    )? {
5594                        None => (String::new(), Vec::new()),
5595                        Some(sql) => (
5596                            format!(
5597                                ", ({}) AS {}",
5598                                sql,
5599                                postrust_sql::escape_ident(CHECK_COLUMN)
5600                            ),
5601                            values,
5602                        ),
5603                    }
5604                }
5605            }
5606        };
5607
5608        let names = column_names;
5609        let written = if names.is_empty() {
5610            // Every column defaulted. `DEFAULT VALUES` is how SQL says that;
5611            // an empty column list is a syntax error.
5612            let sql = format!(
5613                "INSERT INTO {}.{} AS {} DEFAULT VALUES{} RETURNING {}{}",
5614                postrust_sql::escape_ident(schema_name),
5615                postrust_sql::escape_ident(table_name),
5616                qualified_table,
5617                conflict_sql,
5618                row_json(&qualified_table, &column_types),
5619                check_sql
5620            );
5621            let mut query = sqlx::query(AssertSqlSafe(sql));
5622            for value in &conflict_values {
5623                query = bind_json_value(query, value);
5624            }
5625            for value in &check_values {
5626                query = bind_json_value(query, value);
5627            }
5628            query
5629                .fetch_optional(&mut *conn)
5630                .await
5631                // A constraint the write violated is reported against the rows
5632                // the statement was given, which is where Hasura reports it.
5633                .map_err(|error| at_path(database_error(error), &context.objects))?
5634        } else {
5635            let placeholders: Vec<String> = names
5636                .iter()
5637                .enumerate()
5638                .map(|(i, column)| {
5639                    let placeholder = format!("${}", i + 1);
5640                    match columns.get(*column) {
5641                        Some(value) => write_expression(&column_types, column, value, &placeholder),
5642                        None => placeholder,
5643                    }
5644                })
5645                .collect();
5646            let sql = format!(
5647                "INSERT INTO {}.{} AS {} ({}) VALUES ({}){} RETURNING {}{}",
5648                postrust_sql::escape_ident(schema_name),
5649                postrust_sql::escape_ident(table_name),
5650                qualified_table,
5651                names
5652                    .iter()
5653                    .map(|c| postrust_sql::escape_ident(c))
5654                    .collect::<Vec<_>>()
5655                    .join(", "),
5656                placeholders.join(", "),
5657                conflict_sql,
5658                row_json(&qualified_table, &column_types),
5659                check_sql
5660            );
5661            trace!("Executing INSERT SQL: {}", sql);
5662            let mut query = sqlx::query(AssertSqlSafe(sql));
5663            for column in &names {
5664                if let Some(value) = columns.get(*column) {
5665                    query = bind_json_value(query, &write_operand(&column_types, column, value));
5666                }
5667            }
5668            for value in &conflict_values {
5669                query = bind_json_value(query, value);
5670            }
5671            for value in &check_values {
5672                query = bind_json_value(query, value);
5673            }
5674            query
5675                .fetch_optional(&mut *conn)
5676                .await
5677                // A constraint the write violated is reported against the rows
5678                // the statement was given, which is where Hasura reports it.
5679                .map_err(|error| at_path(database_error(error), &context.objects))?
5680        };
5681
5682        // `DO NOTHING` writes nothing and returns nothing, which is the answer
5683        // rather than an error: the row that was already there stays.
5684        let Some(written) = written else {
5685            return Ok(serde_json::Value::Null);
5686        };
5687        refuse_unchecked_rows(std::slice::from_ref(&written), !check_sql.is_empty())
5688            .map_err(|error| at_path(error, &context.objects))?;
5689        let row: serde_json::Value = written.try_get(0).unwrap_or(serde_json::Value::Null);
5690        *written_count += 1;
5691
5692        // Then the rows that point at this one, which need its key.
5693        for (relationship, data, conflict) in to_many {
5694            let plan =
5695                postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, context.cache)
5696                    .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5697            let children = match data {
5698                serde_json::Value::Array(items) => items,
5699                serde_json::Value::Object(map) => vec![serde_json::Value::Object(map)],
5700                serde_json::Value::Null => Vec::new(),
5701                _ => {
5702                    return Err(async_graphql::Error::new(format!(
5703                        "\"{}\" takes objects to insert",
5704                        relationship.name
5705                    )))
5706                }
5707            };
5708            for (child_index, child) in children.into_iter().enumerate() {
5709                let serde_json::Value::Object(mut child) = child else {
5710                    continue;
5711                };
5712                for (local, foreign) in &plan.columns {
5713                    // The parent's key is what makes the child a child, so a
5714                    // child that writes it too is asking for a different
5715                    // parent than the one it is nested inside.
5716                    if child.get(foreign).is_some_and(|v| !v.is_null()) {
5717                        return Err(at_path(
5718                            validation_error(format!(
5719                                "cannot insert \"{}\" columns as their values are already \
5720                                 being determined by parent insert",
5721                                foreign
5722                            )),
5723                            &format!(
5724                                "{}.{}{}",
5725                                context.row,
5726                                relationship.name,
5727                                match relationship.is_list {
5728                                    true => format!(".data[{}]", child_index),
5729                                    false => ".data".to_string(),
5730                                }
5731                            ),
5732                        ));
5733                    }
5734                    if let Some(value) = row.get(local) {
5735                        child.insert(foreign.clone(), value.clone());
5736                    }
5737                }
5738                // `...objects[0].articles.data[0]`, which is the path
5739                // Hasura answers for a child that writes its parent's key.
5740                // One row written after its parent -- a mapped object
5741                // relationship with `after_parent` -- has no index: there is
5742                // no list for it to be an item of.
5743                let at = match relationship.is_list {
5744                    true => format!(".data[{}]", child_index),
5745                    false => ".data".to_string(),
5746                };
5747                let under = format!("{}.{}", context.row, relationship.name);
5748                let nested = InsertContext {
5749                    on_conflict: conflict.clone(),
5750                    cache: context.cache,
5751                    relationships: context.relationships,
5752                    type_names: context.type_names,
5753                    names: context.names,
5754                    caller: context.caller,
5755                    row: format!("{}{}", under, at),
5756                    objects: format!("{}.data", under),
5757                    conflict: format!("{}.on_conflict", under),
5758                };
5759                insert_row(
5760                    conn,
5761                    &plan.foreign_schema,
5762                    &plan.foreign_table,
5763                    child,
5764                    &nested,
5765                    written_count,
5766                )
5767                .await?;
5768            }
5769        }
5770
5771        Ok(row)
5772    })
5773}
5774
5775/// What a nested insert needs to follow a relationship.
5776///
5777/// Cloned per row and per nested row, which costs three strings: the paths are
5778/// the only part that differs between them, and the rest is references and a
5779/// `Caller`.
5780#[derive(Clone)]
5781struct InsertContext<'a> {
5782    /// What to do when this row conflicts. A nested row carries its own, from
5783    /// the `on_conflict` beside its `data`.
5784    on_conflict: Option<serde_json::Value>,
5785    cache: &'a SchemaCache,
5786    relationships: &'a HashMap<String, Vec<RelationshipField>>,
5787    /// (schema, table) -> the GraphQL type name, which keys the relationship
5788    /// map. A table's type is not always its name: a second schema prefixes
5789    /// it, and a name may have been given.
5790    type_names: &'a HashMap<(String, String), String>,
5791    /// The names columns are exposed under, so a written value keyed by a
5792    /// field reaches the column it names.
5793    names: &'a crate::names::NameOverrides,
5794    /// Who is writing, so that a permission's presets and its check reach
5795    /// every row this insert writes -- including the nested ones, which are
5796    /// rows of other tables under other rules.
5797    caller: crate::role::Caller<'a>,
5798    /// Where this row is in the request, as Hasura writes such a place:
5799    /// `$.selectionSet.insert_author.args.objects[0]`, and one level down
5800    /// `$.selectionSet.insert_author.args.objects[0].articles.data[0]`. A
5801    /// column of it is that with the field's name appended.
5802    row: String,
5803    /// Where the rows this statement writes were named. What a refused `check`
5804    /// is reported against -- the argument, not the row inside it, which is
5805    /// what Hasura answers.
5806    objects: String,
5807    /// Where this statement's `on_conflict` was named.
5808    conflict: String,
5809}
5810
5811/// Re-read written rows so that a mutation's `returning` can carry
5812/// relationships and computed fields.
5813///
5814/// `RETURNING row_to_json(t.*)` gives the table's own columns and nothing
5815/// else, so a relationship asked for beside them had no value to resolve --
5816/// and a non-null list field with no value is an error, which meant a mutation
5817/// that had written its rows correctly answered as though it had failed. The
5818/// write is not in doubt; only the shape of the answer is.
5819///
5820/// So the rows are read again by their primary key, through the same
5821/// projection an ordinary query uses. One extra round trip, and only when the
5822/// selection actually asks for something `RETURNING` cannot give.
5823#[allow(clippy::too_many_arguments)]
5824async fn reread_returning(
5825    pool: &PgPool,
5826    gql_ctx: &GraphQLContext,
5827    schema_name: &str,
5828    table_name: &str,
5829    type_name: &str,
5830    rows: Vec<Value>,
5831    returning: async_graphql::SelectionField<'_>,
5832    relationships: &HashMap<String, Vec<RelationshipField>>,
5833    names: &crate::names::NameOverrides,
5834    max_rows: Option<i64>,
5835) -> Result<Vec<Value>, async_graphql::Error> {
5836    let guard = gql_ctx
5837        .schema_cache
5838        .get()
5839        .await
5840        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5841    let Some(cache) = guard.as_ref() else {
5842        return Ok(rows);
5843    };
5844    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5845    let Some(table) = cache.get_table(&qi) else {
5846        return Ok(rows);
5847    };
5848    if table.pk_cols.is_empty() {
5849        // Nothing to identify the rows by. The columns are still right.
5850        return Ok(rows);
5851    }
5852
5853    let mut param_idx = 1usize;
5854    let mut values: Vec<serde_json::Value> = Vec::new();
5855    let mut alias_counter = 0usize;
5856    let embeds = build_embed_expressions(
5857        &gql_ctx.caller(),
5858        cache,
5859        relationships,
5860        type_name,
5861        "src",
5862        returning.selection_set(),
5863        max_rows,
5864        &mut alias_counter,
5865        &mut param_idx,
5866        &mut values,
5867        names,
5868    )?;
5869    let computed = computed_projections(
5870        table,
5871        returning.selection_set(),
5872        "src",
5873        names,
5874        cache,
5875        &mut param_idx,
5876        &mut values,
5877    )?;
5878    // A rename is reason enough to read the rows again: `RETURNING` answers in
5879    // the table's own column names, which are not the names the client asked
5880    // under.
5881    let renames = names.renames_columns(&table.schema, &table.name);
5882    if embeds.is_empty() && computed.is_empty() && !renames {
5883        return Ok(rows);
5884    }
5885
5886    // One row per key written, in the order they were written.
5887    let mut conditions = Vec::with_capacity(rows.len());
5888    for row in &rows {
5889        let mut parts = Vec::with_capacity(table.pk_cols.len());
5890        for column in &table.pk_cols {
5891            let Value::Object(map) = row else {
5892                return Ok(rows);
5893            };
5894            let Some(value) = map.get(&async_graphql::Name::new(column)) else {
5895                return Ok(rows);
5896            };
5897            parts.push(format!(
5898                "{} = ${}",
5899                postrust_sql::escape_ident(column),
5900                param_idx
5901            ));
5902            values.push(value_to_json(value));
5903            param_idx += 1;
5904        }
5905        conditions.push(format!("({})", parts.join(" AND ")));
5906    }
5907    if conditions.is_empty() {
5908        return Ok(rows);
5909    }
5910
5911    let mut projection =
5912        rename_projection(table, "src", names).unwrap_or_else(|| "src.*".to_string());
5913    for expression in &computed {
5914        projection.push_str(", ");
5915        projection.push_str(expression);
5916    }
5917    for (name, expression) in &embeds {
5918        projection.push_str(", ");
5919        projection.push_str(expression);
5920        projection.push_str(" AS ");
5921        projection.push_str(&postrust_sql::escape_ident(name));
5922    }
5923
5924    let sql = format!(
5925        "SELECT {} FROM (SELECT {} FROM (SELECT * FROM {}.{} WHERE {}) AS src) AS pgrst_r",
5926        row_json("pgrst_r", &exposed_column_types(table, names)),
5927        projection,
5928        postrust_sql::escape_ident(schema_name),
5929        postrust_sql::escape_ident(table_name),
5930        conditions.join(" OR ")
5931    );
5932
5933    // The same transaction the write went into: the rows it is reading are the
5934    // rows that write produced, and nothing has committed yet.
5935    let mut guard = write_tx(gql_ctx, pool).await?;
5936    let conn = guard.as_mut().expect("write_tx opens one");
5937    let reread = execute_query_on(conn, &sql, &values).await?;
5938    drop(guard);
5939
5940    if reread.is_empty() {
5941        return Ok(rows);
5942    }
5943    Ok(reread.into_iter().map(json_to_value).collect())
5944}
5945
5946/// Execute an insert mutation.
5947async fn execute_insert(
5948    pool: &PgPool,
5949    gql_ctx: &GraphQLContext,
5950    schema_name: &str,
5951    table_name: &str,
5952    objects: serde_json::Value,
5953    context: &InsertContext<'_>,
5954    // Whether the client wrote one row rather than a list of them. Only the
5955    // error paths care: `insert_x_one(object: {...})` has no row to index, so
5956    // its rows are named `args.object` and not `args.object[0]`.
5957    single: bool,
5958) -> Result<(Vec<Value>, usize), async_graphql::Error> {
5959    trace!("Insert mutation for {}: {:?}", table_name, objects);
5960
5961    // Handle both array and single object
5962    let objects_array = match objects {
5963        serde_json::Value::Array(arr) => arr,
5964        serde_json::Value::Object(obj) => vec![serde_json::Value::Object(obj)],
5965        _ => {
5966            return Err(async_graphql::Error::new(
5967                "objects must be an array or object",
5968            ))
5969        }
5970    };
5971
5972    if objects_array.is_empty() {
5973        return Err(async_graphql::Error::new("objects cannot be empty"));
5974    }
5975
5976    let mut guard = write_tx(gql_ctx, pool).await?;
5977    let conn = guard.as_mut().expect("write_tx opens one");
5978
5979    let mut inserted: Vec<Value> = Vec::new();
5980    let mut written = 0usize;
5981
5982    for (index, object) in objects_array.into_iter().enumerate() {
5983        let serde_json::Value::Object(map) = object else {
5984            return Err(async_graphql::Error::new(
5985                "each object to insert is an object",
5986            ));
5987        };
5988        // This row's own place in the request, which is what an error inside
5989        // it is reported against.
5990        let context = InsertContext {
5991            row: match single {
5992                true => context.objects.clone(),
5993                false => format!("{}[{}]", context.objects, index),
5994            },
5995            ..context.clone()
5996        };
5997        let row = insert_row(conn, schema_name, table_name, map, &context, &mut written).await?;
5998        // A row `DO NOTHING` left alone is not in `returning` and is not in
5999        // `affected_rows` either: nothing was written, and the row that was
6000        // already there is not this mutation's to report.
6001        if !row.is_null() {
6002            inserted.push(json_to_value(row));
6003        }
6004    }
6005
6006    Ok((inserted, written))
6007}
6008
6009/// Shape a mutation's result for the field that asked for it.
6010///
6011/// A by-key mutation answers with the row, or with null where the key matched
6012/// nothing. Every other mutation answers with the table's mutation response,
6013/// which carries `affected_rows` alongside the rows themselves -- a client may
6014/// ask for no rows back and still need the count, which is the usual case for
6015/// a delete.
6016///
6017/// The count is passed in rather than taken from the rows, because a nested
6018/// insert writes more rows than it returns: two articles each carrying a new
6019/// author is four rows written and two returned, and four is the answer.
6020fn mutation_result<'a>(rows: Vec<Value>, affected: usize, by_key: bool) -> Option<FieldValue<'a>> {
6021    if by_key {
6022        return rows.into_iter().next().map(FieldValue::value);
6023    }
6024    let mut response = async_graphql::indexmap::IndexMap::new();
6025    response.insert(
6026        async_graphql::Name::new("affected_rows"),
6027        Value::from(affected),
6028    );
6029    response.insert(async_graphql::Name::new("returning"), Value::List(rows));
6030    Some(FieldValue::value(Value::Object(response)))
6031}
6032
6033/// Bind a JSON value to a sqlx query.
6034///
6035/// Every value a GraphQL request carries reaches the database through here, as
6036/// a bound parameter, and that is what makes the `AssertSqlSafe` around each
6037/// statement in this module true rather than hopeful. sqlx 0.9 takes only a
6038/// `&'static str` as SQL unless told otherwise, and the statements here are
6039/// built at runtime because their shape follows the request -- which columns,
6040/// which tables, how many rows. What is spliced in comes from the schema cache
6041/// or from this module, never from the request: identifiers, each quoted with
6042/// `postrust_sql::escape_ident` first, the catalog's type names, and SQL
6043/// written here.
6044fn bind_json_value<'q>(
6045    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
6046    value: &serde_json::Value,
6047) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
6048    match value {
6049        serde_json::Value::Null => query.bind(None::<String>),
6050        serde_json::Value::Bool(b) => query.bind(*b),
6051        serde_json::Value::Number(n) => {
6052            if let Some(i) = n.as_i64() {
6053                query.bind(i)
6054            } else if let Some(f) = n.as_f64() {
6055                query.bind(f)
6056            } else {
6057                query.bind(n.to_string())
6058            }
6059        }
6060        serde_json::Value::String(s) => query.bind(s.clone()),
6061        _ => query.bind(value.to_string()),
6062    }
6063}
6064
6065/// Execute an update mutation.
6066#[allow(clippy::too_many_arguments)] // the predicate needs the schema it reads
6067async fn execute_update(
6068    pool: &PgPool,
6069    gql_ctx: &GraphQLContext,
6070    schema_name: &str,
6071    table_name: &str,
6072    type_name: &str,
6073    operators: Vec<(&'static str, serde_json::Value)>,
6074    column_types: HashMap<String, String>,
6075    where_clause: Option<serde_json::Value>,
6076    relationships: &HashMap<String, Vec<RelationshipField>>,
6077    names: &crate::names::NameOverrides,
6078) -> Result<Vec<Value>, async_graphql::Error> {
6079    use sqlx::Row;
6080
6081    trace!("Update mutation for {}: {:?}", table_name, operators);
6082
6083    // Build the SET clause. Each operator writes a column in terms of itself
6084    // except `_set`, which replaces it -- `_inc` adds, the jsonb operators
6085    // concatenate or remove, and a client may send several in one mutation as
6086    // long as they name different columns.
6087    let mut set_parts: Vec<String> = Vec::new();
6088    let mut set_values: Vec<serde_json::Value> = Vec::new();
6089    let mut param_idx = 1;
6090    let mut written: HashSet<String> = HashSet::new();
6091
6092    // What the permission writes whatever the request said. A preset overrides
6093    // rather than collides -- one a client could override is not a preset --
6094    // so these go in first and the operators below step around the columns
6095    // they name.
6096    //
6097    // This is also what makes an update with no `_set` at all a real update:
6098    // `update_resident(where: {...})` under a permission whose `set` names
6099    // `city` changes `city`, and answers with the rows it changed rather than
6100    // with nothing.
6101    let preset = crate::role::presets(
6102        &gql_ctx.caller(),
6103        names,
6104        schema_name,
6105        table_name,
6106        crate::role::Verb::Update,
6107    )
6108    .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
6109    let preset_columns: HashSet<&str> = preset.iter().map(|(name, _)| name.as_str()).collect();
6110    for (column, value) in &preset {
6111        let placeholder =
6112            write_expression(&column_types, column, value, &format!("${}", param_idx));
6113        set_parts.push(format!(
6114            "{} = {}",
6115            postrust_sql::escape_ident(column),
6116            placeholder
6117        ));
6118        set_values.push(write_operand(&column_types, column, value));
6119        param_idx += 1;
6120    }
6121
6122    for (operator, payload) in &operators {
6123        let serde_json::Value::Object(map) = payload else {
6124            return Err(async_graphql::Error::new(format!(
6125                "\"{}\" takes an object mapping columns to values",
6126                operator
6127            )));
6128        };
6129        for (field, value) in map {
6130            let column = &names
6131                .column_source(schema_name, table_name, field)
6132                .unwrap_or(field)
6133                .to_string();
6134            // A preset has this column. Not the duplicate-write error below:
6135            // the request is allowed to name it, and the permission wins.
6136            if preset_columns.contains(column.as_str()) {
6137                continue;
6138            }
6139            if !written.insert(column.clone()) {
6140                return Err(async_graphql::Error::new(format!(
6141                    "\"{}\" is written twice in one update; a column may be \
6142                     changed by one operator at a time",
6143                    column
6144                )));
6145            }
6146            let quoted = postrust_sql::escape_ident(column);
6147            // `_set` writes the column and `_inc` adds to it, so both take a
6148            // value of the column's type and are cast to it -- `money + $1`
6149            // is not an operator PostgreSQL has, and neither is `money +
6150            // double precision`, which is what a bound number arrives as. The
6151            // others already say what they need -- `::jsonb` for a
6152            // concatenation, `::text[]` for a path -- and casting twice would
6153            // be wrong for `_delete_elem`, whose operand is an integer rather
6154            // than a value of the column.
6155            let placeholder = match *operator {
6156                "_set" | "_inc" => {
6157                    write_expression(&column_types, column, value, &format!("${}", param_idx))
6158                }
6159                _ => format!("${}", param_idx),
6160            };
6161            // The assignment PostgreSQL needs, which for everything but `_set`
6162            // reads the column's current value.
6163            let assignment = match *operator {
6164                "_set" => format!("{} = {}", quoted, placeholder),
6165                "_inc" => format!("{} = {} + {}", quoted, quoted, placeholder),
6166                "_append" => format!("{} = {} || {}::jsonb", quoted, quoted, placeholder),
6167                "_prepend" => format!("{} = {}::jsonb || {}", quoted, placeholder, quoted),
6168                "_delete_key" => format!("{} = {} - {}::text", quoted, quoted, placeholder),
6169                "_delete_elem" => format!("{} = {} - {}::int", quoted, quoted, placeholder),
6170                // A path is a list of keys, and one parameter carrying
6171                // `["name","last"]` is a JSON array -- which PostgreSQL reads
6172                // as an array literal and refuses, `malformed array literal`.
6173                // The elements are bound one at a time into an `ARRAY[...]`,
6174                // the same way the key-existence comparisons take theirs.
6175                "_delete_at_path" => {
6176                    let Some(steps) = value.as_array() else {
6177                        return Err(async_graphql::Error::new(format!(
6178                            "\"_delete_at_path\" on \"{}\" takes a list of keys",
6179                            column
6180                        )));
6181                    };
6182                    let path = sql_array(steps, "text[]", &mut param_idx, &mut set_values);
6183                    set_parts.push(format!("{} = {} #- {}", quoted, quoted, path));
6184                    continue;
6185                }
6186                other => {
6187                    return Err(async_graphql::Error::new(format!(
6188                        "unsupported update operator \"{}\"",
6189                        other
6190                    )))
6191                }
6192            };
6193            if *operator == "_set"
6194                && matches!(
6195                    column_types.get(column).map(String::as_str),
6196                    Some("geometry") | Some("geography")
6197                )
6198            {
6199                check_geojson(value)?;
6200            }
6201            set_parts.push(assignment);
6202            set_values.push(match *operator {
6203                "_set" => write_operand(&column_types, column, value),
6204                _ => value.clone(),
6205            });
6206            param_idx += 1;
6207        }
6208    }
6209
6210    // An update that changes nothing changes no rows. Refusing it looks like
6211    // the stricter answer and is the wrong one: a client building `_set` from
6212    // a form the user submitted unchanged sends an empty object, and the
6213    // honest report of what happened is that nothing did.
6214    if set_parts.is_empty() {
6215        return Ok(Vec::new());
6216    }
6217
6218    // Build WHERE clause. It can follow a relationship, the same way a query's
6219    // can: `update_article(where: {author: {name: {_eq: "x"}}})` names the
6220    // rows by something they point at rather than by a column of their own.
6221    let guard = gql_ctx
6222        .schema_cache
6223        .get()
6224        .await
6225        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
6226    let cache = guard
6227        .as_ref()
6228        .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
6229    let scope = WhereScope::table(schema_name, table_name, type_name, names)
6230        .under_alias(WRITTEN_ROW)
6231        .with_resolution(cache, relationships);
6232    let (where_sql, where_values) = build_where_clause(where_clause.as_ref(), param_idx, &scope)?;
6233
6234    // An absent or unrecognised `where` argument yields an empty clause, which
6235    // would update every row in the table. Refuse instead.
6236    if where_sql.is_empty() {
6237        return Err(async_graphql::Error::new(format!(
6238            "update on \"{}\" requires a `where` argument with at least one \
6239             recognised condition; refusing to update every row",
6240            table_name
6241        )));
6242    }
6243
6244    // What the changed row has to satisfy for the change to stand. Evaluated
6245    // in the `RETURNING` clause, against the row as written -- which is the
6246    // only place it can honestly be evaluated, and costs neither a re-read nor
6247    // a way to identify the rows afterwards.
6248    let (check_sql, check_values) = permission_check_sql(
6249        gql_ctx,
6250        names,
6251        schema_name,
6252        table_name,
6253        crate::role::Verb::Update,
6254        &scope,
6255        param_idx + where_values.len(),
6256    )?;
6257
6258    let sql = format!(
6259        "UPDATE {}.{} AS {} SET {} {} RETURNING {}{}",
6260        postrust_sql::escape_ident(schema_name),
6261        postrust_sql::escape_ident(table_name),
6262        postrust_sql::escape_ident(WRITTEN_ROW),
6263        set_parts.join(", "),
6264        where_sql,
6265        row_json(&postrust_sql::escape_ident(WRITTEN_ROW), &column_types),
6266        check_sql
6267    );
6268
6269    trace!("Executing UPDATE SQL: {}", sql);
6270
6271    // Build query with parameters
6272    let mut query = sqlx::query(AssertSqlSafe(sql));
6273
6274    // Bind SET values
6275    for val in &set_values {
6276        query = bind_json_value(query, val);
6277    }
6278
6279    // Bind WHERE values
6280    for val in &where_values {
6281        query = bind_json_value(query, val);
6282    }
6283
6284    // And the check's, last, because `RETURNING` is.
6285    for val in &check_values {
6286        query = bind_json_value(query, val);
6287    }
6288
6289    let mut guard = write_tx(gql_ctx, pool).await?;
6290    let conn = guard.as_mut().expect("write_tx opens one");
6291    let rows = query.fetch_all(&mut **conn).await.map_err(database_error)?;
6292
6293    refuse_unchecked_rows(&rows, !check_sql.is_empty())?;
6294
6295    let updated: Vec<Value> = rows
6296        .iter()
6297        .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
6298        .map(json_to_value)
6299        .collect();
6300
6301    Ok(updated)
6302}
6303
6304/// A permission's check, as a column of the write's `RETURNING`.
6305///
6306/// Empty where nothing has to be checked. Otherwise `, (<predicate>) AS ...`,
6307/// evaluated per written row against the row itself -- so a row the permission
6308/// refuses is known before the transaction is settled, and settling it is
6309/// already a rollback once an error is reported.
6310fn permission_check_sql(
6311    gql_ctx: &GraphQLContext,
6312    names: &crate::names::NameOverrides,
6313    schema_name: &str,
6314    table_name: &str,
6315    verb: crate::role::Verb,
6316    scope: &WhereScope<'_>,
6317    start_param_idx: usize,
6318) -> Result<(String, Vec<serde_json::Value>), async_graphql::Error> {
6319    let check = crate::role::write_check(&gql_ctx.caller(), names, schema_name, table_name, verb)
6320        .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
6321    let Some(check) = check else {
6322        return Ok((String::new(), Vec::new()));
6323    };
6324
6325    let mut values = Vec::new();
6326    let mut param_idx = start_param_idx;
6327    let mut alias_counter = 0usize;
6328    let condition = build_condition(
6329        &check,
6330        scope,
6331        &mut param_idx,
6332        &mut values,
6333        &mut alias_counter,
6334    )?;
6335    Ok(match condition {
6336        // A check that compiles to nothing restricts nothing, which is what an
6337        // empty one says.
6338        None => (String::new(), Vec::new()),
6339        Some(sql) => (
6340            format!(
6341                ", ({}) AS {}",
6342                sql,
6343                postrust_sql::escape_ident(CHECK_COLUMN)
6344            ),
6345            values,
6346        ),
6347    })
6348}
6349
6350/// The column a permission's check is returned in.
6351const CHECK_COLUMN: &str = "pgrst_permission_check";
6352
6353/// Refuse the whole write if any row it produced fails the permission's check.
6354///
6355/// Every row, not the first: a mutation is one transaction and a single
6356/// refused row takes the rest with it, which is what makes a check a rule
6357/// about the write rather than about a row. A null counts as a failure -- an
6358/// unknown is not a satisfied condition.
6359fn refuse_unchecked_rows(
6360    rows: &[sqlx::postgres::PgRow],
6361    checked: bool,
6362) -> Result<(), async_graphql::Error> {
6363    if !checked {
6364        return Ok(());
6365    }
6366    use sqlx::Row;
6367    let all_passed = rows
6368        .iter()
6369        .all(|row| row.try_get::<bool, _>(CHECK_COLUMN).unwrap_or(false));
6370    match all_passed {
6371        true => Ok(()),
6372        false => Err(coded_error("permission-error", crate::role::CHECK_FAILED)),
6373    }
6374}
6375
6376/// Execute a delete mutation.
6377#[allow(clippy::too_many_arguments)] // the projection needs the schema it reads
6378async fn execute_delete(
6379    pool: &PgPool,
6380    gql_ctx: &GraphQLContext,
6381    schema_name: &str,
6382    table_name: &str,
6383    type_name: &str,
6384    where_clause: Option<serde_json::Value>,
6385    returning: Option<async_graphql::SelectionField<'_>>,
6386    relationships: &HashMap<String, Vec<RelationshipField>>,
6387    names: &crate::names::NameOverrides,
6388    max_rows: Option<i64>,
6389) -> Result<Vec<Value>, async_graphql::Error> {
6390    use sqlx::Row;
6391
6392    trace!("Delete mutation for {}", table_name);
6393
6394    let guard = gql_ctx
6395        .schema_cache
6396        .get()
6397        .await
6398        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
6399    let cache = guard
6400        .as_ref()
6401        .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
6402    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
6403    let column_types = cache
6404        .get_table(&qi)
6405        .map(|table| exposed_column_types(table, names))
6406        .unwrap_or_default();
6407
6408    // Build WHERE clause. It can follow a relationship -- `delete_article(where:
6409    // {author: {id: {_eq: 2}}})` is the article-by-author delete anyone writes
6410    // -- so the scope is given the schema to resolve one with.
6411    let scope = WhereScope::table(schema_name, table_name, type_name, names)
6412        .under_alias(WRITTEN_ROW)
6413        .with_resolution(cache, relationships);
6414    let (where_sql, mut values) = build_where_clause(where_clause.as_ref(), 1, &scope)?;
6415
6416    // An absent or unrecognised `where` argument yields an empty clause, which
6417    // would delete every row in the table. Refuse instead.
6418    if where_sql.is_empty() {
6419        return Err(async_graphql::Error::new(format!(
6420            "delete on \"{}\" requires a `where` argument with at least one \
6421             recognised condition; refusing to delete every row",
6422            table_name
6423        )));
6424    }
6425
6426    // A relationship or computed field asked for in `returning` cannot be read
6427    // afterwards -- the rows are gone by then, which is why this used to answer
6428    // the plain columns and then fail on a non-null list. Inside one statement
6429    // the deleted rows are still a table: the delete goes in a CTE and the
6430    // projection reads from it, while the rows it points at are still there.
6431    let mut projection = String::new();
6432    let renamed = cache
6433        .get_table(&qi)
6434        .and_then(|table| rename_projection(table, "src", names));
6435    if let Some(returning) = returning {
6436        let mut param_idx = values.len() + 1;
6437        let mut alias_counter = 0usize;
6438        let embeds = build_embed_expressions(
6439            &gql_ctx.caller(),
6440            cache,
6441            relationships,
6442            type_name,
6443            "src",
6444            returning.selection_set(),
6445            max_rows,
6446            &mut alias_counter,
6447            &mut param_idx,
6448            &mut values,
6449            names,
6450        )?;
6451        let computed = match cache.get_table(&qi) {
6452            Some(table) => computed_projections(
6453                table,
6454                returning.selection_set(),
6455                "src",
6456                names,
6457                cache,
6458                &mut param_idx,
6459                &mut values,
6460            )?,
6461            None => Vec::new(),
6462        };
6463        for expression in &computed {
6464            projection.push_str(", ");
6465            projection.push_str(expression);
6466        }
6467        for (name, expression) in &embeds {
6468            projection.push_str(", ");
6469            projection.push_str(expression);
6470            projection.push_str(" AS ");
6471            projection.push_str(&postrust_sql::escape_ident(name));
6472        }
6473    }
6474
6475    let written = postrust_sql::escape_ident(WRITTEN_ROW);
6476    let sql = if projection.is_empty() && renamed.is_none() {
6477        format!(
6478            "DELETE FROM {}.{} AS {} {} RETURNING {}",
6479            postrust_sql::escape_ident(schema_name),
6480            postrust_sql::escape_ident(table_name),
6481            written,
6482            where_sql,
6483            row_json(&written, &column_types)
6484        )
6485    } else {
6486        format!(
6487            "WITH pgrst_deleted AS (DELETE FROM {}.{} AS {} {} RETURNING {}.*) \
6488             SELECT {} FROM (SELECT {}{} FROM pgrst_deleted AS src) AS pgrst_r",
6489            postrust_sql::escape_ident(schema_name),
6490            postrust_sql::escape_ident(table_name),
6491            written,
6492            where_sql,
6493            written,
6494            row_json("pgrst_r", &column_types),
6495            renamed.unwrap_or_else(|| "src.*".to_string()),
6496            projection
6497        )
6498    };
6499
6500    trace!("Executing DELETE SQL: {}", sql);
6501
6502    let mut query = sqlx::query(AssertSqlSafe(sql));
6503    for val in &values {
6504        query = bind_json_value(query, val);
6505    }
6506
6507    let mut guard = write_tx(gql_ctx, pool).await?;
6508    let conn = guard.as_mut().expect("write_tx opens one");
6509    let rows = query.fetch_all(&mut **conn).await.map_err(database_error)?;
6510
6511    let deleted: Vec<Value> = rows
6512        .iter()
6513        .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
6514        .map(json_to_value)
6515        .collect();
6516
6517    Ok(deleted)
6518}
6519
6520/// The predicate a role's permission adds to every read of one table.
6521///
6522/// `None` where nothing restricts the read: no permission document, an
6523/// administrator, or a permission whose filter is `{}`. The value is a
6524/// `<table>_bool_exp` like any other, because [`crate::role::permission_where`]
6525/// rewrites it into one -- which is what lets the same compiler serve both and
6526/// keeps a permission able to say everything a `where` can.
6527fn permission_predicate(
6528    caller: &crate::role::Caller<'_>,
6529    names: &crate::names::NameOverrides,
6530    schema: &str,
6531    table: &str,
6532) -> Result<Option<serde_json::Value>, async_graphql::Error> {
6533    permission_filter(caller, names, schema, table, crate::role::Verb::Select)
6534}
6535
6536/// The same, for whichever grant the operation is asking under.
6537fn permission_filter(
6538    caller: &crate::role::Caller<'_>,
6539    names: &crate::names::NameOverrides,
6540    schema: &str,
6541    table: &str,
6542    verb: crate::role::Verb,
6543) -> Result<Option<serde_json::Value>, async_graphql::Error> {
6544    crate::role::row_filter(caller, names, schema, table, verb)
6545        .map(|filter| filter.map(|predicate| serde_json::json!({ PERMISSION: predicate })))
6546        .map_err(|fault| coded_error(fault.code(), fault.to_string()))
6547}
6548
6549/// The key a permission's own predicate is wrapped in on its way to the
6550/// compiler.
6551///
6552/// The two halves of a `where` are the same language and are compiled by the
6553/// same code, which is what keeps a permission able to say everything a client
6554/// can. They are not evaluated by the same party: a client's half asks what
6555/// *this caller* may see, and a permission's half is the server's own
6556/// predicate, evaluated as the server.
6557///
6558/// The difference shows on a relationship. `{"Artist": {"id":
6559/// "X-Hasura-Artist-Id"}}` on `Track` grants the tracks belonging to the
6560/// caller's artist -- to a role that has no permission on `Artist` at all, and
6561/// is not meant to have one: the predicate consults that table, it does not
6562/// expose it. Compiled as the caller, it needs a permission that does not
6563/// exist and refuses itself; compiled as the server, it says what it was
6564/// written to say. `_exists` has always worked this way and says so where it
6565/// is built; this is the same rule for the relationship a permission follows.
6566///
6567/// The name cannot collide with a column: no boolean expression a client can
6568/// write has this field, because no input type declares it.
6569const PERMISSION: &str = "_permission";
6570
6571/// How many rows a permission lets one read return.
6572///
6573/// A ceiling rather than a default: a request asking for more gets this, one
6574/// asking for fewer gets what it asked for, and one asking for nothing gets
6575/// the ceiling. The same rule `PGRST_MAX_ROWS` follows, folded with it.
6576fn permission_limit(
6577    caller: &crate::role::Caller<'_>,
6578    names: &crate::names::NameOverrides,
6579    schema: &str,
6580    table: &str,
6581) -> Option<i64> {
6582    crate::role::read_limit(caller, names, schema, table)
6583}
6584
6585/// Both predicates, as one.
6586///
6587/// Written as an `_and` rather than as two clauses so that everything
6588/// downstream -- parameter numbering, relationship resolution, the `EXISTS`
6589/// that a relationship predicate becomes -- happens once, in one place, for
6590/// both halves.
6591fn and_predicates(
6592    request: Option<serde_json::Value>,
6593    permission: Option<serde_json::Value>,
6594) -> Option<serde_json::Value> {
6595    match (request, permission) {
6596        (None, None) => None,
6597        (Some(only), None) | (None, Some(only)) => Some(only),
6598        (Some(request), Some(permission)) => {
6599            Some(serde_json::json!({ "_and": [request, permission] }))
6600        }
6601    }
6602}
6603
6604/// Build a WHERE clause from a boolean expression.
6605///
6606/// The expression is the JSON form of a `<table>_bool_exp`: column names
6607/// mapping to comparisons, and `_and`, `_or` and `_not` for structure. It
6608/// nests, so this recurses.
6609///
6610/// Nothing is dropped silently. An operator that is not recognised widens the
6611/// result set if it is ignored -- every row for a query, every row for a
6612/// mutation -- so it is an error instead.
6613fn build_where_clause(
6614    where_value: Option<&serde_json::Value>,
6615    start_param_idx: usize,
6616    scope: &WhereScope<'_>,
6617) -> Result<(String, Vec<serde_json::Value>), async_graphql::Error> {
6618    let mut values: Vec<serde_json::Value> = Vec::new();
6619    let mut param_idx = start_param_idx;
6620    let mut alias_counter = 0usize;
6621
6622    let condition = match where_value {
6623        Some(value) => build_condition(
6624            value,
6625            scope,
6626            &mut param_idx,
6627            &mut values,
6628            &mut alias_counter,
6629        )?,
6630        None => None,
6631    };
6632
6633    Ok(match condition {
6634        Some(sql) => (format!("WHERE {}", sql), values),
6635        None => (String::new(), values),
6636    })
6637}
6638
6639/// The table a boolean expression is being read against.
6640///
6641/// Column references are qualified with `sql_ref` so that a predicate over a
6642/// relationship -- which becomes a correlated `EXISTS` against another table --
6643/// can tell the two apart. Without the qualification a child column sharing a
6644/// parent column's name would silently resolve to whichever PostgreSQL
6645/// preferred.
6646///
6647/// `resolution` is absent where a caller has no schema cache to hand, which is
6648/// how the mutation paths are called. A relationship predicate then reports
6649/// that it cannot be resolved rather than being read as a column.
6650pub struct WhereScope<'a> {
6651    /// The table itself, for the comparisons that need a column's type.
6652    qualified: postrust_core::api_request::QualifiedIdentifier,
6653    /// How to refer to this table's columns in SQL.
6654    sql_ref: String,
6655    /// How to refer to this table's *row*, which is what a function taking the
6656    /// row is passed. A qualified name reads as a column reference there, so
6657    /// this is the bare alias.
6658    row_ref: String,
6659    /// The GraphQL type name, which is the key into the relationship map.
6660    type_name: String,
6661    /// How to refer to the columns of the table the predicate started at, and
6662    /// which table that is.
6663    ///
6664    /// A column comparison written `["$", "name"]` means that table's column,
6665    /// however many relationships the predicate has descended through since --
6666    /// which is what makes the form worth having. Equal to this table's own
6667    /// until an `EXISTS` is entered.
6668    root_ref: String,
6669    root_qualified: postrust_core::api_request::QualifiedIdentifier,
6670    /// The names this table's columns are exposed under, so a predicate
6671    /// written against a field can be written as SQL against a column.
6672    names: &'a crate::names::NameOverrides,
6673    resolution: Option<WhereResolution<'a>>,
6674    /// Who is asking, so that a predicate following a relationship narrows the
6675    /// far side to what that caller may read.
6676    ///
6677    /// Unrestricted unless a scope is told otherwise, which is what leaves
6678    /// every path that has no caller to hand -- the mutation ones -- behaving
6679    /// as it did.
6680    caller: Option<crate::role::Caller<'a>>,
6681}
6682
6683/// What a scope needs to follow a relationship.
6684struct WhereResolution<'a> {
6685    cache: &'a SchemaCache,
6686    relationships: &'a HashMap<String, Vec<RelationshipField>>,
6687}
6688
6689impl<'a> WhereScope<'a> {
6690    /// A scope over a table addressed by its qualified name.
6691    pub fn table(
6692        schema: &str,
6693        table: &str,
6694        type_name: &str,
6695        names: &'a crate::names::NameOverrides,
6696    ) -> Self {
6697        Self {
6698            qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6699            sql_ref: format!(
6700                "{}.{}",
6701                postrust_sql::escape_ident(schema),
6702                postrust_sql::escape_ident(table)
6703            ),
6704            row_ref: postrust_sql::escape_ident(table),
6705            type_name: type_name.to_string(),
6706            root_ref: format!(
6707                "{}.{}",
6708                postrust_sql::escape_ident(schema),
6709                postrust_sql::escape_ident(table)
6710            ),
6711            root_qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6712            names,
6713            resolution: None,
6714            caller: None,
6715        }
6716    }
6717
6718    /// The same, referred to by an alias rather than by its name.
6719    ///
6720    /// A statement that writes a table has to name that table's row in
6721    /// `RETURNING`, and a bare table name there is read as a *column* first --
6722    /// so `area.area`, a geography column in a table of the same name, made
6723    /// `to_jsonb("area")` the shape rather than the row. The alias is a name
6724    /// no column has.
6725    fn under_alias(mut self, alias: &str) -> Self {
6726        // The root moves with it: this is the outermost table being renamed,
6727        // not a step into another one.
6728        if self.root_ref == self.sql_ref {
6729            self.root_ref = postrust_sql::escape_ident(alias);
6730        }
6731        self.sql_ref = postrust_sql::escape_ident(alias);
6732        self.row_ref = postrust_sql::escape_ident(alias);
6733        self
6734    }
6735
6736    /// The same, able to follow relationships.
6737    fn with_resolution(
6738        mut self,
6739        cache: &'a SchemaCache,
6740        relationships: &'a HashMap<String, Vec<RelationshipField>>,
6741    ) -> Self {
6742        self.resolution = Some(WhereResolution {
6743            cache,
6744            relationships,
6745        });
6746        self
6747    }
6748
6749    /// A scope over an aliased table, able to follow relationships.
6750    #[allow(clippy::too_many_arguments)]
6751    fn for_alias(
6752        schema: &str,
6753        table: &str,
6754        alias: &str,
6755        type_name: &str,
6756        cache: &'a SchemaCache,
6757        relationships: &'a HashMap<String, Vec<RelationshipField>>,
6758        names: &'a crate::names::NameOverrides,
6759    ) -> Self {
6760        Self {
6761            qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6762            sql_ref: postrust_sql::escape_ident(alias),
6763            row_ref: postrust_sql::escape_ident(alias),
6764            type_name: type_name.to_string(),
6765            root_ref: postrust_sql::escape_ident(alias),
6766            root_qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6767            names,
6768            resolution: Some(WhereResolution {
6769                cache,
6770                relationships,
6771            }),
6772            caller: None,
6773        }
6774    }
6775
6776    /// A scope over an aliased table, for the inside of an `EXISTS`.
6777    /// A scope over the *other* table of a relationship, under an alias.
6778    ///
6779    /// The child's own qualified name, not the parent's: a comparison inside
6780    /// an `EXISTS` is against the child's columns, so it is the child's types
6781    /// and the child's renames that decide how to write it.
6782    fn aliased(
6783        schema: &str,
6784        table: &str,
6785        alias: &str,
6786        type_name: &str,
6787        from: &WhereScope<'a>,
6788    ) -> Self {
6789        Self {
6790            qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6791            sql_ref: postrust_sql::escape_ident(alias),
6792            row_ref: postrust_sql::escape_ident(alias),
6793            type_name: type_name.to_string(),
6794            // Carried, not replaced: `$` names the table the predicate began
6795            // at, which is the whole point of descending with it.
6796            root_ref: from.root_ref.clone(),
6797            root_qualified: from.root_qualified.clone(),
6798            names: from.names,
6799            resolution: from.resolution.as_ref().map(|r| WhereResolution {
6800                cache: r.cache,
6801                relationships: r.relationships,
6802            }),
6803            // Carried across the relationship: the caller does not change on
6804            // the way into an EXISTS, and the far side has its own permission
6805            // to be narrowed by.
6806            caller: from.caller,
6807        }
6808    }
6809
6810    /// Narrow what this scope's predicates may reach to one caller.
6811    pub fn for_caller(mut self, caller: crate::role::Caller<'a>) -> Self {
6812        self.caller = Some(caller);
6813        self
6814    }
6815
6816    /// The same scope with no caller: what a permission's own predicate is
6817    /// evaluated as. See `PERMISSION`.
6818    fn as_system(&self) -> WhereScope<'a> {
6819        WhereScope {
6820            qualified: self.qualified.clone(),
6821            sql_ref: self.sql_ref.clone(),
6822            row_ref: self.row_ref.clone(),
6823            type_name: self.type_name.clone(),
6824            // The root moves here. `$` in a permission names the table the
6825            // permission is *written on*, which is this one -- not whatever
6826            // table the query happened to start at. Reading `dml_rbp_tasks`
6827            // through a project's `where: {tasks: {...}}` compared the task's
6828            // grant against a column of `dml_rbp_projects` until this, and
6829            // answered with rows the role may not see.
6830            root_ref: self.sql_ref.clone(),
6831            root_qualified: self.qualified.clone(),
6832            names: self.names,
6833            resolution: self.resolution.as_ref().map(|r| WhereResolution {
6834                cache: r.cache,
6835                relationships: r.relationships,
6836            }),
6837            caller: None,
6838        }
6839    }
6840
6841    /// What a field name refers to, as SQL: a column of this table, or the
6842    /// call that produces a computed field.
6843    ///
6844    /// A computed field is in the boolean expression because it is on the type
6845    /// -- `where: {sum_float_offset: {_gt: 5}}` is a question a client can
6846    /// write -- and reading it as a column answered `column
6847    /// float_test.sum_float_offset does not exist`.
6848    fn column(&self, name: &str) -> String {
6849        let column = self.column_name(name);
6850        let plain = format!("{}.{}", self.sql_ref, postrust_sql::escape_ident(column));
6851        let Some(cache) = self.resolution.as_ref().map(|r| r.cache) else {
6852            return plain;
6853        };
6854        let Some(table) = cache.get_table(&self.qualified) else {
6855            return plain;
6856        };
6857        if table.get_column(column).is_some() {
6858            return plain;
6859        }
6860        let function = self
6861            .names
6862            .computed_source(&table.schema, &table.name, name)
6863            .unwrap_or(name);
6864        match table.get_computed_column(function) {
6865            Some(definition) => {
6866                computed_call(definition, &format!("{}.*", self.row_ref), &self.row_ref)
6867            }
6868            None => plain,
6869        }
6870    }
6871
6872    /// The column behind a field name.
6873    fn column_name<'n>(&'n self, name: &'n str) -> &'n str {
6874        self.names
6875            .column_source(&self.qualified.schema, &self.qualified.name, name)
6876            .unwrap_or(name)
6877    }
6878
6879    /// The PostgreSQL type of one of this table's columns, where it can be
6880    /// found. A spatial comparison needs it: the same function takes a
6881    /// geometry or a geography and the operand has to be cast to match.
6882    fn column_type(&self, name: &str) -> Option<String> {
6883        let cache = self.resolution.as_ref()?.cache;
6884        let table = cache.get_table(&self.qualified)?;
6885        table
6886            .get_column(self.column_name(name))
6887            .map(|c| c.nominal_type.clone())
6888    }
6889
6890    /// The other side of a column-to-column comparison, as SQL.
6891    ///
6892    /// Hasura writes the operand two ways. A bare name is a column of *this*
6893    /// table -- `{"bid_price": {"$cgt": "price"}}` compares two columns of one
6894    /// auction. `["$", "name"]` is a column of the table the permission is
6895    /// written on, which is what makes the form useful inside a predicate over
6896    /// a relationship: `{"item": {"item_quantity": {"_cgte": ["$",
6897    /// "order_cart_quantity"]}}}` asks whether the item has as many in stock
6898    /// as the cart is asking for, and the cart is the outer row.
6899    ///
6900    /// Nothing else is accepted. A longer path would walk relationships to
6901    /// reach the column, which Hasura allows and no case here writes -- and
6902    /// reading it wrongly would widen a permission rather than narrow it.
6903    fn other_column(
6904        &self,
6905        operand: &serde_json::Value,
6906        op: &str,
6907    ) -> Result<String, async_graphql::Error> {
6908        use serde_json::Value;
6909
6910        let refused = |what: &str| {
6911            async_graphql::Error::new(format!(
6912                "the \"{}\" comparison takes the name of a column, {}",
6913                op, what
6914            ))
6915        };
6916        let (against, qualified, name) = match operand {
6917            Value::String(name) => (&self.sql_ref, &self.qualified, name.as_str()),
6918            Value::Array(path) => match path.as_slice() {
6919                [Value::String(name)] => (&self.sql_ref, &self.qualified, name.as_str()),
6920                [Value::String(root), Value::String(name)] if root == "$" => {
6921                    (&self.root_ref, &self.root_qualified, name.as_str())
6922                }
6923                _ => return Err(refused("or [\"$\", \"a column\"]")),
6924            },
6925            _ => return Err(refused("written as a string")),
6926        };
6927        // Read against whichever table it belongs to, since a rename is
6928        // per-table and the two are not the same table.
6929        let column = self
6930            .names
6931            .column_source(&qualified.schema, &qualified.name, name)
6932            .unwrap_or(name);
6933        Ok(format!(
6934            "{}.{}",
6935            against,
6936            postrust_sql::escape_ident(column)
6937        ))
6938    }
6939
6940    /// The relationship a predicate is following, where there is one.
6941    ///
6942    /// Looked up in the schema's own map first, which is the answer for every
6943    /// relationship the role can read. A permission may name one it cannot:
6944    /// role `Artist` reads `Track` and filters it by `{"Artist": {"id": ...}}`
6945    /// while having no permission on `Artist` at all, so that relationship is
6946    /// in no schema this role is served. The catalogue still has it -- the
6947    /// cache a scope resolves against is the unreduced one -- and the
6948    /// relationship is derived from it there.
6949    ///
6950    /// Deriving it cannot let a client reach a hidden table: a key that is not
6951    /// a field of the boolean expression is refused before any of this runs,
6952    /// and the only writer of such a key is a permission.
6953    fn relationship(&self, name: &str) -> Option<std::borrow::Cow<'a, RelationshipField>> {
6954        let resolution = self.resolution.as_ref()?;
6955        let published = resolution
6956            .relationships
6957            .get(&self.type_name)
6958            .and_then(|fields| fields.iter().find(|r| r.name == name));
6959        if let Some(found) = published {
6960            return Some(std::borrow::Cow::Borrowed(found));
6961        }
6962
6963        let table = resolution.cache.get_table(&self.qualified)?;
6964
6965        // A relationship metadata declares, which may be a mapped join the
6966        // catalogue has never heard of. `message.members` is one, and a
6967        // permission on `message` is written through it -- so this is not a
6968        // convenience: without it that filter cannot be compiled at all and
6969        // the read is refused rather than narrowed.
6970        if let Some(declared) = self
6971            .names
6972            .declared_relationships(&table.schema, &table.name)
6973        {
6974            if let Some(entry) = declared.iter().find(|entry| entry.name == name) {
6975                // Reached by a mapping, which the catalogue has never heard
6976                // of.
6977                let target = entry
6978                    .target(&table.schema)
6979                    .map(|(_, target)| target)
6980                    .unwrap_or_default();
6981                if let Some(field) = crate::schema::mapped_relationship_field(
6982                    entry,
6983                    table,
6984                    resolution.cache,
6985                    &table.schema,
6986                    &target,
6987                    &target,
6988                    &target,
6989                ) {
6990                    return Some(std::borrow::Cow::Owned(field));
6991                }
6992                // Or by a key, under the name the declaration gives it --
6993                // which is the only place that name is written down now that
6994                // a declaration carries it.
6995                if let Some(key) = entry.using.as_deref() {
6996                    if let Some(found) = resolution
6997                        .cache
6998                        .get_relationships(&self.qualified, &table.schema)
6999                        .into_iter()
7000                        .flatten()
7001                        .find(|rel| {
7002                            crate::schema::relationship_keys(rel)
7003                                .iter()
7004                                .any(|found| found == key)
7005                        })
7006                    {
7007                        return Some(std::borrow::Cow::Owned(
7008                            crate::schema::relationship::RelationshipField::from_relationship_named(
7009                                found,
7010                                &found.foreign_table().name,
7011                                Some(&entry.name),
7012                            ),
7013                        ));
7014                    }
7015                }
7016            }
7017        }
7018
7019        resolution
7020            .cache
7021            .get_relationships(&self.qualified, &table.schema)?
7022            .iter()
7023            .find_map(|rel| {
7024                let given = crate::schema::relationship_keys(rel)
7025                    .iter()
7026                    .find_map(|key| self.names.relationship(&table.schema, &table.name, key));
7027                // The target's own name stands in for its GraphQL type, which
7028                // this role has none of. Nothing reads it but the lookup
7029                // above, and that lookup will land here again.
7030                let field = RelationshipField::from_relationship_named(
7031                    rel,
7032                    &rel.foreign_table().name,
7033                    given,
7034                );
7035                (field.name == name).then_some(std::borrow::Cow::Owned(field))
7036            })
7037    }
7038}
7039
7040/// The SQL operator behind a column-to-column comparison, where this is one.
7041///
7042/// `_ceq`, `_cne`, `_cgt`, `_cgte`, `_clt`, `_clte`: the `c` is for column.
7043/// Only a permission writes these -- no boolean expression a client can write
7044/// has them, because a client has no way to name the row a comparison would be
7045/// against. A permission does: `{"bid_price": {"$cgt": "price"}}` on `auction`
7046/// grants the rows whose bid has passed the reserve, which is a fact about the
7047/// row rather than about the caller.
7048fn column_comparison(op: &str) -> Option<&'static str> {
7049    Some(match op {
7050        "_ceq" => "=",
7051        "_cne" => "<>",
7052        "_cgt" => ">",
7053        "_cgte" => ">=",
7054        "_clt" => "<",
7055        "_clte" => "<=",
7056        _ => return None,
7057    })
7058}
7059
7060/// One boolean expression, as SQL. `None` where it constrains nothing.
7061fn build_condition(
7062    value: &serde_json::Value,
7063    scope: &WhereScope<'_>,
7064    param_idx: &mut usize,
7065    values: &mut Vec<serde_json::Value>,
7066    alias_counter: &mut usize,
7067) -> Result<Option<String>, async_graphql::Error> {
7068    let serde_json::Value::Object(map) = value else {
7069        return Ok(None);
7070    };
7071
7072    let mut conditions: Vec<String> = Vec::new();
7073
7074    for (key, val) in map {
7075        match key.as_str() {
7076            // An empty `_and` is true and an empty `_or` is false, which is
7077            // what SQL's own identities give: nothing to AND constrains
7078            // nothing, nothing to OR matches nothing.
7079            "_and" | "_or" => {
7080                let members = val.as_array().ok_or_else(|| {
7081                    async_graphql::Error::new(format!("\"{}\" takes a list of expressions", key))
7082                })?;
7083                let mut parts = Vec::new();
7084                for member in members {
7085                    if let Some(sql) =
7086                        build_condition(member, scope, param_idx, values, alias_counter)?
7087                    {
7088                        parts.push(sql);
7089                    }
7090                }
7091                if parts.is_empty() {
7092                    if key == "_or" {
7093                        conditions.push("false".to_string());
7094                    }
7095                    continue;
7096                }
7097                let joiner = if key == "_and" { " AND " } else { " OR " };
7098                conditions.push(format!("({})", parts.join(joiner)));
7099            }
7100            "_not" => {
7101                if let Some(sql) = build_condition(val, scope, param_idx, values, alias_counter)? {
7102                    conditions.push(format!("NOT ({})", sql));
7103                }
7104            }
7105            // A permission's own predicate, which is the server's rather
7106            // than the caller's. See `PERMISSION`.
7107            PERMISSION => {
7108                if let Some(sql) =
7109                    build_condition(val, &scope.as_system(), param_idx, values, alias_counter)?
7110                {
7111                    conditions.push(sql);
7112                }
7113            }
7114            // A question about a table nothing relates this one to. Only a
7115            // permission writes it; no client can, because no boolean
7116            // expression has the field.
7117            "_exists" => {
7118                conditions.push(table_exists_sql(
7119                    val,
7120                    scope,
7121                    param_idx,
7122                    values,
7123                    alias_counter,
7124                )?);
7125            }
7126            // A relationship is filtered by filtering the rows at its other
7127            // end. `where: {articles: {title: {_eq: "x"}}}` keeps the authors
7128            // that have such an article -- an `EXISTS` correlated back to the
7129            // parent row, which is also what it means for a to-one
7130            // relationship, where the subquery simply cannot match twice.
7131            name if scope.relationship(name).is_some() => {
7132                let relationship = scope.relationship(name).expect("just checked");
7133                conditions.push(exists_sql(
7134                    &relationship,
7135                    val,
7136                    scope,
7137                    param_idx,
7138                    values,
7139                    alias_counter,
7140                )?);
7141            }
7142            // A question about the whole related set rather than about any
7143            // one row of it. `where: {articles_aggregate: {count: {predicate:
7144            // {_gt: 2}}}}` keeps the authors with more than two articles,
7145            // which no `EXISTS` over one article can say.
7146            name if scope.column_type(name).is_none()
7147                && name
7148                    .strip_suffix("_aggregate")
7149                    .and_then(|rel| scope.relationship(rel))
7150                    .is_some_and(|rel| rel.is_list) =>
7151            {
7152                let relationship = name
7153                    .strip_suffix("_aggregate")
7154                    .and_then(|rel| scope.relationship(rel))
7155                    .expect("just checked");
7156                conditions.push(aggregate_predicate_sql(
7157                    &relationship,
7158                    val,
7159                    scope,
7160                    param_idx,
7161                    values,
7162                    alias_counter,
7163                )?);
7164            }
7165            column => {
7166                let quoted = scope.column(column);
7167                match val {
7168                    serde_json::Value::Object(ops) => {
7169                        let column_type = scope.column_type(column);
7170                        for (op, operand) in ops {
7171                            // A comparison against another column rather than
7172                            // against a value, which only a permission can
7173                            // write. It needs the scope to say *which* column,
7174                            // so it is answered here rather than in
7175                            // `comparison_sql`, which sees one side.
7176                            if let Some(other) = column_comparison(op) {
7177                                conditions.push(format!(
7178                                    "{} {} {}",
7179                                    quoted,
7180                                    other,
7181                                    scope.other_column(operand, op)?
7182                                ));
7183                                continue;
7184                            }
7185                            conditions.push(comparison_sql(
7186                                &quoted,
7187                                column,
7188                                column_type.as_deref(),
7189                                op,
7190                                operand,
7191                                param_idx,
7192                                values,
7193                            )?);
7194                        }
7195                    }
7196                    // `{id: 1}` rather than `{id: {_eq: 1}}`. Not a spelling
7197                    // Hasura accepts, but one that costs nothing to read and
7198                    // that hand-written queries reach for.
7199                    other => {
7200                        conditions.push(format!("{} = ${}", quoted, param_idx));
7201                        values.push(other.clone());
7202                        *param_idx += 1;
7203                    }
7204                }
7205            }
7206        }
7207    }
7208
7209    Ok(if conditions.is_empty() {
7210        None
7211    } else if conditions.len() == 1 {
7212        conditions.pop()
7213    } else {
7214        Some(conditions.join(" AND "))
7215    })
7216}
7217
7218/// A predicate over a relationship, as a correlated `EXISTS`.
7219///
7220/// Only a plain key join is expressible this way. A many-to-many through a
7221/// junction and a computed relationship both need more than a pair of columns
7222/// to correlate on, and saying so is the only honest answer -- reading the
7223/// predicate as though it constrained nothing would return every parent row.
7224fn exists_sql(
7225    relationship: &RelationshipField,
7226    child_expression: &serde_json::Value,
7227    scope: &WhereScope<'_>,
7228    param_idx: &mut usize,
7229    values: &mut Vec<serde_json::Value>,
7230    alias_counter: &mut usize,
7231) -> Result<String, async_graphql::Error> {
7232    let cache = scope.resolution.as_ref().map(|r| r.cache).ok_or_else(|| {
7233        async_graphql::Error::new(format!(
7234            "filtering on the relationship \"{}\" is not available here",
7235            relationship.name
7236        ))
7237    })?;
7238
7239    let plan = postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, cache)
7240        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
7241
7242    if plan.junction.is_some() || (plan.function.is_none() && plan.columns.is_empty()) {
7243        return Err(async_graphql::Error::new(format!(
7244            "filtering on \"{}\" is not supported: it is reached through a junction \
7245             rather than by a key",
7246            relationship.name
7247        )));
7248    }
7249
7250    *alias_counter += 1;
7251    let alias = format!("pgrst_rel_{}", alias_counter);
7252    let child_scope = WhereScope::aliased(
7253        &plan.foreign_schema,
7254        &plan.foreign_table,
7255        &alias,
7256        &relationship.target_type,
7257        scope,
7258    );
7259
7260    // A computed relationship is correlated by argument -- the function takes
7261    // the parent row -- where a key relationship is correlated by columns.
7262    let (source, mut correlation) = match &plan.function {
7263        Some(function) => (
7264            format!(
7265                "{}.{}({})",
7266                postrust_sql::escape_ident(&function.schema),
7267                postrust_sql::escape_ident(&function.name),
7268                scope.row_ref
7269            ),
7270            Vec::new(),
7271        ),
7272        None => {
7273            let mut columns = Vec::with_capacity(plan.columns.len());
7274            for (parent_column, child_column) in &plan.columns {
7275                columns.push(format!(
7276                    "{} = {}",
7277                    scope.column(parent_column),
7278                    child_scope.column(child_column)
7279                ));
7280            }
7281            (
7282                format!(
7283                    "{}.{}",
7284                    postrust_sql::escape_ident(&plan.foreign_schema),
7285                    postrust_sql::escape_ident(&plan.foreign_table)
7286                ),
7287                columns,
7288            )
7289        }
7290    };
7291
7292    let child_condition = build_condition(
7293        child_expression,
7294        &child_scope,
7295        param_idx,
7296        values,
7297        alias_counter,
7298    )?;
7299    if let Some(sql) = child_condition {
7300        correlation.push(format!("({})", sql));
7301    }
7302
7303    // The far side's own permission. `where: {author: {name: {_eq: "Ann"}}}`
7304    // asks whether a related row exists, and a row this caller may not read is
7305    // one it may not learn the existence of either -- so the child's filter
7306    // narrows the EXISTS exactly as it narrows a read of the same table.
7307    if let Some(caller) = &child_scope.caller {
7308        // Through `permission_predicate` rather than `role::read_predicate`,
7309        // so the far side's filter is marked as the server's own -- see
7310        // `PERMISSION`. Without the mark it was compiled as the caller, and a
7311        // filter that follows a relationship of its own then needed a
7312        // permission on *that* table: `dml_rbp_tasks` is filtered through
7313        // `grants`, which the role reading tasks may not read.
7314        let permission = permission_predicate(
7315            caller,
7316            child_scope.names,
7317            &plan.foreign_schema,
7318            &plan.foreign_table,
7319        )?;
7320        if let Some(predicate) = permission {
7321            if let Some(sql) =
7322                build_condition(&predicate, &child_scope, param_idx, values, alias_counter)?
7323            {
7324                correlation.push(format!("({})", sql));
7325            }
7326        }
7327    }
7328    if correlation.is_empty() {
7329        correlation.push("true".to_string());
7330    }
7331
7332    Ok(format!(
7333        "EXISTS (SELECT 1 FROM {} AS {} WHERE {})",
7334        source,
7335        postrust_sql::escape_ident(&alias),
7336        correlation.join(" AND ")
7337    ))
7338}
7339
7340/// `_exists`, the predicate only a permission can write, as SQL.
7341///
7342/// ```json
7343/// {"_exists": {"_table": "user", "_where": {"id": "X-Hasura-User-Id",
7344///                                           "is_admin": true}}}
7345/// ```
7346///
7347/// It asks whether a row exists in *another* table -- one no foreign key
7348/// relates to this one. That is how Hasura writes "the caller is an
7349/// administrator" without asking the caller to say so: the row that decides it
7350/// lives in a table of its own, and whether the account this predicate guards
7351/// is readable does not depend on which account it is.
7352///
7353/// So the subselect is **uncorrelated**, which is the whole difference from
7354/// the `EXISTS` a relationship predicate builds. There are no key columns to
7355/// join on -- if there were, the permission would have been written as a
7356/// relationship -- and the `_where` is read against the named table's columns
7357/// alone.
7358///
7359/// The caller's own permissions are not applied inside it, and that is not an
7360/// oversight. The point of `_exists` is to consult a table the role has no
7361/// access to: in Hasura's corpus the role that reads `account` through this
7362/// predicate may not read `public.user` at all. Narrowing the subselect to
7363/// what the caller may read would make the predicate refuse itself.
7364fn table_exists_sql(
7365    spec: &serde_json::Value,
7366    scope: &WhereScope<'_>,
7367    param_idx: &mut usize,
7368    values: &mut Vec<serde_json::Value>,
7369    alias_counter: &mut usize,
7370) -> Result<String, async_graphql::Error> {
7371    let Some((schema, table)) = crate::role::exists_target(spec, &scope.qualified.schema) else {
7372        return Err(async_graphql::Error::new(
7373            "\"_exists\" needs a \"_table\" to look in",
7374        ));
7375    };
7376
7377    // The name comes from a permission document rather than from a request,
7378    // but it still reaches SQL, and a table that is not there would reach it as
7379    // a syntax error at the far end rather than as an answer here.
7380    let qualified = postrust_core::api_request::QualifiedIdentifier::new(&schema, &table);
7381    if scope
7382        .resolution
7383        .as_ref()
7384        .is_some_and(|r| r.cache.get_table(&qualified).is_none())
7385    {
7386        return Err(async_graphql::Error::new(format!(
7387            "\"_exists\" names a table this server does not have: \"{}.{}\"",
7388            schema, table
7389        )));
7390    }
7391
7392    *alias_counter += 1;
7393    let alias = format!("pgrst_exists_{}", alias_counter);
7394    // The type this table is exposed as, which is the key into the
7395    // relationship map -- so a `_where` may follow the named table's own
7396    // relationships, the way any other predicate over it could.
7397    let type_name = scope
7398        .names
7399        .base_name(&schema, &table)
7400        .unwrap_or(&table)
7401        .to_string();
7402    let mut inner = WhereScope::aliased(&schema, &table, &alias, &type_name, scope);
7403    // See above: the predicate is the permission, so it is not itself
7404    // subject to one.
7405    inner.caller = None;
7406
7407    let condition = match spec.get("_where") {
7408        Some(predicate) => build_condition(predicate, &inner, param_idx, values, alias_counter)?,
7409        None => None,
7410    };
7411
7412    Ok(format!(
7413        "EXISTS (SELECT 1 FROM {}.{} AS {} WHERE {})",
7414        postrust_sql::escape_ident(&schema),
7415        postrust_sql::escape_ident(&table),
7416        postrust_sql::escape_ident(&alias),
7417        condition.unwrap_or_else(|| "true".to_string())
7418    ))
7419}
7420
7421/// A predicate over an aggregate of a related set, as SQL.
7422///
7423/// `{count: {predicate: {_gt: 2}, filter: {...}}}` becomes a scalar subselect
7424/// correlated back to the parent row, compared the way any column is:
7425///
7426/// ```text
7427/// (SELECT count(*) FROM "public"."article" AS pgrst_rel_1
7428///   WHERE "author"."id" = pgrst_rel_1."author_id" AND (...)) > $1
7429/// ```
7430///
7431/// A scalar subselect rather than an `EXISTS`, because the answer is a number
7432/// or a truth value and not whether a row is there -- and because over no rows
7433/// at all `count` is zero and `bool_and` is null, which is what SQL says and
7434/// what a client asking "no articles" is relying on.
7435fn aggregate_predicate_sql(
7436    relationship: &RelationshipField,
7437    expression: &serde_json::Value,
7438    scope: &WhereScope<'_>,
7439    param_idx: &mut usize,
7440    values: &mut Vec<serde_json::Value>,
7441    alias_counter: &mut usize,
7442) -> Result<String, async_graphql::Error> {
7443    let serde_json::Value::Object(over) = expression else {
7444        return Ok("true".to_string());
7445    };
7446
7447    let cache = scope.resolution.as_ref().map(|r| r.cache).ok_or_else(|| {
7448        async_graphql::Error::new(format!(
7449            "filtering on the relationship \"{}\" is not available here",
7450            relationship.name
7451        ))
7452    })?;
7453    let plan = postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, cache)
7454        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
7455    if plan.junction.is_some() || (plan.function.is_none() && plan.columns.is_empty()) {
7456        return Err(async_graphql::Error::new(format!(
7457            "aggregating over \"{}\" is not supported: it is reached through a junction \
7458             rather than by a key",
7459            relationship.name
7460        )));
7461    }
7462
7463    let mut conditions: Vec<String> = Vec::new();
7464    for (function, spec) in over {
7465        if spec.is_null() {
7466            continue;
7467        }
7468        let serde_json::Value::Object(spec) = spec else {
7469            continue;
7470        };
7471        let Some(predicate) = spec.get("predicate").filter(|p| !p.is_null()) else {
7472            return Err(validation_error(format!(
7473                "\"{}\" over \"{}\" needs a predicate",
7474                function, relationship.name
7475            )));
7476        };
7477
7478        *alias_counter += 1;
7479        let alias = format!("pgrst_agg_{}", alias_counter);
7480        let child_scope = WhereScope::aliased(
7481            &plan.foreign_schema,
7482            &plan.foreign_table,
7483            &alias,
7484            &relationship.target_type,
7485            scope,
7486        );
7487
7488        // Correlated the way an `EXISTS` over the same relationship is: by
7489        // the key, or by handing the parent row to the function.
7490        let (source, mut correlation) = match &plan.function {
7491            Some(routine) => (
7492                format!(
7493                    "{}.{}({})",
7494                    postrust_sql::escape_ident(&routine.schema),
7495                    postrust_sql::escape_ident(&routine.name),
7496                    scope.row_ref
7497                ),
7498                Vec::new(),
7499            ),
7500            None => {
7501                let mut columns = Vec::with_capacity(plan.columns.len());
7502                for (parent_column, child_column) in &plan.columns {
7503                    columns.push(format!(
7504                        "{} = {}",
7505                        scope.column(parent_column),
7506                        child_scope.column(child_column)
7507                    ));
7508                }
7509                (
7510                    format!(
7511                        "{}.{}",
7512                        postrust_sql::escape_ident(&plan.foreign_schema),
7513                        postrust_sql::escape_ident(&plan.foreign_table)
7514                    ),
7515                    columns,
7516                )
7517            }
7518        };
7519        // `filter` narrows what is aggregated, and is an ordinary boolean
7520        // expression over the child.
7521        if let Some(filter) = spec.get("filter").filter(|f| !f.is_null()) {
7522            if let Some(sql) =
7523                build_condition(filter, &child_scope, param_idx, values, alias_counter)?
7524            {
7525                correlation.push(format!("({})", sql));
7526            }
7527        }
7528        if correlation.is_empty() {
7529            correlation.push("true".to_string());
7530        }
7531
7532        let arguments = spec.get("arguments").filter(|a| !a.is_null());
7533        let distinct = matches!(spec.get("distinct"), Some(serde_json::Value::Bool(true)));
7534        let (aggregate, operand_type) = match function.as_str() {
7535            "count" => {
7536                let columns: Vec<String> = match arguments {
7537                    Some(serde_json::Value::Array(items)) => items
7538                        .iter()
7539                        .filter_map(|item| item.as_str())
7540                        .map(|column| child_scope.column(column))
7541                        .collect(),
7542                    Some(serde_json::Value::String(one)) => vec![child_scope.column(one)],
7543                    _ => Vec::new(),
7544                };
7545                let counted = match columns.len() {
7546                    0 => "*".to_string(),
7547                    1 => columns.into_iter().next().unwrap_or_default(),
7548                    _ => format!("({})", columns.join(", ")),
7549                };
7550                let counted = match distinct && counted != "*" {
7551                    true => format!("DISTINCT {}", counted),
7552                    false => counted,
7553                };
7554                (format!("count({})", counted), "integer")
7555            }
7556            "bool_and" | "bool_or" => {
7557                let Some(column) = arguments.and_then(|a| a.as_str()) else {
7558                    return Err(validation_error(format!(
7559                        "\"{}\" over \"{}\" needs the column to fold",
7560                        function, relationship.name
7561                    )));
7562                };
7563                (
7564                    format!("{}({})", function, child_scope.column(column)),
7565                    "boolean",
7566                )
7567            }
7568            other => {
7569                return Err(validation_error(format!(
7570                    "\"{}\" is not an aggregate a predicate can be written over",
7571                    other
7572                )))
7573            }
7574        };
7575
7576        let subselect = format!(
7577            "(SELECT {} FROM {} AS {} WHERE {})",
7578            aggregate,
7579            source,
7580            postrust_sql::escape_ident(&alias),
7581            correlation.join(" AND ")
7582        );
7583        let serde_json::Value::Object(operators) = predicate else {
7584            return Err(validation_error(format!(
7585                "the predicate on \"{}\" is not a comparison",
7586                function
7587            )));
7588        };
7589        for (operator, operand) in operators {
7590            conditions.push(comparison_sql(
7591                &subselect,
7592                function,
7593                Some(operand_type),
7594                operator,
7595                operand,
7596                param_idx,
7597                values,
7598            )?);
7599        }
7600    }
7601
7602    Ok(match conditions.is_empty() {
7603        true => "true".to_string(),
7604        false => format!("({})", conditions.join(" AND ")),
7605    })
7606}
7607
7608/// One spatial comparison, as a PostGIS call.
7609///
7610/// The operand arrives as GeoJSON, which is what Hasura accepts and what a
7611/// client sends, so it is parsed by `ST_GeomFromGeoJSON` rather than bound as
7612/// a shape. The cast that follows is the column's own type: the same function
7613/// takes a geometry or a geography and picking the wrong one is not an
7614/// overload PostGIS has.
7615#[allow(clippy::too_many_arguments)]
7616fn postgis_sql(
7617    quoted: &str,
7618    column_type: Option<&str>,
7619    function: &str,
7620    op: &str,
7621    operand: &serde_json::Value,
7622    param_idx: &mut usize,
7623    values: &mut Vec<serde_json::Value>,
7624) -> Result<String, async_graphql::Error> {
7625    let is_geography = column_type == Some("geography");
7626    let mut shape = |value: &serde_json::Value, param_idx: &mut usize| -> String {
7627        let placeholder = format!("${}", param_idx);
7628        *param_idx += 1;
7629        values.push(value.clone());
7630        match is_geography {
7631            true => format!("ST_GeomFromGeoJSON({})::geography", placeholder),
7632            false => format!("ST_GeomFromGeoJSON({})", placeholder),
7633        }
7634    };
7635
7636    match op {
7637        // `{distance, from}`: the shape and how far from it.
7638        "_st_d_within" | "_st_3d_d_within" => {
7639            let serde_json::Value::Object(spec) = operand else {
7640                return Err(async_graphql::Error::new(format!(
7641                    "\"{}\" takes {{distance, from}}",
7642                    op
7643                )));
7644            };
7645            let Some(from) = spec.get("from") else {
7646                return Err(async_graphql::Error::new(format!(
7647                    "\"{}\" needs a shape to measure from",
7648                    op
7649                )));
7650            };
7651            let Some(distance) = spec.get("distance") else {
7652                return Err(async_graphql::Error::new(format!(
7653                    "\"{}\" needs a distance",
7654                    op
7655                )));
7656            };
7657            let from_sql = shape(from, param_idx);
7658            let distance_sql = format!("${}", param_idx);
7659            *param_idx += 1;
7660            values.push(distance.clone());
7661            // On a sphere the answer depends on which sphere: `ST_DWithin`
7662            // over geography measures on the spheroid by default and on a
7663            // perfect sphere when told not to, and the two disagree by enough
7664            // to change which rows come back. Geometry has no such argument.
7665            let spheroid = match (is_geography, spec.get("use_spheroid")) {
7666                (true, Some(use_spheroid)) if !use_spheroid.is_null() => {
7667                    let placeholder = format!("${}", param_idx);
7668                    *param_idx += 1;
7669                    values.push(use_spheroid.clone());
7670                    format!(", {}::boolean", placeholder)
7671                }
7672                _ => String::new(),
7673            };
7674            Ok(format!(
7675                "{}({}, {}, {}::float8{})",
7676                function, quoted, from_sql, distance_sql, spheroid
7677            ))
7678        }
7679        // A raster against another raster, bound as one rather than parsed.
7680        "_st_intersects_rast" => {
7681            let placeholder = format!("${}", param_idx);
7682            *param_idx += 1;
7683            values.push(operand.clone());
7684            Ok(format!("{}({}, {}::raster)", function, quoted, placeholder))
7685        }
7686        // A raster against a shape, in one band or in any.
7687        "_st_intersects_geom_nband" | "_st_intersects_nband_geom" => {
7688            let serde_json::Value::Object(spec) = operand else {
7689                return Err(async_graphql::Error::new(format!(
7690                    "\"{}\" takes an object",
7691                    op
7692                )));
7693            };
7694            let Some(geometry) = spec.get("geommin") else {
7695                return Err(async_graphql::Error::new(format!(
7696                    "\"{}\" needs a shape",
7697                    op
7698                )));
7699            };
7700            let band = spec.get("nband").filter(|v| !v.is_null());
7701            let geometry_sql = shape(geometry, param_idx);
7702            Ok(match band {
7703                None => format!("{}({}, {})", function, quoted, geometry_sql),
7704                Some(band) => {
7705                    let placeholder = format!("${}", param_idx);
7706                    *param_idx += 1;
7707                    values.push(band.clone());
7708                    // `ST_Intersects(raster, nband, geometry)` is the spelling
7709                    // with a band; the argument order is PostGIS's, not the
7710                    // input's.
7711                    format!(
7712                        "{}({}, {}::int, {})",
7713                        function, quoted, placeholder, geometry_sql
7714                    )
7715                }
7716            })
7717        }
7718        // Everything else is the relation between this shape and one other.
7719        _ => {
7720            let other = shape(operand, param_idx);
7721            Ok(format!("{}({}, {})", function, quoted, other))
7722        }
7723    }
7724}
7725
7726/// A list of values as an array PostgreSQL will read.
7727///
7728/// Bound one element at a time rather than as one parameter. A JSON array
7729/// arrives as the text `["a","b"]`, which is not an array literal -- PostgreSQL
7730/// answers `malformed array literal` and means it.
7731fn sql_array(
7732    items: &[serde_json::Value],
7733    cast: &str,
7734    param_idx: &mut usize,
7735    values: &mut Vec<serde_json::Value>,
7736) -> String {
7737    if items.is_empty() {
7738        return format!("ARRAY[]::{}", cast);
7739    }
7740    let placeholders: Vec<String> = items
7741        .iter()
7742        .map(|item| {
7743            let placeholder = format!("${}", param_idx);
7744            *param_idx += 1;
7745            values.push(item.clone());
7746            placeholder
7747        })
7748        .collect();
7749    format!("ARRAY[{}]::{}", placeholders.join(", "), cast)
7750}
7751
7752/// One comparison against one column.
7753#[allow(clippy::too_many_arguments)]
7754fn comparison_sql(
7755    quoted: &str,
7756    column: &str,
7757    column_type: Option<&str>,
7758    op: &str,
7759    operand: &serde_json::Value,
7760    param_idx: &mut usize,
7761    values: &mut Vec<serde_json::Value>,
7762) -> Result<String, async_graphql::Error> {
7763    // `_cast` is not a comparison but a change of what is being compared: the
7764    // column becomes another type and the comparisons inside it apply to that.
7765    // A geometry and a geography answer different questions about the same
7766    // shape -- one on a plane, one on a sphere -- and this is how a client asks
7767    // for the other without the schema carrying two columns.
7768    if op == "_cast" {
7769        let serde_json::Value::Object(casts) = operand else {
7770            return Err(async_graphql::Error::new(
7771                "_cast takes an object naming the type to compare as",
7772            ));
7773        };
7774        let mut conditions = Vec::new();
7775        for (target, comparisons) in casts {
7776            // The GraphQL name of what is being compared as, and the
7777            // PostgreSQL type behind it. `String` is the one that differs:
7778            // a document compared as text is compared as `text`.
7779            let pg_type = match target.as_str() {
7780                "geometry" | "geography" => target.as_str(),
7781                "String" => "text",
7782                _ => {
7783                    return Err(async_graphql::Error::new(format!(
7784                        "cannot compare \"{}\" as \"{}\"",
7785                        column, target
7786                    )))
7787                }
7788            };
7789            let serde_json::Value::Object(ops) = comparisons else {
7790                continue;
7791            };
7792            let cast = format!("{}::{}", quoted, pg_type);
7793            for (nested_op, nested_operand) in ops {
7794                conditions.push(comparison_sql(
7795                    &cast,
7796                    column,
7797                    Some(pg_type),
7798                    nested_op,
7799                    nested_operand,
7800                    param_idx,
7801                    values,
7802                )?);
7803            }
7804        }
7805        return Ok(match conditions.len() {
7806            0 => "true".to_string(),
7807            1 => conditions.pop().expect("just counted"),
7808            _ => format!("({})", conditions.join(" AND ")),
7809        });
7810    }
7811
7812    // A spatial relation is a function of two shapes rather than an operator
7813    // between them, so it is written before the operator table is consulted.
7814    if let Some(function) = crate::input::bool_exp::postgis_function(op) {
7815        return postgis_sql(
7816            quoted,
7817            column_type,
7818            function,
7819            op,
7820            operand,
7821            param_idx,
7822            values,
7823        );
7824    }
7825
7826    // A tree comparison is an operator, but one whose operand has to be cast:
7827    // `?` is "any of these labels" for an ltree and "has this key" for a
7828    // jsonb, and PostgreSQL tells them apart by the operand's type alone.
7829    if let Some((operator, cast)) = crate::input::bool_exp::ltree_operator(op) {
7830        if cast.ends_with("[]") {
7831            let items = operand.as_array().ok_or_else(|| {
7832                async_graphql::Error::new(format!(
7833                    "the \"{}\" comparison on \"{}\" takes a list",
7834                    op, column
7835                ))
7836            })?;
7837            return Ok(format!(
7838                "{} {} {}",
7839                quoted,
7840                operator,
7841                sql_array(items, cast, param_idx, values)
7842            ));
7843        }
7844        let placeholder = format!("${}", param_idx);
7845        *param_idx += 1;
7846        values.push(operand.clone());
7847        return Ok(format!("{} {} {}::{}", quoted, operator, placeholder, cast));
7848    }
7849
7850    // The path language is a query over the document rather than a comparison
7851    // against one, so it is a function of the column and the path: `_exists`
7852    // asks whether the path selects anything, `_match` whether the predicate
7853    // it ends in holds.
7854    if let Some(function) = match op {
7855        "_jsonb_path_exists" => Some("jsonb_path_exists"),
7856        "_jsonb_path_match" => Some("jsonb_path_match"),
7857        _ => None,
7858    } {
7859        let placeholder = format!("${}", param_idx);
7860        *param_idx += 1;
7861        values.push(operand.clone());
7862        return Ok(format!(
7863            "{}({}, {}::jsonpath)",
7864            function, quoted, placeholder
7865        ));
7866    }
7867
7868    // Comparisons binding exactly one parameter, by the SQL they become.
7869    let binary = match op {
7870        "_eq" => Some("="),
7871        "_neq" => Some("<>"),
7872        "_gt" => Some(">"),
7873        "_gte" => Some(">="),
7874        "_lt" => Some("<"),
7875        "_lte" => Some("<="),
7876        "_like" => Some("LIKE"),
7877        "_nlike" => Some("NOT LIKE"),
7878        "_ilike" => Some("ILIKE"),
7879        "_nilike" => Some("NOT ILIKE"),
7880        "_similar" => Some("SIMILAR TO"),
7881        "_nsimilar" => Some("NOT SIMILAR TO"),
7882        "_regex" => Some("~"),
7883        "_nregex" => Some("!~"),
7884        "_iregex" => Some("~*"),
7885        "_niregex" => Some("!~*"),
7886        "_contains" => Some("@>"),
7887        "_contained_in" => Some("<@"),
7888        "_has_key" => Some("?"),
7889        _ => None,
7890    };
7891
7892    if let Some(sql_op) = binary {
7893        let placeholder = format!("${}", param_idx);
7894        *param_idx += 1;
7895        // A containment operand is a whole document, and `"latest"` is one --
7896        // a JSON string, which is not the same text as `latest`. Binding the
7897        // bare string answered `invalid input syntax for type json`, so what
7898        // goes over the wire is the value as it is written in JSON.
7899        values.push(match op {
7900            "_contains" | "_contained_in" => match operand {
7901                serde_json::Value::String(_)
7902                | serde_json::Value::Number(_)
7903                | serde_json::Value::Bool(_) => serde_json::Value::String(operand.to_string()),
7904                other => other.clone(),
7905            },
7906            _ => operand.clone(),
7907        });
7908        // A bound parameter arrives as text and PostgreSQL infers a type for
7909        // it from the operator, which works only while the inference is
7910        // unambiguous. `jsonb @> text` is not an operator at all; and `id =
7911        // $1` against an integer column answers `operator does not exist:
7912        // integer = text` the moment the value is one PostgreSQL cannot read
7913        // as a number -- a null, most obviously, which is how a client asks a
7914        // question it expects an empty answer to.
7915        //
7916        // So the operand says what it is. The containment and key operators
7917        // name the type the operator needs; everything else names the
7918        // column's, which is the type it is being compared against.
7919        let cast = match op {
7920            "_contains" | "_contained_in" => "::jsonb".to_string(),
7921            "_has_key" => "::text".to_string(),
7922            // Only where inference would otherwise pick text and be wrong. A
7923            // cast tells PostgreSQL what the *result* is, and it infers the
7924            // parameter feeding it as text -- so `$1::int4` bound with a
7925            // number sends binary int8 bytes into a text parameter and
7926            // answers `invalid byte sequence for encoding "UTF8"`. A value
7927            // PostgreSQL can read as a number needs no help; a null is the one
7928            // that does, because `id = $1` with nothing to infer from is
7929            // `integer = text`.
7930            _ if operand.is_null() => match column_type {
7931                Some(pg_type) => format!("::{}", pg_type),
7932                None => String::new(),
7933            },
7934            // A parameter arrives as `text`, and PostgreSQL then resolves the
7935            // operator by taking the *column* down to text where it can --
7936            // which is the wrong operator, and sometimes no operator at all.
7937            // `citext = text` compares case-sensitively against a
7938            // case-insensitive column; `uuid = text` does not exist. So a
7939            // written value names the type it is being compared against.
7940            //
7941            // Only a string: a number bound with a cast is sent as binary into
7942            // a parameter PostgreSQL has inferred as text, which is the
7943            // `invalid byte sequence for encoding "UTF8"` this used to answer.
7944            _ if operand.is_string() => match column_type {
7945                Some(pg_type) => format!("::{}", pg_type),
7946                None => String::new(),
7947            },
7948            _ => String::new(),
7949        };
7950        return Ok(format!("{} {} {}{}", quoted, sql_op, placeholder, cast));
7951    }
7952
7953    match op {
7954        "_is_null" => Ok(if operand.as_bool().unwrap_or(false) {
7955            format!("{} IS NULL", quoted)
7956        } else {
7957            format!("{} IS NOT NULL", quoted)
7958        }),
7959        "_in" | "_nin" => {
7960            let items = operand.as_array().ok_or_else(|| {
7961                async_graphql::Error::new(format!(
7962                    "the \"{}\" comparison on \"{}\" requires a list of values",
7963                    op, column
7964                ))
7965            })?;
7966            if items.is_empty() {
7967                // `IN ()` is not valid SQL. An empty `_in` matches nothing and
7968                // an empty `_nin` matches everything.
7969                return Ok(if op == "_in" { "false" } else { "true" }.to_string());
7970            }
7971            let mut placeholders = Vec::with_capacity(items.len());
7972            for item in items {
7973                // Cast only a null, for the reason the binary comparisons
7974                // give: a cast makes PostgreSQL infer the parameter as text.
7975                let cast = match (item.is_null() || item.is_string(), column_type) {
7976                    (true, Some(pg_type)) => format!("::{}", pg_type),
7977                    _ => String::new(),
7978                };
7979                placeholders.push(format!("${}{}", param_idx, cast));
7980                values.push(item.clone());
7981                *param_idx += 1;
7982            }
7983            Ok(format!(
7984                "{} {} ({})",
7985                quoted,
7986                if op == "_in" { "IN" } else { "NOT IN" },
7987                placeholders.join(", ")
7988            ))
7989        }
7990        "_has_keys_any" | "_has_keys_all" => {
7991            let items = operand.as_array().ok_or_else(|| {
7992                async_graphql::Error::new(format!(
7993                    "the \"{}\" comparison on \"{}\" requires a list of keys",
7994                    op, column
7995                ))
7996            })?;
7997            Ok(format!(
7998                "{} {} {}",
7999                quoted,
8000                if op == "_has_keys_any" { "?|" } else { "?&" },
8001                sql_array(items, "text[]", param_idx, values)
8002            ))
8003        }
8004        other => Err(async_graphql::Error::new(format!(
8005            "unsupported comparison \"{}\" on \"{}\"",
8006            other, column
8007        ))),
8008    }
8009}
8010
8011/// Build an `ORDER BY` clause from the `order_by` argument.
8012///
8013/// The argument is a list of single-column objects -- `[{name: asc}, {id:
8014/// desc}]` -- and the list is ordered, which is why it is a list and not one
8015/// object with several keys. Column names are checked against the table in the
8016/// schema cache before being quoted, so a name that is unknown, or crafted to
8017/// inject SQL, is rejected rather than interpolated. Returns an empty string
8018/// when no ordering was requested.
8019#[allow(clippy::too_many_arguments)] // one parameter per SQL clause
8020async fn build_order_by_clause(
8021    ctx: &ResolverContext<'_>,
8022    schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
8023    schema_name: &str,
8024    table_name: &str,
8025    type_name: &str,
8026    relationships: &HashMap<String, Vec<RelationshipField>>,
8027    reference: &str,
8028    names: &crate::names::NameOverrides,
8029) -> Result<String, async_graphql::Error> {
8030    let Ok(order_arg) = ctx.args.try_get("order_by") else {
8031        return Ok(String::new());
8032    };
8033
8034    let value = accessor_to_json(&order_arg);
8035    // A single object is accepted as a one-entry list, which is what a client
8036    // writing `order_by: {name: asc}` means and what Hasura reads it as.
8037    let entries: Vec<&serde_json::Value> = match &value {
8038        serde_json::Value::Array(items) => items.iter().collect(),
8039        serde_json::Value::Object(_) => vec![&value],
8040        serde_json::Value::Null => return Ok(String::new()),
8041        _ => {
8042            return Err(async_graphql::Error::new(
8043                "order_by takes an object or a list of them",
8044            ))
8045        }
8046    };
8047    if entries.is_empty() {
8048        return Ok(String::new());
8049    }
8050
8051    let guard = schema_cache
8052        .get()
8053        .await
8054        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8055    let cache = guard
8056        .as_ref()
8057        .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
8058    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8059    let table = cache
8060        .get_table(&qi)
8061        .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8062
8063    let mut terms = Vec::new();
8064    let mut alias_counter = 0usize;
8065    for entry in entries {
8066        order_terms_into(
8067            entry,
8068            cache,
8069            relationships,
8070            type_name,
8071            table,
8072            reference,
8073            names,
8074            &mut alias_counter,
8075            &mut terms,
8076        )?;
8077    }
8078
8079    if terms.is_empty() {
8080        return Ok(String::new());
8081    }
8082    Ok(format!(" ORDER BY {}", terms.join(", ")))
8083}
8084
8085/// Collect the `ORDER BY` terms one entry contributes.
8086///
8087/// A key whose value is a direction is a column of this table. A key whose
8088/// value is an object is something the row points at, and ordering by it is a
8089/// correlated subselect: one related row contributes its column, and many
8090/// contribute an aggregate. That is the whole difference between the two
8091/// sides, and PostgreSQL will take a scalar subquery anywhere a column goes.
8092#[allow(clippy::too_many_arguments)]
8093fn order_terms_into(
8094    entry: &serde_json::Value,
8095    cache: &SchemaCache,
8096    relationships: &HashMap<String, Vec<RelationshipField>>,
8097    type_name: &str,
8098    table: &postrust_core::schema_cache::Table,
8099    reference: &str,
8100    names: &crate::names::NameOverrides,
8101    alias_counter: &mut usize,
8102    terms: &mut Vec<String>,
8103) -> Result<(), async_graphql::Error> {
8104    let serde_json::Value::Object(map) = entry else {
8105        return Err(async_graphql::Error::new(
8106            "each order_by entry is an object mapping a column to a direction",
8107        ));
8108    };
8109    let available: &[RelationshipField] = relationships
8110        .get(type_name)
8111        .map(|r| r.as_slice())
8112        .unwrap_or(&[]);
8113
8114    for (key, value) in map {
8115        // A direction given as null is no direction. `order_by: {id:
8116        // $direction}` with nothing bound for `$direction` is how a client
8117        // makes an ordering optional without writing the query twice, and the
8118        // same goes for `{author: $author_order_by}`, which is a whole
8119        // ordering left out.
8120        if value.is_null() {
8121            continue;
8122        }
8123
8124        // A direction: this table's own column, or a function of its row.
8125        if let Some(name) = value.as_str() {
8126            let sql = crate::input::order_by::direction_sql(name).ok_or_else(|| {
8127                async_graphql::Error::new(format!(
8128                    "\"{}\" is not a sort direction; expected one of asc, desc, \
8129                     asc_nulls_first, asc_nulls_last, desc_nulls_first, desc_nulls_last",
8130                    name
8131                ))
8132            })?;
8133            let column = table_column_for(names, table, key);
8134            if table.get_column(column).is_some() {
8135                terms.push(format!(
8136                    "{}.{} {}",
8137                    reference,
8138                    postrust_sql::escape_ident(column),
8139                    sql
8140                ));
8141                continue;
8142            }
8143            // A computed field is a column as far as ordering is concerned:
8144            // the row is the argument, and the call is what is sorted on.
8145            let function = names
8146                .computed_source(&table.schema, &table.name, key)
8147                .unwrap_or(key);
8148            if let Some(definition) = table.get_computed_column(function) {
8149                terms.push(format!(
8150                    "{} {}",
8151                    computed_call(definition, &format!("{}.*", reference), reference),
8152                    sql
8153                ));
8154                continue;
8155            }
8156            return Err(async_graphql::Error::new(format!(
8157                "cannot order by unknown column \"{}\" on \"{}\"",
8158                key, table.name
8159            )));
8160        }
8161
8162        // An aggregate of the rows that point here.
8163        if let Some(rel) = key
8164            .strip_suffix("_aggregate")
8165            .and_then(|name| available.iter().find(|r| r.name == name && r.is_list))
8166        {
8167            aggregate_order_terms(value, rel, cache, reference, alias_counter, terms)?;
8168            continue;
8169        }
8170
8171        // A column of the row this one points at.
8172        if let Some(rel) = available.iter().find(|r| r.name == *key && !r.is_list) {
8173            let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, cache)
8174                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8175            if plan.columns.is_empty() {
8176                return Err(async_graphql::Error::new(format!(
8177                    "cannot order by \"{}\": it is not reached by a key",
8178                    key
8179                )));
8180            }
8181            *alias_counter += 1;
8182            let alias = format!("pgrst_ord_{}", alias_counter);
8183            let quoted_alias = postrust_sql::escape_ident(&alias);
8184            let correlation = plan
8185                .columns
8186                .iter()
8187                .map(|(local, foreign)| {
8188                    format!(
8189                        "{} = {}.{}",
8190                        format_args!("{}.{}", reference, postrust_sql::escape_ident(local)),
8191                        quoted_alias,
8192                        postrust_sql::escape_ident(foreign)
8193                    )
8194                })
8195                .collect::<Vec<_>>()
8196                .join(" AND ");
8197
8198            let target_qi = postrust_core::api_request::QualifiedIdentifier::new(
8199                &plan.foreign_schema,
8200                &plan.foreign_table,
8201            );
8202            let Some(target) = cache.get_table(&target_qi) else {
8203                return Err(async_graphql::Error::new(format!(
8204                    "unknown table \"{}\"",
8205                    plan.foreign_table
8206                )));
8207            };
8208
8209            // The related row's own terms, then wrapped one at a time: a
8210            // subquery yields one value, so each term is its own subselect.
8211            let mut nested = Vec::new();
8212            order_terms_into(
8213                value,
8214                cache,
8215                relationships,
8216                &rel.target_type,
8217                target,
8218                &quoted_alias,
8219                names,
8220                alias_counter,
8221                &mut nested,
8222            )?;
8223            for term in nested {
8224                let (expression, direction) = term
8225                    .rsplit_once(' ')
8226                    .map(|(e, d)| (e.to_string(), d.to_string()))
8227                    .unwrap_or((term.clone(), String::new()));
8228                terms.push(format!(
8229                    "(SELECT {} FROM {}.{} AS {} WHERE {}) {}",
8230                    expression,
8231                    postrust_sql::escape_ident(&plan.foreign_schema),
8232                    postrust_sql::escape_ident(&plan.foreign_table),
8233                    quoted_alias,
8234                    correlation,
8235                    direction
8236                ));
8237            }
8238            continue;
8239        }
8240
8241        return Err(async_graphql::Error::new(format!(
8242            "cannot order by \"{}\" on \"{}\"",
8243            key, table.name
8244        )));
8245    }
8246    Ok(())
8247}
8248
8249/// The `ORDER BY` terms for an aggregate of a row's children.
8250fn aggregate_order_terms(
8251    value: &serde_json::Value,
8252    rel: &RelationshipField,
8253    cache: &SchemaCache,
8254    reference: &str,
8255    alias_counter: &mut usize,
8256    terms: &mut Vec<String>,
8257) -> Result<(), async_graphql::Error> {
8258    let serde_json::Value::Object(spec) = value else {
8259        return Err(async_graphql::Error::new(
8260            "ordering by an aggregate takes an object, such as {count: desc}",
8261        ));
8262    };
8263    let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, cache)
8264        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8265    if plan.columns.is_empty() && plan.function.is_none() {
8266        return Err(async_graphql::Error::new(format!(
8267            "cannot order by an aggregate of \"{}\": it is not reached by a key",
8268            rel.name
8269        )));
8270    }
8271    // A computed relationship whose function takes more than the row cannot be
8272    // ordered by here: there is nowhere in `order_by` to write the arguments.
8273    if plan.function.is_some() && !rel.arguments.is_empty() {
8274        return Err(async_graphql::Error::new(format!(
8275            "cannot order by an aggregate of \"{}\": it takes arguments, and an \
8276             ordering has nowhere to write them",
8277            rel.name
8278        )));
8279    }
8280
8281    *alias_counter += 1;
8282    let alias = postrust_sql::escape_ident(&format!("pgrst_ord_{}", alias_counter));
8283    // A computed relationship is correlated by argument -- the function takes
8284    // the parent row -- where a key relationship is correlated by columns.
8285    let (source, correlation) = match &plan.function {
8286        Some(function) => {
8287            let session = plan.row_argument.as_ref().and_then(|row_argument| {
8288                computed_session_argument(cache, function, row_argument)
8289                    .map(|session| (row_argument.clone(), session))
8290            });
8291            let call = match session {
8292                Some((row_argument, session)) => format!(
8293                    "{} => {}, {} => {}",
8294                    postrust_sql::escape_ident(&row_argument),
8295                    reference,
8296                    postrust_sql::escape_ident(&session),
8297                    SESSION_ARGUMENT
8298                ),
8299                None => reference.to_string(),
8300            };
8301            (
8302                format!(
8303                    "{}.{}({})",
8304                    postrust_sql::escape_ident(&function.schema),
8305                    postrust_sql::escape_ident(&function.name),
8306                    call
8307                ),
8308                "true".to_string(),
8309            )
8310        }
8311        None => (
8312            format!(
8313                "{}.{}",
8314                postrust_sql::escape_ident(&plan.foreign_schema),
8315                postrust_sql::escape_ident(&plan.foreign_table)
8316            ),
8317            plan.columns
8318                .iter()
8319                .map(|(local, foreign)| {
8320                    format!(
8321                        "{}.{} = {}.{}",
8322                        reference,
8323                        postrust_sql::escape_ident(local),
8324                        alias,
8325                        postrust_sql::escape_ident(foreign)
8326                    )
8327                })
8328                .collect::<Vec<_>>()
8329                .join(" AND "),
8330        ),
8331    };
8332
8333    // `{count: desc}` is one term; `{max: {id: desc}}` is one per column.
8334    let mut wanted: Vec<(String, String)> = Vec::new();
8335    for (function, argument) in spec {
8336        // A direction given as null is no direction, as everywhere else an
8337        // ordering is read.
8338        if argument.is_null() {
8339            continue;
8340        }
8341        if function == "count" {
8342            let name = argument.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            wanted.push(("count(*)".to_string(), direction.to_string()));
8350            continue;
8351        }
8352        let serde_json::Value::Object(columns) = argument else {
8353            continue;
8354        };
8355        for (column, direction) in columns {
8356            if direction.is_null() {
8357                continue;
8358            }
8359            let name = direction.as_str().unwrap_or_default();
8360            let Some(direction) = crate::input::order_by::direction_sql(name) else {
8361                return Err(async_graphql::Error::new(format!(
8362                    "\"{}\" is not a sort direction",
8363                    name
8364                )));
8365            };
8366            // The function comes from the generated input, not from the
8367            // request: a client can only name one that was offered.
8368            wanted.push((
8369                format!(
8370                    "{}({}.{})",
8371                    function,
8372                    alias,
8373                    postrust_sql::escape_ident(column)
8374                ),
8375                direction.to_string(),
8376            ));
8377        }
8378    }
8379
8380    for (expression, direction) in wanted {
8381        terms.push(format!(
8382            "(SELECT {} FROM {} AS {} WHERE {}) {}",
8383            expression, source, alias, correlation, direction
8384        ));
8385    }
8386    Ok(())
8387}
8388
8389/// The `DISTINCT ON (...)` prefix, and the ordering that has to go with it.
8390///
8391/// PostgreSQL keeps the first row of each DISTINCT ON group in the query's own
8392/// order, and picks arbitrarily where the ordering does not begin with the
8393/// distinct columns -- so which row survives would depend on the plan. Hasura
8394/// refuses that query rather than answering it, and so does this: prepending
8395/// the distinct columns instead produced an answer, and a wrong one, since
8396/// `ORDER BY "department", "department" DESC` is decided by its first term and
8397/// sorts ascending. Where nothing was ordered at all there is nothing to
8398/// disagree with, so the distinct columns become the ordering.
8399///
8400/// `written` is the ordering as its comma-separated terms, without the
8401/// keyword; the answer is in the same spelling.
8402fn distinct_on_clause(
8403    distinct_on: &[String],
8404    written: Option<&str>,
8405) -> Result<(String, Option<String>), async_graphql::Error> {
8406    if distinct_on.is_empty() {
8407        return Ok((String::new(), written.map(str::to_string)));
8408    }
8409    let terms: Vec<&str> = written
8410        .map(|written| written.split(", ").collect())
8411        .unwrap_or_default();
8412    // Terms are qualified and the distinct columns may not be, so they are
8413    // compared by the name itself.
8414    let column_of = |term: &str| {
8415        let expression = term.split_whitespace().next().unwrap_or(term);
8416        expression
8417            .rsplit_once('.')
8418            .map(|(_, name)| name)
8419            .unwrap_or(expression)
8420            .to_string()
8421    };
8422    let leading: Vec<String> = terms
8423        .iter()
8424        .take(distinct_on.len())
8425        .map(|term| column_of(term))
8426        .collect();
8427    if !terms.is_empty()
8428        && (leading.len() != distinct_on.len()
8429            || distinct_on
8430                .iter()
8431                .any(|column| !leading.contains(&column_of(column))))
8432    {
8433        return Err(validation_error(
8434            "\"distinct_on\" columns must match initial \"order_by\" columns",
8435        ));
8436    }
8437    let order = match terms.is_empty() {
8438        true => Some(distinct_on.join(", ")),
8439        false => written.map(str::to_string),
8440    };
8441    Ok((format!("DISTINCT ON ({}) ", distinct_on.join(", ")), order))
8442}
8443
8444/// Build the `DISTINCT ON (...)` prefix from the `distinct_on` argument.
8445///
8446/// PostgreSQL requires the leftmost `ORDER BY` terms to match the distinct
8447/// columns, and picks an arbitrary surviving row otherwise. The caller
8448/// prepends these terms to whatever ordering was asked for rather than
8449/// replacing it, so `distinct_on: [name]` with `order_by: [{id: desc}]` keeps
8450/// the highest id per name instead of an unpredictable one.
8451async fn build_distinct_on(
8452    ctx: &ResolverContext<'_>,
8453    schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
8454    schema_name: &str,
8455    table_name: &str,
8456    names: &crate::names::NameOverrides,
8457) -> Result<Vec<String>, async_graphql::Error> {
8458    let Ok(arg) = ctx.args.try_get("distinct_on") else {
8459        return Ok(Vec::new());
8460    };
8461    let value = accessor_to_json(&arg);
8462    let requested: Vec<String> = match &value {
8463        serde_json::Value::Array(items) => items
8464            .iter()
8465            .filter_map(|i| i.as_str().map(|s| s.to_string()))
8466            .collect(),
8467        serde_json::Value::String(one) => vec![one.clone()],
8468        _ => Vec::new(),
8469    };
8470    if requested.is_empty() {
8471        return Ok(Vec::new());
8472    }
8473
8474    let guard = schema_cache
8475        .get()
8476        .await
8477        .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8478    let cache = guard
8479        .as_ref()
8480        .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
8481    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8482    let table = cache
8483        .get_table(&qi)
8484        .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8485
8486    let mut quoted = Vec::with_capacity(requested.len());
8487    for field in requested {
8488        let name = table_column_for(names, table, &field).to_string();
8489        if table.get_column(&name).is_none() {
8490            return Err(async_graphql::Error::new(format!(
8491                "cannot take distinct on unknown column \"{}\" of \"{}\"",
8492                field, table_name
8493            )));
8494        }
8495        quoted.push(postrust_sql::escape_ident(&name));
8496    }
8497    Ok(quoted)
8498}
8499
8500/// Build the SELECT-list expressions that embed relationships in one query.
8501///
8502/// The GraphQL mirror of the REST builder: each requested relationship becomes a
8503/// correlated subselect yielding JSON, so the whole selection comes back from
8504/// the parent query instead of one query per relationship per level.
8505/// The SELECT-list entries for any computed columns the selection asks for.
8506///
8507/// A computed column is a function of one argument of the table's own row
8508/// type, so it is not in `*` and has to be named. PostgreSQL's functional
8509/// notation reads `upper_name(author.*)` and `author.upper_name` as the same
8510/// call; the explicit form is written here because it says which function is
8511/// being called.
8512#[allow(clippy::too_many_arguments)] // the fields, their source, and the binding state
8513fn computed_projections<'a>(
8514    table: &postrust_core::schema_cache::Table,
8515    fields: impl IntoIterator<Item = SelectionField<'a>>,
8516    row_reference: &str,
8517    names: &crate::names::NameOverrides,
8518    schema_cache: &SchemaCache,
8519    param_idx: &mut usize,
8520    values: &mut Vec<serde_json::Value>,
8521) -> Result<Vec<String>, async_graphql::Error> {
8522    let mut projections = Vec::new();
8523    for field in fields {
8524        let name = field.name();
8525        // A real column wins, and the projection already carries it -- under
8526        // this name, whether or not that is the column's own.
8527        if table
8528            .get_column(table_column_for(names, table, name))
8529            .is_some()
8530        {
8531            continue;
8532        }
8533        // The field may be exposed under a name that was given rather than
8534        // the function's own, so the call is looked up from either side.
8535        let function = names
8536            .computed_source(&table.schema, &table.name, name)
8537            .unwrap_or(name);
8538        let Some(computed) = table.get_computed_column(function) else {
8539            continue;
8540        };
8541        let arguments = crate::schema::computed_caller_arguments(computed, schema_cache);
8542        let given = match arguments.is_empty() {
8543            true => None,
8544            false => embed_arguments(field).remove("args"),
8545        };
8546        projections.push(format!(
8547            "{} AS {}",
8548            computed_column_call(
8549                computed,
8550                row_reference,
8551                name,
8552                &arguments,
8553                given.as_ref(),
8554                param_idx,
8555                values,
8556            )?,
8557            postrust_sql::escape_ident(name)
8558        ));
8559    }
8560    Ok(projections)
8561}
8562
8563/// The call behind a computed field, including whatever the caller passed.
8564///
8565/// The ordinary case is a function of the row alone, which is written
8566/// positionally: that is the call REST writes, and the one a client that never
8567/// heard of `args` is asking for. Anything else has to be written by name --
8568/// the row is then not the only parameter and may not be the first -- so the
8569/// row, the session where the function asks for one, and each argument the
8570/// caller gave are all named.
8571fn computed_column_call(
8572    computed: &postrust_core::schema_cache::ComputedColumn,
8573    row: &str,
8574    field_name: &str,
8575    arguments: &[(String, String, bool)],
8576    given: Option<&serde_json::Value>,
8577    param_idx: &mut usize,
8578    values: &mut Vec<serde_json::Value>,
8579) -> Result<String, async_graphql::Error> {
8580    if arguments.is_empty() {
8581        return Ok(computed_call(computed, row, row));
8582    }
8583    let Some(row_argument) = &computed.row_argument else {
8584        return Ok(computed_call(computed, row, row));
8585    };
8586    let function = format!(
8587        "{}.{}",
8588        postrust_sql::escape_ident(&computed.function.schema),
8589        postrust_sql::escape_ident(&computed.function.name)
8590    );
8591    let mut passed = vec![format!(
8592        "{} => {}",
8593        postrust_sql::escape_ident(row_argument),
8594        row
8595    )];
8596    if let Some(session) = &computed.session_argument {
8597        passed.push(format!(
8598            "{} => {}",
8599            postrust_sql::escape_ident(session),
8600            SESSION_ARGUMENT
8601        ));
8602    }
8603    for (name, pg_type, required) in arguments {
8604        match given.and_then(|given| given.get(name)) {
8605            None if *required => {
8606                return Err(async_graphql::Error::new(format!(
8607                    "{} needs the argument \"{}\"",
8608                    field_name, name
8609                )))
8610            }
8611            // Left out is left out, so the function's own default applies.
8612            None => continue,
8613            Some(value) => {
8614                passed.push(format!(
8615                    "{} => ${}::{}",
8616                    postrust_sql::escape_ident(name),
8617                    param_idx,
8618                    pg_type
8619                ));
8620                *param_idx += 1;
8621                values.push(value.clone());
8622            }
8623        }
8624    }
8625    Ok(format!("{}({})", function, passed.join(", ")))
8626}
8627
8628/// The `count(...)` a selection asked for.
8629///
8630/// `count` alone is `count(*)`, which counts rows. `count(columns: [a])` is
8631/// `count("a")`, which counts the rows where `a` is not null -- a different
8632/// number, and the one the client asked for. `distinct: true` counts the
8633/// distinct values among them, and several columns are counted as the row
8634/// they make, which is how PostgreSQL counts more than one thing at once.
8635///
8636/// The column names come from the generated enum, so a selection can only
8637/// name a column the table has; what it may not know is the column's own name
8638/// where the schema exposes it under another.
8639fn count_expression(
8640    field: async_graphql::SelectionField<'_>,
8641    table: (&str, &str),
8642    alias: Option<&str>,
8643    names: &crate::names::NameOverrides,
8644) -> String {
8645    let arguments = embed_arguments(field);
8646    let requested = match arguments.get("columns") {
8647        Some(serde_json::Value::Array(items)) => items
8648            .iter()
8649            .filter_map(|item| item.as_str())
8650            .collect::<Vec<_>>(),
8651        Some(serde_json::Value::String(one)) => vec![one.as_str()],
8652        _ => Vec::new(),
8653    };
8654    if requested.is_empty() {
8655        return "count(*)".to_string();
8656    }
8657    let columns: Vec<String> = requested
8658        .into_iter()
8659        .map(|column| {
8660            let (schema, name) = table;
8661            let source = column_for(names, schema, name, column);
8662            match alias {
8663                Some(alias) => format!(
8664                    "{}.{}",
8665                    postrust_sql::escape_ident(alias),
8666                    postrust_sql::escape_ident(source)
8667                ),
8668                None => postrust_sql::escape_ident(source),
8669            }
8670        })
8671        .collect();
8672    // One column counts itself; several count the row they make, since
8673    // `count(a, b)` is not a call PostgreSQL has.
8674    let counted = match columns.len() {
8675        1 => columns.into_iter().next().unwrap_or_default(),
8676        _ => format!("({})", columns.join(", ")),
8677    };
8678    let distinct = matches!(
8679        arguments.get("distinct"),
8680        Some(serde_json::Value::Bool(true))
8681    );
8682    match distinct {
8683        true => format!("count(DISTINCT {})", counted),
8684        false => format!("count({})", counted),
8685    }
8686}
8687
8688/// The SELECT list for a nested aggregate.
8689///
8690/// `articles_aggregate { aggregate { count } nodes { title } }` becomes one
8691/// row per parent, correlated the way any embed is. Both halves are aggregates
8692/// over the same correlated set, so they go in one select list rather than two
8693/// queries -- `count(*)` and `json_agg(...)` read the same rows.
8694#[allow(clippy::too_many_arguments)] // the recursion carries its whole context
8695fn nested_aggregate_select(
8696    caller: &crate::role::Caller<'_>,
8697    selection: async_graphql::SelectionField<'_>,
8698    child_alias: &str,
8699    schema_cache: &SchemaCache,
8700    relationships: &HashMap<String, Vec<RelationshipField>>,
8701    target_type: &str,
8702    child_table: Option<&postrust_core::schema_cache::Table>,
8703    max_rows: Option<i64>,
8704    alias_counter: &mut usize,
8705    param_idx: &mut usize,
8706    values: &mut Vec<serde_json::Value>,
8707    names: &crate::names::NameOverrides,
8708) -> Result<String, async_graphql::Error> {
8709    use crate::schema::aggregate as agg;
8710
8711    let mut parts: Vec<String> = Vec::new();
8712
8713    for child in selection.selection_set() {
8714        match child.name() {
8715            "aggregate" => {
8716                let of_table = child_table
8717                    .map(|table| (table.schema.as_str(), table.name.as_str()))
8718                    .unwrap_or(("", ""));
8719                // Each `count` is answered under the name it was asked for,
8720                // since two of them may count different things. Every other
8721                // aggregate is one object read under however many names, so
8722                // its columns are the union of what all of them named.
8723                let mut counts: Vec<(String, String)> = Vec::new();
8724                let mut wanted: BTreeMap<&str, Vec<String>> = BTreeMap::new();
8725                for function in child.selection_set() {
8726                    if function.name() == "count" {
8727                        counts.push((
8728                            function.alias().unwrap_or("count").to_string(),
8729                            count_expression(function, of_table, Some(child_alias), names),
8730                        ));
8731                        continue;
8732                    }
8733                    let sql_function = agg::NUMERIC_AGGREGATES
8734                        .iter()
8735                        .chain(agg::ORDERED_AGGREGATES.iter())
8736                        .find(|(name, _)| *name == function.name())
8737                        .map(|(name, _)| *name);
8738                    let Some(sql_function) = sql_function else {
8739                        continue;
8740                    };
8741                    let columns = wanted.entry(sql_function).or_default();
8742                    for column in function.selection_set() {
8743                        let name = column.name().to_string();
8744                        // Answered by the schema, not a column.
8745                        if name != "__typename" && !columns.contains(&name) {
8746                            columns.push(name);
8747                        }
8748                    }
8749                }
8750                // Answered whether or not it was asked for, for the reason
8751                // the root aggregate answers it.
8752                let mut fields = match counts.iter().any(|(key, _)| key == "count") {
8753                    true => Vec::new(),
8754                    false => vec!["'count', count(*)".to_string()],
8755                };
8756                for (key, expression) in &counts {
8757                    fields.push(format!(
8758                        "{}, {}",
8759                        postrust_sql::quote_literal(key),
8760                        expression
8761                    ));
8762                }
8763                for (sql_function, named) in &wanted {
8764                    let columns: Vec<String> = named
8765                        .iter()
8766                        .map(|column| {
8767                            let source = child_table
8768                                .map(|table| table_column_for(names, table, column))
8769                                .unwrap_or(column.as_str());
8770                            format!(
8771                                "{}, {}({}.{})",
8772                                postrust_sql::quote_literal(column),
8773                                sql_function,
8774                                postrust_sql::escape_ident(child_alias),
8775                                postrust_sql::escape_ident(source)
8776                            )
8777                        })
8778                        .collect();
8779                    // Pushed even when empty, as at the root: `max { __typename }`
8780                    // is an object with nothing in it, not a null.
8781                    fields.push(format!(
8782                        "'{}', json_build_object({})",
8783                        sql_function,
8784                        columns.join(", ")
8785                    ));
8786                }
8787                parts.push(format!(
8788                    "json_build_object({}) AS {}",
8789                    fields.join(", "),
8790                    postrust_sql::escape_ident("aggregate")
8791                ));
8792            }
8793            // `nodes` under an aggregate is a rows selection like any other:
8794            // what it names may be a column, a computed field, or a
8795            // relationship of its own, and the last of those is a further
8796            // correlated subselect rather than a column of this one.
8797            "nodes" => {
8798                let embeds = build_embed_expressions(
8799                    caller,
8800                    schema_cache,
8801                    relationships,
8802                    target_type,
8803                    child_alias,
8804                    child.selection_set(),
8805                    max_rows,
8806                    alias_counter,
8807                    param_idx,
8808                    values,
8809                    names,
8810                )?;
8811                let mut columns: Vec<String> = Vec::new();
8812                for column in child.selection_set() {
8813                    let name = column.name();
8814                    if name == "__typename" || embeds.iter().any(|(field, _)| field == name) {
8815                        continue;
8816                    }
8817                    columns.push(format!(
8818                        "{}, {}",
8819                        postrust_sql::quote_literal(name),
8820                        column_expression(child_table, child_alias, name, names)
8821                    ));
8822                }
8823                for (field, expression) in &embeds {
8824                    columns.push(format!(
8825                        "{}, {}",
8826                        postrust_sql::quote_literal(field),
8827                        expression
8828                    ));
8829                }
8830                let row = if columns.is_empty() {
8831                    format!("row_to_json({})", postrust_sql::escape_ident(child_alias))
8832                } else {
8833                    format!("json_build_object({})", columns.join(", "))
8834                };
8835                parts.push(format!(
8836                    "COALESCE(json_agg({}), '[]'::json) AS {}",
8837                    row,
8838                    postrust_sql::escape_ident("nodes")
8839                ));
8840            }
8841            _ => {}
8842        }
8843    }
8844
8845    if parts.is_empty() {
8846        // A selection of nothing but `__typename`. One row, no columns, is not
8847        // valid SQL; a count nobody reads is.
8848        parts.push("count(*) AS pgrst_empty".to_string());
8849    }
8850    Ok(parts.join(", "))
8851}
8852
8853/// How one named field of a row is read, given the alias the row goes by.
8854///
8855/// A column is itself; a computed field is the call that produces it. Which of
8856/// the two a name is depends on the table, so this is the one place that asks.
8857fn column_expression(
8858    table: Option<&postrust_core::schema_cache::Table>,
8859    alias: &str,
8860    name: &str,
8861    names: &crate::names::NameOverrides,
8862) -> String {
8863    let column = table
8864        .map(|t| table_column_for(names, t, name))
8865        .unwrap_or(name);
8866    let plain = format!(
8867        "{}.{}",
8868        postrust_sql::escape_ident(alias),
8869        postrust_sql::escape_ident(column)
8870    );
8871    let computed = table
8872        .filter(|t| t.get_column(column).is_none())
8873        .and_then(|t| {
8874            let function = names
8875                .computed_source(&t.schema, &t.name, name)
8876                .unwrap_or(name);
8877            t.get_computed_column(function)
8878        });
8879    match computed {
8880        Some(definition) => computed_call(
8881            definition,
8882            &format!("{}.*", postrust_sql::escape_ident(alias)),
8883            &postrust_sql::escape_ident(alias),
8884        ),
8885        None => plain,
8886    }
8887}
8888
8889/// Render `order_by` terms against a table, qualified with an alias.
8890///
8891/// The root field's ordering reads its argument from the resolver context and
8892/// needs the schema cache asynchronously; an embed already holds both, so this
8893/// takes the value directly. Columns are checked against the table before they
8894/// are quoted, so an unknown or crafted name is refused rather than
8895/// interpolated.
8896fn order_terms(
8897    order: &serde_json::Value,
8898    schema_cache: &SchemaCache,
8899    schema_name: &str,
8900    table_name: &str,
8901    alias: &str,
8902    names: &crate::names::NameOverrides,
8903) -> Result<Option<String>, async_graphql::Error> {
8904    let entries: Vec<&serde_json::Value> = match order {
8905        serde_json::Value::Array(items) => items.iter().collect(),
8906        serde_json::Value::Object(_) => vec![order],
8907        _ => return Ok(None),
8908    };
8909
8910    let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8911    let table = schema_cache
8912        .get_table(&qi)
8913        .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8914
8915    let mut terms = Vec::new();
8916    for entry in entries {
8917        let serde_json::Value::Object(map) = entry else {
8918            continue;
8919        };
8920        for (field, direction) in map {
8921            // A direction given as null is no direction, as at the root.
8922            if direction.is_null() {
8923                continue;
8924            }
8925            let column = table_column_for(names, table, field);
8926            if table.get_column(column).is_none() {
8927                return Err(async_graphql::Error::new(format!(
8928                    "cannot order by unknown column \"{}\" on \"{}\"",
8929                    field, table_name
8930                )));
8931            }
8932            let name = direction.as_str().unwrap_or_default();
8933            let sql = crate::input::order_by::direction_sql(name).ok_or_else(|| {
8934                async_graphql::Error::new(format!("\"{}\" is not a sort direction", name))
8935            })?;
8936            terms.push(format!(
8937                "{}.{} {}",
8938                postrust_sql::escape_ident(alias),
8939                postrust_sql::escape_ident(column),
8940                sql
8941            ));
8942        }
8943    }
8944
8945    Ok(if terms.is_empty() {
8946        None
8947    } else {
8948        Some(terms.join(", "))
8949    })
8950}
8951
8952/// Whether a to-one relationship always has a row at the other end.
8953///
8954/// It does when this row's own key columns cannot be null: a foreign key
8955/// guarantees a matching row for every value, so a `NOT NULL` key is a
8956/// relationship that cannot be absent, and the field is non-null. A client
8957/// generating types then gets `author` rather than `author | null`, which is
8958/// what the schema actually promises.
8959///
8960/// Only where a foreign key says so. A computed relationship is a function
8961/// call, and a one-to-one reached through the *child's* key is a row that may
8962/// simply not exist.
8963fn always_present(rel: &RelationshipField, table: &postrust_core::schema_cache::Table) -> bool {
8964    use postrust_core::schema_cache::{Cardinality, Relationship};
8965    let Relationship::ForeignKey { cardinality, .. } = &rel.relationship else {
8966        return false;
8967    };
8968    match cardinality {
8969        Cardinality::M2O { .. } => {}
8970        Cardinality::O2O {
8971            is_parent: false, ..
8972        } => {}
8973        _ => return false,
8974    }
8975    let columns = cardinality.columns();
8976    !columns.is_empty()
8977        && columns.iter().all(|(local, _)| {
8978            table
8979                .get_column(local)
8980                .is_some_and(|column| !column.nullable)
8981        })
8982}
8983
8984/// Whether the row at the other end of a relationship carries the key.
8985///
8986/// If it does, this row is written first and its key is pushed down; if this
8987/// row's own column carries it, the other row is written first and its key is
8988/// read back. Cardinality alone does not answer it: a one-to-one is one row in
8989/// either direction, and which side holds the foreign key is the whole
8990/// difference between the two orders.
8991fn child_holds_the_key(relationship: &postrust_core::schema_cache::Relationship) -> bool {
8992    use postrust_core::schema_cache::{Cardinality, Relationship};
8993    match relationship {
8994        Relationship::ForeignKey { cardinality, .. } => match cardinality {
8995            Cardinality::M2O { .. } => false,
8996            Cardinality::O2O { is_parent, .. } => *is_parent,
8997            _ => true,
8998        },
8999        Relationship::Computed { .. } => true,
9000    }
9001}
9002
9003/// The name of a function's session parameter, if it has one.
9004fn computed_session_argument(
9005    cache: &SchemaCache,
9006    function: &postrust_core::api_request::QualifiedIdentifier,
9007    row_argument: &str,
9008) -> Option<String> {
9009    let _ = row_argument;
9010    cache
9011        .routines
9012        .get(function)
9013        .into_iter()
9014        .flatten()
9015        .find(|routine| routine.name == function.name)?
9016        .params
9017        .iter()
9018        .find(|param| {
9019            param.name == "hasura_session" && matches!(param.param_type.as_str(), "json" | "jsonb")
9020        })
9021        .map(|param| param.name.clone())
9022}
9023
9024/// The name of the input holding a computed relationship's own arguments.
9025fn computed_args_type_name(type_name: &str, field: &str) -> String {
9026    format!("{}_{}_args", type_name, field)
9027}
9028
9029/// The argument list a computed relationship's function is called with.
9030///
9031/// `None` where the parent row is the only thing it takes -- the ordinary case,
9032/// and the positional call the REST surface writes. Anything else is written by
9033/// name: the row, the session where the function asks for one, and whatever the
9034/// client put under `args`.
9035fn computed_arguments(
9036    relationship: &RelationshipField,
9037    plan: &postrust_core::embed::EmbedPlan,
9038    parent_row: &str,
9039    given: Option<&serde_json::Value>,
9040    param_idx: &mut usize,
9041    values: &mut Vec<serde_json::Value>,
9042    schema_cache: &SchemaCache,
9043) -> Result<Option<String>, async_graphql::Error> {
9044    let (Some(function), Some(row_argument)) = (&plan.function, &plan.row_argument) else {
9045        return Ok(None);
9046    };
9047    let session = schema_cache
9048        .routines
9049        .get(function)
9050        .into_iter()
9051        .flatten()
9052        .find(|routine| routine.name == function.name)
9053        .and_then(|routine| {
9054            routine
9055                .params
9056                .iter()
9057                .find(|param| {
9058                    param.name == "hasura_session"
9059                        && matches!(param.param_type.as_str(), "json" | "jsonb")
9060                })
9061                .map(|param| param.name.clone())
9062        });
9063    if relationship.arguments.is_empty() && session.is_none() {
9064        return Ok(None);
9065    }
9066
9067    let mut passed = vec![format!(
9068        "{} => {}",
9069        postrust_sql::escape_ident(row_argument),
9070        parent_row
9071    )];
9072    if let Some(session) = session {
9073        passed.push(format!(
9074            "{} => {}",
9075            postrust_sql::escape_ident(&session),
9076            SESSION_ARGUMENT
9077        ));
9078    }
9079    for (name, pg_type, required) in &relationship.arguments {
9080        match given.and_then(|given| given.get(name)) {
9081            None if *required => {
9082                return Err(async_graphql::Error::new(format!(
9083                    "{} needs the argument \"{}\"",
9084                    relationship.name, name
9085                )))
9086            }
9087            // Left out is left out, so the function's own default applies.
9088            None => continue,
9089            Some(value) => {
9090                passed.push(format!(
9091                    "{} => ${}::{}",
9092                    postrust_sql::escape_ident(name),
9093                    param_idx,
9094                    pg_type
9095                ));
9096                *param_idx += 1;
9097                values.push(value.clone());
9098            }
9099        }
9100    }
9101    Ok(Some(passed.join(", ")))
9102}
9103
9104/// The arguments written on an embedded field, as JSON.
9105fn embed_arguments(field: async_graphql::SelectionField<'_>) -> HashMap<String, serde_json::Value> {
9106    field
9107        .arguments()
9108        .map(|args| {
9109            args.into_iter()
9110                .map(|(name, value)| {
9111                    (
9112                        name.to_string(),
9113                        plain_numbers(value.into_json().unwrap_or(serde_json::Value::Null)),
9114                    )
9115                })
9116                .collect()
9117        })
9118        .unwrap_or_default()
9119}
9120
9121/// What an embed's arguments narrow its child rows to: a `DISTINCT ON`
9122/// prefix, a predicate, an ordering, a limit and an offset, in the order the
9123/// SQL takes them.
9124type Narrowing = (String, Option<String>, Option<String>, Option<i64>, i64);
9125
9126/// What an embed's arguments narrow its child rows to.
9127///
9128/// A list and an aggregate of that same list take the same four arguments and
9129/// mean the same thing by them; only what is done with the surviving rows
9130/// differs, so the reading of the arguments is shared.
9131#[allow(clippy::too_many_arguments)] // one parameter per SQL clause, plus the binding state
9132fn embed_narrowing(
9133    arguments: &HashMap<String, serde_json::Value>,
9134    plan: &postrust_core::embed::EmbedPlan,
9135    schema_cache: &SchemaCache,
9136    relationships: &HashMap<String, Vec<RelationshipField>>,
9137    target_type: &str,
9138    child_alias: &str,
9139    max_rows: Option<i64>,
9140    param_idx: &mut usize,
9141    values: &mut Vec<serde_json::Value>,
9142    names: &crate::names::NameOverrides,
9143    caller: &crate::role::Caller<'_>,
9144) -> Result<Narrowing, async_graphql::Error> {
9145    // The child's own permission, which is the whole reason an embed is a
9146    // place this has to be applied: `author { articles { ... } }` reads two
9147    // tables, and the rule on the second is not the rule on the first.
9148    let permission =
9149        permission_predicate(caller, names, &plan.foreign_schema, &plan.foreign_table)?;
9150    let requested = arguments.get("where").filter(|v| !v.is_null()).cloned();
9151    let child_where = match and_predicates(requested, permission) {
9152        Some(expression) => {
9153            let child_scope = WhereScope::for_alias(
9154                &plan.foreign_schema,
9155                &plan.foreign_table,
9156                child_alias,
9157                target_type,
9158                schema_cache,
9159                relationships,
9160                names,
9161            )
9162            .for_caller(*caller);
9163            let mut nested_alias = 0usize;
9164            build_condition(
9165                &expression,
9166                &child_scope,
9167                param_idx,
9168                values,
9169                &mut nested_alias,
9170            )?
9171        }
9172        None => None,
9173    };
9174
9175    let child_order = match arguments.get("order_by") {
9176        Some(order) if !order.is_null() => order_terms(
9177            order,
9178            schema_cache,
9179            &plan.foreign_schema,
9180            &plan.foreign_table,
9181            child_alias,
9182            names,
9183        )?,
9184        _ => None,
9185    };
9186
9187    // A limit written on the embed is what the client asked for; the
9188    // configured ceiling still applies as an upper bound, the same way it
9189    // does at the top level -- and so does the child's own permission, which
9190    // bounds rows per parent here rather than per query.
9191    let ceiling = match (
9192        max_rows,
9193        crate::role::read_limit(caller, names, &plan.foreign_schema, &plan.foreign_table),
9194    ) {
9195        (Some(configured), Some(granted)) => Some(configured.min(granted)),
9196        (only, None) | (None, only) => only,
9197    };
9198    let child_limit = match arguments.get("limit").and_then(|v| v.as_i64()) {
9199        Some(requested) => match ceiling {
9200            Some(ceiling) => Some(requested.min(ceiling)),
9201            None => Some(requested),
9202        },
9203        None => ceiling,
9204    };
9205    let child_offset = arguments
9206        .get("offset")
9207        .and_then(|v| v.as_i64())
9208        .unwrap_or(0);
9209
9210    // `author { articles(distinct_on: [title], order_by: {title: asc}) }` --
9211    // one article per title, the same question the root field answers and
9212    // under the same rule about what may be ordered by.
9213    let requested = match arguments.get("distinct_on") {
9214        Some(serde_json::Value::Array(items)) => items
9215            .iter()
9216            .filter_map(|item| item.as_str())
9217            .collect::<Vec<_>>(),
9218        Some(serde_json::Value::String(one)) => vec![one.as_str()],
9219        _ => Vec::new(),
9220    };
9221    let mut distinct_on = Vec::with_capacity(requested.len());
9222    if !requested.is_empty() {
9223        let qi = postrust_core::api_request::QualifiedIdentifier::new(
9224            &plan.foreign_schema,
9225            &plan.foreign_table,
9226        );
9227        let table = schema_cache.get_table(&qi).ok_or_else(|| {
9228            async_graphql::Error::new(format!("unknown table \"{}\"", plan.foreign_table))
9229        })?;
9230        for field in requested {
9231            let column = table_column_for(names, table, field).to_string();
9232            if table.get_column(&column).is_none() {
9233                return Err(async_graphql::Error::new(format!(
9234                    "cannot take distinct on unknown column \"{}\" of \"{}\"",
9235                    field, plan.foreign_table
9236                )));
9237            }
9238            distinct_on.push(format!(
9239                "{}.{}",
9240                postrust_sql::escape_ident(child_alias),
9241                postrust_sql::escape_ident(&column)
9242            ));
9243        }
9244    }
9245    let (distinct, child_order) = distinct_on_clause(&distinct_on, child_order.as_deref())?;
9246
9247    Ok((
9248        distinct,
9249        child_where,
9250        child_order,
9251        child_limit,
9252        child_offset,
9253    ))
9254}
9255
9256#[allow(clippy::too_many_arguments)] // one parameter per SQL clause, plus the binding state
9257fn build_embed_expressions<'a>(
9258    caller: &crate::role::Caller<'_>,
9259    schema_cache: &SchemaCache,
9260    relationships: &HashMap<String, Vec<RelationshipField>>,
9261    type_name: &str,
9262    parent_alias: &str,
9263    fields: impl IntoIterator<Item = SelectionField<'a>>,
9264    max_rows: Option<i64>,
9265    alias_counter: &mut usize,
9266    param_idx: &mut usize,
9267    values: &mut Vec<serde_json::Value>,
9268    names: &crate::names::NameOverrides,
9269) -> Result<Vec<(String, String)>, async_graphql::Error> {
9270    let Some(available) = relationships.get(type_name) else {
9271        return Ok(Vec::new());
9272    };
9273
9274    let mut expressions = Vec::new();
9275
9276    for field in fields {
9277        // `<relationship>_aggregate` is the same embed with an aggregate
9278        // select list, so it is resolved here rather than by a resolver of its
9279        // own -- the correlation is what makes it a per-parent answer.
9280        let aggregate_of = field
9281            .name()
9282            .strip_suffix("_aggregate")
9283            .and_then(|name| available.iter().find(|r| r.name == name && r.is_list));
9284
9285        if let Some(rel) = aggregate_of {
9286            let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, schema_cache)
9287                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9288            *alias_counter += 1;
9289            let child_alias = format!("a{}", alias_counter);
9290
9291            // The same narrowing an embedded list takes. `where` here decides
9292            // which rows are counted, not which are returned, so it goes on the
9293            // set the aggregate reads rather than on the answer.
9294            let arguments = embed_arguments(field);
9295            let (child_distinct, child_where, child_order, child_limit, child_offset) =
9296                embed_narrowing(
9297                    &arguments,
9298                    &plan,
9299                    schema_cache,
9300                    relationships,
9301                    &rel.target_type,
9302                    &child_alias,
9303                    max_rows,
9304                    param_idx,
9305                    values,
9306                    names,
9307                    caller,
9308                )?;
9309
9310            let child_table =
9311                schema_cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
9312                    &plan.foreign_schema,
9313                    &plan.foreign_table,
9314                ));
9315            let select = nested_aggregate_select(
9316                caller,
9317                field,
9318                &child_alias,
9319                schema_cache,
9320                relationships,
9321                &rel.target_type,
9322                child_table,
9323                max_rows,
9324                alias_counter,
9325                param_idx,
9326                values,
9327                names,
9328            )?;
9329
9330            let call = computed_arguments(
9331                rel,
9332                &plan,
9333                &postrust_sql::escape_ident(parent_alias),
9334                arguments.get("args"),
9335                param_idx,
9336                values,
9337                schema_cache,
9338            )?;
9339            let expression = plan
9340                .aggregate_expression(
9341                    parent_alias,
9342                    &postrust_sql::escape_ident(parent_alias),
9343                    &child_alias,
9344                    &select,
9345                    child_limit,
9346                    child_offset,
9347                    child_where.as_deref(),
9348                    child_order.as_deref(),
9349                    call.as_deref(),
9350                    &child_distinct,
9351                    // A GraphQL body is JSON throughout -- nothing here
9352                    // renders a row as text -- and Hasura keeps the order the
9353                    // fields were selected in.
9354                    postrust_core::EmbedRendering::Verbatim,
9355                )
9356                .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9357            expressions.push((field.name().to_string(), expression));
9358            continue;
9359        }
9360
9361        let Some(rel) = available.iter().find(|r| r.name == field.name()) else {
9362            continue;
9363        };
9364
9365        let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, schema_cache)
9366            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9367
9368        *alias_counter += 1;
9369        let child_alias = format!("e{}", alias_counter);
9370
9371        let nested = build_embed_expressions(
9372            caller,
9373            schema_cache,
9374            relationships,
9375            &rel.target_type,
9376            &child_alias,
9377            field.selection_set(),
9378            max_rows,
9379            alias_counter,
9380            param_idx,
9381            values,
9382            names,
9383        )?;
9384
9385        // The arguments written on the embed itself.
9386        let arguments = embed_arguments(field);
9387        let (child_distinct, child_where, child_order, child_limit, child_offset) =
9388            embed_narrowing(
9389                &arguments,
9390                &plan,
9391                schema_cache,
9392                relationships,
9393                &rel.target_type,
9394                &child_alias,
9395                max_rows,
9396                param_idx,
9397                values,
9398                names,
9399                caller,
9400            )?;
9401
9402        // Leaf fields are columns; anything that resolved to a relationship is
9403        // an expression instead.
9404        let child_relationships = relationships.get(&rel.target_type);
9405        let child_qi = postrust_core::api_request::QualifiedIdentifier::new(
9406            &plan.foreign_schema,
9407            &plan.foreign_table,
9408        );
9409        let child_table = schema_cache.get_table(&child_qi);
9410        let mut parts: Vec<String> = Vec::new();
9411        for sub in field.selection_set() {
9412            let name = sub.name();
9413            let is_relationship = child_relationships
9414                .map(|rels| {
9415                    rels.iter().any(|r| {
9416                        r.name == name || (r.is_list && format!("{}_aggregate", r.name) == name)
9417                    })
9418                })
9419                .unwrap_or(false);
9420            // `__typename` is answered by the schema, not the row -- and it is
9421            // asked for here constantly: Apollo Client adds it to every
9422            // selection, and a Federation router to every entity reference.
9423            if is_relationship || name == "__typename" {
9424                continue;
9425            }
9426            // A computed column inside an embed is the same call, against the
9427            // child's alias rather than the table.
9428            let column = child_table
9429                .map(|t| table_column_for(names, t, name))
9430                .unwrap_or(name);
9431            let computed = child_table
9432                .filter(|t| t.get_column(column).is_none())
9433                .and_then(|t| {
9434                    let function = names
9435                        .computed_source(&t.schema, &t.name, name)
9436                        .unwrap_or(name);
9437                    t.get_computed_column(function)
9438                });
9439            match computed {
9440                Some(definition) => parts.push(format!(
9441                    "{} AS {}",
9442                    computed_call(
9443                        definition,
9444                        &format!("{}.*", postrust_sql::escape_ident(&child_alias)),
9445                        &postrust_sql::escape_ident(&child_alias),
9446                    ),
9447                    postrust_sql::escape_ident(name)
9448                )),
9449                // A column the child exposes under another name is selected as
9450                // that name, since the row it lands in is the client's.
9451                None if column != name => parts.push(format!(
9452                    "{} AS {}",
9453                    postrust_sql::escape_ident(column),
9454                    postrust_sql::escape_ident(name)
9455                )),
9456                None => parts.push(postrust_sql::escape_ident(name)),
9457            }
9458        }
9459        if parts.is_empty() && nested.is_empty() {
9460            parts.push(
9461                child_table
9462                    .and_then(|table| rename_projection(table, &child_alias, names))
9463                    .unwrap_or_else(|| format!("{}.*", postrust_sql::escape_ident(&child_alias))),
9464            );
9465        }
9466        for (field_name, expression) in nested {
9467            parts.push(format!(
9468                "{} AS {}",
9469                expression,
9470                postrust_sql::escape_ident(&field_name)
9471            ));
9472        }
9473
9474        let computed_call_arguments = computed_arguments(
9475            rel,
9476            &plan,
9477            &postrust_sql::escape_ident(parent_alias),
9478            arguments.get("args"),
9479            param_idx,
9480            values,
9481            schema_cache,
9482        )?;
9483        let expression = plan
9484            .embed_expression(
9485                parent_alias,
9486                // A computed relationship is correlated by argument rather
9487                // than by a key: the function takes the parent row, and an
9488                // alias names that row.
9489                &postrust_sql::escape_ident(parent_alias),
9490                &child_alias,
9491                &format!("{}{}", child_distinct, parts.join(", ")),
9492                child_limit,
9493                child_offset,
9494                child_where.as_deref(),
9495                child_order.as_deref(),
9496                computed_call_arguments.as_deref(),
9497                postrust_core::EmbedRendering::Verbatim,
9498            )
9499            .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9500
9501        expressions.push((rel.name.clone(), expression));
9502    }
9503
9504    Ok(expressions)
9505}
9506
9507/// What embedding a relationship needs, independent of the rows involved.
9508///
9509/// The connection is passed alongside rather than held here: embedding runs on
9510/// the request's transaction, and a shared reference to this struct could not
9511/// hand out the mutable borrow the queries need.
9512struct EmbedContext<'c> {
9513    schema_cache: &'c SchemaCache,
9514    relationships: &'c HashMap<String, Vec<RelationshipField>>,
9515    max_rows: Option<i64>,
9516}
9517
9518/// Embed the relationship fields requested on `rows`.
9519///
9520/// One query per relationship per level, not one per row: the parents' join
9521/// keys are collected and passed as a single array. Recurses so a nested
9522/// selection costs one further query per relationship at each depth.
9523fn embed_relationships<'f>(
9524    conn: &'f mut sqlx::PgConnection,
9525    ctx: &'f EmbedContext<'f>,
9526    type_name: &'f str,
9527    selection: async_graphql::SelectionField<'f>,
9528    rows: &'f mut [serde_json::Value],
9529) -> futures::future::BoxFuture<'f, Result<(), async_graphql::Error>> {
9530    Box::pin(async move {
9531        if rows.is_empty() {
9532            return Ok(());
9533        }
9534
9535        let Some(available) = ctx.relationships.get(type_name) else {
9536            return Ok(());
9537        };
9538
9539        for requested in selection.selection_set() {
9540            let Some(rel) = available.iter().find(|r| r.name == requested.name()) else {
9541                continue;
9542            };
9543
9544            let plan =
9545                postrust_core::embed::EmbedPlan::resolve(&rel.relationship, ctx.schema_cache)
9546                    .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9547
9548            let keys = postrust_core::embed::parent_keys(rows, &plan.local_column);
9549
9550            // Project only what the selection asked for. A GraphQL selection
9551            // names its leaf fields, so the columns are known before the query
9552            // and an unrequested column need not be read, serialised, sent and
9553            // parsed just to be dropped.
9554            //
9555            // A nested relationship joins on a column of the child row, so that
9556            // column is added even when it was not selected; it is removed again
9557            // when the response is shaped. A selection whose sub-fields cannot
9558            // all be resolved to columns falls back to every column.
9559            let mut child_columns: Vec<String> = Vec::new();
9560            let mut project_everything = false;
9561            let child_relationships = ctx.relationships.get(&rel.target_type);
9562            for field in requested.selection_set() {
9563                let name = field.name();
9564                match child_relationships.and_then(|rels| rels.iter().find(|r| r.name == name)) {
9565                    Some(nested_rel) => {
9566                        match postrust_core::embed::EmbedPlan::resolve(
9567                            &nested_rel.relationship,
9568                            ctx.schema_cache,
9569                        ) {
9570                            Ok(nested_plan) => child_columns.push(nested_plan.local_column),
9571                            Err(_) => project_everything = true,
9572                        }
9573                    }
9574                    // Answered by the schema, not a column.
9575                    None if name == "__typename" => {}
9576                    None => child_columns.push(name.to_string()),
9577                }
9578            }
9579            if project_everything || child_columns.is_empty() {
9580                child_columns.clear();
9581            }
9582
9583            let mut grouped = if keys.is_empty() {
9584                std::collections::HashMap::new()
9585            } else {
9586                let sql = plan
9587                    .children_grouped_sql(ctx.max_rows, &child_columns)
9588                    .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9589
9590                let fetched = sqlx::query(AssertSqlSafe(sql))
9591                    .bind(&keys)
9592                    .fetch_all(&mut *conn)
9593                    .await
9594                    .map_err(database_error)?;
9595
9596                // The query returns the join key and a JSON array of that key's
9597                // children, grouped by PostgreSQL rather than row by row here.
9598                use sqlx::Row;
9599                let pairs: Vec<(serde_json::Value, serde_json::Value)> = fetched
9600                    .into_iter()
9601                    .filter_map(|row| {
9602                        Some((
9603                            row.try_get::<serde_json::Value, _>(0).ok()?,
9604                            row.try_get::<serde_json::Value, _>(1).ok()?,
9605                        ))
9606                    })
9607                    .collect();
9608
9609                postrust_core::embed::group_from_aggregated(pairs)
9610            };
9611
9612            // Recurse before attaching, so nested embeds land in the values
9613            // copied onto the parents. One query serves every child row at this
9614            // level, so the rows are flattened for the call and put back
9615            // afterwards; skipped when the selection asks for nothing deeper.
9616            let has_deeper_embed = ctx
9617                .relationships
9618                .get(&rel.target_type)
9619                .map(|rels| {
9620                    requested
9621                        .selection_set()
9622                        .any(|field| rels.iter().any(|r| r.name == field.name()))
9623                })
9624                .unwrap_or(false);
9625
9626            if has_deeper_embed {
9627                let mut order: Vec<(String, usize)> = Vec::with_capacity(grouped.len());
9628                let mut flat: Vec<serde_json::Value> = Vec::new();
9629                for (key, children) in grouped.drain() {
9630                    order.push((key, children.len()));
9631                    flat.extend(children);
9632                }
9633
9634                embed_relationships(&mut *conn, ctx, &rel.target_type, requested, &mut flat)
9635                    .await?;
9636
9637                let mut rest = flat.into_iter();
9638                for (key, count) in order {
9639                    grouped.insert(key, rest.by_ref().take(count).collect());
9640                }
9641            }
9642
9643            for row in rows.iter_mut() {
9644                postrust_core::embed::attach_to_parent(row, &rel.name, &plan, &grouped);
9645            }
9646        }
9647
9648        Ok(())
9649    })
9650}
9651
9652/// Build a `where` document that addresses exactly one row by primary key.
9653///
9654/// Used by the by-PK mutations, which take the key columns as arguments instead
9655/// of a free-form `where`.
9656fn pk_where_from_args(
9657    ctx: &ResolverContext<'_>,
9658    schema_name: &str,
9659    table_name: &str,
9660    pk_columns: &[(String, String)],
9661    names: &crate::names::NameOverrides,
9662) -> Result<serde_json::Value, async_graphql::Error> {
9663    if pk_columns.is_empty() {
9664        return Err(async_graphql::Error::new(format!(
9665            "\"{}\" has no primary key, so it cannot be mutated by key",
9666            table_name
9667        )));
9668    }
9669
9670    // `update_x_by_pk` takes its key as one `pk_columns` object; the others
9671    // take the key columns as arguments of their own. Both spellings are what
9672    // a client was generated against, so both are read here.
9673    let from_object = ctx
9674        .args
9675        .try_get("pk_columns")
9676        .ok()
9677        .map(|v| accessor_to_json(&v));
9678
9679    let mut conditions = serde_json::Map::new();
9680    for (col_name, _) in pk_columns {
9681        // Under the name the key column is exposed as, on both sides: the
9682        // argument the client wrote, and the predicate handed on to the same
9683        // builder every other `where` goes through.
9684        let field = names
9685            .column(schema_name, table_name, col_name)
9686            .unwrap_or(col_name);
9687        let value = match &from_object {
9688            Some(serde_json::Value::Object(map)) => map.get(field).cloned().ok_or_else(|| {
9689                async_graphql::Error::new(format!(
9690                    "pk_columns is missing the key column \"{}\"",
9691                    field
9692                ))
9693            })?,
9694            _ => {
9695                let arg = ctx.args.try_get(field).map_err(|_| {
9696                    async_graphql::Error::new(format!(
9697                        "missing required primary key argument \"{}\"",
9698                        field
9699                    ))
9700                })?;
9701                accessor_to_json(&arg)
9702            }
9703        };
9704        conditions.insert(field.to_string(), serde_json::json!({ "_eq": value }));
9705    }
9706
9707    Ok(serde_json::Value::Object(conditions))
9708}
9709
9710/// GraphQL scalar name to use for a primary key argument of the given
9711/// PostgreSQL type.
9712///
9713/// Falls back to `String` for anything that does not map to a plain scalar --
9714/// a composite or array key cannot be expressed as a single named argument, and
9715/// the value is cast to the column's type in SQL anyway.
9716fn pk_argument_type(pg_type: &str) -> String {
9717    let rendered = crate::types::pg_type_to_graphql(pg_type).to_string();
9718    if rendered.starts_with('[') {
9719        "String".to_string()
9720    } else {
9721        rendered
9722    }
9723}
9724
9725/// The public GraphQL type of a primary-key argument.
9726///
9727/// SQL execution still carries the PostgreSQL type beside the key and uses it
9728/// for casts and binding. This is only the schema-facing type.
9729fn exposed_pk_argument_type(
9730    names: &crate::names::NameOverrides,
9731    schema: &str,
9732    table: &str,
9733    column: &str,
9734    pg_type: &str,
9735) -> String {
9736    names
9737        .column_type(schema, table, column)
9738        .map(|given| given.to_string())
9739        .unwrap_or_else(|| pk_argument_type(pg_type))
9740}
9741
9742/// Convert a GraphQL type string to a TypeRef.
9743fn graphql_type_ref(type_str: &str) -> TypeRef {
9744    // Parse type string like "[Users!]!" or "String" or "Int!"
9745    let is_list = type_str.starts_with('[');
9746    let is_nn = type_str.ends_with('!');
9747
9748    // Strip outer modifiers: first the trailing !, then the brackets
9749    let inner = if is_list {
9750        let stripped = type_str
9751            .trim_end_matches('!') // Remove outer !
9752            .trim_start_matches('[') // Remove [
9753            .trim_end_matches(']'); // Remove ]
9754        stripped
9755    } else {
9756        type_str.trim_end_matches('!')
9757    };
9758
9759    let inner_nn = inner.ends_with('!');
9760    let base_type = inner.trim_end_matches('!');
9761
9762    if is_list {
9763        if is_nn {
9764            if inner_nn {
9765                TypeRef::named_nn_list_nn(base_type)
9766            } else {
9767                TypeRef::named_list_nn(base_type)
9768            }
9769        } else if inner_nn {
9770            TypeRef::named_nn_list(base_type)
9771        } else {
9772            TypeRef::named_list(base_type)
9773        }
9774    } else if is_nn {
9775        TypeRef::named_nn(base_type)
9776    } else {
9777        TypeRef::named(base_type)
9778    }
9779}
9780
9781/// The key serde_json wraps a number in when it is keeping its digits.
9782///
9783/// This crate reads `serde_json` with `arbitrary_precision`, so a PostgreSQL
9784/// `numeric` survives a round trip through JSON with every digit it had. The
9785/// cost is on the way in: a fractional number in a *variable* is deserialized
9786/// into async-graphql's own value type as a one-key object holding the text,
9787/// because the generic path cannot know it is looking at a number. Integers
9788/// are unaffected, which is why this went unnoticed until a shape arrived by
9789/// variable and every coordinate in it read as zero.
9790const NUMBER_AS_TEXT: &str = "$serde_json::private::Number";
9791
9792/// The number an arbitrary-precision wrapper is holding, if that is what this
9793/// object is.
9794fn number_kept_as_text(
9795    map: &serde_json::Map<String, serde_json::Value>,
9796) -> Option<serde_json::Value> {
9797    if map.len() != 1 {
9798        return None;
9799    }
9800    let text = map.get(NUMBER_AS_TEXT)?.as_str()?;
9801    serde_json::from_str::<serde_json::Value>(text)
9802        .ok()
9803        .filter(|value| value.is_number())
9804}
9805
9806/// The same, applied to a whole document that came in as one.
9807fn plain_numbers(value: serde_json::Value) -> serde_json::Value {
9808    match value {
9809        serde_json::Value::Object(map) => match number_kept_as_text(&map) {
9810            Some(number) => number,
9811            None => serde_json::Value::Object(
9812                map.into_iter()
9813                    .map(|(k, v)| (k, plain_numbers(v)))
9814                    .collect(),
9815            ),
9816        },
9817        serde_json::Value::Array(items) => {
9818            serde_json::Value::Array(items.into_iter().map(plain_numbers).collect())
9819        }
9820        other => other,
9821    }
9822}
9823
9824/// Convert ValueAccessor to JSON.
9825fn accessor_to_json(accessor: &ValueAccessor<'_>) -> serde_json::Value {
9826    // Use the deserialize method if available, or convert manually
9827    if accessor.is_null() {
9828        serde_json::Value::Null
9829    } else if let Ok(b) = accessor.boolean() {
9830        serde_json::Value::Bool(b)
9831    } else if let Ok(i) = accessor.i64() {
9832        serde_json::Value::Number(i.into())
9833    } else if let Ok(f) = accessor.f64() {
9834        serde_json::Number::from_f64(f)
9835            .map(serde_json::Value::Number)
9836            .unwrap_or(serde_json::Value::Null)
9837    } else if let Ok(s) = accessor.string() {
9838        serde_json::Value::String(s.to_string())
9839    } else if let Ok(name) = accessor.enum_name() {
9840        // An enum value is not a string to `string()`, and falling through to
9841        // null made every `order_by: {name: asc}` read as an empty direction.
9842        serde_json::Value::String(name.to_string())
9843    } else if let Ok(list) = accessor.list() {
9844        serde_json::Value::Array(list.iter().map(|v| accessor_to_json(&v)).collect())
9845    } else if let Ok(obj) = accessor.object() {
9846        let map: serde_json::Map<String, serde_json::Value> = obj
9847            .iter()
9848            .map(|(k, v)| (k.to_string(), accessor_to_json(&v)))
9849            .collect();
9850        match number_kept_as_text(&map) {
9851            Some(number) => number,
9852            None => serde_json::Value::Object(map),
9853        }
9854    } else {
9855        serde_json::Value::Null
9856    }
9857}
9858
9859/// Convert async-graphql Value to JSON.
9860fn value_to_json(value: &Value) -> serde_json::Value {
9861    match value {
9862        Value::Null => serde_json::Value::Null,
9863        Value::Boolean(b) => serde_json::Value::Bool(*b),
9864        Value::Number(n) => {
9865            if let Some(i) = n.as_i64() {
9866                serde_json::Value::Number(i.into())
9867            } else if let Some(f) = n.as_f64() {
9868                serde_json::Value::Number(serde_json::Number::from_f64(f).unwrap())
9869            } else {
9870                serde_json::Value::Null
9871            }
9872        }
9873        Value::String(s) => serde_json::Value::String(s.clone()),
9874        Value::List(arr) => serde_json::Value::Array(arr.iter().map(value_to_json).collect()),
9875        Value::Object(obj) => {
9876            let map: serde_json::Map<String, serde_json::Value> = obj
9877                .iter()
9878                .map(|(k, v)| (k.to_string(), value_to_json(v)))
9879                .collect();
9880            serde_json::Value::Object(map)
9881        }
9882        Value::Binary(b) => serde_json::Value::String(base64::Engine::encode(
9883            &base64::engine::general_purpose::STANDARD,
9884            b,
9885        )),
9886        Value::Enum(e) => serde_json::Value::String(e.to_string()),
9887    }
9888}
9889
9890/// Convert JSON to async-graphql Value.
9891fn json_to_value(json: serde_json::Value) -> Value {
9892    match json {
9893        serde_json::Value::Null => Value::Null,
9894        serde_json::Value::Bool(b) => Value::Boolean(b),
9895        serde_json::Value::Number(n) => {
9896            if let Some(i) = n.as_i64() {
9897                Value::Number(i.into())
9898            } else if let Some(f) = n.as_f64() {
9899                Value::Number(async_graphql::Number::from_f64(f).unwrap())
9900            } else {
9901                Value::Null
9902            }
9903        }
9904        serde_json::Value::String(s) => Value::String(s),
9905        serde_json::Value::Array(arr) => Value::List(arr.into_iter().map(json_to_value).collect()),
9906        serde_json::Value::Object(obj) => {
9907            let map: indexmap::IndexMap<async_graphql::Name, Value> = obj
9908                .into_iter()
9909                .map(|(k, v)| (async_graphql::Name::new(k), json_to_value(v)))
9910                .collect();
9911            Value::Object(map)
9912        }
9913    }
9914}
9915
9916/// Register filter input types.
9917///
9918/// These are currently unreachable: the `filter` and `where` arguments are
9919/// declared as the `JSON` scalar, so no field references these input objects
9920/// and async-graphql prunes them from the published schema (introspecting
9921/// `IntFilterInput` returns null). They are kept as the shape to move to if
9922/// filters become typed per column; until then the operators a filter actually
9923/// supports are the ones `build_where_clause` implements, and it rejects
9924/// anything else rather than ignoring it.
9925#[cfg(test)]
9926mod tests {
9927    use super::*;
9928    use indexmap::IndexMap;
9929    use postrust_core::schema_cache::{Cardinality, Column, Relationship, Table};
9930    use postrust_core::QualifiedIdentifier;
9931    use std::collections::{HashMap, HashSet};
9932
9933    fn entity_key_column(pg_type: &str, explicit_id: bool) -> EntityKeyColumn {
9934        EntityKeyColumn {
9935            field_name: "id".to_string(),
9936            column_name: "id".to_string(),
9937            pg_type: pg_type.to_string(),
9938            explicit_id,
9939        }
9940    }
9941
9942    #[test]
9943    fn federation_integer_keys_reject_strings() {
9944        let column = entity_key_column("int4", false);
9945
9946        assert_eq!(
9947            normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap(),
9948            serde_json::json!(2)
9949        );
9950        let error = normalize_entity_key_value("users", &column, &serde_json::json!("2"))
9951            .expect_err("a GraphQL Int cannot be a string");
9952        assert_eq!(
9953            error.message,
9954            "entity representation for \"users\" has invalid key field \"id\": expected a value compatible with PostgreSQL type \"int4\", found a string"
9955        );
9956    }
9957
9958    #[test]
9959    fn federation_bigint_keys_accept_exact_decimal_strings() {
9960        let column = entity_key_column("int8", false);
9961
9962        assert_eq!(
9963            normalize_entity_key_value("users", &column, &serde_json::json!(7)).unwrap(),
9964            serde_json::json!(7)
9965        );
9966        assert_eq!(
9967            normalize_entity_key_value("users", &column, &serde_json::json!("9007199254740993"))
9968                .unwrap(),
9969            serde_json::json!(9_007_199_254_740_993_i64)
9970        );
9971        assert!(normalize_entity_key_value(
9972            "users",
9973            &column,
9974            &serde_json::json!("9223372036854775808")
9975        )
9976        .is_err());
9977        assert!(normalize_entity_key_value("users", &column, &serde_json::json!("7.5")).is_err());
9978    }
9979
9980    #[test]
9981    fn federation_numeric_keys_accept_exact_decimal_strings() {
9982        let column = entity_key_column("numeric", false);
9983
9984        assert_eq!(
9985            normalize_entity_key_value("users", &column, &serde_json::json!(7.5)).unwrap(),
9986            serde_json::json!("7.5")
9987        );
9988        assert_eq!(
9989            normalize_entity_key_value(
9990                "users",
9991                &column,
9992                &serde_json::json!("9007199254740993.123456789")
9993            )
9994            .unwrap(),
9995            serde_json::json!("9007199254740993.123456789")
9996        );
9997        assert!(
9998            normalize_entity_key_value("users", &column, &serde_json::json!("not-a-number"))
9999                .is_err()
10000        );
10001    }
10002
10003    #[test]
10004    fn federation_integer_backed_ids_have_one_normal_form() {
10005        let column = entity_key_column("int4", true);
10006
10007        let number = normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap();
10008        let string = normalize_entity_key_value("users", &column, &serde_json::json!("2")).unwrap();
10009        assert_eq!(number, serde_json::json!(2));
10010        assert_eq!(string, number);
10011        assert!(normalize_entity_key_value("users", &column, &serde_json::json!("two")).is_err());
10012    }
10013
10014    #[test]
10015    fn federation_text_backed_ids_normalize_integer_input_to_text() {
10016        let column = entity_key_column("text", true);
10017
10018        let number = normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap();
10019        let string = normalize_entity_key_value("users", &column, &serde_json::json!("2")).unwrap();
10020        assert_eq!(number, serde_json::json!("2"));
10021        assert_eq!(string, number);
10022    }
10023
10024    #[test]
10025    fn federation_uuid_backed_ids_are_validated_and_canonicalized() {
10026        let column = entity_key_column("uuid", true);
10027
10028        assert_eq!(
10029            normalize_entity_key_value(
10030                "users",
10031                &column,
10032                &serde_json::json!("550E8400-E29B-41D4-A716-446655440000")
10033            )
10034            .unwrap(),
10035            serde_json::json!("550e8400-e29b-41d4-a716-446655440000")
10036        );
10037        assert!(
10038            normalize_entity_key_value("users", &column, &serde_json::json!("not-a-uuid")).is_err()
10039        );
10040    }
10041
10042    fn create_test_table(name: &str) -> Table {
10043        let mut columns = IndexMap::new();
10044        columns.insert(
10045            "id".into(),
10046            Column {
10047                name: "id".into(),
10048                description: None,
10049                nullable: false,
10050                data_type: "integer".into(),
10051                nominal_type: "int4".into(),
10052                max_len: None,
10053                default: Some("nextval('id_seq')".into()),
10054                enum_values: vec![],
10055                is_pk: true,
10056                position: 1,
10057                always_generated: false,
10058                domain_type: None,
10059            },
10060        );
10061        columns.insert(
10062            "name".into(),
10063            Column {
10064                name: "name".into(),
10065                description: None,
10066                nullable: false,
10067                data_type: "text".into(),
10068                nominal_type: "text".into(),
10069                max_len: None,
10070                default: None,
10071                enum_values: vec![],
10072                is_pk: false,
10073                position: 2,
10074                always_generated: false,
10075                domain_type: None,
10076            },
10077        );
10078
10079        Table {
10080            schema: "public".into(),
10081            name: name.into(),
10082            description: None,
10083            is_view: false,
10084            insertable: true,
10085            updatable: true,
10086            deletable: true,
10087            pk_cols: vec!["id".into()],
10088            unique_constraints: Vec::new(),
10089            columns,
10090            computed_columns: Default::default(),
10091            is_partitioned: false,
10092        }
10093    }
10094
10095    fn create_test_schema_cache() -> SchemaCache {
10096        let mut tables = HashMap::new();
10097        let users = create_test_table("users");
10098        tables.insert(users.qualified_identifier(), users);
10099
10100        SchemaCache {
10101            tables,
10102            relationships: HashMap::new(),
10103            routines: HashMap::new(),
10104            timezones: HashSet::new(),
10105            media_handlers: HashMap::new(),
10106            pg_version: 150000,
10107            representations: Default::default(),
10108        }
10109    }
10110
10111    fn add_test_table(cache: &mut SchemaCache, name: &str) {
10112        let table = create_test_table(name);
10113        cache.tables.insert(table.qualified_identifier(), table);
10114    }
10115
10116    fn add_test_posts_relationship(cache: &mut SchemaCache) {
10117        let users = QualifiedIdentifier::new("public", "users");
10118        cache.relationships.insert(
10119            (users.clone(), "public".into()),
10120            vec![Relationship::ForeignKey {
10121                table: users,
10122                foreign_table: QualifiedIdentifier::new("public", "posts"),
10123                is_self: false,
10124                cardinality: Cardinality::O2M {
10125                    constraint: "posts_user_id_fkey".into(),
10126                    columns: vec![("id".into(), "user_id".into())],
10127                },
10128                table_is_view: false,
10129                foreign_table_is_view: false,
10130                constraint_name: "posts_user_id_fkey".into(),
10131            }],
10132        );
10133    }
10134
10135    // ============================================================================
10136    // Type Reference Tests
10137    // ============================================================================
10138
10139    #[test]
10140    fn test_graphql_type_ref_simple() {
10141        let _type_ref = graphql_type_ref("String");
10142        // TypeRef doesn't implement PartialEq, so we just test it doesn't panic
10143    }
10144
10145    #[test]
10146    fn test_graphql_type_ref_non_null() {
10147        let _type_ref = graphql_type_ref("String!");
10148    }
10149
10150    #[test]
10151    fn test_graphql_type_ref_list() {
10152        let _type_ref = graphql_type_ref("[String]");
10153    }
10154
10155    #[test]
10156    fn test_graphql_type_ref_list_non_null() {
10157        let _type_ref = graphql_type_ref("[String!]!");
10158    }
10159
10160    // ============================================================================
10161    // Value Conversion Tests
10162    // ============================================================================
10163
10164    #[test]
10165    fn test_value_to_json_null() {
10166        let value = Value::Null;
10167        let json = value_to_json(&value);
10168        assert_eq!(json, serde_json::Value::Null);
10169    }
10170
10171    #[test]
10172    fn test_value_to_json_boolean() {
10173        let value = Value::Boolean(true);
10174        let json = value_to_json(&value);
10175        assert_eq!(json, serde_json::Value::Bool(true));
10176    }
10177
10178    #[test]
10179    fn test_value_to_json_number() {
10180        let value = Value::Number(42.into());
10181        let json = value_to_json(&value);
10182        assert_eq!(json, serde_json::json!(42));
10183    }
10184
10185    #[test]
10186    fn test_value_to_json_string() {
10187        let value = Value::String("hello".to_string());
10188        let json = value_to_json(&value);
10189        assert_eq!(json, serde_json::Value::String("hello".to_string()));
10190    }
10191
10192    #[test]
10193    fn test_value_to_json_list() {
10194        let value = Value::List(vec![Value::Number(1.into()), Value::Number(2.into())]);
10195        let json = value_to_json(&value);
10196        assert_eq!(json, serde_json::json!([1, 2]));
10197    }
10198
10199    #[test]
10200    fn test_json_to_value_null() {
10201        let json = serde_json::Value::Null;
10202        let value = json_to_value(json);
10203        assert!(matches!(value, Value::Null));
10204    }
10205
10206    #[test]
10207    fn test_json_to_value_boolean() {
10208        let json = serde_json::Value::Bool(false);
10209        let value = json_to_value(json);
10210        assert!(matches!(value, Value::Boolean(false)));
10211    }
10212
10213    #[test]
10214    fn test_json_to_value_number() {
10215        let json = serde_json::json!(123);
10216        let value = json_to_value(json);
10217        assert!(matches!(value, Value::Number(_)));
10218    }
10219
10220    #[test]
10221    fn test_json_to_value_string() {
10222        let json = serde_json::Value::String("test".to_string());
10223        let value = json_to_value(json);
10224        assert!(matches!(value, Value::String(_)));
10225    }
10226
10227    #[test]
10228    fn test_json_to_value_array() {
10229        let json = serde_json::json!([1, 2, 3]);
10230        let value = json_to_value(json);
10231        assert!(matches!(value, Value::List(_)));
10232    }
10233
10234    #[test]
10235    fn test_json_to_value_object() {
10236        let json = serde_json::json!({"key": "value"});
10237        let value = json_to_value(json);
10238        assert!(matches!(value, Value::Object(_)));
10239    }
10240
10241    // ============================================================================
10242    // Schema Building Tests
10243    // ============================================================================
10244
10245    #[test]
10246    fn test_build_dynamic_schema() {
10247        let cache = create_test_schema_cache();
10248        let config = SchemaConfig::default();
10249        let generated = build_schema(&cache, &config);
10250
10251        let result = build_dynamic_schema(
10252            &generated,
10253            &cache,
10254            None,
10255            None,
10256            Arc::new(Default::default()),
10257            std::time::Duration::from_secs(30),
10258            None,
10259        );
10260        if let Err(ref e) = result {
10261            eprintln!("Schema build error: {:?}", e);
10262        }
10263        assert!(result.is_ok(), "Schema build failed: {:?}", result.err());
10264    }
10265
10266    #[test]
10267    fn a_column_type_override_reaches_fields_and_key_arguments() {
10268        let cache = create_test_schema_cache();
10269        let names = crate::names::NameOverrides::parse(
10270            r#"{"tables": {"public.users": {"column_types": {"id": "ID"}}}}"#,
10271        )
10272        .unwrap();
10273        let config = SchemaConfig {
10274            names: names.clone(),
10275            ..SchemaConfig::default()
10276        };
10277        let generated = build_schema(&cache, &config);
10278        let schema = build_dynamic_schema(
10279            &generated,
10280            &cache,
10281            None,
10282            None,
10283            Arc::new(names),
10284            std::time::Duration::from_secs(30),
10285            None,
10286        )
10287        .expect("schema with an ID override should build");
10288        let sdl = schema.sdl();
10289
10290        let input_body = |name: &str| {
10291            sdl.split_once(&format!("input {name} {{"))
10292                .and_then(|(_, rest)| rest.split_once('}'))
10293                .map(|(body, _)| body.to_string())
10294                .unwrap_or_else(|| panic!("missing input {name}:\n{sdl}"))
10295        };
10296
10297        assert!(sdl.contains("id: ID!"), "object and input fields:\n{sdl}");
10298        assert!(
10299            sdl.contains("users_by_pk(id: ID!): users"),
10300            "query key argument:\n{sdl}"
10301        );
10302        assert!(
10303            sdl.contains("delete_users_by_pk(id: ID!): users"),
10304            "delete key argument:\n{sdl}"
10305        );
10306        assert!(
10307            input_body("users_pk_columns_input").contains("id: ID!"),
10308            "update key input:\n{sdl}"
10309        );
10310        assert!(
10311            input_body("users_bool_exp").contains("id: ID_comparison_exp"),
10312            "comparison input:\n{sdl}"
10313        );
10314        assert!(
10315            input_body("users_insert_input").contains("id: ID"),
10316            "write input:\n{sdl}"
10317        );
10318    }
10319
10320    #[test]
10321    fn a_type_prefix_names_the_complete_dynamic_schema() {
10322        let cache = create_test_schema_cache();
10323        let config = SchemaConfig {
10324            type_prefix: Some("test".into()),
10325            ..SchemaConfig::default()
10326        };
10327        let generated = build_schema(&cache, &config);
10328        let schema = build_dynamic_schema(
10329            &generated,
10330            &cache,
10331            None,
10332            None,
10333            Arc::new(Default::default()),
10334            std::time::Duration::from_secs(30),
10335            None,
10336        )
10337        .expect("a prefixed schema should build");
10338        let sdl = schema.sdl();
10339
10340        assert!(sdl.contains("type test_users "), "object type:\n{sdl}");
10341        assert!(sdl.contains("test_users("), "query root:\n{sdl}");
10342        assert!(sdl.contains("test_users_by_pk("), "by-PK root:\n{sdl}");
10343        assert!(sdl.contains("test_users_bool_exp"), "derived input:\n{sdl}");
10344        assert!(
10345            sdl.contains("test_users_aggregate"),
10346            "aggregate type:\n{sdl}"
10347        );
10348        assert!(sdl.contains("test_insert_users("), "mutation root:\n{sdl}");
10349    }
10350
10351    #[test]
10352    fn federation_is_absent_by_default() {
10353        let cache = create_test_schema_cache();
10354        let generated = build_schema(&cache, &SchemaConfig::default());
10355        let schema = build_dynamic_schema(
10356            &generated,
10357            &cache,
10358            None,
10359            None,
10360            Arc::new(Default::default()),
10361            std::time::Duration::from_secs(30),
10362            None,
10363        )
10364        .expect("a non-federated schema should build");
10365        let sdl = schema.sdl();
10366
10367        assert!(!sdl.contains("_Service"), "service type:\n{sdl}");
10368        assert!(!sdl.contains("_service"), "service field:\n{sdl}");
10369        assert!(!sdl.contains("@key"), "federation key:\n{sdl}");
10370    }
10371
10372    #[test]
10373    fn federation_entity_selections_respect_fragment_type_conditions() {
10374        let document = async_graphql::parser::parse_query(
10375            r#"
10376            query {
10377              _entities(representations: []) {
10378                __typename
10379                ... on authors { id items { title } }
10380                ...ShopFields
10381                ... { common }
10382                ...EntityName
10383              }
10384            }
10385            fragment ShopFields on shops { id items { sku } }
10386            fragment EntityName on _Entity { __typename }
10387            "#,
10388        )
10389        .expect("query parses");
10390        let (_, operation) = document.operations.iter().next().expect("one operation");
10391        let entity = operation
10392            .node
10393            .selection_set
10394            .node
10395            .items
10396            .iter()
10397            .find_map(|selection| match &selection.node {
10398                Selection::Field(field) if field.node.name.node == "_entities" => Some(&field.node),
10399                _ => None,
10400            })
10401            .expect("_entities field");
10402
10403        assert_eq!(
10404            entity_field_applicability(&entity.selection_set.node, &document.fragments, "authors"),
10405            vec![true, true, true, false, false, true, true]
10406        );
10407        assert_eq!(
10408            entity_field_applicability(&entity.selection_set.node, &document.fragments, "shops"),
10409            vec![true, false, false, true, true, true, true]
10410        );
10411    }
10412
10413    #[tokio::test]
10414    async fn federation_entity_lists_allow_null_members() {
10415        let entity =
10416            Object::new("widgets").field(Field::new("id", TypeRef::named_nn(TypeRef::INT), |_| {
10417                FieldFuture::new(async { Ok(Some(Value::from(2))) })
10418            }));
10419        let union = Union::new("_Entity").possible_type("widgets");
10420        let query = Object::new("Query").field(Field::new(
10421            "_entities",
10422            TypeRef::named_list_nn("_Entity"),
10423            |_| {
10424                FieldFuture::new(async {
10425                    Ok(Some(FieldValue::list([
10426                        FieldValue::NULL,
10427                        FieldValue::NULL.with_type("widgets"),
10428                    ])))
10429                })
10430            },
10431        ));
10432        let schema = Schema::build("Query", None, None)
10433            .extension(NullableFederationEntity)
10434            .register(entity)
10435            .register(union)
10436            .register(query)
10437            .finish()
10438            .expect("schema builds");
10439
10440        let response = schema
10441            .execute("{ _entities { ... on widgets { id } } }")
10442            .await;
10443
10444        assert!(response.errors.is_empty(), "{:?}", response.errors);
10445        assert_eq!(
10446            response.data,
10447            async_graphql::value!({ "_entities": [null, { "id": 2 }] })
10448        );
10449    }
10450
10451    #[test]
10452    fn federation_metadata_is_byte_for_byte_inert_when_disabled() {
10453        let cache = create_test_schema_cache();
10454        let sdl_for = |config: SchemaConfig| {
10455            let generated = build_schema(&cache, &config);
10456            build_dynamic_schema(
10457                &generated,
10458                &cache,
10459                None,
10460                None,
10461                Arc::new(config.names.clone()),
10462                std::time::Duration::from_secs(30),
10463                None,
10464            )
10465            .expect("schema should build")
10466            .sdl()
10467        };
10468
10469        let baseline = sdl_for(SchemaConfig {
10470            type_prefix: Some("test".into()),
10471            ..SchemaConfig::default()
10472        });
10473        let with_disabled_federation_metadata = sdl_for(SchemaConfig {
10474            enable_federation: false,
10475            type_prefix: Some("test".into()),
10476            names: crate::names::NameOverrides::parse(
10477                r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10478            )
10479            .expect("metadata"),
10480            ..SchemaConfig::default()
10481        });
10482
10483        assert_eq!(with_disabled_federation_metadata, baseline);
10484        assert!(
10485            with_disabled_federation_metadata.contains("type test_users "),
10486            "prefixed object type remains when federation is disabled:\n{with_disabled_federation_metadata}"
10487        );
10488        assert!(
10489            !with_disabled_federation_metadata.contains("_Service"),
10490            "service type:\n{with_disabled_federation_metadata}"
10491        );
10492        assert!(
10493            !with_disabled_federation_metadata.contains("@key"),
10494            "federation key:\n{with_disabled_federation_metadata}"
10495        );
10496    }
10497
10498    #[test]
10499    fn shared_entities_make_relationship_fields_shareable() {
10500        let federation_sdl = |shared: bool| {
10501            let mut cache = create_test_schema_cache();
10502            add_test_table(&mut cache, "posts");
10503            add_test_posts_relationship(&mut cache);
10504            let names = match shared {
10505                true => crate::names::NameOverrides::parse(
10506                    r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10507                )
10508                .expect("metadata"),
10509                false => crate::names::NameOverrides::default(),
10510            };
10511            let config = SchemaConfig {
10512                enable_federation: true,
10513                type_prefix: Some("test".into()),
10514                names: names.clone(),
10515                ..SchemaConfig::default()
10516            };
10517            let generated = build_schema(&cache, &config);
10518            build_dynamic_schema(
10519                &generated,
10520                &cache,
10521                None,
10522                None,
10523                Arc::new(names),
10524                std::time::Duration::from_secs(30),
10525                None,
10526            )
10527            .expect("federated schema should build")
10528            .sdl_with_options(async_graphql::SDLExportOptions::new().federation())
10529        };
10530
10531        let shared = federation_sdl(true);
10532        assert!(
10533            shared.contains("): [test_posts!]! @shareable"),
10534            "shared relationship field:\n{shared}"
10535        );
10536        assert!(
10537            shared.contains("): test_posts_aggregate! @shareable"),
10538            "shared relationship aggregate field:\n{shared}"
10539        );
10540
10541        let not_shared = federation_sdl(false);
10542        assert!(
10543            not_shared.contains("): [test_posts!]!"),
10544            "non-shared relationship field:\n{not_shared}"
10545        );
10546        assert!(
10547            !not_shared.contains("): [test_posts!]! @shareable"),
10548            "non-shared relationship field must not be shareable:\n{not_shared}"
10549        );
10550        assert!(
10551            not_shared.contains("): test_posts_aggregate!"),
10552            "non-shared relationship aggregate field:\n{not_shared}"
10553        );
10554        assert!(
10555            !not_shared.contains("): test_posts_aggregate! @shareable"),
10556            "non-shared relationship aggregate must not be shareable:\n{not_shared}"
10557        );
10558    }
10559
10560    #[tokio::test]
10561    async fn federation_exposes_service_sdl_and_entity_keys() {
10562        let mut cache = create_test_schema_cache();
10563        add_test_table(&mut cache, "posts");
10564        let config = SchemaConfig {
10565            enable_federation: true,
10566            type_prefix: Some("test".into()),
10567            names: crate::names::NameOverrides::parse(
10568                r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10569            )
10570            .expect("metadata"),
10571            ..SchemaConfig::default()
10572        };
10573        let generated = build_schema(&cache, &config);
10574        let schema = build_dynamic_schema(
10575            &generated,
10576            &cache,
10577            None,
10578            None,
10579            Arc::new(Default::default()),
10580            std::time::Duration::from_secs(30),
10581            None,
10582        )
10583        .expect("a federated schema should build");
10584        let sdl = schema.sdl();
10585        let federation_sdl =
10586            schema.sdl_with_options(async_graphql::SDLExportOptions::new().federation());
10587
10588        assert!(sdl.contains("_Service"), "service type:\n{sdl}");
10589        assert!(sdl.contains("_service"), "service field:\n{sdl}");
10590        assert!(
10591            federation_sdl.contains("type users @key(fields: \"id\") @shareable"),
10592            "users key and type-level @shareable:\n{federation_sdl}"
10593        );
10594        assert!(
10595            federation_sdl.contains("@shareable"),
10596            "shared field directive:\n{federation_sdl}"
10597        );
10598        assert!(sdl.contains("type users "), "shared object type:\n{sdl}");
10599        assert!(
10600            !sdl.contains("type test_users "),
10601            "prefixed shared object type:\n{sdl}"
10602        );
10603        assert!(sdl.contains("test_users("), "query root:\n{sdl}");
10604        assert!(sdl.contains("test_users_by_pk("), "by-PK root:\n{sdl}");
10605        assert!(sdl.contains("test_users_bool_exp"), "derived input:\n{sdl}");
10606        assert!(
10607            !sdl.contains("input users_bool_exp "),
10608            "unprefixed derived input:\n{sdl}"
10609        );
10610        assert!(
10611            sdl.contains("test_users_aggregate"),
10612            "aggregate type:\n{sdl}"
10613        );
10614        assert!(
10615            !sdl.contains("type users_aggregate "),
10616            "unprefixed aggregate type:\n{sdl}"
10617        );
10618        assert!(
10619            sdl.contains("test_users_mutation_response"),
10620            "mutation response type:\n{sdl}"
10621        );
10622        assert!(
10623            !sdl.contains("type users_mutation_response "),
10624            "unprefixed mutation response type:\n{sdl}"
10625        );
10626        assert!(
10627            sdl.contains("type test_posts {"),
10628            "non-shared object type remains prefixed:\n{sdl}"
10629        );
10630        assert!(
10631            !sdl.contains("type posts {"),
10632            "non-shared object type must not become unprefixed:\n{sdl}"
10633        );
10634        assert!(sdl.contains("test_posts("), "prefixed posts root:\n{sdl}");
10635        assert!(
10636            sdl.contains("test_posts_bool_exp"),
10637            "prefixed posts bool_exp:\n{sdl}"
10638        );
10639
10640        let response = schema.execute("{ _service { sdl } }").await;
10641        assert!(
10642            response.errors.is_empty(),
10643            "service query errors: {:?}",
10644            response.errors
10645        );
10646        let service = response.data.into_json().expect("service response JSON");
10647        let service_sdl = service
10648            .get("_service")
10649            .and_then(|value| value.get("sdl"))
10650            .and_then(serde_json::Value::as_str)
10651            .expect("service SDL string");
10652        assert!(
10653            service_sdl.contains("type Query"),
10654            "federation root type:\n{service_sdl}"
10655        );
10656        assert!(
10657            service_sdl.contains("test_users("),
10658            "query fields are on the federation root:\n{service_sdl}"
10659        );
10660        assert!(
10661            service_sdl.contains("test_posts("),
10662            "non-shared query fields are on the federation root:\n{service_sdl}"
10663        );
10664        assert!(
10665            !service_sdl.contains("type query_root"),
10666            "Apollo composition treats query_root as an ordinary object without a schema definition:\n{service_sdl}"
10667        );
10668        assert!(
10669            service_sdl.contains("type users @key(fields: \"id\")"),
10670            "{service_sdl}"
10671        );
10672        assert!(
10673            service_sdl.contains("type test_posts @key(fields: \"id\")"),
10674            "{service_sdl}"
10675        );
10676    }
10677
10678    /// `_exists` becomes a subselect over the table it names, correlated with
10679    /// nothing -- which is the difference between it and a relationship.
10680    #[test]
10681    fn exists_is_a_subselect_over_another_table() {
10682        let cache = create_test_schema_cache();
10683        let names = crate::names::NameOverrides::default();
10684        let relationships: HashMap<String, Vec<RelationshipField>> = HashMap::new();
10685        let scope = WhereScope::table("public", "users", "users", &names)
10686            .with_resolution(&cache, &relationships);
10687
10688        let mut param_idx = 1usize;
10689        let mut values: Vec<serde_json::Value> = Vec::new();
10690        let mut aliases = 0usize;
10691        let sql = build_condition(
10692            &serde_json::json!({
10693                "_exists": {"_table": "users", "_where": {"name": {"_eq": "Ann"}}}
10694            }),
10695            &scope,
10696            &mut param_idx,
10697            &mut values,
10698            &mut aliases,
10699        )
10700        .expect("compiles")
10701        .expect("constrains something");
10702
10703        assert_eq!(
10704            sql,
10705            "EXISTS (SELECT 1 FROM \"public\".\"users\" AS \"pgrst_exists_1\" \
10706             WHERE \"pgrst_exists_1\".\"name\" = $1::text)"
10707        );
10708        assert_eq!(values, vec![serde_json::json!("Ann")]);
10709    }
10710
10711    /// A `_table` nobody has is refused rather than written into the query.
10712    #[test]
10713    fn exists_names_a_table_the_server_has() {
10714        let cache = create_test_schema_cache();
10715        let names = crate::names::NameOverrides::default();
10716        let relationships: HashMap<String, Vec<RelationshipField>> = HashMap::new();
10717        let scope = WhereScope::table("public", "users", "users", &names)
10718            .with_resolution(&cache, &relationships);
10719        let error = build_condition(
10720            &serde_json::json!({"_exists": {"_table": "nowhere", "_where": {}}}),
10721            &scope,
10722            &mut 1,
10723            &mut Vec::new(),
10724            &mut 0,
10725        )
10726        .expect_err("a table that is not there is an error");
10727        assert!(
10728            error.message.contains("public.nowhere"),
10729            "{}",
10730            error.message
10731        );
10732    }
10733
10734    /// A role granted "how many" and not "which" gets the count and no rows.
10735    ///
10736    /// A select permission naming no columns, with `allow_aggregations`, is
10737    /// Hasura's way of writing that. The table has an aggregate root and no
10738    /// row type, so `nodes` is not there to be a list of one -- and `count`
10739    /// takes no `columns`, because there are none to name.
10740    #[test]
10741    fn a_table_a_role_may_count_and_not_read_has_a_count_and_no_rows() {
10742        let cache = create_test_schema_cache();
10743        let names = crate::names::NameOverrides::parse(
10744            r#"{"tables": {"public.users": {"permissions":
10745                 {"counter": {"select": {"columns": [], "filter": {},
10746                                         "allow_aggregations": true}}}}}}"#,
10747        )
10748        .unwrap();
10749        let view = crate::role::cache_for_role(&cache, &names, "counter", false);
10750        assert!(!view.tables.is_empty(), "the table is there to be counted");
10751
10752        let config = SchemaConfig {
10753            names: names.clone(),
10754            role: Some("counter".to_string()),
10755            ..SchemaConfig::default()
10756        };
10757        let generated = build_schema(&view, &config);
10758        let schema = build_dynamic_schema(
10759            &generated,
10760            &view,
10761            None,
10762            None,
10763            Arc::new(names),
10764            std::time::Duration::from_secs(30),
10765            Some("counter"),
10766        )
10767        .expect("a role that may only count still has a buildable schema");
10768        let sdl = schema.sdl();
10769
10770        assert!(
10771            sdl.contains("users_aggregate"),
10772            "the count is there:\n{}",
10773            sdl
10774        );
10775        assert!(sdl.contains("count: Int!"), "and it is a count:\n{}", sdl);
10776        // No row type, so nothing that would answer with one.
10777        assert!(!sdl.contains("type users "), "no row type:\n{}", sdl);
10778        assert!(
10779            !sdl.contains("nodes"),
10780            "and no rows beside the numbers:\n{}",
10781            sdl
10782        );
10783        assert!(
10784            !sdl.contains("users_select_column"),
10785            "no column enum to order by or count over:\n{}",
10786            sdl
10787        );
10788        // The functions that read column data are absent with the columns.
10789        assert!(!sdl.contains("users_max_fields"), "no max:\n{}", sdl);
10790    }
10791
10792    /// A role granted `insert` and no `select` gets the write and no type.
10793    ///
10794    /// Hasura's own corpus does this eight times over. What has to hold is
10795    /// that the schema still builds: `insert_users` is there, `users` is not,
10796    /// and the response the insert answers with has no `returning` to name a
10797    /// type that does not exist.
10798    #[test]
10799    fn a_table_a_role_may_only_write_gets_the_write_and_no_type() {
10800        let cache = create_test_schema_cache();
10801        let names = crate::names::NameOverrides::parse(
10802            r#"{"tables": {"public.users": {"permissions":
10803                 {"writer": {"insert": {"columns": "*", "check": {}}}}}}}"#,
10804        )
10805        .unwrap();
10806        let view = crate::role::cache_for_role(&cache, &names, "writer", false);
10807        let config = SchemaConfig {
10808            names: names.clone(),
10809            role: Some("writer".to_string()),
10810            ..SchemaConfig::default()
10811        };
10812        let generated = build_schema(&view, &config);
10813
10814        let schema = build_dynamic_schema(
10815            &generated,
10816            &view,
10817            None,
10818            None,
10819            Arc::new(names),
10820            std::time::Duration::from_secs(30),
10821            Some("writer"),
10822        )
10823        .expect("a role that may only write still has a buildable schema");
10824        let sdl = schema.sdl();
10825
10826        assert!(
10827            sdl.contains("insert_users("),
10828            "the write is there:\n{}",
10829            sdl
10830        );
10831        assert!(
10832            sdl.contains("users_insert_input"),
10833            "and its input:\n{}",
10834            sdl
10835        );
10836        // No row type, and so none of the three fields that answer with one.
10837        assert!(!sdl.contains("type users "), "no row type:\n{}", sdl);
10838        assert!(!sdl.contains("insert_users_one"), "no insert_one:\n{}", sdl);
10839        assert!(
10840            !sdl.contains("returning"),
10841            "and nothing to return:\n{}",
10842            sdl
10843        );
10844        assert!(
10845            sdl.contains("users_mutation_response"),
10846            "the count is still answered:\n{}",
10847            sdl
10848        );
10849        assert!(
10850            !sdl.contains("_mutation_response_mutation_response"),
10851            "and no type is named twice over:\n{}",
10852            sdl
10853        );
10854    }
10855
10856    /// A cache with one VOLATILE function returning rows of `users`, which is
10857    /// the shape `add_to_score` has in Hasura's corpus.
10858    fn cache_with_a_mutation_function() -> SchemaCache {
10859        use postrust_core::schema_cache::{FuncVolatility, RetType, Routine};
10860
10861        let mut cache = create_test_schema_cache();
10862        let routine = Routine {
10863            schema: "public".into(),
10864            name: "add_to_score".into(),
10865            description: None,
10866            params: Vec::new(),
10867            return_type: RetType::SetOf("users".into()),
10868            returns_composite: true,
10869            volatility: FuncVolatility::Volatile,
10870            has_variadic: false,
10871            isolation_level: None,
10872            settings: Vec::new(),
10873            is_procedure: false,
10874            media_type: None,
10875            media_base_type: None,
10876            output_columns: Vec::new(),
10877        };
10878        cache
10879            .routines
10880            .insert(routine.qualified_identifier(), vec![routine]);
10881        cache
10882    }
10883
10884    /// A function with side effects is not granted by permission to read the
10885    /// table it returns. Hasura infers a query function's permission from
10886    /// that select and infers nothing for a mutation, so a role never named
10887    /// by a function permission has no mutation root at all.
10888    #[test]
10889    fn a_mutation_function_needs_the_role_to_be_named() {
10890        let cache = cache_with_a_mutation_function();
10891        let withheld = crate::names::NameOverrides::parse(
10892            r#"{"tables": {"public.users": {"permissions":
10893                 {"reader": {"select": {"columns": "*", "filter": {}}}}}},
10894                "functions": {"public.add_to_score": {"exposed_as": "mutation"}}}"#,
10895        )
10896        .unwrap();
10897        let granted = crate::names::NameOverrides::parse(
10898            r#"{"tables": {"public.users": {"permissions":
10899                 {"reader": {"select": {"columns": "*", "filter": {}}}}}},
10900                "functions": {"public.add_to_score":
10901                  {"exposed_as": "mutation", "roles": ["reader"]}}}"#,
10902        )
10903        .unwrap();
10904
10905        let sdl_for = |names: &crate::names::NameOverrides| {
10906            let view = crate::role::cache_for_role(&cache, names, "reader", false);
10907            let config = SchemaConfig {
10908                names: names.clone(),
10909                role: Some("reader".to_string()),
10910                ..SchemaConfig::default()
10911            };
10912            let generated = build_schema(&view, &config);
10913            build_dynamic_schema(
10914                &generated,
10915                &view,
10916                None,
10917                None,
10918                Arc::new(names.clone()),
10919                std::time::Duration::from_secs(30),
10920                Some("reader"),
10921            )
10922            .expect("schema builds")
10923            .sdl()
10924        };
10925
10926        let without = sdl_for(&withheld);
10927        assert!(
10928            !without.contains("add_to_score"),
10929            "not granted, so not there:\n{}",
10930            without
10931        );
10932        // And with no mutation of any kind left, there is no mutation root --
10933        // which is what `no mutations exist` is answered from.
10934        assert!(
10935            !without.contains("mutation: mutation_root"),
10936            "and no mutation root at all:\n{}",
10937            without
10938        );
10939
10940        let with = sdl_for(&granted);
10941        assert!(
10942            with.contains("add_to_score"),
10943            "named by a function permission, so it is:\n{}",
10944            with
10945        );
10946    }
10947
10948    /// An unrecognised role is a role that was granted nothing, not an error.
10949    #[test]
10950    fn a_role_the_document_never_names_is_granted_nothing() {
10951        let cache = Arc::new(create_test_schema_cache());
10952        let config = SchemaConfig {
10953            names: crate::names::NameOverrides::parse(
10954                r#"{"tables": {"public.users": {"permissions":
10955                     {"reader": {"select": {"columns": "*", "filter": {}}}}}}}"#,
10956            )
10957            .unwrap(),
10958            ..SchemaConfig::default()
10959        };
10960        let empty = build_ungranted_schema(&cache, &config).expect("it builds");
10961        let sdl = empty.sdl();
10962        assert!(
10963            sdl.contains("no_queries_available"),
10964            "nothing to read:\n{}",
10965            sdl
10966        );
10967        assert!(!sdl.contains("type users "), "and no table:\n{}", sdl);
10968        // A document with no permissions at all has no unrecognised roles.
10969        assert!(build_ungranted_schema(&cache, &SchemaConfig::default()).is_none());
10970    }
10971
10972    /// A column the role may write and not read is in the input and not in the
10973    /// type. The two column sets are the point: one schema cache, two answers.
10974    #[test]
10975    fn a_column_a_role_may_set_without_seeing_is_in_the_input_alone() {
10976        let cache = create_test_schema_cache();
10977        let names = crate::names::NameOverrides::parse(
10978            r#"{"tables": {"public.users": {"permissions":
10979                 {"user": {"select": {"columns": ["id"], "filter": {}},
10980                           "insert": {"columns": "*", "check": {}}}}}}}"#,
10981        )
10982        .unwrap();
10983        let view = crate::role::cache_for_role(&cache, &names, "user", false);
10984        let config = SchemaConfig {
10985            names: names.clone(),
10986            role: Some("user".to_string()),
10987            ..SchemaConfig::default()
10988        };
10989        let generated = build_schema(&view, &config);
10990        let object = &generated.object_types["users"];
10991        assert_eq!(
10992            object
10993                .fields
10994                .iter()
10995                .map(|f| f.name.as_str())
10996                .collect::<Vec<_>>(),
10997            vec!["id"],
10998            "the type shows what may be read"
10999        );
11000        assert!(
11001            object.writable_fields.iter().any(|f| f.name == "name"),
11002            "and the input keeps what may be written"
11003        );
11004
11005        let schema = build_dynamic_schema(
11006            &generated,
11007            &view,
11008            None,
11009            None,
11010            Arc::new(names),
11011            std::time::Duration::from_secs(30),
11012            Some("user"),
11013        )
11014        .expect("schema builds");
11015        let sdl = schema.sdl();
11016        let input = sdl
11017            .split("input users_insert_input")
11018            .nth(1)
11019            .and_then(|rest| rest.split('}').next())
11020            .expect("the insert input is registered");
11021        assert!(input.contains("name:"), "settable without being readable");
11022    }
11023
11024    /// A column PostgreSQL generates always is in the row type and in no
11025    /// write input. It is not a permission -- no role may name it -- so the
11026    /// refusal belongs to the schema rather than to the database.
11027    #[test]
11028    fn a_generated_column_is_readable_and_not_writable() {
11029        let mut cache = create_test_schema_cache();
11030        cache
11031            .tables
11032            .get_mut(&postrust_core::api_request::QualifiedIdentifier::new(
11033                "public", "users",
11034            ))
11035            .expect("the fixture has users")
11036            .columns
11037            .get_mut("id")
11038            .expect("with an id")
11039            .always_generated = true;
11040
11041        let names = crate::names::NameOverrides::default();
11042        let config = SchemaConfig {
11043            names: names.clone(),
11044            ..SchemaConfig::default()
11045        };
11046        let generated = build_schema(&cache, &config);
11047        let schema = build_dynamic_schema(
11048            &generated,
11049            &cache,
11050            None,
11051            None,
11052            Arc::new(names),
11053            std::time::Duration::from_secs(30),
11054            None,
11055        )
11056        .expect("schema builds");
11057        let sdl = schema.sdl();
11058
11059        let block = |header: &str| {
11060            sdl.split(header)
11061                .nth(1)
11062                .and_then(|rest| rest.split('}').next())
11063                .unwrap_or_else(|| panic!("{} is registered:\n{}", header, sdl))
11064                .to_string()
11065        };
11066        assert!(
11067            block("type users ").contains("id:"),
11068            "still readable:\n{}",
11069            sdl
11070        );
11071        for header in ["input users_insert_input", "input users_set_input"] {
11072            assert!(
11073                !block(header).contains("id:"),
11074                "{} may not name it:\n{}",
11075                header,
11076                block(header)
11077            );
11078        }
11079        // The table's only number was the generated column, so there is
11080        // nothing left to add to and no type for adding to it.
11081        assert!(
11082            !sdl.contains("users_inc_input"),
11083            "and nothing is left to increment:\n{}",
11084            sdl
11085        );
11086        assert!(
11087            block("input users_insert_input").contains("name:"),
11088            "and the rest of the table is untouched",
11089        );
11090    }
11091
11092    #[test]
11093    fn test_create_object_type() {
11094        let table = create_test_table("users");
11095        let obj = TableObjectType::from_table(&table);
11096        let _gql_obj = create_object_type(&obj, &[], None);
11097    }
11098
11099    #[test]
11100    fn test_create_query_type() {
11101        let cache = create_test_schema_cache();
11102        let config = SchemaConfig::default();
11103        let generated = build_schema(&cache, &config);
11104
11105        let _query = create_query_type(
11106            &generated,
11107            "query_root",
11108            None,
11109            Arc::new(HashMap::new()),
11110            Arc::new(Default::default()),
11111        );
11112    }
11113
11114    #[test]
11115    fn test_create_mutation_type() {
11116        let cache = create_test_schema_cache();
11117        let config = SchemaConfig::default();
11118        let generated = build_schema(&cache, &config);
11119
11120        let _mutation = create_mutation_type(
11121            &generated,
11122            "mutation_root",
11123            Arc::new(HashMap::new()),
11124            Arc::new(HashMap::new()),
11125            Arc::new(Default::default()),
11126            None,
11127            None,
11128        );
11129    }
11130
11131    // ============================================================================
11132    // Scalar Tests
11133    // ============================================================================
11134
11135    #[test]
11136    fn a_scalar_is_named_the_way_a_client_declares_it() {
11137        use crate::types::{pg_type_to_graphql, GraphQLType};
11138
11139        // These names appear in the client's own queries -- `query ($x:
11140        // jsonb!)` names a type that has to exist under exactly that
11141        // spelling -- so they are asserted rather than left to the Display
11142        // impl.
11143        assert_eq!(pg_type_to_graphql("jsonb").to_string(), "jsonb");
11144        assert_eq!(pg_type_to_graphql("json").to_string(), "json");
11145        assert_eq!(pg_type_to_graphql("int8").to_string(), "bigint");
11146        assert_eq!(pg_type_to_graphql("numeric").to_string(), "numeric");
11147        assert_eq!(pg_type_to_graphql("timestamptz").to_string(), "timestamptz");
11148        assert_eq!(pg_type_to_graphql("timestamp").to_string(), "timestamp");
11149        assert_eq!(pg_type_to_graphql("uuid").to_string(), "uuid");
11150
11151        // A type this server knows nothing about keeps its own name, which is
11152        // how a PostGIS column and a database enum both become usable.
11153        assert_eq!(pg_type_to_graphql("geometry").to_string(), "geometry");
11154        assert_eq!(
11155            pg_type_to_graphql("colors_enum"),
11156            GraphQLType::Custom("colors_enum".to_string())
11157        );
11158
11159        // And the leaf of an array is what gets registered, not the array.
11160        assert_eq!(
11161            leaf_scalar_name(&pg_type_to_graphql("_text")),
11162            "String".to_string()
11163        );
11164    }
11165
11166    // ============================================================================
11167    // Filter Input Type Tests
11168    // ============================================================================
11169
11170    #[test]
11171    fn every_table_gets_a_boolean_expression() {
11172        let cache = create_test_schema_cache();
11173        let config = SchemaConfig::default();
11174        let generated = build_schema(&cache, &config);
11175
11176        let (inputs, _) = crate::input::bool_exp::build_inputs(
11177            &generated.object_types,
11178            &generated.relationship_fields,
11179        );
11180        let names: HashSet<String> = inputs.iter().map(|i| i.type_name().to_string()).collect();
11181
11182        for table in generated.object_types.keys() {
11183            let expected = format!("{}_bool_exp", table);
11184            assert!(
11185                names.contains(&expected),
11186                "no {} among {:?}",
11187                expected,
11188                names
11189            );
11190        }
11191        // The scalars the fixture's columns use.
11192        assert!(names.contains("String_comparison_exp"));
11193        assert!(names.contains("Int_comparison_exp"));
11194    }
11195
11196    #[test]
11197    fn a_schema_carrying_the_boolean_expressions_still_builds() {
11198        let cache = create_test_schema_cache();
11199        let config = SchemaConfig::default();
11200        let generated = build_schema(&cache, &config);
11201
11202        let schema = build_dynamic_schema(
11203            &generated,
11204            &cache,
11205            None,
11206            None,
11207            Arc::new(Default::default()),
11208            std::time::Duration::from_secs(30),
11209            None,
11210        );
11211        assert!(schema.is_ok(), "{:?}", schema.err());
11212
11213        let sdl = schema.unwrap().sdl();
11214        assert!(
11215            sdl.contains("_bool_exp"),
11216            "no boolean expressions in:\n{}",
11217            sdl
11218        );
11219        assert!(sdl.contains("_and"), "no _and in the generated expressions");
11220    }
11221
11222    // ============================================================================
11223    // Subscription Tests
11224    // ============================================================================
11225
11226    #[test]
11227    fn test_build_schema_with_subscriptions() {
11228        let cache = create_test_schema_cache();
11229        let config = SchemaConfig {
11230            enable_subscriptions: true,
11231            ..SchemaConfig::default()
11232        };
11233        let generated = build_schema(&cache, &config);
11234
11235        // Generate subscription fields
11236        let sub_fields = generate_subscription_fields(&cache, &generated);
11237        assert!(!sub_fields.is_empty(), "Should have subscription fields");
11238
11239        // Build schema with subscriptions
11240        let result = build_dynamic_schema(
11241            &generated,
11242            &cache,
11243            Some(&sub_fields),
11244            None,
11245            Arc::new(Default::default()),
11246            std::time::Duration::from_secs(30),
11247            None,
11248        );
11249        assert!(result.is_ok(), "Schema with subscriptions should build");
11250    }
11251
11252    #[test]
11253    fn test_subscription_field_generation() {
11254        let cache = create_test_schema_cache();
11255        let config = SchemaConfig::default();
11256        let generated = build_schema(&cache, &config);
11257
11258        let fields = generate_subscription_fields(&cache, &generated);
11259
11260        // Should have one subscription field for the users table
11261        assert_eq!(fields.len(), 1);
11262        assert_eq!(fields[0].name, "users");
11263        assert_eq!(fields[0].table_name, "users");
11264        assert_eq!(fields[0].channel_name(), "postrust_public_users");
11265    }
11266
11267    #[test]
11268    fn test_create_subscription_type() {
11269        let cache = create_test_schema_cache();
11270        let config = SchemaConfig::default();
11271        let generated = build_schema(&cache, &config);
11272        // A live query per queryable root: the subscription root mirrors the
11273        // query root, which is the whole contract.
11274        let _subscription = create_subscription_type(
11275            &generated,
11276            "subscription_root",
11277            None,
11278            Arc::new(Default::default()),
11279            Arc::new(Default::default()),
11280            std::time::Duration::from_secs(30),
11281        );
11282    }
11283}
11284
11285/// One step of a JSON path: a key of an object or an index of an array.
11286#[derive(Debug, PartialEq, Eq)]
11287enum PathStep {
11288    Key(String),
11289    Index(usize),
11290}
11291
11292/// Read one part of a document, by the path spelling Hasura accepts.
11293///
11294/// `column(path: "objs[0]['你好']")` -- an optional leading `$`, then keys
11295/// written bare or after a dot, and indices or quoted keys written in
11296/// brackets. A step that names something the document does not have is null,
11297/// which is what `#>` answers to the same path.
11298fn walk_json_path(value: &Value, path: &str) -> Result<Value, async_graphql::Error> {
11299    let mut at = value;
11300    for step in parse_json_path(path)? {
11301        let next = match (&step, at) {
11302            (PathStep::Key(key), Value::Object(map)) => map.get(key.as_str()),
11303            (PathStep::Index(index), Value::List(items)) => items.get(*index),
11304            // An index of an object or a key of an array reads nothing, and so
11305            // does anything asked of a scalar.
11306            _ => None,
11307        };
11308        match next {
11309            Some(next) => at = next,
11310            None => return Ok(Value::Null),
11311        }
11312    }
11313    Ok(at.clone())
11314}
11315
11316/// A path whose bracket never closes: written wrong rather than written oddly.
11317fn unclosed_bracket(path: &str) -> async_graphql::Error {
11318    let message = format!("\"{}\" is not a JSON path: a bracket is never closed", path);
11319    validation_error(&message)
11320}
11321
11322/// Parse the path spelling Hasura accepts into its steps.
11323///
11324/// Deliberately tolerant about separators, because the corpus writes the same
11325/// path four ways: `objs[0]["x"]`, `objs[0].["x"]`, `objs.[0].["x"]` and
11326/// `.objs[0]['x']` all name one thing. What is not tolerated is a bracket that
11327/// never closes, which is a path the client got wrong rather than a spelling.
11328fn parse_json_path(path: &str) -> Result<Vec<PathStep>, async_graphql::Error> {
11329    let mut steps = Vec::new();
11330    let mut chars = path.chars().peekable();
11331    // `$` is the document itself, and naming it is optional.
11332    if chars.peek() == Some(&'$') {
11333        chars.next();
11334    }
11335    while let Some(&c) = chars.peek() {
11336        match c {
11337            // A separator carries no step of its own.
11338            '.' => {
11339                chars.next();
11340            }
11341            '[' => {
11342                chars.next();
11343                let quote = match chars.peek() {
11344                    Some(&q @ ('\'' | '"')) => {
11345                        chars.next();
11346                        Some(q)
11347                    }
11348                    _ => None,
11349                };
11350                let mut inner = String::new();
11351                loop {
11352                    let Some(c) = chars.next() else {
11353                        return Err(unclosed_bracket(path));
11354                    };
11355                    match (quote, c) {
11356                        (Some(quote), c) if c == quote => break,
11357                        (None, ']') => break,
11358                        _ => inner.push(c),
11359                    }
11360                }
11361                // A quoted key's closing bracket, which the quote ended before.
11362                if quote.is_some() {
11363                    match chars.next() {
11364                        Some(']') => {}
11365                        _ => return Err(unclosed_bracket(path)),
11366                    }
11367                }
11368                // An unquoted number is an index; anything else is a key,
11369                // since an object may be keyed by a word as well as a digit.
11370                match (quote, inner.parse::<usize>()) {
11371                    (None, Ok(index)) => steps.push(PathStep::Index(index)),
11372                    _ => steps.push(PathStep::Key(inner)),
11373                }
11374            }
11375            _ => {
11376                let mut key = String::new();
11377                while let Some(&c) = chars.peek() {
11378                    if matches!(c, '.' | '[') {
11379                        break;
11380                    }
11381                    key.push(c);
11382                    chars.next();
11383                }
11384                steps.push(PathStep::Key(key));
11385            }
11386        }
11387    }
11388    Ok(steps)
11389}
11390
11391#[cfg(test)]
11392mod json_path_tests {
11393    use super::*;
11394
11395    fn steps(path: &str) -> Vec<PathStep> {
11396        parse_json_path(path).expect("the path parses")
11397    }
11398
11399    fn key(name: &str) -> PathStep {
11400        PathStep::Key(name.to_string())
11401    }
11402
11403    #[test]
11404    fn the_document_itself_has_no_steps() {
11405        assert_eq!(steps("$"), vec![]);
11406        assert_eq!(steps(""), vec![]);
11407    }
11408
11409    #[test]
11410    fn a_key_is_written_bare_or_after_a_dot() {
11411        assert_eq!(steps("a"), vec![key("a")]);
11412        assert_eq!(steps(".obj.c1"), vec![key("obj"), key("c1")]);
11413        assert_eq!(steps("._underscore"), vec![key("_underscore")]);
11414    }
11415
11416    #[test]
11417    fn a_bracket_holds_an_index_or_a_quoted_key() {
11418        assert_eq!(steps("arr[0]"), vec![key("arr"), PathStep::Index(0)]);
11419        assert_eq!(steps("['!@#$%^']"), vec![key("!@#$%^")]);
11420        assert_eq!(
11421            steps("translations['hello world!']"),
11422            vec![key("translations"), key("hello world!")]
11423        );
11424    }
11425
11426    /// The corpus writes one path four ways, and Hasura reads them all alike.
11427    #[test]
11428    fn a_dot_before_a_bracket_changes_nothing() {
11429        let expected = vec![key("objs"), PathStep::Index(0), key("\u{4f60}\u{597d}")];
11430        for spelling in [
11431            "objs[0]['\u{4f60}\u{597d}']",
11432            "objs[0][\"\u{4f60}\u{597d}\"]",
11433            "objs[0].[\"\u{4f60}\u{597d}\"]",
11434            "objs.[0].[\"\u{4f60}\u{597d}\"]",
11435        ] {
11436            assert_eq!(steps(spelling), expected, "{}", spelling);
11437        }
11438    }
11439
11440    #[test]
11441    fn a_bracket_that_never_closes_is_refused() {
11442        assert!(parse_json_path("arr[0").is_err());
11443        assert!(parse_json_path("['key'").is_err());
11444    }
11445
11446    #[test]
11447    fn a_step_the_document_does_not_have_reads_null() {
11448        let document = Value::from_json(serde_json::json!({
11449            "obj": {"c1": "c2"},
11450            "arr": [1, 2, 3],
11451        }))
11452        .expect("a document");
11453        let at = |path| walk_json_path(&document, path).expect("the path parses");
11454        assert_eq!(at(".obj.c1"), Value::String("c2".to_string()));
11455        assert_eq!(at("arr[1]"), Value::Number(2.into()));
11456        assert_eq!(at("arr[9]"), Value::Null);
11457        assert_eq!(at(".obj.nothing"), Value::Null);
11458        // An index of an object, and a key of an array: neither reads
11459        // anything, which is what `#>` answers.
11460        assert_eq!(at("obj[0]"), Value::Null);
11461        assert_eq!(at("arr.first"), Value::Null);
11462    }
11463}