1use 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
30pub struct GraphQLState {
32 pub pool: PgPool,
34 pub schema_cache: Arc<SchemaCache>,
36 pub generated_schema: GeneratedSchema,
38 pub schema: Schema,
43 pub role_schemas: HashMap<(String, bool), Schema>,
59 pub ungranted_schema: Option<Schema>,
72 pub config: SchemaConfig,
74 pub subscription_fields: Vec<SubField>,
76 pub broker: Arc<RwLock<Option<NotifyBroker>>>,
78}
79
80struct 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 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
125fn 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 if role == postrust_auth::hasura::ADMIN_ROLE {
149 continue;
150 }
151
152 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 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 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
209fn 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 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 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 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 .or_else(|| self.role_schemas.get(&(role.to_string(), false)))
319 .or(self.ungranted_schema.as_ref()),
320 }
321 }
322
323 #[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 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 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 let mut broker_guard = self.broker.write().await;
377 *broker_guard = Some(broker);
378
379 Ok(())
380 }
381
382 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 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 pub async fn get_broker(&self) -> Option<Arc<RwLock<Option<NotifyBroker>>>> {
421 Some(Arc::clone(&self.broker))
422 }
423}
424
425pub 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
439pub 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
471pub 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
479fn 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
494fn 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
503fn 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
539fn 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
560fn 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
572fn 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
580fn 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 role: Option<&str>,
593) -> Result<Schema, GraphQLError> {
594 let mut object_types: HashMap<String, Object> = HashMap::new();
596
597 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 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 let mutable: HashMap<String, String> = generated
642 .mutation_fields
643 .iter()
644 .filter_map(|f| {
645 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 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 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 let relationships = Arc::new(generated.relationship_fields.clone());
696 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 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 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 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 for (_, obj) in object_types {
788 builder = builder.register(obj);
789 }
790
791 builder = builder.register(query);
793
794 if let Some(mutation) = mutation {
796 builder = builder.register(mutation);
797 }
798
799 if let Some(subscription) = subscription {
801 builder = builder.register(subscription);
802 }
803
804 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 for field in object.fields.iter().chain(&object.writable_fields) {
826 scalar_names.insert(leaf_scalar_name(&field.graphql_type));
827 }
828 }
829 scalar_names.insert("JSON".to_string());
832 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 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 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 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 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 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 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 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 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 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 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 if any_numeric {
1071 builder = builder.register(numeric);
1072 }
1073
1074 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 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 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 args = args.field(InputValue::new(name, TypeRef::named(scalar)));
1151 }
1152 builder = builder.register(args);
1153 }
1154
1155 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 args = args.field(InputValue::new(name, TypeRef::named(scalar)));
1179 }
1180 builder = builder.register(args);
1181 }
1182 }
1183
1184 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 args = args.field(InputValue::new(name, TypeRef::named(scalar)));
1203 }
1204 builder = builder.register(args);
1205 }
1206 }
1207
1208 {
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 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 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 for object in generated.object_types.values() {
1304 let local_type_name = object.local_name.as_str();
1305 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 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 .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 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 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
1409const PLACEHOLDER_COLUMN: &str = "_PLACEHOLDER";
1416
1417pub fn mutation_response_type_name(base_name: &str) -> String {
1419 format!("{}_mutation_response", base_name)
1420}
1421
1422fn 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 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
1475fn 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 let fields_type = agg::aggregate_fields_type_name(base_name);
1487 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 let mut count = Field::new("count", TypeRef::named_nn(TypeRef::INT), |ctx| {
1522 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 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
1584fn agg_select_column(base_name: &str) -> String {
1586 crate::input::order_by::select_column_type_name(base_name)
1587}
1588
1589fn 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
1597fn 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
1608fn 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
1621fn validation_error(message: impl Into<String>) -> async_graphql::Error {
1623 coded_error("validation-failed", message)
1624}
1625
1626fn 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 Some("23505") => "Uniqueness violation. ",
1645 Some("23502") => "Not-NULL violation. ",
1646 Some("23503") => "Foreign key violation. ",
1647 Some("23514") => "Check constraint violation. ",
1648 _ => "",
1652 };
1653 let error = async_graphql::Error::new(format!("{}{}", described, db.message()));
1654 let coded = match db.code().as_deref() {
1659 Some(code) if code.starts_with("23") => Some("constraint-violation"),
1660 Some("22025") => Some("bad-request"),
1664 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
1674fn 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
1682fn 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 object = match obj.description() {
1715 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 let mut taken: HashSet<String> = obj.fields.iter().map(|f| f.name.clone()).collect();
1738
1739 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 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 let gql_field = Field::new(&field.name, field_type, move |ctx| {
1762 let field_name = field_name.clone();
1763 FieldFuture::new(async move {
1764 if let Some(Value::Object(map)) = ctx.parent_value.as_value() {
1766 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 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 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 let gql_field = match field.arguments.is_empty() {
1808 true => gql_field,
1809 false => gql_field.argument(InputValue::new(
1810 "args",
1811 TypeRef::named_nn(computed_args_type_name(&obj.local_name, &field.name)),
1812 )),
1813 };
1814
1815 let gql_field = if let Some(desc) = &field.description {
1816 gql_field.description(desc)
1817 } else {
1818 gql_field
1819 };
1820 fields.push((field.name.clone(), gql_field));
1821 }
1822
1823 for rel in relationships {
1827 if !taken.insert(rel.name.clone()) {
1828 tracing::warn!(
1829 "{}: not exposing the relationship to \"{}\" as `{}` -- the table \
1830 already has a column of that name",
1831 obj.name,
1832 rel.target_type,
1833 rel.name
1834 );
1835 continue;
1836 }
1837 let field_name = rel.name.clone();
1838 let field_type = if rel.is_list {
1839 TypeRef::named_nn_list_nn(&rel.target_type)
1840 } else if always_present(rel, &obj.table) {
1841 TypeRef::named_nn(&rel.target_type)
1842 } else {
1843 TypeRef::named(&rel.target_type)
1844 };
1845
1846 let is_list = rel.is_list;
1847 let mut gql_field = Field::new(&rel.name, field_type, move |ctx| {
1848 let field_name = field_name.clone();
1849 FieldFuture::new(async move {
1850 if let Some(Value::Object(map)) = ctx.parent_value.as_value() {
1851 let key = async_graphql::Name::new(&field_name);
1852 match map.get(&key) {
1853 Some(Value::Null) if !is_list => return Ok(None),
1858 Some(val) => return Ok(Some(FieldValue::value(val.clone()))),
1859 None => {}
1860 }
1861 }
1862 Ok(None)
1863 })
1864 });
1865
1866 if !rel.arguments.is_empty() {
1877 gql_field = gql_field.argument(InputValue::new(
1878 "args",
1879 TypeRef::named_nn(computed_args_type_name(&obj.local_name, &rel.name)),
1880 ));
1881 }
1882 if rel.is_list {
1883 gql_field = gql_field
1884 .argument(InputValue::new(
1885 "distinct_on",
1886 TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
1887 &rel.target_local_name,
1888 )),
1889 ))
1890 .argument(InputValue::new(
1891 "where",
1892 TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
1893 &rel.target_local_name,
1894 )),
1895 ))
1896 .argument(InputValue::new(
1897 "order_by",
1898 TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
1899 &rel.target_local_name,
1900 )),
1901 ))
1902 .argument(InputValue::new("limit", TypeRef::named("Int")))
1903 .argument(InputValue::new("offset", TypeRef::named("Int")));
1904 }
1905
1906 let gql_field = if let Some(desc) = &rel.description {
1907 gql_field.description(desc)
1908 } else {
1909 gql_field
1910 };
1911 fields.push((rel.name.clone(), gql_field));
1912
1913 if rel.is_list {
1918 let aggregate_field = format!("{}_aggregate", rel.name);
1919 if taken.insert(aggregate_field.clone()) {
1920 let key = aggregate_field.clone();
1921 fields.push((
1922 aggregate_field.clone(),
1923 Field::new(
1924 &aggregate_field,
1925 TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
1926 &rel.target_local_name,
1927 )),
1928 move |ctx| {
1929 let key = key.clone();
1930 FieldFuture::new(async move {
1931 Ok(Some(FieldValue::value(
1935 child_value(&ctx, &key).unwrap_or(Value::Null),
1936 )))
1937 })
1938 },
1939 )
1940 .argument(InputValue::new(
1945 "distinct_on",
1946 TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
1947 &rel.target_local_name,
1948 )),
1949 ))
1950 .argument(InputValue::new(
1951 "where",
1952 TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
1953 &rel.target_local_name,
1954 )),
1955 ))
1956 .argument(InputValue::new(
1957 "order_by",
1958 TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
1959 &rel.target_local_name,
1960 )),
1961 ))
1962 .argument(InputValue::new("limit", TypeRef::named("Int")))
1963 .argument(InputValue::new("offset", TypeRef::named("Int")))
1964 .description(format!("Aggregates over {}.", rel.name)),
1965 ));
1966 if !rel.arguments.is_empty() {
1969 let last = fields.len() - 1;
1970 let (name, field) = fields.remove(last);
1971 fields.push((
1972 name,
1973 field.argument(InputValue::new(
1974 "args",
1975 TypeRef::named_nn(computed_args_type_name(&obj.local_name, &rel.name)),
1976 )),
1977 ));
1978 }
1979 }
1980 }
1981 }
1982
1983 fields.sort_by(|(a, _), (b, _)| a.cmp(b));
1984 for (_, field) in fields {
1985 object = object.field(field);
1986 }
1987
1988 object
1989}
1990
1991trait RootField: Sized {
1998 fn with_argument(self, value: InputValue) -> Self;
1999}
2000
2001impl RootField for Field {
2002 fn with_argument(self, value: InputValue) -> Self {
2003 self.argument(value)
2004 }
2005}
2006
2007impl RootField for SubscriptionField {
2008 fn with_argument(self, value: InputValue) -> Self {
2009 self.argument(value)
2010 }
2011}
2012
2013fn with_row_arguments<F: RootField>(field: F, type_name: &str) -> F {
2016 with_row_arguments_named(field, type_name, true)
2017}
2018
2019fn with_row_arguments_named<F: RootField>(field: F, type_name: &str, columns: bool) -> F {
2027 let mut field = field;
2028 if columns {
2029 field = field.with_argument(InputValue::new(
2030 "distinct_on",
2031 TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(type_name)),
2032 ));
2033 }
2034 field = field
2035 .with_argument(InputValue::new("limit", TypeRef::named("Int")))
2036 .with_argument(InputValue::new("offset", TypeRef::named("Int")));
2037 if columns {
2038 field = field.with_argument(InputValue::new(
2039 "order_by",
2040 TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(type_name)),
2041 ));
2042 }
2043 field.with_argument(InputValue::new(
2044 "where",
2045 TypeRef::named(crate::input::bool_exp::bool_exp_type_name(type_name)),
2046 ))
2047}
2048
2049fn with_key_arguments<F: RootField>(
2052 field: F,
2053 schema_name: &str,
2054 table_name: &str,
2055 pk_columns: &[(String, String)],
2056 names: &crate::names::NameOverrides,
2057) -> F {
2058 let mut field = field;
2059 for (column, pg_type) in pk_columns {
2060 field = field.with_argument(InputValue::new(
2061 names
2062 .column(schema_name, table_name, column)
2063 .unwrap_or(column),
2064 TypeRef::named_nn(exposed_pk_argument_type(
2065 names,
2066 schema_name,
2067 table_name,
2068 column,
2069 pg_type,
2070 )),
2071 ));
2072 }
2073 field
2074}
2075
2076fn create_query_type(
2078 generated: &GeneratedSchema,
2079 root_name: &str,
2080 max_rows: Option<i64>,
2081 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2082 names: Arc<crate::names::NameOverrides>,
2083) -> Object {
2084 let mut roots: Vec<(String, Field)> = Vec::new();
2089
2090 for field in &generated.query_fields {
2091 let table_name = field.table_name.clone();
2092 let schema_name = field.schema_name.clone();
2093 let type_name = field.type_name.clone();
2094 let local_type_name = field.local_type_name.clone();
2095 let is_by_pk = field.is_by_pk;
2096 let pk_columns = field.pk_columns.clone();
2097 let return_type = graphql_type_ref(&field.return_type);
2098
2099 let spec_type_name = local_type_name.clone();
2100 let spec = Arc::new(QueryFieldSpec {
2101 schema_name,
2102 table_name,
2103 type_name,
2104 is_by_pk,
2105 pk_columns: pk_columns.clone(),
2106 max_rows,
2107 relationships: Arc::clone(&relationships),
2108 names: Arc::clone(&names),
2109 call: None,
2110 });
2111
2112 let mut gql_field = Field::new(&field.name, return_type, move |ctx| {
2113 let spec = Arc::clone(&spec);
2114 FieldFuture::new(async move { resolve_query(&ctx, &spec).await })
2115 });
2116
2117 gql_field = match is_by_pk {
2119 false => with_row_arguments(gql_field, &spec_type_name),
2120 true => with_key_arguments(
2121 gql_field,
2122 &field.schema_name,
2123 &field.table_name,
2124 &pk_columns,
2125 names.as_ref(),
2126 ),
2127 };
2128
2129 if let Some(desc) = &field.description {
2130 gql_field = gql_field.description(desc);
2131 }
2132
2133 if field.rows {
2138 roots.push((field.name.clone(), gql_field));
2139 }
2140
2141 if !is_by_pk && field.aggregates {
2149 let agg_spec = Arc::new(AggregateSpec {
2150 schema_name: field.schema_name.clone(),
2151 table_name: field.table_name.clone(),
2152 type_name: field.type_name.clone(),
2153 max_rows,
2154 relationships: Arc::clone(&relationships),
2155 names: Arc::clone(&names),
2156 call: None,
2157 });
2158 let aggregate_field_name = field.aggregate_name.clone().unwrap_or_else(|| {
2159 crate::schema::aggregate::aggregate_type_name(&field.local_type_name)
2160 });
2161 let aggregate_field_name_for_sorting = aggregate_field_name.clone();
2162 let mut agg_field = Field::new(
2163 aggregate_field_name,
2164 TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
2165 &field.local_type_name,
2166 )),
2167 move |ctx| {
2168 let agg_spec = Arc::clone(&agg_spec);
2169 FieldFuture::new(async move { resolve_aggregate(&ctx, &agg_spec).await })
2170 },
2171 );
2172 agg_field = with_row_arguments_named(agg_field, &spec_type_name, field.rows);
2173 agg_field = match field.aggregate_description.as_deref() {
2174 Some("") => agg_field,
2175 Some(given) => agg_field.description(given),
2176 None => agg_field.description(format!(
2177 "fetch aggregated fields from the table: \"{}\"",
2178 field.table_name
2179 )),
2180 };
2181 roots.push((aggregate_field_name_for_sorting, agg_field));
2182 }
2183 }
2184
2185 roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2186 let mut query = Object::new(root_name);
2187 if roots.is_empty() {
2191 return query.field(
2192 Field::new("no_queries_available", TypeRef::named("String"), |_| {
2193 FieldFuture::new(async move { Ok(None::<Value>) })
2194 })
2195 .description("There are no queries available to the current role."),
2196 );
2197 }
2198 for (_, field) in roots {
2199 query = query.field(field);
2200 }
2201
2202 query
2203}
2204
2205type JsonbOperator = (&'static str, fn() -> TypeRef);
2207
2208const JSONB_OPERATORS: &[JsonbOperator] = &[
2215 ("_append", || TypeRef::named("jsonb")),
2216 ("_delete_at_path", || TypeRef::named_nn_list("String")),
2217 ("_delete_elem", || TypeRef::named("Int")),
2218 ("_delete_key", || TypeRef::named("String")),
2219 ("_prepend", || TypeRef::named("jsonb")),
2220];
2221
2222fn jsonb_operator_input(type_name: &str, operator: &str) -> String {
2224 format!("{}{}_input", type_name, operator)
2225}
2226
2227fn with_update_operators(
2234 field: Field,
2235 base_name: &str,
2236 has_numeric: bool,
2237 has_jsonb: bool,
2238) -> Field {
2239 let mut field = field;
2240 if has_jsonb {
2243 for (operator, _) in JSONB_OPERATORS {
2244 field = field.argument(InputValue::new(
2245 *operator,
2246 TypeRef::named(jsonb_operator_input(base_name, operator)),
2247 ));
2248 }
2249 }
2250 if has_numeric {
2251 field = field.argument(InputValue::new(
2252 "_inc",
2253 TypeRef::named(format!("{}_inc_input", base_name)),
2254 ));
2255 }
2256 field.argument(InputValue::new(
2257 "_set",
2258 TypeRef::named(format!("{}_set_input", base_name)),
2259 ))
2260}
2261
2262fn write_fields<'a>(
2272 object: &'a crate::schema::object::TableObjectType,
2273 names: &crate::names::NameOverrides,
2274 role: Option<&str>,
2275 verb: crate::role::Verb,
2276) -> Vec<&'a crate::schema::object::GraphQLField> {
2277 let allowed = role.and_then(|role| {
2278 names
2279 .permissions(&object.table.schema, &object.table.name, role)
2280 .and_then(|granted| granted.write_columns(verb))
2281 });
2282 object
2283 .writable_fields
2284 .iter()
2285 .filter(|field| {
2286 let column = table_column_for(names, &object.table, &field.name);
2287 object
2295 .table
2296 .get_column(column)
2297 .is_some_and(|c| !c.always_generated)
2298 && allowed.is_none_or(|set| set.allows(column))
2299 })
2300 .collect()
2301}
2302
2303fn update_inputs(
2305 object: &crate::schema::object::TableObjectType,
2306 names: &crate::names::NameOverrides,
2307 role: Option<&str>,
2308) -> (bool, bool) {
2309 let fields = write_fields(object, names, role, crate::role::Verb::Update);
2310 (
2311 fields
2312 .iter()
2313 .any(|f| crate::schema::aggregate::is_incrementable(&f.graphql_type)),
2314 fields
2315 .iter()
2316 .any(|f| matches!(&f.graphql_type, crate::types::GraphQLType::Json)),
2317 )
2318}
2319
2320fn create_mutation_type(
2321 generated: &GeneratedSchema,
2322 root_name: &str,
2323 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2324 type_names: Arc<HashMap<(String, String), String>>,
2325 names: Arc<crate::names::NameOverrides>,
2326 max_rows: Option<i64>,
2327 role: Option<&str>,
2328) -> Object {
2329 let mut mutation = Object::new(root_name);
2330 let mut roots: Vec<(String, Field)> = Vec::new();
2332
2333 let mut has_numeric_column: HashSet<String> = HashSet::new();
2340 let mut has_jsonb_column: HashSet<String> = HashSet::new();
2341 for object in generated.object_types.values() {
2342 let (numeric, jsonb) = update_inputs(object, &names, role);
2343 if numeric {
2344 has_numeric_column.insert(object.local_name.clone());
2345 }
2346 if jsonb {
2347 has_jsonb_column.insert(object.local_name.clone());
2348 }
2349 }
2350
2351 let has_conflict_target: HashSet<String> = generated
2352 .object_types
2353 .iter()
2354 .filter(|(_, object)| !object.table.unique_constraints.is_empty())
2355 .map(|(_, object)| object.local_name.clone())
2356 .collect();
2357
2358 for field in &generated.mutation_fields {
2359 let table_name = field.table_name.clone();
2360 let schema_name = field.schema_name.clone();
2361 let mutation_type = field.mutation_type;
2362 let pk_columns = field.pk_columns.clone();
2363 let return_type = graphql_type_ref(&field.return_type);
2364
2365 let where_type = field.local_type_name.clone();
2369
2370 let resolver_pk_columns = pk_columns.clone();
2371 let field_relationships = Arc::clone(&relationships);
2372 let field_type_names = Arc::clone(&type_names);
2373 let field_names = Arc::clone(&names);
2374 let mut gql_field = Field::new(&field.name, return_type, move |ctx| {
2375 let table_name = table_name.clone();
2376 let schema_name = schema_name.clone();
2377 let pk_columns = resolver_pk_columns.clone();
2378 let relationships = Arc::clone(&field_relationships);
2379 let type_names = Arc::clone(&field_type_names);
2380 let names = Arc::clone(&field_names);
2381 FieldFuture::new(async move {
2382 resolve_mutation(
2383 &ctx,
2384 &schema_name,
2385 &table_name,
2386 mutation_type,
2387 &pk_columns,
2388 &relationships,
2389 &type_names,
2390 &names,
2391 max_rows,
2392 )
2393 .await
2394 })
2395 });
2396
2397 match mutation_type {
2403 MutationType::Insert | MutationType::InsertOne => {
2404 let insert_input = format!("{}_insert_input", where_type);
2405 gql_field = if mutation_type == MutationType::Insert {
2406 gql_field.argument(InputValue::new(
2407 "objects",
2408 TypeRef::named_nn_list_nn(&insert_input),
2409 ))
2410 } else {
2411 gql_field.argument(InputValue::new("object", TypeRef::named_nn(&insert_input)))
2414 };
2415 if has_conflict_target.contains(&where_type) {
2416 gql_field = gql_field.argument(InputValue::new(
2417 "on_conflict",
2418 TypeRef::named(format!("{}_on_conflict", where_type)),
2419 ));
2420 }
2421 }
2422 MutationType::UpdateByPk => {
2423 gql_field = gql_field.argument(InputValue::new(
2424 "pk_columns",
2425 TypeRef::named_nn(format!("{}_pk_columns_input", where_type)),
2426 ));
2427 gql_field = with_update_operators(
2428 gql_field,
2429 &where_type,
2430 has_numeric_column.contains(&where_type),
2431 has_jsonb_column.contains(&where_type),
2432 );
2433 }
2434 MutationType::Update => {
2435 gql_field = gql_field.argument(InputValue::new(
2436 "where",
2437 TypeRef::named_nn(crate::input::bool_exp::bool_exp_type_name(&where_type)),
2438 ));
2439 gql_field = with_update_operators(
2440 gql_field,
2441 &where_type,
2442 has_numeric_column.contains(&where_type),
2443 has_jsonb_column.contains(&where_type),
2444 );
2445 }
2446 MutationType::UpdateMany => {
2447 gql_field = gql_field.argument(InputValue::new(
2448 "updates",
2449 TypeRef::named_nn_list_nn(format!("{}_updates", where_type)),
2450 ));
2451 }
2452 MutationType::DeleteByPk => {
2453 for (col_name, pg_type) in &pk_columns {
2454 gql_field = gql_field.argument(InputValue::new(
2455 names
2456 .column(&field.schema_name, &field.table_name, col_name)
2457 .unwrap_or(col_name),
2458 TypeRef::named_nn(exposed_pk_argument_type(
2459 names.as_ref(),
2460 &field.schema_name,
2461 &field.table_name,
2462 col_name,
2463 pg_type,
2464 )),
2465 ));
2466 }
2467 }
2468 MutationType::Delete => {
2469 gql_field = gql_field.argument(InputValue::new(
2476 "where",
2477 TypeRef::named_nn(crate::input::bool_exp::bool_exp_type_name(&where_type)),
2478 ));
2479 }
2480 }
2481
2482 if let Some(desc) = &field.description {
2483 gql_field = gql_field.description(desc);
2484 }
2485
2486 roots.push((field.name.clone(), gql_field));
2487 }
2488
2489 roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2490 for (_, field) in roots {
2491 mutation = mutation.field(field);
2492 }
2493
2494 mutation
2495}
2496
2497fn create_subscription_type(
2514 generated: &GeneratedSchema,
2515 root_name: &str,
2516 max_rows: Option<i64>,
2517 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2518 names: Arc<crate::names::NameOverrides>,
2519 refresh: std::time::Duration,
2520) -> Subscription {
2521 let mut roots: Vec<(String, SubscriptionField)> = Vec::new();
2522
2523 for field in &generated.query_fields {
2524 let spec_type_name = field.local_type_name.clone();
2525 let pk_columns = field.pk_columns.clone();
2526 let is_by_pk = field.is_by_pk;
2527 let return_type = graphql_type_ref(&field.return_type);
2528 let watched = vec![crate::subscription::table_channel_name(
2529 &field.schema_name,
2530 &field.table_name,
2531 )];
2532
2533 let spec = Arc::new(QueryFieldSpec {
2534 schema_name: field.schema_name.clone(),
2535 table_name: field.table_name.clone(),
2536 type_name: field.type_name.clone(),
2537 is_by_pk,
2538 pk_columns: pk_columns.clone(),
2539 max_rows,
2540 relationships: Arc::clone(&relationships),
2541 names: Arc::clone(&names),
2542 call: None,
2543 });
2544
2545 let mut gql_field = SubscriptionField::new(&field.name, return_type, move |ctx| {
2546 let spec = Arc::clone(&spec);
2547 let watched = watched.clone();
2548 SubscriptionFieldFuture::new(async move {
2549 let wake = wake_on(&ctx, &watched, refresh).await;
2550 Ok(live(ctx, LiveSource::Rows(spec), wake))
2551 })
2552 });
2553
2554 gql_field = match is_by_pk {
2555 false => with_row_arguments(gql_field, &spec_type_name),
2556 true => with_key_arguments(
2557 gql_field,
2558 &field.schema_name,
2559 &field.table_name,
2560 &pk_columns,
2561 names.as_ref(),
2562 ),
2563 };
2564 if let Some(desc) = &field.description {
2565 gql_field = gql_field.description(desc);
2566 }
2567 if field.rows {
2569 roots.push((field.name.clone(), gql_field));
2570 }
2571
2572 if is_by_pk || !field.aggregates {
2575 continue;
2576 }
2577
2578 let agg_spec = Arc::new(AggregateSpec {
2580 schema_name: field.schema_name.clone(),
2581 table_name: field.table_name.clone(),
2582 type_name: field.type_name.clone(),
2583 max_rows,
2584 relationships: Arc::clone(&relationships),
2585 names: Arc::clone(&names),
2586 call: None,
2587 });
2588 let agg_watched = vec![crate::subscription::table_channel_name(
2589 &field.schema_name,
2590 &field.table_name,
2591 )];
2592 let agg_name = field.aggregate_name.clone().unwrap_or_else(|| {
2593 crate::schema::aggregate::aggregate_type_name(&field.local_type_name)
2594 });
2595 let mut agg_field = SubscriptionField::new(
2596 agg_name.clone(),
2597 TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
2598 &field.local_type_name,
2599 )),
2600 move |ctx| {
2601 let agg_spec = Arc::clone(&agg_spec);
2602 let watched = agg_watched.clone();
2603 SubscriptionFieldFuture::new(async move {
2604 let wake = wake_on(&ctx, &watched, refresh).await;
2605 Ok(live(ctx, LiveSource::Aggregate(agg_spec), wake))
2606 })
2607 },
2608 );
2609 agg_field = with_row_arguments_named(agg_field, &spec_type_name, field.rows);
2610 agg_field = match field.aggregate_description.as_deref() {
2611 Some("") => agg_field,
2612 Some(given) => agg_field.description(given),
2613 None => agg_field.description(format!(
2614 "fetch aggregated fields from the table: \"{}\"",
2615 field.table_name
2616 )),
2617 };
2618 roots.push((agg_name, agg_field));
2619 }
2620
2621 roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2622 let mut subscription = Subscription::new(root_name);
2623 if roots.is_empty() {
2626 return subscription.field(SubscriptionField::new(
2627 "no_subscriptions_available",
2628 TypeRef::named("String"),
2629 |_| {
2630 SubscriptionFieldFuture::new(async move {
2631 Ok(futures::stream::empty::<
2632 Result<FieldValue, async_graphql::Error>,
2633 >())
2634 })
2635 },
2636 ));
2637 }
2638 for (_, field) in roots {
2639 subscription = subscription.field(field);
2640 }
2641 subscription
2642}
2643
2644async fn wake_on(
2650 ctx: &ResolverContext<'_>,
2651 channels: &[String],
2652 refresh: std::time::Duration,
2653) -> futures::stream::BoxStream<'static, ()> {
2654 use futures::StreamExt;
2655
2656 let mut streams: Vec<futures::stream::BoxStream<'static, ()>> =
2657 Vec::with_capacity(channels.len() + 1);
2658 streams.push(
2661 tokio_stream::wrappers::IntervalStream::new({
2662 let mut interval = tokio::time::interval(refresh);
2663 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
2664 interval
2665 })
2666 .map(|_| ())
2667 .boxed(),
2668 );
2669
2670 if let Ok(broker_arc) = ctx.data::<Arc<RwLock<Option<NotifyBroker>>>>() {
2671 let guard = broker_arc.read().await;
2672 if let Some(broker) = guard.as_ref() {
2673 for channel in channels {
2674 streams.push(
2678 broker
2679 .subscribe_or_create(channel)
2680 .await
2681 .map(|_| ())
2682 .boxed(),
2683 );
2684 }
2685 }
2686 }
2687
2688 futures::stream::select_all(streams).boxed()
2689}
2690
2691enum LiveSource {
2697 Rows(Arc<QueryFieldSpec>),
2698 Aggregate(Arc<AggregateSpec>),
2699}
2700
2701async fn read_live<'a>(
2703 ctx: &ResolverContext<'a>,
2704 source: &LiveSource,
2705) -> Result<(serde_json::Value, Option<FieldValue<'a>>), async_graphql::Error> {
2706 match source {
2707 LiveSource::Rows(spec) => {
2708 let rows = query_rows(ctx, spec).await?;
2709 Ok((
2710 serde_json::Value::Array(rows.clone()),
2711 rows_as_field_value(rows, spec.is_by_pk),
2712 ))
2713 }
2714 LiveSource::Aggregate(spec) => {
2715 let value = aggregate_value(ctx, spec).await?;
2716 let seen = serde_json::to_value(&value).unwrap_or_default();
2717 Ok((seen, Some(FieldValue::value(value))))
2718 }
2719 }
2720}
2721
2722fn live<'a>(
2730 ctx: ResolverContext<'a>,
2731 source: LiveSource,
2732 wake: futures::stream::BoxStream<'static, ()>,
2733) -> impl futures::Stream<Item = Result<FieldValue<'a>, async_graphql::Error>> + Send + 'a {
2734 use futures::StreamExt;
2735
2736 struct Live<'a> {
2737 ctx: ResolverContext<'a>,
2738 source: LiveSource,
2739 wake: futures::stream::BoxStream<'static, ()>,
2740 sent: Option<serde_json::Value>,
2741 started: bool,
2742 failed: bool,
2744 _active: crate::subscription::ActiveSubscription,
2746 }
2747
2748 futures::stream::unfold(
2749 Live {
2750 ctx,
2751 source,
2752 wake,
2753 sent: None,
2754 started: false,
2755 failed: false,
2756 _active: crate::subscription::ActiveSubscription::open(),
2757 },
2758 |mut live: Live<'a>| async move {
2759 if live.failed {
2760 return None;
2761 }
2762 loop {
2763 if live.started {
2764 live.wake.next().await?;
2765 } else {
2766 live.started = true;
2767 }
2768 let read = read_live(&live.ctx, &live.source).await;
2769 match read {
2770 Err(e) => {
2778 live.failed = true;
2779 return Some((Err(e), live));
2780 }
2781 Ok((seen, value)) => {
2782 if live.sent.as_ref() == Some(&seen) {
2783 continue;
2784 }
2785 live.sent = Some(seen);
2786 let value = value.unwrap_or_else(|| FieldValue::value(Value::Null));
2787 return Some((Ok(value), live));
2788 }
2789 }
2790 }
2791 },
2792 )
2793}
2794
2795struct QueryFieldSpec {
2797 schema_name: String,
2798 table_name: String,
2799 type_name: String,
2800 is_by_pk: bool,
2801 pk_columns: Vec<(String, String)>,
2802 max_rows: Option<i64>,
2803 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2804 names: Arc<crate::names::NameOverrides>,
2805 call: Option<Arc<FunctionCall>>,
2808}
2809
2810#[derive(Clone)]
2812struct EntityLookup {
2813 schema_name: String,
2814 table_name: String,
2815 type_name: String,
2816 key_columns: Vec<EntityKeyColumn>,
2817 row_column_types: HashMap<String, String>,
2818}
2819
2820#[derive(Clone)]
2821struct EntityKeyColumn {
2822 field_name: String,
2823 column_name: String,
2824 pg_type: String,
2825 explicit_id: bool,
2826}
2827
2828struct EntityResolverState {
2830 entities: HashMap<String, EntityLookup>,
2831 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2832 names: Arc<crate::names::NameOverrides>,
2833 max_rows: Option<i64>,
2834}
2835
2836impl EntityResolverState {
2837 fn new(
2838 generated: &GeneratedSchema,
2839 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2840 names: Arc<crate::names::NameOverrides>,
2841 max_rows: Option<i64>,
2842 ) -> Self {
2843 let mut entities = HashMap::new();
2844 for (type_name, entity) in &generated.federation_entities {
2845 let Some(object) = generated.object_types.get(type_name) else {
2846 continue;
2847 };
2848 let mut key_columns = Vec::with_capacity(entity.key_fields.len());
2849 for field_name in &entity.key_fields {
2850 let column_name = names
2851 .column_source(&object.table.schema, &object.table.name, field_name)
2852 .unwrap_or(field_name);
2853 let Some(column) = object.table.get_column(column_name) else {
2854 continue;
2855 };
2856 key_columns.push(EntityKeyColumn {
2857 field_name: field_name.clone(),
2858 column_name: column.name.clone(),
2859 pg_type: column.nominal_type.clone(),
2860 explicit_id: matches!(
2861 names.column_type(&object.table.schema, &object.table.name, &column.name),
2862 Some(crate::types::GraphQLType::Id)
2863 ),
2864 });
2865 }
2866 if key_columns.len() != entity.key_fields.len() {
2867 continue;
2868 }
2869 entities.insert(
2870 type_name.clone(),
2871 EntityLookup {
2872 schema_name: object.table.schema.clone(),
2873 table_name: object.table.name.clone(),
2874 type_name: type_name.clone(),
2875 key_columns,
2876 row_column_types: exposed_column_types(&object.table, names.as_ref()),
2877 },
2878 );
2879 }
2880 Self {
2881 entities,
2882 relationships,
2883 names,
2884 max_rows,
2885 }
2886 }
2887}
2888
2889struct EntityRepresentation {
2890 index: usize,
2891 type_name: String,
2892 values: serde_json::Map<String, serde_json::Value>,
2893}
2894
2895fn entity_field_applicability(
2902 selection_set: &SelectionSet,
2903 fragments: &HashMap<Name, Positioned<FragmentDefinition>>,
2904 type_name: &str,
2905) -> Vec<bool> {
2906 fn condition_matches(condition: Option<&Positioned<TypeCondition>>, type_name: &str) -> bool {
2907 condition.is_none_or(|condition| {
2908 let condition = condition.node.on.node.as_str();
2909 condition == type_name || condition == "_Entity"
2910 })
2911 }
2912
2913 fn collect(
2914 selection_set: &SelectionSet,
2915 fragments: &HashMap<Name, Positioned<FragmentDefinition>>,
2916 type_name: &str,
2917 parent_matches: bool,
2918 applicability: &mut Vec<bool>,
2919 ) {
2920 for selection in &selection_set.items {
2921 match &selection.node {
2922 Selection::Field(_) => applicability.push(parent_matches),
2923 Selection::FragmentSpread(spread) => {
2924 let Some(fragment) = fragments.get(&spread.node.fragment_name.node) else {
2925 continue;
2926 };
2927 collect(
2928 &fragment.node.selection_set.node,
2929 fragments,
2930 type_name,
2931 parent_matches
2932 && condition_matches(Some(&fragment.node.type_condition), type_name),
2933 applicability,
2934 );
2935 }
2936 Selection::InlineFragment(fragment) => collect(
2937 &fragment.node.selection_set.node,
2938 fragments,
2939 type_name,
2940 parent_matches
2941 && condition_matches(fragment.node.type_condition.as_ref(), type_name),
2942 applicability,
2943 ),
2944 }
2945 }
2946 }
2947
2948 let mut applicability = Vec::new();
2949 collect(
2950 selection_set,
2951 fragments,
2952 type_name,
2953 true,
2954 &mut applicability,
2955 );
2956 applicability
2957}
2958
2959fn entity_selection_fields<'ctx, 'a>(
2960 ctx: &'ctx ResolverContext<'a>,
2961 type_name: &str,
2962) -> Vec<SelectionField<'ctx>> {
2963 let applicability = entity_field_applicability(
2964 &ctx.ctx.item.node.selection_set.node,
2965 &ctx.ctx.query_env.fragments,
2966 type_name,
2967 );
2968 let fields: Vec<_> = ctx.field().selection_set().collect();
2969 debug_assert_eq!(fields.len(), applicability.len());
2970 fields
2971 .into_iter()
2972 .zip(applicability)
2973 .filter_map(|(field, applies)| applies.then_some(field))
2974 .collect()
2975}
2976
2977async fn resolve_entities<'a>(
2978 ctx: &ResolverContext<'a>,
2979 state: &EntityResolverState,
2980) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
2981 let representations = ctx.args.try_get("representations")?.list()?;
2982 let mut grouped: HashMap<String, Vec<EntityRepresentation>> = HashMap::new();
2983 let mut count = 0;
2984 for (index, representation) in representations.iter().enumerate() {
2985 count += 1;
2986 let value = accessor_to_json(&representation);
2987 let serde_json::Value::Object(values) = value else {
2988 return Err(async_graphql::Error::new(
2989 "entity representation must be an object",
2990 ));
2991 };
2992 let type_name = values
2993 .get("__typename")
2994 .and_then(serde_json::Value::as_str)
2995 .ok_or_else(|| {
2996 async_graphql::Error::new("entity representation is missing __typename")
2997 })?
2998 .to_string();
2999 grouped
3000 .entry(type_name.clone())
3001 .or_default()
3002 .push(EntityRepresentation {
3003 index,
3004 type_name,
3005 values,
3006 });
3007 }
3008
3009 let mut resolved: Vec<Option<FieldValue<'a>>> =
3010 std::iter::repeat_with(|| None).take(count).collect();
3011 for (type_name, representations) in grouped {
3012 let lookup = state.entities.get(&type_name).ok_or_else(|| {
3013 async_graphql::Error::new(format!("unknown federation entity \"{}\"", type_name))
3014 })?;
3015 let rows = resolve_entity_group(ctx, lookup, &representations, state).await?;
3016 for (ordinality, representation) in representations.into_iter().enumerate() {
3017 resolved[representation.index] = Some(match &rows[ordinality] {
3018 Some(row) => FieldValue::value(json_to_value(row.clone()))
3019 .with_type(representation.type_name),
3020 None => FieldValue::NULL,
3021 });
3022 }
3023 }
3024
3025 Ok(Some(FieldValue::list(resolved.into_iter().map(|value| {
3026 value.expect("every representation was resolved or errored")
3027 }))))
3028}
3029
3030async fn resolve_entity_group(
3031 ctx: &ResolverContext<'_>,
3032 lookup: &EntityLookup,
3033 representations: &[EntityRepresentation],
3034 state: &EntityResolverState,
3035) -> Result<Vec<Option<serde_json::Value>>, async_graphql::Error> {
3036 if representations.is_empty() {
3037 return Ok(Vec::new());
3038 }
3039
3040 let pool = ctx.data::<PgPool>()?;
3041 let gql_ctx = ctx.data::<GraphQLContext>()?;
3042 let mut bound_values = Vec::new();
3043 let mut value_rows = Vec::with_capacity(representations.len());
3044 for (ordinality, representation) in representations.iter().enumerate() {
3045 let normalized_values = normalized_entity_key_values(
3046 &representation.values,
3047 &lookup.key_columns,
3048 &lookup.type_name,
3049 )?;
3050 let mut values = Vec::with_capacity(lookup.key_columns.len() + 1);
3051 for (key_column, value) in lookup.key_columns.iter().zip(normalized_values) {
3052 values.push(format!(
3053 "${}::{}",
3054 bound_values.len() + 1,
3055 key_column.pg_type
3056 ));
3057 bound_values.push(value);
3058 }
3059 values.push(ordinality.to_string());
3060 value_rows.push(format!("({})", values.join(", ")));
3061 }
3062
3063 let representation_alias = "pgrst_entity_representation";
3064 let ordinality_column = "pgrst_entity_ordinality";
3065 let key_aliases: Vec<String> = (0..lookup.key_columns.len())
3066 .map(|index| format!("pgrst_entity_key_{index}"))
3067 .collect();
3068 let mut representation_columns: Vec<String> = key_aliases
3069 .iter()
3070 .map(|column| postrust_sql::escape_ident(column))
3071 .collect();
3072 representation_columns.push(postrust_sql::escape_ident(ordinality_column));
3073 let representations_sql = format!(
3074 "(VALUES {}) AS {} ({})",
3075 value_rows.join(", "),
3076 postrust_sql::escape_ident(representation_alias),
3077 representation_columns.join(", ")
3078 );
3079 let key_predicate = lookup
3080 .key_columns
3081 .iter()
3082 .zip(&key_aliases)
3083 .map(|(key_column, key_alias)| {
3084 format!(
3085 "{}.{} = {}.{}",
3086 postrust_sql::escape_ident(READ_ROW),
3087 postrust_sql::escape_ident(&key_column.column_name),
3088 postrust_sql::escape_ident(representation_alias),
3089 postrust_sql::escape_ident(key_alias)
3090 )
3091 })
3092 .collect::<Vec<_>>()
3093 .join(" AND ");
3094 let mut where_sql = format!(" WHERE ({key_predicate})");
3095
3096 let permission = permission_predicate(
3097 &gql_ctx.caller(),
3098 state.names.as_ref(),
3099 &lookup.schema_name,
3100 &lookup.table_name,
3101 )?;
3102 if let Some(predicate) = permission {
3103 let guard = gql_ctx
3104 .schema_cache
3105 .get()
3106 .await
3107 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3108 let cache = guard
3109 .as_ref()
3110 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3111 let scope = WhereScope::table(
3112 &lookup.schema_name,
3113 &lookup.table_name,
3114 &lookup.type_name,
3115 state.names.as_ref(),
3116 )
3117 .under_alias(READ_ROW)
3118 .with_resolution(cache, state.relationships.as_ref())
3119 .for_caller(gql_ctx.caller());
3120 let (filter_sql, filter_values) =
3121 build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
3122 if !filter_sql.is_empty() {
3123 where_sql = format!(
3124 "{} AND ({})",
3125 where_sql,
3126 filter_sql.trim_start_matches("WHERE ")
3127 );
3128 bound_values.extend(filter_values);
3129 }
3130 }
3131
3132 let source = format!(
3133 "{}.{} AS {}",
3134 postrust_sql::escape_ident(&lookup.schema_name),
3135 postrust_sql::escape_ident(&lookup.table_name),
3136 postrust_sql::escape_ident(READ_ROW)
3137 );
3138 let source_rows = format!(
3139 "SELECT {}.* FROM {}{}",
3140 postrust_sql::escape_ident(READ_ROW),
3141 source,
3142 where_sql
3143 );
3144 let mut projection = {
3145 let guard = gql_ctx
3146 .schema_cache
3147 .get()
3148 .await
3149 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3150 guard
3151 .as_ref()
3152 .and_then(|cache| {
3153 cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
3154 &lookup.schema_name,
3155 &lookup.table_name,
3156 ))
3157 })
3158 .and_then(|table| rename_projection(table, "src", state.names.as_ref()))
3159 .unwrap_or_else(|| "src.*".to_string())
3160 };
3161 let projected_rows = {
3162 let guard = gql_ctx
3163 .schema_cache
3164 .get()
3165 .await
3166 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3167 let cache = guard
3168 .as_ref()
3169 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3170 let table = cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
3171 &lookup.schema_name,
3172 &lookup.table_name,
3173 ));
3174 let selected_fields = entity_selection_fields(ctx, &lookup.type_name);
3175 let mut param_idx = bound_values.len() + 1;
3176 let computed = match table {
3177 Some(table) => computed_projections(
3178 table,
3179 selected_fields.iter().copied(),
3180 "src",
3181 state.names.as_ref(),
3182 cache,
3183 &mut param_idx,
3184 &mut bound_values,
3185 )?,
3186 None => Vec::new(),
3187 };
3188 let embeds = build_embed_expressions(
3189 &gql_ctx.caller(),
3190 cache,
3191 state.relationships.as_ref(),
3192 &lookup.type_name,
3193 "src",
3194 selected_fields,
3195 state.max_rows,
3196 &mut 0,
3197 &mut param_idx,
3198 &mut bound_values,
3199 state.names.as_ref(),
3200 )?;
3201 for expression in &computed {
3202 projection.push_str(", ");
3203 projection.push_str(expression);
3204 }
3205 for (field_name, expression) in &embeds {
3206 projection.push_str(", ");
3207 projection.push_str(expression);
3208 projection.push_str(" AS ");
3209 projection.push_str(&postrust_sql::escape_ident(field_name));
3210 }
3211 format!("SELECT {} FROM ({}) AS src", projection, source_rows)
3212 };
3213 let sql = format!(
3218 "SELECT json_build_array({}.{}, {}) FROM {} CROSS JOIN LATERAL ({}) AS t",
3219 postrust_sql::escape_ident(representation_alias),
3220 postrust_sql::escape_ident(ordinality_column),
3221 row_json("t", &lookup.row_column_types),
3222 representations_sql,
3223 projected_rows,
3224 );
3225 let mut tx = begin_with_session(pool, gql_ctx).await?;
3226 let rows = execute_query_on(&mut tx, &sql, &bound_values).await?;
3227 tx.commit().await?;
3228
3229 let mut by_ordinal = std::iter::repeat_with(|| None)
3230 .take(representations.len())
3231 .collect::<Vec<_>>();
3232 for result in rows {
3233 let serde_json::Value::Array(mut pair) = result else {
3234 return Err(async_graphql::Error::new(
3235 "entity query returned an invalid result",
3236 ));
3237 };
3238 if pair.len() != 2 {
3239 return Err(async_graphql::Error::new(
3240 "entity query returned an invalid result",
3241 ));
3242 }
3243 let row = pair.pop().expect("the result pair has two values");
3244 let ordinality = pair
3245 .pop()
3246 .and_then(|value| value.as_u64())
3247 .and_then(|value| usize::try_from(value).ok())
3248 .filter(|value| *value < by_ordinal.len())
3249 .ok_or_else(|| async_graphql::Error::new("entity query returned an invalid ordinal"))?;
3250 by_ordinal[ordinality] = Some(row);
3251 }
3252 Ok(by_ordinal)
3253}
3254
3255fn normalized_entity_key_values(
3259 values: &serde_json::Map<String, serde_json::Value>,
3260 key_columns: &[EntityKeyColumn],
3261 type_name: &str,
3262) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
3263 let mut key = Vec::with_capacity(key_columns.len());
3264 for key_column in key_columns {
3265 let value = values.get(&key_column.field_name).ok_or_else(|| {
3266 async_graphql::Error::new(format!(
3267 "entity representation for \"{}\" is missing key field \"{}\"",
3268 type_name, key_column.field_name
3269 ))
3270 })?;
3271 key.push(normalize_entity_key_value(type_name, key_column, value)?);
3272 }
3273 Ok(key)
3274}
3275
3276fn normalize_entity_key_value(
3277 type_name: &str,
3278 key_column: &EntityKeyColumn,
3279 value: &serde_json::Value,
3280) -> Result<serde_json::Value, async_graphql::Error> {
3281 let invalid = |expected: &str| {
3282 async_graphql::Error::new(format!(
3283 "entity representation for \"{}\" has invalid key field \"{}\": expected {}, found {}",
3284 type_name,
3285 key_column.field_name,
3286 expected,
3287 json_value_kind(value)
3288 ))
3289 };
3290
3291 if key_column.explicit_id {
3292 return normalize_graphql_id(value, &key_column.pg_type).ok_or_else(|| {
3293 invalid(&format!(
3294 "an ID compatible with PostgreSQL type \"{}\"",
3295 key_column.pg_type
3296 ))
3297 });
3298 }
3299
3300 let pg_type = key_column.pg_type.trim().to_ascii_lowercase();
3301 let normalized = if matches!(pg_type.as_str(), "int8" | "bigint") {
3302 match value {
3303 serde_json::Value::Number(number) => number.as_i64(),
3304 serde_json::Value::String(text) => text.parse::<i64>().ok(),
3305 _ => None,
3306 }
3307 .map(serde_json::Value::from)
3308 } else if integer_bounds(&pg_type).is_some() {
3309 value.as_i64().and_then(|integer| {
3310 let (min, max) = integer_bounds(&pg_type)?;
3311 (min..=max)
3312 .contains(&integer)
3313 .then(|| serde_json::Value::from(integer))
3314 })
3315 } else if matches!(
3316 pg_type.as_str(),
3317 "float4" | "float8" | "real" | "double precision"
3318 ) {
3319 value
3320 .as_f64()
3321 .and_then(serde_json::Number::from_f64)
3322 .map(serde_json::Value::Number)
3323 } else if matches!(pg_type.as_str(), "numeric" | "decimal") {
3324 match value {
3325 serde_json::Value::Number(number) => {
3326 Some(serde_json::Value::String(number.to_string()))
3327 }
3328 serde_json::Value::String(text) if text.parse::<sqlx::types::BigDecimal>().is_ok() => {
3329 Some(serde_json::Value::String(text.clone()))
3330 }
3331 _ => None,
3332 }
3333 } else if matches!(pg_type.as_str(), "bool" | "boolean") {
3334 value.as_bool().map(serde_json::Value::Bool)
3335 } else if matches!(pg_type.as_str(), "json" | "jsonb") {
3336 Some(value.clone())
3337 } else if is_array_type(&pg_type) {
3338 value.is_array().then(|| value.clone())
3339 } else {
3340 value
3341 .as_str()
3342 .map(|text| serde_json::Value::String(text.to_string()))
3343 };
3344
3345 normalized.ok_or_else(|| {
3346 invalid(&format!(
3347 "a value compatible with PostgreSQL type \"{}\"",
3348 key_column.pg_type
3349 ))
3350 })
3351}
3352
3353fn normalize_graphql_id(value: &serde_json::Value, pg_type: &str) -> Option<serde_json::Value> {
3354 if integer_bounds(pg_type).is_some() {
3355 let integer = match value {
3356 serde_json::Value::Number(number) => number.as_i64(),
3357 serde_json::Value::String(text) => text.parse::<i64>().ok(),
3358 _ => None,
3359 }?;
3360 let (min, max) = integer_bounds(pg_type)?;
3361 return (min..=max)
3362 .contains(&integer)
3363 .then(|| serde_json::Value::from(integer));
3364 }
3365 if pg_type.eq_ignore_ascii_case("uuid") {
3366 return normalize_uuid(value).map(serde_json::Value::String);
3367 }
3368 if is_text_type(pg_type) {
3369 return match value {
3370 serde_json::Value::String(s) => Some(serde_json::Value::String(s.clone())),
3371 serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => {
3372 Some(serde_json::Value::String(n.to_string()))
3373 }
3374 _ => None,
3375 };
3376 }
3377 None
3378}
3379
3380fn integer_bounds(pg_type: &str) -> Option<(i64, i64)> {
3381 match pg_type.trim().to_ascii_lowercase().as_str() {
3382 "int2" | "smallint" => Some((i16::MIN.into(), i16::MAX.into())),
3383 "int4" | "int" | "integer" => Some((i32::MIN.into(), i32::MAX.into())),
3384 "int8" | "bigint" => Some((i64::MIN, i64::MAX)),
3385 _ => None,
3386 }
3387}
3388
3389fn is_text_type(pg_type: &str) -> bool {
3390 matches!(
3391 pg_type.trim().to_ascii_lowercase().as_str(),
3392 "text" | "varchar" | "character varying" | "char" | "character" | "bpchar" | "citext"
3393 )
3394}
3395
3396fn normalize_uuid(value: &serde_json::Value) -> Option<String> {
3397 sqlx::types::Uuid::parse_str(value.as_str()?)
3398 .ok()
3399 .map(|uuid| uuid.to_string())
3400}
3401
3402fn json_value_kind(value: &serde_json::Value) -> &'static str {
3403 match value {
3404 serde_json::Value::Null => "null",
3405 serde_json::Value::Bool(_) => "a boolean",
3406 serde_json::Value::Number(_) => "a number",
3407 serde_json::Value::String(_) => "a string",
3408 serde_json::Value::Array(_) => "an array",
3409 serde_json::Value::Object(_) => "an object",
3410 }
3411}
3412
3413fn add_function_fields(
3420 mut root: Object,
3421 generated: &GeneratedSchema,
3422 volatile: bool,
3423 max_rows: Option<i64>,
3424 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
3425 names: Arc<crate::names::NameOverrides>,
3426) -> Object {
3427 let taken: HashSet<&str> = if volatile {
3432 generated
3433 .mutation_fields
3434 .iter()
3435 .map(|f| f.name.as_str())
3436 .collect()
3437 } else {
3438 generated
3439 .query_fields
3440 .iter()
3441 .map(|f| f.name.as_str())
3442 .collect()
3443 };
3444
3445 for function in &generated.function_fields {
3446 if function.volatile != volatile {
3447 continue;
3448 }
3449 if taken.contains(function.name.as_str()) {
3450 tracing::warn!(
3451 "not exposing {}.{}({}) -- a table already has a root field \
3452 called {}",
3453 function.schema_name,
3454 function.function_name,
3455 function.argument_signature(),
3456 function.name,
3457 );
3458 continue;
3459 }
3460 let spec = Arc::new(QueryFieldSpec {
3461 schema_name: function.returns_table.0.clone(),
3462 table_name: function.returns_table.1.clone(),
3463 type_name: function.returns.clone(),
3464 is_by_pk: false,
3465 pk_columns: Vec::new(),
3466 max_rows,
3467 relationships: Arc::clone(&relationships),
3468 names: Arc::clone(&names),
3469 call: Some(Arc::new(FunctionCall {
3470 schema: function.schema_name.clone(),
3471 name: function.function_name.clone(),
3472 arguments: function.arguments.clone(),
3473 session_argument: function.session_argument.clone(),
3474 })),
3475 });
3476
3477 let mut field = Field::new(
3478 &function.name,
3479 TypeRef::named_nn_list_nn(&function.returns),
3480 move |ctx| {
3481 let spec = Arc::clone(&spec);
3482 FieldFuture::new(async move { resolve_query(&ctx, &spec).await })
3483 },
3484 );
3485 if !function.arguments.is_empty() {
3486 field = field.argument(InputValue::new(
3487 "args",
3488 TypeRef::named_nn(format!("{}_args", function.name)),
3489 ));
3490 }
3491 field = field
3492 .argument(InputValue::new(
3493 "where",
3494 TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
3495 &function.local_returns,
3496 )),
3497 ))
3498 .argument(InputValue::new(
3499 "order_by",
3500 TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
3501 &function.local_returns,
3502 )),
3503 ))
3504 .argument(InputValue::new(
3505 "distinct_on",
3506 TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
3507 &function.local_returns,
3508 )),
3509 ))
3510 .argument(InputValue::new("limit", TypeRef::named("Int")))
3511 .argument(InputValue::new("offset", TypeRef::named("Int")));
3512 if let Some(description) = &function.description {
3513 field = field.description(description);
3514 }
3515 root = root.field(field);
3516
3517 let agg_spec = Arc::new(AggregateSpec {
3522 schema_name: function.returns_table.0.clone(),
3523 table_name: function.returns_table.1.clone(),
3524 type_name: function.returns.clone(),
3525 max_rows,
3526 relationships: Arc::clone(&relationships),
3527 names: Arc::clone(&names),
3528 call: Some(Arc::new(FunctionCall {
3529 schema: function.schema_name.clone(),
3530 name: function.function_name.clone(),
3531 arguments: function.arguments.clone(),
3532 session_argument: function.session_argument.clone(),
3533 })),
3534 });
3535 let mut aggregate = Field::new(
3536 format!("{}_aggregate", function.name),
3537 TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
3538 &function.local_returns,
3539 )),
3540 move |ctx| {
3541 let agg_spec = Arc::clone(&agg_spec);
3542 FieldFuture::new(async move { resolve_aggregate(&ctx, &agg_spec).await })
3543 },
3544 );
3545 if !function.arguments.is_empty() {
3546 aggregate = aggregate.argument(InputValue::new(
3547 "args",
3548 TypeRef::named_nn(format!("{}_args", function.name)),
3549 ));
3550 }
3551 aggregate = with_row_arguments(aggregate, &function.local_returns).description(format!(
3552 "fetch aggregated fields from the table: \"{}\"",
3553 function.returns_table.1
3554 ));
3555 root = root.field(aggregate);
3556 }
3557 root
3558}
3559
3560fn function_source(
3568 ctx: &ResolverContext<'_>,
3569 call: &FunctionCall,
3570 alias: &str,
3571 bound_values: &mut Vec<serde_json::Value>,
3572) -> Result<String, async_graphql::Error> {
3573 let given = ctx
3574 .args
3575 .try_get("args")
3576 .ok()
3577 .map(|v| accessor_to_json(&v))
3578 .unwrap_or_else(|| serde_json::json!({}));
3579 let mut passed = Vec::new();
3580 for (name, _, required) in &call.arguments {
3581 match given.get(name) {
3582 None if *required => {
3583 return Err(async_graphql::Error::new(format!(
3584 "{} needs the argument \"{}\"",
3585 call.name, name
3586 )))
3587 }
3588 None => continue,
3591 Some(value) => {
3592 let (_, pg_type, _) = call
3599 .arguments
3600 .iter()
3601 .find(|(argument, _, _)| argument == name)
3602 .expect("iterating the arguments");
3603 passed.push(format!(
3604 "{} => ${}::{}",
3605 postrust_sql::escape_ident(name),
3606 bound_values.len() + 1,
3607 pg_type
3608 ));
3609 bound_values.push(value.clone());
3610 }
3611 }
3612 }
3613 if let Some(session) = &call.session_argument {
3617 passed.push(format!(
3618 "{} => {}",
3619 postrust_sql::escape_ident(session),
3620 SESSION_ARGUMENT
3621 ));
3622 }
3623 Ok(format!(
3624 "{}.{}({}) AS {}",
3625 postrust_sql::escape_ident(&call.schema),
3626 postrust_sql::escape_ident(&call.name),
3627 passed.join(", "),
3628 postrust_sql::escape_ident(alias)
3629 ))
3630}
3631
3632struct FunctionCall {
3634 schema: String,
3635 name: String,
3636 arguments: Vec<(String, String, bool)>,
3637 session_argument: Option<String>,
3640}
3641
3642struct AggregateSpec {
3644 schema_name: String,
3645 table_name: String,
3646 type_name: String,
3647 max_rows: Option<i64>,
3648 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
3649 names: Arc<crate::names::NameOverrides>,
3650 call: Option<Arc<FunctionCall>>,
3654}
3655
3656async fn resolve_aggregate<'a>(
3663 ctx: &ResolverContext<'a>,
3664 spec: &AggregateSpec,
3665) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
3666 Ok(Some(FieldValue::value(aggregate_value(ctx, spec).await?)))
3667}
3668
3669async fn aggregate_value(
3674 ctx: &ResolverContext<'_>,
3675 spec: &AggregateSpec,
3676) -> Result<Value, async_graphql::Error> {
3677 use crate::schema::aggregate as agg;
3678
3679 let pool = ctx.data::<PgPool>()?;
3680 let gql_ctx = ctx.data::<GraphQLContext>()?;
3681
3682 let mut bound_values: Vec<serde_json::Value> = Vec::new();
3683 let source = match &spec.call {
3687 None => format!(
3688 "{}.{}",
3689 postrust_sql::escape_ident(&spec.schema_name),
3690 postrust_sql::escape_ident(&spec.table_name)
3691 ),
3692 Some(call) => function_source(ctx, call, &spec.table_name, &mut bound_values)?,
3693 };
3694
3695 let mut where_sql = String::new();
3696 {
3697 let requested = ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v));
3701 let permission = permission_predicate(
3702 &gql_ctx.caller(),
3703 spec.names.as_ref(),
3704 &spec.schema_name,
3705 &spec.table_name,
3706 )?;
3707 if let Some(predicate) = and_predicates(requested, permission) {
3708 let guard = gql_ctx
3709 .schema_cache
3710 .get()
3711 .await
3712 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3713 let cache = guard
3714 .as_ref()
3715 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3716 let scope = match &spec.call {
3723 None => WhereScope::table(
3724 &spec.schema_name,
3725 &spec.table_name,
3726 &spec.type_name,
3727 spec.names.as_ref(),
3728 )
3729 .with_resolution(cache, spec.relationships.as_ref()),
3730 Some(_) => WhereScope::for_alias(
3731 &spec.schema_name,
3732 &spec.table_name,
3733 &spec.table_name,
3734 &spec.type_name,
3735 cache,
3736 spec.relationships.as_ref(),
3737 spec.names.as_ref(),
3738 ),
3739 }
3740 .for_caller(gql_ctx.caller());
3741 let (sql, values) =
3742 build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
3743 if !sql.is_empty() {
3744 where_sql = format!(" {}", sql);
3745 bound_values.extend(values);
3746 }
3747 }
3748 }
3749
3750 let order_sql = build_order_by_clause(
3751 ctx,
3752 &gql_ctx.schema_cache,
3753 &spec.schema_name,
3754 &spec.table_name,
3755 &spec.type_name,
3756 spec.relationships.as_ref(),
3757 &format!(
3758 "{}.{}",
3759 postrust_sql::escape_ident(&spec.schema_name),
3760 postrust_sql::escape_ident(&spec.table_name)
3761 ),
3762 spec.names.as_ref(),
3763 )
3764 .await?;
3765
3766 let requested_limit = ctx.args.try_get("limit").ok().and_then(|v| v.i64().ok());
3767 let offset = ctx.args.try_get("offset").ok().and_then(|v| v.i64().ok());
3768 let ceiling = match (
3769 spec.max_rows,
3770 permission_limit(
3771 &gql_ctx.caller(),
3772 spec.names.as_ref(),
3773 &spec.schema_name,
3774 &spec.table_name,
3775 ),
3776 ) {
3777 (Some(configured), Some(granted)) => Some(configured.min(granted)),
3778 (only, None) | (None, only) => only,
3779 };
3780 let limit = match (requested_limit, ceiling) {
3781 (Some(requested), Some(ceiling)) => Some(requested.min(ceiling)),
3782 (Some(requested), None) => Some(requested),
3783 (None, ceiling) => ceiling,
3784 };
3785
3786 let rows = format!("SELECT * FROM {}{}{}", source, where_sql, order_sql);
3787
3788 let mut inner = rows.clone();
3790 if let Some(limit) = limit {
3791 inner.push_str(&format!(" LIMIT {}", limit));
3792 }
3793 if let Some(offset) = offset {
3794 inner.push_str(&format!(" OFFSET {}", offset));
3795 }
3796
3797 let mut counted = rows;
3811 if let Some(limit) = requested_limit {
3812 counted.push_str(&format!(" LIMIT {}", limit));
3813 }
3814 if let Some(offset) = offset {
3815 counted.push_str(&format!(" OFFSET {}", offset));
3816 }
3817
3818 let mut wants_nodes = false;
3823 let mut wants_aggregate = false;
3824 let mut wanted: BTreeMap<String, Vec<String>> = BTreeMap::new();
3825 let mut counts: Vec<(String, String)> = Vec::new();
3828 for selection in ctx.field().selection_set() {
3829 match selection.name() {
3830 "nodes" => wants_nodes = true,
3831 "aggregate" => {
3832 wants_aggregate = true;
3833 for function in selection.selection_set() {
3834 if function.name() == "__typename" {
3836 continue;
3837 }
3838 if function.name() == "count" {
3839 counts.push((
3840 function.alias().unwrap_or("count").to_string(),
3841 count_expression(
3842 function,
3843 (&spec.schema_name, &spec.table_name),
3844 None,
3845 spec.names.as_ref(),
3846 ),
3847 ));
3848 continue;
3849 }
3850 let columns = wanted.entry(function.name().to_string()).or_default();
3853 for column in function.selection_set() {
3854 let name = column.name().to_string();
3855 if name != "__typename" && !columns.contains(&name) {
3856 columns.push(name);
3857 }
3858 }
3859 }
3860 }
3861 _ => {}
3862 }
3863 }
3864
3865 let mut result = async_graphql::indexmap::IndexMap::new();
3866
3867 if wants_aggregate {
3870 let mut parts = match counts.iter().any(|(key, _)| key == "count") {
3874 true => Vec::new(),
3875 false => vec!["'count', count(*)".to_string()],
3876 };
3877 for (key, expression) in &counts {
3878 parts.push(format!(
3879 "{}, {}",
3880 postrust_sql::quote_literal(key),
3881 expression
3882 ));
3883 }
3884 for (function, columns) in &wanted {
3885 let sql_function = agg::NUMERIC_AGGREGATES
3889 .iter()
3890 .chain(agg::ORDERED_AGGREGATES.iter())
3891 .find(|(name, _)| name == function)
3892 .map(|(name, _)| *name)
3893 .ok_or_else(|| {
3894 async_graphql::Error::new(format!("unknown aggregate \"{}\"", function))
3895 })?;
3896 let per_column: Vec<String> = columns
3897 .iter()
3898 .map(|field| {
3899 let source = spec
3900 .names
3901 .column_source(&spec.schema_name, &spec.table_name, field)
3902 .unwrap_or(field);
3903 format!(
3904 "{}, {}({})",
3905 postrust_sql::quote_literal(field),
3906 sql_function,
3907 postrust_sql::escape_ident(source)
3908 )
3909 })
3910 .collect();
3911 parts.push(format!(
3912 "'{}', json_build_object({})",
3913 sql_function,
3914 per_column.join(", ")
3915 ));
3916 }
3917
3918 let sql = format!(
3919 "SELECT json_build_object({}) FROM ({}) AS pgrst_agg",
3920 parts.join(", "),
3921 counted
3922 );
3923 let mut conn = begin_with_session(pool, gql_ctx).await?;
3924 let rows = execute_query_on(&mut conn, &sql, &bound_values).await?;
3925 conn.commit().await?;
3926 if let Some(first) = rows.into_iter().next() {
3927 if let Value::Object(map) = json_to_value(first) {
3928 result.insert(async_graphql::Name::new("aggregate"), Value::Object(map));
3929 }
3930 }
3931 }
3932
3933 if wants_nodes {
3934 let nodes = ctx
3940 .field()
3941 .selection_set()
3942 .find(|selection| selection.name() == "nodes")
3943 .ok_or_else(|| async_graphql::Error::new("nodes was asked for and then was not"))?;
3944
3945 let mut node_values = bound_values.clone();
3949 let (projection, row_column_types) = {
3950 let guard = gql_ctx
3951 .schema_cache
3952 .get()
3953 .await
3954 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3955 let cache = guard
3956 .as_ref()
3957 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3958 let qi = postrust_core::api_request::QualifiedIdentifier::new(
3959 &spec.schema_name,
3960 &spec.table_name,
3961 );
3962 let table = cache.get_table(&qi);
3963 let mut param_idx = node_values.len() + 1;
3964 let computed = match table {
3965 Some(table) => computed_projections(
3966 table,
3967 nodes.selection_set(),
3968 "src",
3969 spec.names.as_ref(),
3970 cache,
3971 &mut param_idx,
3972 &mut node_values,
3973 )?,
3974 None => Vec::new(),
3975 };
3976 let embeds = build_embed_expressions(
3977 &gql_ctx.caller(),
3978 cache,
3979 spec.relationships.as_ref(),
3980 &spec.type_name,
3981 "src",
3982 nodes.selection_set(),
3983 spec.max_rows,
3984 &mut 0,
3985 &mut param_idx,
3986 &mut node_values,
3987 spec.names.as_ref(),
3988 )?;
3989 let mut projection = table
3993 .and_then(|table| rename_projection(table, "src", spec.names.as_ref()))
3994 .unwrap_or_else(|| "src.*".to_string());
3995 for expression in &computed {
3996 projection.push_str(", ");
3997 projection.push_str(expression);
3998 }
3999 for (field_name, expression) in &embeds {
4000 projection.push_str(", ");
4001 projection.push_str(expression);
4002 projection.push_str(" AS ");
4003 projection.push_str(&postrust_sql::escape_ident(field_name));
4004 }
4005 (
4006 projection,
4007 table
4008 .map(|table| exposed_column_types(table, spec.names.as_ref()))
4009 .unwrap_or_default(),
4010 )
4011 };
4012
4013 let sql = format!(
4014 "SELECT {} FROM (SELECT {} FROM ({}) AS src) AS pgrst_nodes",
4015 row_json("pgrst_nodes", &row_column_types),
4016 projection,
4017 inner
4018 );
4019 let mut conn = begin_with_session(pool, gql_ctx).await?;
4020 let rows = execute_query_on(&mut conn, &sql, &node_values).await?;
4021 conn.commit().await?;
4022 result.insert(
4023 async_graphql::Name::new("nodes"),
4024 Value::List(rows.into_iter().map(json_to_value).collect()),
4025 );
4026 }
4027
4028 let _ = &spec.type_name;
4029 Ok(Value::Object(result))
4030}
4031
4032async fn resolve_query<'a>(
4034 ctx: &ResolverContext<'a>,
4035 spec: &QueryFieldSpec,
4036) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
4037 Ok(rows_as_field_value(
4038 query_rows(ctx, spec).await?,
4039 spec.is_by_pk,
4040 ))
4041}
4042
4043async fn query_rows(
4049 ctx: &ResolverContext<'_>,
4050 spec: &QueryFieldSpec,
4051) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
4052 let schema_name = spec.schema_name.as_str();
4053 let table_name = spec.table_name.as_str();
4054 let type_name = spec.type_name.as_str();
4055 let is_by_pk = spec.is_by_pk;
4056 let pk_columns = spec.pk_columns.as_slice();
4057 let max_rows = spec.max_rows;
4058 let relationships = spec.relationships.as_ref();
4059
4060 let pool = ctx.data::<PgPool>()?;
4061 let gql_ctx = ctx.data::<GraphQLContext>()?;
4062
4063 debug!("Resolving query for table: {}", table_name);
4064
4065 let requested_limit: Option<i64> = ctx.args.try_get("limit").ok().and_then(|v| v.i64().ok());
4067
4068 let offset: Option<i64> = ctx.args.try_get("offset").ok().and_then(|v| v.i64().ok());
4069
4070 let limit: Option<i64> = if is_by_pk {
4075 Some(1)
4076 } else {
4077 let ceiling = match (
4081 max_rows,
4082 permission_limit(
4083 &gql_ctx.caller(),
4084 spec.names.as_ref(),
4085 schema_name,
4086 table_name,
4087 ),
4088 ) {
4089 (Some(configured), Some(granted)) => Some(configured.min(granted)),
4090 (only, None) | (None, only) => only,
4091 };
4092 match (requested_limit, ceiling) {
4093 (Some(requested), Some(ceiling)) => Some(requested.min(ceiling)),
4094 (Some(requested), None) => Some(requested),
4095 (None, ceiling) => ceiling,
4096 }
4097 };
4098
4099 let mut where_sql = String::new();
4107 let mut bound_values: Vec<serde_json::Value> = Vec::new();
4108
4109 let source = match &spec.call {
4113 None => format!(
4119 "{}.{} AS {}",
4120 postrust_sql::escape_ident(schema_name),
4121 postrust_sql::escape_ident(table_name),
4122 postrust_sql::escape_ident(READ_ROW)
4123 ),
4124 Some(call) => function_source(ctx, call, table_name, &mut bound_values)?,
4125 };
4126
4127 let source_ref = match &spec.call {
4130 None => postrust_sql::escape_ident(READ_ROW),
4131 Some(_) => postrust_sql::escape_ident(table_name),
4132 };
4133
4134 if is_by_pk {
4135 if pk_columns.is_empty() {
4136 return Err(async_graphql::Error::new(format!(
4137 "\"{}\" has no primary key, so it cannot be queried by key",
4138 table_name
4139 )));
4140 }
4141
4142 let mut conditions = Vec::with_capacity(pk_columns.len());
4143 for (idx, (col_name, pg_type)) in pk_columns.iter().enumerate() {
4144 let field = spec
4145 .names
4146 .column(schema_name, table_name, col_name)
4147 .unwrap_or(col_name);
4148 let value = ctx.args.try_get(field).map_err(|_| {
4149 async_graphql::Error::new(format!(
4150 "missing required primary key argument \"{}\"",
4151 field
4152 ))
4153 })?;
4154
4155 conditions.push(format!(
4156 "{} = ${}::{}",
4157 postrust_sql::escape_ident(col_name),
4158 idx + 1,
4159 pg_type
4160 ));
4161 bound_values.push(accessor_to_json(&value));
4162 }
4163 where_sql = format!(" WHERE {}", conditions.join(" AND "));
4164 }
4165
4166 {
4171 let requested = match is_by_pk {
4172 true => None,
4173 false => ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v)),
4174 };
4175 let permission = permission_predicate(
4176 &gql_ctx.caller(),
4177 spec.names.as_ref(),
4178 schema_name,
4179 table_name,
4180 )?;
4181
4182 if let Some(predicate) = and_predicates(requested, permission) {
4183 let guard = gql_ctx
4184 .schema_cache
4185 .get()
4186 .await
4187 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4188 let cache = guard
4189 .as_ref()
4190 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4191 let scope = match &spec.call {
4192 None => WhereScope::table(schema_name, table_name, type_name, spec.names.as_ref())
4193 .under_alias(READ_ROW)
4194 .with_resolution(cache, relationships)
4195 .for_caller(gql_ctx.caller()),
4196 Some(_) => WhereScope::for_alias(
4199 schema_name,
4200 table_name,
4201 table_name,
4202 type_name,
4203 cache,
4204 relationships,
4205 spec.names.as_ref(),
4206 )
4207 .for_caller(gql_ctx.caller()),
4208 };
4209 let (filter_sql, filter_values) =
4210 build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
4211 if !filter_sql.is_empty() {
4212 where_sql = match where_sql.is_empty() {
4215 true => format!(" {}", filter_sql),
4216 false => format!(
4217 "{} AND ({})",
4218 where_sql,
4219 filter_sql.trim_start_matches("WHERE ")
4220 ),
4221 };
4222 bound_values.extend(filter_values);
4223 }
4224 }
4225 }
4226
4227 let (order_sql, distinct_on) = if is_by_pk {
4230 (String::new(), Vec::new())
4231 } else {
4232 (
4233 build_order_by_clause(
4234 ctx,
4235 &gql_ctx.schema_cache,
4236 schema_name,
4237 table_name,
4238 type_name,
4239 relationships,
4240 &source_ref,
4241 spec.names.as_ref(),
4242 )
4243 .await?,
4244 build_distinct_on(
4245 ctx,
4246 &gql_ctx.schema_cache,
4247 schema_name,
4248 table_name,
4249 spec.names.as_ref(),
4250 )
4251 .await?,
4252 )
4253 };
4254
4255 let (distinct_sql, order_sql) = {
4263 let written = order_sql.strip_prefix(" ORDER BY ");
4264 let (prefix, order) = distinct_on_clause(&distinct_on, written).map_err(|error| {
4267 at_path(
4268 error,
4269 &format!(
4270 "$.selectionSet.{}.args",
4271 ctx.ctx.field().alias().unwrap_or(ctx.ctx.field().name())
4272 ),
4273 )
4274 })?;
4275 (
4276 prefix,
4277 match order {
4278 Some(order) => format!(" ORDER BY {}", order),
4279 None => String::new(),
4280 },
4281 )
4282 };
4283
4284 let (computed, row_column_types) = {
4287 let guard = gql_ctx
4288 .schema_cache
4289 .get()
4290 .await
4291 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4292 match guard.as_ref() {
4293 Some(cache) => {
4294 let qi =
4295 postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
4296 match cache.get_table(&qi) {
4297 Some(table) => {
4298 let mut param_idx = bound_values.len() + 1;
4299 (
4300 computed_projections(
4301 table,
4302 ctx.field().selection_set(),
4303 "src",
4304 spec.names.as_ref(),
4305 cache,
4306 &mut param_idx,
4307 &mut bound_values,
4308 )?,
4309 exposed_column_types(table, spec.names.as_ref()),
4310 )
4311 }
4312 None => (Vec::new(), HashMap::new()),
4313 }
4314 }
4315 None => (Vec::new(), HashMap::new()),
4316 }
4317 };
4318 let mut inner = format!(
4322 "SELECT {}* FROM {}{}{}",
4323 distinct_sql, source, where_sql, order_sql
4324 );
4325
4326 if let Some(limit) = limit {
4327 inner.push_str(&format!(" LIMIT {}", limit));
4328 }
4329
4330 if let Some(offset) = offset {
4331 inner.push_str(&format!(" OFFSET {}", offset));
4332 }
4333
4334 let embed_expressions = {
4337 let guard = gql_ctx
4338 .schema_cache
4339 .get()
4340 .await
4341 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4342 match guard.as_ref() {
4343 Some(cache) => {
4344 let mut param_idx = bound_values.len() + 1;
4349 build_embed_expressions(
4350 &gql_ctx.caller(),
4351 cache,
4352 relationships,
4353 type_name,
4354 "src",
4355 ctx.field().selection_set(),
4356 max_rows,
4357 &mut 0,
4358 &mut param_idx,
4359 &mut bound_values,
4360 spec.names.as_ref(),
4361 )?
4362 }
4363 None => Vec::new(),
4364 }
4365 };
4366
4367 let renamed = {
4375 let guard = gql_ctx
4376 .schema_cache
4377 .get()
4378 .await
4379 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4380 guard
4381 .as_ref()
4382 .and_then(|cache| {
4383 cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
4384 schema_name,
4385 table_name,
4386 ))
4387 })
4388 .and_then(|table| rename_projection(table, "src", spec.names.as_ref()))
4389 };
4390 let inner = if embed_expressions.is_empty() && computed.is_empty() && renamed.is_none() {
4391 inner
4392 } else {
4393 let mut projection = renamed.unwrap_or_else(|| "src.*".to_string());
4394 for expression in &computed {
4395 projection.push_str(", ");
4396 projection.push_str(expression);
4397 }
4398 for (field_name, expression) in &embed_expressions {
4399 projection.push_str(", ");
4400 projection.push_str(expression);
4401 projection.push_str(" AS ");
4402 projection.push_str(&postrust_sql::escape_ident(field_name));
4403 }
4404 format!("SELECT {} FROM ({}) AS src", projection, inner)
4405 };
4406
4407 let sql = format!(
4408 "SELECT {} FROM ({}) t",
4409 row_json("t", &row_column_types),
4410 inner
4411 );
4412
4413 let mut tx = begin_with_session(pool, gql_ctx).await?;
4417
4418 let mut result = execute_query_on(&mut tx, &sql, &bound_values).await?;
4420
4421 if embed_expressions.is_empty() {
4423 let guard = gql_ctx
4424 .schema_cache
4425 .get()
4426 .await
4427 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4428 let cache = guard
4429 .as_ref()
4430 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4431
4432 let embed_ctx = EmbedContext {
4433 schema_cache: cache,
4434 relationships,
4435 max_rows,
4436 };
4437
4438 embed_relationships(&mut tx, &embed_ctx, type_name, ctx.field(), &mut result).await?;
4439 }
4440
4441 tx.commit().await?;
4442
4443 Ok(result)
4444}
4445
4446fn rows_as_field_value<'a>(rows: Vec<serde_json::Value>, is_by_pk: bool) -> Option<FieldValue<'a>> {
4451 match is_by_pk {
4452 true => rows
4453 .into_iter()
4454 .next()
4455 .map(|v| FieldValue::value(json_to_value(v))),
4456 false => Some(FieldValue::list(
4457 rows.into_iter()
4458 .map(|v| FieldValue::value(json_to_value(v))),
4459 )),
4460 }
4461}
4462
4463#[allow(clippy::too_many_arguments)]
4465async fn resolve_mutation<'a>(
4466 ctx: &ResolverContext<'a>,
4467 schema_name: &str,
4468 table_name: &str,
4469 mutation_type: MutationType,
4470 pk_columns: &[(String, String)],
4471 relationships: &Arc<HashMap<String, Vec<RelationshipField>>>,
4472 type_names: &Arc<HashMap<(String, String), String>>,
4473 names: &Arc<crate::names::NameOverrides>,
4474 max_rows: Option<i64>,
4475) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
4476 let pool = ctx.data::<PgPool>()?;
4477 let gql_ctx = ctx.data::<GraphQLContext>()?;
4478
4479 debug!(
4480 "Resolving mutation for table: {} type: {:?}",
4481 table_name, mutation_type
4482 );
4483
4484 let type_name = type_names
4490 .get(&(schema_name.to_string(), table_name.to_string()))
4491 .cloned()
4492 .unwrap_or_else(|| table_name.to_string());
4493
4494 let by_key = matches!(
4495 mutation_type,
4496 MutationType::InsertOne | MutationType::UpdateByPk | MutationType::DeleteByPk
4497 );
4498 let returning = if by_key {
4499 Some(ctx.field())
4500 } else {
4501 ctx.field()
4502 .selection_set()
4503 .find(|selection| selection.name() == "returning")
4504 };
4505
4506 if mutation_type == MutationType::UpdateMany {
4511 let updates = ctx
4512 .args
4513 .try_get("updates")
4514 .ok()
4515 .map(|v| accessor_to_json(&v))
4516 .unwrap_or(serde_json::Value::Null);
4517 let serde_json::Value::Array(entries) = updates else {
4518 return Err(async_graphql::Error::new(
4519 "\"updates\" takes a list of {where, _set, …} objects",
4520 ));
4521 };
4522 let column_types = column_types_of(&gql_ctx.schema_cache, schema_name, table_name).await;
4523 let mut answers: Vec<FieldValue<'_>> = Vec::with_capacity(entries.len());
4524 for entry in entries {
4525 let serde_json::Value::Object(entry) = entry else {
4526 return Err(async_graphql::Error::new(
4527 "each update is an object of {where, _set, …}",
4528 ));
4529 };
4530 let operators: Vec<(&'static str, serde_json::Value)> = UPDATE_OPERATORS
4531 .iter()
4532 .filter_map(|name| entry.get(*name).map(|value| (*name, value.clone())))
4533 .filter(|(_, value)| !value.is_null())
4534 .collect();
4535 let rows = execute_update(
4536 pool,
4537 gql_ctx,
4538 schema_name,
4539 table_name,
4540 &type_name,
4541 operators,
4542 column_types.clone(),
4543 entry.get("where").cloned(),
4544 relationships.as_ref(),
4545 names.as_ref(),
4546 )
4547 .await?;
4548 let affected = rows.len();
4549 let rows = match returning {
4550 Some(returning) if !rows.is_empty() => {
4551 reread_returning(
4552 pool,
4553 gql_ctx,
4554 schema_name,
4555 table_name,
4556 &type_name,
4557 rows,
4558 returning,
4559 relationships.as_ref(),
4560 names.as_ref(),
4561 max_rows,
4562 )
4563 .await?
4564 }
4565 _ => rows,
4566 };
4567 answers.extend(mutation_result(rows, affected, false));
4568 }
4569 return Ok(Some(FieldValue::list(answers)));
4570 }
4571
4572 let (result, affected) = match mutation_type {
4573 MutationType::Insert | MutationType::InsertOne => {
4574 let objects = ctx
4575 .args
4576 .try_get("objects")
4577 .ok()
4578 .map(|v| accessor_to_json(&v))
4579 .or_else(|| {
4580 ctx.args
4583 .try_get("object")
4584 .ok()
4585 .map(|v| serde_json::Value::Array(vec![accessor_to_json(&v)]))
4586 })
4587 .unwrap_or_else(|| serde_json::Value::Array(vec![]));
4588
4589 let guard = gql_ctx
4590 .schema_cache
4591 .get()
4592 .await
4593 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4594 let cache = guard
4595 .as_ref()
4596 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4597 let here = format!(
4601 "$.selectionSet.{}",
4602 ctx.ctx.field().alias().unwrap_or(ctx.ctx.field().name())
4603 );
4604 let named = match mutation_type {
4607 MutationType::InsertOne => "object",
4608 _ => "objects",
4609 };
4610 let context = InsertContext {
4611 on_conflict: ctx
4612 .args
4613 .try_get("on_conflict")
4614 .ok()
4615 .map(|v| accessor_to_json(&v))
4616 .filter(|v| !v.is_null()),
4617 cache,
4618 relationships: relationships.as_ref(),
4619 type_names: type_names.as_ref(),
4620 names: names.as_ref(),
4621 caller: gql_ctx.caller(),
4622 row: String::new(),
4625 objects: format!("{}.args.{}", here, named),
4626 conflict: format!("{}.args.on_conflict", here),
4627 };
4628
4629 execute_insert(
4630 pool,
4631 gql_ctx,
4632 schema_name,
4633 table_name,
4634 objects,
4635 &context,
4636 mutation_type == MutationType::InsertOne,
4637 )
4638 .await?
4639 }
4640 MutationType::UpdateMany | MutationType::Update | MutationType::UpdateByPk => {
4643 let operators: Vec<(&'static str, serde_json::Value)> = UPDATE_OPERATORS
4647 .iter()
4648 .filter_map(|name| {
4649 ctx.args
4650 .try_get(name)
4651 .ok()
4652 .map(|v| (*name, accessor_to_json(&v)))
4653 })
4654 .filter(|(_, value)| !value.is_null())
4655 .collect();
4656
4657 let where_clause = if mutation_type == MutationType::UpdateByPk {
4658 Some(pk_where_from_args(
4659 ctx,
4660 schema_name,
4661 table_name,
4662 pk_columns,
4663 names.as_ref(),
4664 )?)
4665 } else {
4666 ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v))
4667 };
4668 let where_clause = and_predicates(
4672 where_clause,
4673 permission_filter(
4674 &gql_ctx.caller(),
4675 names.as_ref(),
4676 schema_name,
4677 table_name,
4678 crate::role::Verb::Update,
4679 )?,
4680 );
4681
4682 execute_update(
4683 pool,
4684 gql_ctx,
4685 schema_name,
4686 table_name,
4687 &type_name,
4688 operators,
4689 column_types_of(&gql_ctx.schema_cache, schema_name, table_name).await,
4690 where_clause,
4691 relationships.as_ref(),
4692 names.as_ref(),
4693 )
4694 .await
4695 .map(|rows| {
4696 let count = rows.len();
4697 (rows, count)
4698 })?
4699 }
4700 MutationType::Delete | MutationType::DeleteByPk => {
4701 let where_clause = if mutation_type == MutationType::DeleteByPk {
4702 Some(pk_where_from_args(
4703 ctx,
4704 schema_name,
4705 table_name,
4706 pk_columns,
4707 names.as_ref(),
4708 )?)
4709 } else {
4710 ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v))
4711 };
4712 let where_clause = and_predicates(
4713 where_clause,
4714 permission_filter(
4715 &gql_ctx.caller(),
4716 names.as_ref(),
4717 schema_name,
4718 table_name,
4719 crate::role::Verb::Delete,
4720 )?,
4721 );
4722
4723 execute_delete(
4724 pool,
4725 gql_ctx,
4726 schema_name,
4727 table_name,
4728 &type_name,
4729 where_clause,
4730 returning,
4731 relationships.as_ref(),
4732 names.as_ref(),
4733 max_rows,
4734 )
4735 .await
4736 .map(|rows| {
4737 let count = rows.len();
4738 (rows, count)
4739 })?
4740 }
4741 };
4742
4743 let is_delete = matches!(
4744 mutation_type,
4745 MutationType::Delete | MutationType::DeleteByPk
4746 );
4747 let result = match returning {
4748 Some(returning) if !result.is_empty() && !is_delete => {
4749 reread_returning(
4750 pool,
4751 gql_ctx,
4752 schema_name,
4753 table_name,
4754 &type_name,
4755 result,
4756 returning,
4757 relationships.as_ref(),
4758 names.as_ref(),
4759 max_rows,
4760 )
4761 .await?
4762 }
4763 _ => result,
4764 };
4765
4766 Ok(mutation_result(result, affected, by_key))
4767}
4768
4769async fn write_tx<'a>(
4777 gql_ctx: &'a GraphQLContext,
4778 pool: &PgPool,
4779) -> Result<
4780 tokio::sync::MutexGuard<'a, Option<sqlx::Transaction<'static, sqlx::Postgres>>>,
4781 async_graphql::Error,
4782> {
4783 let mut guard = gql_ctx.write.lock().await;
4784 if guard.is_none() {
4785 *guard = Some(begin_with_session(pool, gql_ctx).await?);
4786 }
4787 Ok(guard)
4788}
4789
4790async fn begin_with_session(
4807 pool: &PgPool,
4808 gql_ctx: &GraphQLContext,
4809) -> Result<sqlx::Transaction<'static, sqlx::Postgres>, async_graphql::Error> {
4810 let mut tx = pool.begin().await?;
4811 gql_ctx.session().apply_sqlx(&mut tx).await?;
4812 Ok(tx)
4813}
4814
4815fn row_json(expr: &str, column_types: &HashMap<String, String>) -> String {
4826 let mut shapes: Vec<(&String, &String)> = column_types
4827 .iter()
4828 .filter(|(_, pg_type)| matches!(pg_type.as_str(), "geometry" | "geography"))
4829 .collect();
4830 if shapes.is_empty() {
4831 return format!("row_to_json({})", expr);
4832 }
4833 shapes.sort();
4834
4835 let overrides: Vec<String> = shapes
4836 .iter()
4837 .map(|(name, _)| {
4838 format!(
4839 "{}, ST_AsGeoJSON({}.{}, 9, 4)::jsonb",
4845 postrust_sql::quote_literal(name),
4846 expr,
4847 postrust_sql::escape_ident(name)
4848 )
4849 })
4850 .collect();
4851 format!(
4852 "(to_jsonb({}) || jsonb_build_object({}))",
4853 expr,
4854 overrides.join(", ")
4855 )
4856}
4857
4858async fn execute_query_on(
4861 conn: &mut sqlx::PgConnection,
4862 sql: &str,
4863 params: &[serde_json::Value],
4864) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
4865 use sqlx::Row;
4866
4867 trace!("Executing SQL: {}", sql);
4868
4869 let mut query = sqlx::query(AssertSqlSafe(sql));
4871 for param in params {
4872 query = bind_json_value(query, param);
4873 }
4874 let rows = query.fetch_all(&mut *conn).await.map_err(database_error)?;
4875
4876 let results: Vec<serde_json::Value> = rows
4879 .into_iter()
4880 .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
4881 .collect();
4882
4883 Ok(results)
4884}
4885
4886fn check_geojson(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4899 fn refuse<T>(message: &str) -> Result<T, async_graphql::Error> {
4900 Err(coded_error("parse-failed", message))
4901 }
4902
4903 fn position(
4904 value: &serde_json::Value,
4905 ) -> Result<&Vec<serde_json::Value>, async_graphql::Error> {
4906 match value.as_array() {
4907 Some(items) if items.len() >= 2 && items.iter().all(|i| i.is_number()) => Ok(items),
4908 _ => refuse("A Position needs at least 2 elements"),
4909 }
4910 }
4911
4912 fn positions(
4913 value: Option<&serde_json::Value>,
4914 least: usize,
4915 what: &str,
4916 ) -> Result<Vec<Vec<serde_json::Value>>, async_graphql::Error> {
4917 let items = match value.and_then(|v| v.as_array()) {
4918 Some(items) => items,
4919 None => return refuse(&format!("A {} needs at least {} Positions", what, least)),
4920 };
4921 if items.len() < least {
4922 return refuse(&format!("A {} needs at least {} Positions", what, least));
4923 }
4924 items.iter().map(|item| position(item).cloned()).collect()
4925 }
4926
4927 fn ring(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4928 let points = positions(Some(value), 4, "LinearRing")?;
4929 match (points.first(), points.last()) {
4930 (Some(first), Some(last)) if first == last => Ok(()),
4931 _ => refuse("the first and last locations have to be equal for a LinearRing"),
4932 }
4933 }
4934
4935 fn polygon(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4936 let Some(rings) = value.as_array() else {
4937 return refuse("A LinearRing needs at least 4 Positions");
4938 };
4939 rings.iter().try_for_each(ring)
4940 }
4941
4942 let serde_json::Value::Object(map) = value else {
4943 return Ok(());
4944 };
4945 let Some(kind) = map.get("type").and_then(|v| v.as_str()) else {
4946 return Ok(());
4947 };
4948 let coordinates = map.get("coordinates");
4949 match kind {
4950 "Point" => {
4951 position(coordinates.unwrap_or(&serde_json::Value::Null))?;
4952 }
4953 "MultiPoint" => {
4954 positions(coordinates, 0, "MultiPoint")?;
4955 }
4956 "LineString" => {
4957 positions(coordinates, 2, "LineString")?;
4958 }
4959 "MultiLineString" => {
4960 for line in coordinates.and_then(|v| v.as_array()).into_iter().flatten() {
4961 positions(Some(line), 2, "LineString")?;
4962 }
4963 }
4964 "Polygon" => polygon(coordinates.unwrap_or(&serde_json::Value::Null))?,
4965 "MultiPolygon" => {
4966 for one in coordinates.and_then(|v| v.as_array()).into_iter().flatten() {
4967 polygon(one)?;
4968 }
4969 }
4970 "GeometryCollection" => {
4971 for geometry in map
4972 .get("geometries")
4973 .and_then(|v| v.as_array())
4974 .into_iter()
4975 .flatten()
4976 {
4977 check_geojson(geometry)?;
4978 }
4979 }
4980 other => return refuse(&format!("unexpected geometry type: {}", other)),
4981 }
4982 Ok(())
4983}
4984
4985fn computed_call(
4993 definition: &postrust_core::schema_cache::ComputedColumn,
4994 row: &str,
4995 row_by_name: &str,
4996) -> String {
4997 let function = format!(
4998 "{}.{}",
4999 postrust_sql::escape_ident(&definition.function.schema),
5000 postrust_sql::escape_ident(&definition.function.name)
5001 );
5002 match (&definition.session_argument, &definition.row_argument) {
5003 (Some(session), Some(row_argument)) => format!(
5004 "{}({} => {}, {} => {})",
5005 function,
5006 postrust_sql::escape_ident(row_argument),
5007 row_by_name,
5008 postrust_sql::escape_ident(session),
5009 SESSION_ARGUMENT
5010 ),
5011 _ => format!("{}({})", function, row),
5012 }
5013}
5014
5015const SESSION_ARGUMENT: &str = "coalesce(current_setting('hasura.session', true), '{}')::json";
5022
5023const UPDATE_OPERATORS: [&str; 7] = [
5026 "_set",
5027 "_inc",
5028 "_append",
5029 "_prepend",
5030 "_delete_key",
5031 "_delete_elem",
5032 "_delete_at_path",
5033];
5034
5035const READ_ROW: &str = "pgrst_src";
5041
5042const WRITTEN_ROW: &str = "pgrst_row";
5047
5048fn write_cast(column_types: &HashMap<String, String>, column: &str) -> String {
5056 match column_types.get(column) {
5057 Some(pg_type) => format!("::{}", pg_type),
5058 None => String::new(),
5059 }
5060}
5061
5062fn write_operand(
5069 column_types: &HashMap<String, String>,
5070 column: &str,
5071 value: &serde_json::Value,
5072) -> serde_json::Value {
5073 match column_types.get(column).map(String::as_str) {
5074 Some("json") | Some("jsonb") => match value {
5075 serde_json::Value::String(_)
5076 | serde_json::Value::Number(_)
5077 | serde_json::Value::Bool(_) => serde_json::Value::String(value.to_string()),
5078 other => other.clone(),
5079 },
5080 Some(pg_type) if is_array_type(pg_type) => match value {
5085 serde_json::Value::Array(_) => serde_json::Value::String(array_literal(value)),
5086 other => other.clone(),
5087 },
5088 _ => value.clone(),
5089 }
5090}
5091
5092fn is_array_type(pg_type: &str) -> bool {
5097 pg_type.ends_with("[]") || pg_type.starts_with('_')
5098}
5099
5100fn array_literal(value: &serde_json::Value) -> String {
5106 fn element(value: &serde_json::Value) -> String {
5107 match value {
5108 serde_json::Value::Null => "NULL".to_string(),
5109 serde_json::Value::Array(_) => array_literal(value),
5110 serde_json::Value::String(text) => {
5111 format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
5112 }
5113 other => format!("\"{}\"", other.to_string().replace('"', "\\\"")),
5114 }
5115 }
5116 let items = match value {
5117 serde_json::Value::Array(items) => items,
5118 other => return element(other),
5119 };
5120 format!(
5121 "{{{}}}",
5122 items.iter().map(element).collect::<Vec<_>>().join(",")
5123 )
5124}
5125
5126fn write_expression(
5137 column_types: &HashMap<String, String>,
5138 column: &str,
5139 value: &serde_json::Value,
5140 placeholder: &str,
5141) -> String {
5142 let pg_type = column_types.get(column).map(String::as_str);
5143 if value.is_object() && matches!(pg_type, Some("geometry") | Some("geography")) {
5144 return match pg_type {
5145 Some("geography") => format!("ST_GeomFromGeoJSON({})::geography", placeholder),
5146 _ => format!("ST_GeomFromGeoJSON({})", placeholder),
5147 };
5148 }
5149 if pg_type == Some("money") && value.is_number() {
5155 return format!("{}::numeric::money", placeholder);
5156 }
5157 format!("{}{}", placeholder, write_cast(column_types, column))
5158}
5159
5160async fn column_types_of(
5162 schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
5163 schema_name: &str,
5164 table_name: &str,
5165) -> HashMap<String, String> {
5166 let Ok(guard) = schema_cache.get().await else {
5167 return HashMap::new();
5168 };
5169 let Some(cache) = guard.as_ref() else {
5170 return HashMap::new();
5171 };
5172 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5173 match cache.get_table(&qi) {
5174 Some(table) => table
5175 .columns
5176 .values()
5177 .map(|c| (c.name.clone(), c.nominal_type.clone()))
5178 .collect(),
5179 None => HashMap::new(),
5180 }
5181}
5182
5183fn insert_row<'life>(
5201 conn: &'life mut sqlx::PgConnection,
5202 schema_name: &'life str,
5203 table_name: &'life str,
5204 object: serde_json::Map<String, serde_json::Value>,
5205 context: &'life InsertContext<'life>,
5206 written_count: &'life mut usize,
5207) -> std::pin::Pin<
5208 Box<
5209 dyn std::future::Future<Output = Result<serde_json::Value, async_graphql::Error>>
5210 + Send
5211 + 'life,
5212 >,
5213> {
5214 Box::pin(async move {
5215 use sqlx::Row;
5216
5217 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5218 let table = context.cache.get_table(&qi).ok_or_else(|| {
5219 async_graphql::Error::new(format!("unknown table \"{}\"", table_name))
5220 })?;
5221 let column_types: HashMap<String, String> = table
5222 .columns
5223 .values()
5224 .map(|c| (c.name.clone(), c.nominal_type.clone()))
5225 .collect();
5226
5227 let type_name = context
5229 .type_names
5230 .get(&(schema_name.to_string(), table_name.to_string()));
5231 let relationships: &[RelationshipField] = type_name
5232 .and_then(|name| context.relationships.get(name))
5233 .map(|r| r.as_slice())
5234 .unwrap_or(&[]);
5235
5236 let mut columns = serde_json::Map::new();
5237 type Nested<'r> = (
5238 &'r RelationshipField,
5239 serde_json::Value,
5240 Option<serde_json::Value>,
5241 );
5242 let mut to_one: Vec<Nested> = Vec::new();
5243 let mut to_many: Vec<Nested> = Vec::new();
5244
5245 for (key, value) in object {
5246 match relationships.iter().find(|r| r.name == key) {
5247 None => {
5248 columns.insert(
5251 table_column_for(context.names, table, &key).to_string(),
5252 value,
5253 );
5254 }
5255 Some(_) if value.is_null() => {
5256 continue;
5260 }
5261 Some(relationship) => {
5262 let (data, conflict) = match &value {
5266 serde_json::Value::Object(map) => (
5267 map.get("data").cloned().unwrap_or(value.clone()),
5268 map.get("on_conflict").cloned().filter(|v| !v.is_null()),
5269 ),
5270 other => (other.clone(), None),
5271 };
5272 if child_holds_the_key(&relationship.relationship) {
5279 to_many.push((relationship, data, conflict));
5280 } else {
5281 to_one.push((relationship, data, conflict));
5282 }
5283 }
5284 }
5285 }
5286
5287 for (column, value) in &columns {
5290 if matches!(
5291 column_types.get(column).map(String::as_str),
5292 Some("geometry") | Some("geography")
5293 ) {
5294 check_geojson(value).map_err(|error| {
5297 let field = context
5298 .names
5299 .column(schema_name, table_name, column)
5300 .unwrap_or(column);
5301 at_path(error, &format!("{}.{}", context.row, field))
5302 })?;
5303 }
5304 }
5305
5306 for (relationship, data, conflict) in to_one {
5309 let plan =
5310 postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, context.cache)
5311 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5312 let serde_json::Value::Object(child) = data else {
5313 return Err(async_graphql::Error::new(format!(
5314 "\"{}\" takes an object to insert",
5315 relationship.name
5316 )));
5317 };
5318 for (local, _) in &plan.columns {
5322 if columns.get(local).is_some_and(|v| !v.is_null()) {
5323 return Err(at_path(
5324 validation_error(format!(
5325 "cannot insert object relationship \"{}\" as \"{}\" column \
5326 values are already determined",
5327 relationship.name, local
5328 )),
5329 &format!("{}.{}", context.row, relationship.name),
5330 ));
5331 }
5332 }
5333 let under = format!("{}.{}", context.row, relationship.name);
5336 let nested = InsertContext {
5337 on_conflict: conflict,
5338 cache: context.cache,
5339 relationships: context.relationships,
5340 type_names: context.type_names,
5341 names: context.names,
5342 caller: context.caller,
5343 row: format!("{}.data", under),
5344 objects: format!("{}.data", under),
5345 conflict: format!("{}.on_conflict", under),
5346 };
5347 let written = insert_row(
5348 conn,
5349 &plan.foreign_schema,
5350 &plan.foreign_table,
5351 child,
5352 &nested,
5353 written_count,
5354 )
5355 .await?;
5356 for (local, foreign) in &plan.columns {
5357 if let Some(value) = written.get(foreign) {
5358 columns.insert(local.clone(), value.clone());
5359 }
5360 }
5361 }
5362
5363 for (column, value) in crate::role::presets(
5369 &context.caller,
5370 context.names,
5371 schema_name,
5372 table_name,
5373 crate::role::Verb::Insert,
5374 )
5375 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?
5376 {
5377 columns.insert(column, value);
5378 }
5379
5380 let column_names: Vec<&str> = columns.keys().map(|k| k.as_str()).collect();
5386 let mut conflict_values: Vec<serde_json::Value> = Vec::new();
5387 let conflict_sql = match &context.on_conflict {
5388 Some(serde_json::Value::Object(spec)) => {
5389 let constraint = spec.get("constraint").and_then(|v| v.as_str());
5390 let Some(constraint) = constraint else {
5391 return Err(async_graphql::Error::new(
5392 "on_conflict needs a constraint to resolve against",
5393 ));
5394 };
5395 if !table
5396 .unique_constraints
5397 .iter()
5398 .any(|(name, _)| name == constraint)
5399 {
5400 return Err(async_graphql::Error::new(format!(
5401 "\"{}\" is not a unique constraint of \"{}\"",
5402 constraint, table_name
5403 )));
5404 }
5405 let updates: Vec<&str> = spec
5406 .get("update_columns")
5407 .and_then(|v| v.as_array())
5408 .map(|items| items.iter().filter_map(|i| i.as_str()).collect())
5409 .unwrap_or_default();
5410 if updates.contains(&PLACEHOLDER_COLUMN) {
5414 return Err(at_path(
5415 coded_error("validation-failed", "erroneous column name"),
5416 &context.conflict,
5417 ));
5418 }
5419
5420 if updates.is_empty() {
5421 format!(
5422 " ON CONFLICT ON CONSTRAINT {} DO NOTHING",
5423 postrust_sql::escape_ident(constraint)
5424 )
5425 } else {
5426 let preset = crate::role::presets(
5432 &context.caller,
5433 context.names,
5434 schema_name,
5435 table_name,
5436 crate::role::Verb::Update,
5437 )
5438 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
5439
5440 let mut param_idx = column_names.len() + 1;
5444 let mut assignments: Vec<String> =
5445 Vec::with_capacity(preset.len() + updates.len());
5446 for (column, value) in &preset {
5447 assignments.push(format!(
5448 "{} = {}",
5449 postrust_sql::escape_ident(column),
5450 write_expression(
5451 &column_types,
5452 column,
5453 value,
5454 &format!("${}", param_idx)
5455 )
5456 ));
5457 conflict_values.push(write_operand(&column_types, column, value));
5458 param_idx += 1;
5459 }
5460 for field in &updates {
5461 let column = table_column_for(context.names, table, field);
5462 if preset.iter().any(|(written, _)| written == column) {
5463 continue;
5464 }
5465 assignments.push(format!(
5466 "{} = EXCLUDED.{}",
5467 postrust_sql::escape_ident(column),
5468 postrust_sql::escape_ident(column)
5469 ));
5470 }
5471 let granted = permission_filter(
5484 &context.caller,
5485 context.names,
5486 schema_name,
5487 table_name,
5488 crate::role::Verb::Update,
5489 )?;
5490 let requested = spec.get("where").filter(|f| !f.is_null()).cloned();
5491 let condition = match and_predicates(requested, granted) {
5492 Some(filter) => {
5493 let filter = &filter;
5494 let type_name = context
5495 .type_names
5496 .get(&(schema_name.to_string(), table_name.to_string()))
5497 .map(String::as_str)
5498 .unwrap_or(table_name);
5499 let scope = WhereScope::table(
5500 schema_name,
5501 table_name,
5502 type_name,
5503 context.names,
5504 )
5505 .under_alias(WRITTEN_ROW)
5506 .with_resolution(context.cache, context.relationships);
5507 let mut alias_counter = 0usize;
5508 build_condition(
5509 filter,
5510 &scope,
5511 &mut param_idx,
5512 &mut conflict_values,
5513 &mut alias_counter,
5514 )?
5515 .map(|sql| format!(" WHERE {}", sql))
5516 .unwrap_or_default()
5517 }
5518 None => String::new(),
5519 };
5520 format!(
5521 " ON CONFLICT ON CONSTRAINT {} DO UPDATE SET {}{}",
5522 postrust_sql::escape_ident(constraint),
5523 assignments.join(", "),
5524 condition
5525 )
5526 }
5527 }
5528 _ => String::new(),
5529 };
5530
5531 let qualified_table = postrust_sql::escape_ident(WRITTEN_ROW);
5537
5538 let check_scope = WhereScope::for_alias(
5543 schema_name,
5544 table_name,
5545 WRITTEN_ROW,
5546 context
5547 .type_names
5548 .get(&(schema_name.to_string(), table_name.to_string()))
5549 .map(String::as_str)
5550 .unwrap_or(table_name),
5551 context.cache,
5552 context.relationships,
5553 context.names,
5554 );
5555 let (check_sql, check_values) = {
5556 let check = crate::role::write_check(
5557 &context.caller,
5558 context.names,
5559 schema_name,
5560 table_name,
5561 crate::role::Verb::Insert,
5562 )
5563 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
5564 match check {
5565 None => (String::new(), Vec::new()),
5566 Some(check) => {
5567 let mut values = Vec::new();
5568 let mut param_idx = column_names.len() + conflict_values.len() + 1;
5569 let mut alias_counter = 0usize;
5570 match build_condition(
5571 &check,
5572 &check_scope,
5573 &mut param_idx,
5574 &mut values,
5575 &mut alias_counter,
5576 )? {
5577 None => (String::new(), Vec::new()),
5578 Some(sql) => (
5579 format!(
5580 ", ({}) AS {}",
5581 sql,
5582 postrust_sql::escape_ident(CHECK_COLUMN)
5583 ),
5584 values,
5585 ),
5586 }
5587 }
5588 }
5589 };
5590
5591 let names = column_names;
5592 let written = if names.is_empty() {
5593 let sql = format!(
5596 "INSERT INTO {}.{} AS {} DEFAULT VALUES{} RETURNING {}{}",
5597 postrust_sql::escape_ident(schema_name),
5598 postrust_sql::escape_ident(table_name),
5599 qualified_table,
5600 conflict_sql,
5601 row_json(&qualified_table, &column_types),
5602 check_sql
5603 );
5604 let mut query = sqlx::query(AssertSqlSafe(sql));
5605 for value in &conflict_values {
5606 query = bind_json_value(query, value);
5607 }
5608 for value in &check_values {
5609 query = bind_json_value(query, value);
5610 }
5611 query
5612 .fetch_optional(&mut *conn)
5613 .await
5614 .map_err(|error| at_path(database_error(error), &context.objects))?
5617 } else {
5618 let placeholders: Vec<String> = names
5619 .iter()
5620 .enumerate()
5621 .map(|(i, column)| {
5622 let placeholder = format!("${}", i + 1);
5623 match columns.get(*column) {
5624 Some(value) => write_expression(&column_types, column, value, &placeholder),
5625 None => placeholder,
5626 }
5627 })
5628 .collect();
5629 let sql = format!(
5630 "INSERT INTO {}.{} AS {} ({}) VALUES ({}){} RETURNING {}{}",
5631 postrust_sql::escape_ident(schema_name),
5632 postrust_sql::escape_ident(table_name),
5633 qualified_table,
5634 names
5635 .iter()
5636 .map(|c| postrust_sql::escape_ident(c))
5637 .collect::<Vec<_>>()
5638 .join(", "),
5639 placeholders.join(", "),
5640 conflict_sql,
5641 row_json(&qualified_table, &column_types),
5642 check_sql
5643 );
5644 trace!("Executing INSERT SQL: {}", sql);
5645 let mut query = sqlx::query(AssertSqlSafe(sql));
5646 for column in &names {
5647 if let Some(value) = columns.get(*column) {
5648 query = bind_json_value(query, &write_operand(&column_types, column, value));
5649 }
5650 }
5651 for value in &conflict_values {
5652 query = bind_json_value(query, value);
5653 }
5654 for value in &check_values {
5655 query = bind_json_value(query, value);
5656 }
5657 query
5658 .fetch_optional(&mut *conn)
5659 .await
5660 .map_err(|error| at_path(database_error(error), &context.objects))?
5663 };
5664
5665 let Some(written) = written else {
5668 return Ok(serde_json::Value::Null);
5669 };
5670 refuse_unchecked_rows(std::slice::from_ref(&written), !check_sql.is_empty())
5671 .map_err(|error| at_path(error, &context.objects))?;
5672 let row: serde_json::Value = written.try_get(0).unwrap_or(serde_json::Value::Null);
5673 *written_count += 1;
5674
5675 for (relationship, data, conflict) in to_many {
5677 let plan =
5678 postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, context.cache)
5679 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5680 let children = match data {
5681 serde_json::Value::Array(items) => items,
5682 serde_json::Value::Object(map) => vec![serde_json::Value::Object(map)],
5683 serde_json::Value::Null => Vec::new(),
5684 _ => {
5685 return Err(async_graphql::Error::new(format!(
5686 "\"{}\" takes objects to insert",
5687 relationship.name
5688 )))
5689 }
5690 };
5691 for (child_index, child) in children.into_iter().enumerate() {
5692 let serde_json::Value::Object(mut child) = child else {
5693 continue;
5694 };
5695 for (local, foreign) in &plan.columns {
5696 if child.get(foreign).is_some_and(|v| !v.is_null()) {
5700 return Err(at_path(
5701 validation_error(format!(
5702 "cannot insert \"{}\" columns as their values are already \
5703 being determined by parent insert",
5704 foreign
5705 )),
5706 &format!(
5707 "{}.{}{}",
5708 context.row,
5709 relationship.name,
5710 match relationship.is_list {
5711 true => format!(".data[{}]", child_index),
5712 false => ".data".to_string(),
5713 }
5714 ),
5715 ));
5716 }
5717 if let Some(value) = row.get(local) {
5718 child.insert(foreign.clone(), value.clone());
5719 }
5720 }
5721 let at = match relationship.is_list {
5727 true => format!(".data[{}]", child_index),
5728 false => ".data".to_string(),
5729 };
5730 let under = format!("{}.{}", context.row, relationship.name);
5731 let nested = InsertContext {
5732 on_conflict: conflict.clone(),
5733 cache: context.cache,
5734 relationships: context.relationships,
5735 type_names: context.type_names,
5736 names: context.names,
5737 caller: context.caller,
5738 row: format!("{}{}", under, at),
5739 objects: format!("{}.data", under),
5740 conflict: format!("{}.on_conflict", under),
5741 };
5742 insert_row(
5743 conn,
5744 &plan.foreign_schema,
5745 &plan.foreign_table,
5746 child,
5747 &nested,
5748 written_count,
5749 )
5750 .await?;
5751 }
5752 }
5753
5754 Ok(row)
5755 })
5756}
5757
5758#[derive(Clone)]
5764struct InsertContext<'a> {
5765 on_conflict: Option<serde_json::Value>,
5768 cache: &'a SchemaCache,
5769 relationships: &'a HashMap<String, Vec<RelationshipField>>,
5770 type_names: &'a HashMap<(String, String), String>,
5774 names: &'a crate::names::NameOverrides,
5777 caller: crate::role::Caller<'a>,
5781 row: String,
5786 objects: String,
5790 conflict: String,
5792}
5793
5794#[allow(clippy::too_many_arguments)]
5807async fn reread_returning(
5808 pool: &PgPool,
5809 gql_ctx: &GraphQLContext,
5810 schema_name: &str,
5811 table_name: &str,
5812 type_name: &str,
5813 rows: Vec<Value>,
5814 returning: async_graphql::SelectionField<'_>,
5815 relationships: &HashMap<String, Vec<RelationshipField>>,
5816 names: &crate::names::NameOverrides,
5817 max_rows: Option<i64>,
5818) -> Result<Vec<Value>, async_graphql::Error> {
5819 let guard = gql_ctx
5820 .schema_cache
5821 .get()
5822 .await
5823 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5824 let Some(cache) = guard.as_ref() else {
5825 return Ok(rows);
5826 };
5827 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5828 let Some(table) = cache.get_table(&qi) else {
5829 return Ok(rows);
5830 };
5831 if table.pk_cols.is_empty() {
5832 return Ok(rows);
5834 }
5835
5836 let mut param_idx = 1usize;
5837 let mut values: Vec<serde_json::Value> = Vec::new();
5838 let mut alias_counter = 0usize;
5839 let embeds = build_embed_expressions(
5840 &gql_ctx.caller(),
5841 cache,
5842 relationships,
5843 type_name,
5844 "src",
5845 returning.selection_set(),
5846 max_rows,
5847 &mut alias_counter,
5848 &mut param_idx,
5849 &mut values,
5850 names,
5851 )?;
5852 let computed = computed_projections(
5853 table,
5854 returning.selection_set(),
5855 "src",
5856 names,
5857 cache,
5858 &mut param_idx,
5859 &mut values,
5860 )?;
5861 let renames = names.renames_columns(&table.schema, &table.name);
5865 if embeds.is_empty() && computed.is_empty() && !renames {
5866 return Ok(rows);
5867 }
5868
5869 let mut conditions = Vec::with_capacity(rows.len());
5871 for row in &rows {
5872 let mut parts = Vec::with_capacity(table.pk_cols.len());
5873 for column in &table.pk_cols {
5874 let Value::Object(map) = row else {
5875 return Ok(rows);
5876 };
5877 let Some(value) = map.get(&async_graphql::Name::new(column)) else {
5878 return Ok(rows);
5879 };
5880 parts.push(format!(
5881 "{} = ${}",
5882 postrust_sql::escape_ident(column),
5883 param_idx
5884 ));
5885 values.push(value_to_json(value));
5886 param_idx += 1;
5887 }
5888 conditions.push(format!("({})", parts.join(" AND ")));
5889 }
5890 if conditions.is_empty() {
5891 return Ok(rows);
5892 }
5893
5894 let mut projection =
5895 rename_projection(table, "src", names).unwrap_or_else(|| "src.*".to_string());
5896 for expression in &computed {
5897 projection.push_str(", ");
5898 projection.push_str(expression);
5899 }
5900 for (name, expression) in &embeds {
5901 projection.push_str(", ");
5902 projection.push_str(expression);
5903 projection.push_str(" AS ");
5904 projection.push_str(&postrust_sql::escape_ident(name));
5905 }
5906
5907 let sql = format!(
5908 "SELECT {} FROM (SELECT {} FROM (SELECT * FROM {}.{} WHERE {}) AS src) AS pgrst_r",
5909 row_json("pgrst_r", &exposed_column_types(table, names)),
5910 projection,
5911 postrust_sql::escape_ident(schema_name),
5912 postrust_sql::escape_ident(table_name),
5913 conditions.join(" OR ")
5914 );
5915
5916 let mut guard = write_tx(gql_ctx, pool).await?;
5919 let conn = guard.as_mut().expect("write_tx opens one");
5920 let reread = execute_query_on(conn, &sql, &values).await?;
5921 drop(guard);
5922
5923 if reread.is_empty() {
5924 return Ok(rows);
5925 }
5926 Ok(reread.into_iter().map(json_to_value).collect())
5927}
5928
5929async fn execute_insert(
5931 pool: &PgPool,
5932 gql_ctx: &GraphQLContext,
5933 schema_name: &str,
5934 table_name: &str,
5935 objects: serde_json::Value,
5936 context: &InsertContext<'_>,
5937 single: bool,
5941) -> Result<(Vec<Value>, usize), async_graphql::Error> {
5942 trace!("Insert mutation for {}: {:?}", table_name, objects);
5943
5944 let objects_array = match objects {
5946 serde_json::Value::Array(arr) => arr,
5947 serde_json::Value::Object(obj) => vec![serde_json::Value::Object(obj)],
5948 _ => {
5949 return Err(async_graphql::Error::new(
5950 "objects must be an array or object",
5951 ))
5952 }
5953 };
5954
5955 if objects_array.is_empty() {
5956 return Err(async_graphql::Error::new("objects cannot be empty"));
5957 }
5958
5959 let mut guard = write_tx(gql_ctx, pool).await?;
5960 let conn = guard.as_mut().expect("write_tx opens one");
5961
5962 let mut inserted: Vec<Value> = Vec::new();
5963 let mut written = 0usize;
5964
5965 for (index, object) in objects_array.into_iter().enumerate() {
5966 let serde_json::Value::Object(map) = object else {
5967 return Err(async_graphql::Error::new(
5968 "each object to insert is an object",
5969 ));
5970 };
5971 let context = InsertContext {
5974 row: match single {
5975 true => context.objects.clone(),
5976 false => format!("{}[{}]", context.objects, index),
5977 },
5978 ..context.clone()
5979 };
5980 let row = insert_row(conn, schema_name, table_name, map, &context, &mut written).await?;
5981 if !row.is_null() {
5985 inserted.push(json_to_value(row));
5986 }
5987 }
5988
5989 Ok((inserted, written))
5990}
5991
5992fn mutation_result<'a>(rows: Vec<Value>, affected: usize, by_key: bool) -> Option<FieldValue<'a>> {
6004 if by_key {
6005 return rows.into_iter().next().map(FieldValue::value);
6006 }
6007 let mut response = async_graphql::indexmap::IndexMap::new();
6008 response.insert(
6009 async_graphql::Name::new("affected_rows"),
6010 Value::from(affected),
6011 );
6012 response.insert(async_graphql::Name::new("returning"), Value::List(rows));
6013 Some(FieldValue::value(Value::Object(response)))
6014}
6015
6016fn bind_json_value<'q>(
6028 query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
6029 value: &serde_json::Value,
6030) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
6031 match value {
6032 serde_json::Value::Null => query.bind(None::<String>),
6033 serde_json::Value::Bool(b) => query.bind(*b),
6034 serde_json::Value::Number(n) => {
6035 if let Some(i) = n.as_i64() {
6036 query.bind(i)
6037 } else if let Some(f) = n.as_f64() {
6038 query.bind(f)
6039 } else {
6040 query.bind(n.to_string())
6041 }
6042 }
6043 serde_json::Value::String(s) => query.bind(s.clone()),
6044 _ => query.bind(value.to_string()),
6045 }
6046}
6047
6048#[allow(clippy::too_many_arguments)] async fn execute_update(
6051 pool: &PgPool,
6052 gql_ctx: &GraphQLContext,
6053 schema_name: &str,
6054 table_name: &str,
6055 type_name: &str,
6056 operators: Vec<(&'static str, serde_json::Value)>,
6057 column_types: HashMap<String, String>,
6058 where_clause: Option<serde_json::Value>,
6059 relationships: &HashMap<String, Vec<RelationshipField>>,
6060 names: &crate::names::NameOverrides,
6061) -> Result<Vec<Value>, async_graphql::Error> {
6062 use sqlx::Row;
6063
6064 trace!("Update mutation for {}: {:?}", table_name, operators);
6065
6066 let mut set_parts: Vec<String> = Vec::new();
6071 let mut set_values: Vec<serde_json::Value> = Vec::new();
6072 let mut param_idx = 1;
6073 let mut written: HashSet<String> = HashSet::new();
6074
6075 let preset = crate::role::presets(
6085 &gql_ctx.caller(),
6086 names,
6087 schema_name,
6088 table_name,
6089 crate::role::Verb::Update,
6090 )
6091 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
6092 let preset_columns: HashSet<&str> = preset.iter().map(|(name, _)| name.as_str()).collect();
6093 for (column, value) in &preset {
6094 let placeholder =
6095 write_expression(&column_types, column, value, &format!("${}", param_idx));
6096 set_parts.push(format!(
6097 "{} = {}",
6098 postrust_sql::escape_ident(column),
6099 placeholder
6100 ));
6101 set_values.push(write_operand(&column_types, column, value));
6102 param_idx += 1;
6103 }
6104
6105 for (operator, payload) in &operators {
6106 let serde_json::Value::Object(map) = payload else {
6107 return Err(async_graphql::Error::new(format!(
6108 "\"{}\" takes an object mapping columns to values",
6109 operator
6110 )));
6111 };
6112 for (field, value) in map {
6113 let column = &names
6114 .column_source(schema_name, table_name, field)
6115 .unwrap_or(field)
6116 .to_string();
6117 if preset_columns.contains(column.as_str()) {
6120 continue;
6121 }
6122 if !written.insert(column.clone()) {
6123 return Err(async_graphql::Error::new(format!(
6124 "\"{}\" is written twice in one update; a column may be \
6125 changed by one operator at a time",
6126 column
6127 )));
6128 }
6129 let quoted = postrust_sql::escape_ident(column);
6130 let placeholder = match *operator {
6139 "_set" | "_inc" => {
6140 write_expression(&column_types, column, value, &format!("${}", param_idx))
6141 }
6142 _ => format!("${}", param_idx),
6143 };
6144 let assignment = match *operator {
6147 "_set" => format!("{} = {}", quoted, placeholder),
6148 "_inc" => format!("{} = {} + {}", quoted, quoted, placeholder),
6149 "_append" => format!("{} = {} || {}::jsonb", quoted, quoted, placeholder),
6150 "_prepend" => format!("{} = {}::jsonb || {}", quoted, placeholder, quoted),
6151 "_delete_key" => format!("{} = {} - {}::text", quoted, quoted, placeholder),
6152 "_delete_elem" => format!("{} = {} - {}::int", quoted, quoted, placeholder),
6153 "_delete_at_path" => {
6159 let Some(steps) = value.as_array() else {
6160 return Err(async_graphql::Error::new(format!(
6161 "\"_delete_at_path\" on \"{}\" takes a list of keys",
6162 column
6163 )));
6164 };
6165 let path = sql_array(steps, "text[]", &mut param_idx, &mut set_values);
6166 set_parts.push(format!("{} = {} #- {}", quoted, quoted, path));
6167 continue;
6168 }
6169 other => {
6170 return Err(async_graphql::Error::new(format!(
6171 "unsupported update operator \"{}\"",
6172 other
6173 )))
6174 }
6175 };
6176 if *operator == "_set"
6177 && matches!(
6178 column_types.get(column).map(String::as_str),
6179 Some("geometry") | Some("geography")
6180 )
6181 {
6182 check_geojson(value)?;
6183 }
6184 set_parts.push(assignment);
6185 set_values.push(match *operator {
6186 "_set" => write_operand(&column_types, column, value),
6187 _ => value.clone(),
6188 });
6189 param_idx += 1;
6190 }
6191 }
6192
6193 if set_parts.is_empty() {
6198 return Ok(Vec::new());
6199 }
6200
6201 let guard = gql_ctx
6205 .schema_cache
6206 .get()
6207 .await
6208 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
6209 let cache = guard
6210 .as_ref()
6211 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
6212 let scope = WhereScope::table(schema_name, table_name, type_name, names)
6213 .under_alias(WRITTEN_ROW)
6214 .with_resolution(cache, relationships);
6215 let (where_sql, where_values) = build_where_clause(where_clause.as_ref(), param_idx, &scope)?;
6216
6217 if where_sql.is_empty() {
6220 return Err(async_graphql::Error::new(format!(
6221 "update on \"{}\" requires a `where` argument with at least one \
6222 recognised condition; refusing to update every row",
6223 table_name
6224 )));
6225 }
6226
6227 let (check_sql, check_values) = permission_check_sql(
6232 gql_ctx,
6233 names,
6234 schema_name,
6235 table_name,
6236 crate::role::Verb::Update,
6237 &scope,
6238 param_idx + where_values.len(),
6239 )?;
6240
6241 let sql = format!(
6242 "UPDATE {}.{} AS {} SET {} {} RETURNING {}{}",
6243 postrust_sql::escape_ident(schema_name),
6244 postrust_sql::escape_ident(table_name),
6245 postrust_sql::escape_ident(WRITTEN_ROW),
6246 set_parts.join(", "),
6247 where_sql,
6248 row_json(&postrust_sql::escape_ident(WRITTEN_ROW), &column_types),
6249 check_sql
6250 );
6251
6252 trace!("Executing UPDATE SQL: {}", sql);
6253
6254 let mut query = sqlx::query(AssertSqlSafe(sql));
6256
6257 for val in &set_values {
6259 query = bind_json_value(query, val);
6260 }
6261
6262 for val in &where_values {
6264 query = bind_json_value(query, val);
6265 }
6266
6267 for val in &check_values {
6269 query = bind_json_value(query, val);
6270 }
6271
6272 let mut guard = write_tx(gql_ctx, pool).await?;
6273 let conn = guard.as_mut().expect("write_tx opens one");
6274 let rows = query.fetch_all(&mut **conn).await.map_err(database_error)?;
6275
6276 refuse_unchecked_rows(&rows, !check_sql.is_empty())?;
6277
6278 let updated: Vec<Value> = rows
6279 .iter()
6280 .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
6281 .map(json_to_value)
6282 .collect();
6283
6284 Ok(updated)
6285}
6286
6287fn permission_check_sql(
6294 gql_ctx: &GraphQLContext,
6295 names: &crate::names::NameOverrides,
6296 schema_name: &str,
6297 table_name: &str,
6298 verb: crate::role::Verb,
6299 scope: &WhereScope<'_>,
6300 start_param_idx: usize,
6301) -> Result<(String, Vec<serde_json::Value>), async_graphql::Error> {
6302 let check = crate::role::write_check(&gql_ctx.caller(), names, schema_name, table_name, verb)
6303 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
6304 let Some(check) = check else {
6305 return Ok((String::new(), Vec::new()));
6306 };
6307
6308 let mut values = Vec::new();
6309 let mut param_idx = start_param_idx;
6310 let mut alias_counter = 0usize;
6311 let condition = build_condition(
6312 &check,
6313 scope,
6314 &mut param_idx,
6315 &mut values,
6316 &mut alias_counter,
6317 )?;
6318 Ok(match condition {
6319 None => (String::new(), Vec::new()),
6322 Some(sql) => (
6323 format!(
6324 ", ({}) AS {}",
6325 sql,
6326 postrust_sql::escape_ident(CHECK_COLUMN)
6327 ),
6328 values,
6329 ),
6330 })
6331}
6332
6333const CHECK_COLUMN: &str = "pgrst_permission_check";
6335
6336fn refuse_unchecked_rows(
6343 rows: &[sqlx::postgres::PgRow],
6344 checked: bool,
6345) -> Result<(), async_graphql::Error> {
6346 if !checked {
6347 return Ok(());
6348 }
6349 use sqlx::Row;
6350 let all_passed = rows
6351 .iter()
6352 .all(|row| row.try_get::<bool, _>(CHECK_COLUMN).unwrap_or(false));
6353 match all_passed {
6354 true => Ok(()),
6355 false => Err(coded_error("permission-error", crate::role::CHECK_FAILED)),
6356 }
6357}
6358
6359#[allow(clippy::too_many_arguments)] async fn execute_delete(
6362 pool: &PgPool,
6363 gql_ctx: &GraphQLContext,
6364 schema_name: &str,
6365 table_name: &str,
6366 type_name: &str,
6367 where_clause: Option<serde_json::Value>,
6368 returning: Option<async_graphql::SelectionField<'_>>,
6369 relationships: &HashMap<String, Vec<RelationshipField>>,
6370 names: &crate::names::NameOverrides,
6371 max_rows: Option<i64>,
6372) -> Result<Vec<Value>, async_graphql::Error> {
6373 use sqlx::Row;
6374
6375 trace!("Delete mutation for {}", table_name);
6376
6377 let guard = gql_ctx
6378 .schema_cache
6379 .get()
6380 .await
6381 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
6382 let cache = guard
6383 .as_ref()
6384 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
6385 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
6386 let column_types = cache
6387 .get_table(&qi)
6388 .map(|table| exposed_column_types(table, names))
6389 .unwrap_or_default();
6390
6391 let scope = WhereScope::table(schema_name, table_name, type_name, names)
6395 .under_alias(WRITTEN_ROW)
6396 .with_resolution(cache, relationships);
6397 let (where_sql, mut values) = build_where_clause(where_clause.as_ref(), 1, &scope)?;
6398
6399 if where_sql.is_empty() {
6402 return Err(async_graphql::Error::new(format!(
6403 "delete on \"{}\" requires a `where` argument with at least one \
6404 recognised condition; refusing to delete every row",
6405 table_name
6406 )));
6407 }
6408
6409 let mut projection = String::new();
6415 let renamed = cache
6416 .get_table(&qi)
6417 .and_then(|table| rename_projection(table, "src", names));
6418 if let Some(returning) = returning {
6419 let mut param_idx = values.len() + 1;
6420 let mut alias_counter = 0usize;
6421 let embeds = build_embed_expressions(
6422 &gql_ctx.caller(),
6423 cache,
6424 relationships,
6425 type_name,
6426 "src",
6427 returning.selection_set(),
6428 max_rows,
6429 &mut alias_counter,
6430 &mut param_idx,
6431 &mut values,
6432 names,
6433 )?;
6434 let computed = match cache.get_table(&qi) {
6435 Some(table) => computed_projections(
6436 table,
6437 returning.selection_set(),
6438 "src",
6439 names,
6440 cache,
6441 &mut param_idx,
6442 &mut values,
6443 )?,
6444 None => Vec::new(),
6445 };
6446 for expression in &computed {
6447 projection.push_str(", ");
6448 projection.push_str(expression);
6449 }
6450 for (name, expression) in &embeds {
6451 projection.push_str(", ");
6452 projection.push_str(expression);
6453 projection.push_str(" AS ");
6454 projection.push_str(&postrust_sql::escape_ident(name));
6455 }
6456 }
6457
6458 let written = postrust_sql::escape_ident(WRITTEN_ROW);
6459 let sql = if projection.is_empty() && renamed.is_none() {
6460 format!(
6461 "DELETE FROM {}.{} AS {} {} RETURNING {}",
6462 postrust_sql::escape_ident(schema_name),
6463 postrust_sql::escape_ident(table_name),
6464 written,
6465 where_sql,
6466 row_json(&written, &column_types)
6467 )
6468 } else {
6469 format!(
6470 "WITH pgrst_deleted AS (DELETE FROM {}.{} AS {} {} RETURNING {}.*) \
6471 SELECT {} FROM (SELECT {}{} FROM pgrst_deleted AS src) AS pgrst_r",
6472 postrust_sql::escape_ident(schema_name),
6473 postrust_sql::escape_ident(table_name),
6474 written,
6475 where_sql,
6476 written,
6477 row_json("pgrst_r", &column_types),
6478 renamed.unwrap_or_else(|| "src.*".to_string()),
6479 projection
6480 )
6481 };
6482
6483 trace!("Executing DELETE SQL: {}", sql);
6484
6485 let mut query = sqlx::query(AssertSqlSafe(sql));
6486 for val in &values {
6487 query = bind_json_value(query, val);
6488 }
6489
6490 let mut guard = write_tx(gql_ctx, pool).await?;
6491 let conn = guard.as_mut().expect("write_tx opens one");
6492 let rows = query.fetch_all(&mut **conn).await.map_err(database_error)?;
6493
6494 let deleted: Vec<Value> = rows
6495 .iter()
6496 .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
6497 .map(json_to_value)
6498 .collect();
6499
6500 Ok(deleted)
6501}
6502
6503fn permission_predicate(
6511 caller: &crate::role::Caller<'_>,
6512 names: &crate::names::NameOverrides,
6513 schema: &str,
6514 table: &str,
6515) -> Result<Option<serde_json::Value>, async_graphql::Error> {
6516 permission_filter(caller, names, schema, table, crate::role::Verb::Select)
6517}
6518
6519fn permission_filter(
6521 caller: &crate::role::Caller<'_>,
6522 names: &crate::names::NameOverrides,
6523 schema: &str,
6524 table: &str,
6525 verb: crate::role::Verb,
6526) -> Result<Option<serde_json::Value>, async_graphql::Error> {
6527 crate::role::row_filter(caller, names, schema, table, verb)
6528 .map(|filter| filter.map(|predicate| serde_json::json!({ PERMISSION: predicate })))
6529 .map_err(|fault| coded_error(fault.code(), fault.to_string()))
6530}
6531
6532const PERMISSION: &str = "_permission";
6553
6554fn permission_limit(
6560 caller: &crate::role::Caller<'_>,
6561 names: &crate::names::NameOverrides,
6562 schema: &str,
6563 table: &str,
6564) -> Option<i64> {
6565 crate::role::read_limit(caller, names, schema, table)
6566}
6567
6568fn and_predicates(
6575 request: Option<serde_json::Value>,
6576 permission: Option<serde_json::Value>,
6577) -> Option<serde_json::Value> {
6578 match (request, permission) {
6579 (None, None) => None,
6580 (Some(only), None) | (None, Some(only)) => Some(only),
6581 (Some(request), Some(permission)) => {
6582 Some(serde_json::json!({ "_and": [request, permission] }))
6583 }
6584 }
6585}
6586
6587fn build_where_clause(
6597 where_value: Option<&serde_json::Value>,
6598 start_param_idx: usize,
6599 scope: &WhereScope<'_>,
6600) -> Result<(String, Vec<serde_json::Value>), async_graphql::Error> {
6601 let mut values: Vec<serde_json::Value> = Vec::new();
6602 let mut param_idx = start_param_idx;
6603 let mut alias_counter = 0usize;
6604
6605 let condition = match where_value {
6606 Some(value) => build_condition(
6607 value,
6608 scope,
6609 &mut param_idx,
6610 &mut values,
6611 &mut alias_counter,
6612 )?,
6613 None => None,
6614 };
6615
6616 Ok(match condition {
6617 Some(sql) => (format!("WHERE {}", sql), values),
6618 None => (String::new(), values),
6619 })
6620}
6621
6622pub struct WhereScope<'a> {
6634 qualified: postrust_core::api_request::QualifiedIdentifier,
6636 sql_ref: String,
6638 row_ref: String,
6642 type_name: String,
6644 root_ref: String,
6652 root_qualified: postrust_core::api_request::QualifiedIdentifier,
6653 names: &'a crate::names::NameOverrides,
6656 resolution: Option<WhereResolution<'a>>,
6657 caller: Option<crate::role::Caller<'a>>,
6664}
6665
6666struct WhereResolution<'a> {
6668 cache: &'a SchemaCache,
6669 relationships: &'a HashMap<String, Vec<RelationshipField>>,
6670}
6671
6672impl<'a> WhereScope<'a> {
6673 pub fn table(
6675 schema: &str,
6676 table: &str,
6677 type_name: &str,
6678 names: &'a crate::names::NameOverrides,
6679 ) -> Self {
6680 Self {
6681 qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6682 sql_ref: format!(
6683 "{}.{}",
6684 postrust_sql::escape_ident(schema),
6685 postrust_sql::escape_ident(table)
6686 ),
6687 row_ref: postrust_sql::escape_ident(table),
6688 type_name: type_name.to_string(),
6689 root_ref: format!(
6690 "{}.{}",
6691 postrust_sql::escape_ident(schema),
6692 postrust_sql::escape_ident(table)
6693 ),
6694 root_qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6695 names,
6696 resolution: None,
6697 caller: None,
6698 }
6699 }
6700
6701 fn under_alias(mut self, alias: &str) -> Self {
6709 if self.root_ref == self.sql_ref {
6712 self.root_ref = postrust_sql::escape_ident(alias);
6713 }
6714 self.sql_ref = postrust_sql::escape_ident(alias);
6715 self.row_ref = postrust_sql::escape_ident(alias);
6716 self
6717 }
6718
6719 fn with_resolution(
6721 mut self,
6722 cache: &'a SchemaCache,
6723 relationships: &'a HashMap<String, Vec<RelationshipField>>,
6724 ) -> Self {
6725 self.resolution = Some(WhereResolution {
6726 cache,
6727 relationships,
6728 });
6729 self
6730 }
6731
6732 #[allow(clippy::too_many_arguments)]
6734 fn for_alias(
6735 schema: &str,
6736 table: &str,
6737 alias: &str,
6738 type_name: &str,
6739 cache: &'a SchemaCache,
6740 relationships: &'a HashMap<String, Vec<RelationshipField>>,
6741 names: &'a crate::names::NameOverrides,
6742 ) -> Self {
6743 Self {
6744 qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6745 sql_ref: postrust_sql::escape_ident(alias),
6746 row_ref: postrust_sql::escape_ident(alias),
6747 type_name: type_name.to_string(),
6748 root_ref: postrust_sql::escape_ident(alias),
6749 root_qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6750 names,
6751 resolution: Some(WhereResolution {
6752 cache,
6753 relationships,
6754 }),
6755 caller: None,
6756 }
6757 }
6758
6759 fn aliased(
6766 schema: &str,
6767 table: &str,
6768 alias: &str,
6769 type_name: &str,
6770 from: &WhereScope<'a>,
6771 ) -> Self {
6772 Self {
6773 qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6774 sql_ref: postrust_sql::escape_ident(alias),
6775 row_ref: postrust_sql::escape_ident(alias),
6776 type_name: type_name.to_string(),
6777 root_ref: from.root_ref.clone(),
6780 root_qualified: from.root_qualified.clone(),
6781 names: from.names,
6782 resolution: from.resolution.as_ref().map(|r| WhereResolution {
6783 cache: r.cache,
6784 relationships: r.relationships,
6785 }),
6786 caller: from.caller,
6790 }
6791 }
6792
6793 pub fn for_caller(mut self, caller: crate::role::Caller<'a>) -> Self {
6795 self.caller = Some(caller);
6796 self
6797 }
6798
6799 fn as_system(&self) -> WhereScope<'a> {
6802 WhereScope {
6803 qualified: self.qualified.clone(),
6804 sql_ref: self.sql_ref.clone(),
6805 row_ref: self.row_ref.clone(),
6806 type_name: self.type_name.clone(),
6807 root_ref: self.sql_ref.clone(),
6814 root_qualified: self.qualified.clone(),
6815 names: self.names,
6816 resolution: self.resolution.as_ref().map(|r| WhereResolution {
6817 cache: r.cache,
6818 relationships: r.relationships,
6819 }),
6820 caller: None,
6821 }
6822 }
6823
6824 fn column(&self, name: &str) -> String {
6832 let column = self.column_name(name);
6833 let plain = format!("{}.{}", self.sql_ref, postrust_sql::escape_ident(column));
6834 let Some(cache) = self.resolution.as_ref().map(|r| r.cache) else {
6835 return plain;
6836 };
6837 let Some(table) = cache.get_table(&self.qualified) else {
6838 return plain;
6839 };
6840 if table.get_column(column).is_some() {
6841 return plain;
6842 }
6843 let function = self
6844 .names
6845 .computed_source(&table.schema, &table.name, name)
6846 .unwrap_or(name);
6847 match table.get_computed_column(function) {
6848 Some(definition) => {
6849 computed_call(definition, &format!("{}.*", self.row_ref), &self.row_ref)
6850 }
6851 None => plain,
6852 }
6853 }
6854
6855 fn column_name<'n>(&'n self, name: &'n str) -> &'n str {
6857 self.names
6858 .column_source(&self.qualified.schema, &self.qualified.name, name)
6859 .unwrap_or(name)
6860 }
6861
6862 fn column_type(&self, name: &str) -> Option<String> {
6866 let cache = self.resolution.as_ref()?.cache;
6867 let table = cache.get_table(&self.qualified)?;
6868 table
6869 .get_column(self.column_name(name))
6870 .map(|c| c.nominal_type.clone())
6871 }
6872
6873 fn other_column(
6887 &self,
6888 operand: &serde_json::Value,
6889 op: &str,
6890 ) -> Result<String, async_graphql::Error> {
6891 use serde_json::Value;
6892
6893 let refused = |what: &str| {
6894 async_graphql::Error::new(format!(
6895 "the \"{}\" comparison takes the name of a column, {}",
6896 op, what
6897 ))
6898 };
6899 let (against, qualified, name) = match operand {
6900 Value::String(name) => (&self.sql_ref, &self.qualified, name.as_str()),
6901 Value::Array(path) => match path.as_slice() {
6902 [Value::String(name)] => (&self.sql_ref, &self.qualified, name.as_str()),
6903 [Value::String(root), Value::String(name)] if root == "$" => {
6904 (&self.root_ref, &self.root_qualified, name.as_str())
6905 }
6906 _ => return Err(refused("or [\"$\", \"a column\"]")),
6907 },
6908 _ => return Err(refused("written as a string")),
6909 };
6910 let column = self
6913 .names
6914 .column_source(&qualified.schema, &qualified.name, name)
6915 .unwrap_or(name);
6916 Ok(format!(
6917 "{}.{}",
6918 against,
6919 postrust_sql::escape_ident(column)
6920 ))
6921 }
6922
6923 fn relationship(&self, name: &str) -> Option<std::borrow::Cow<'a, RelationshipField>> {
6937 let resolution = self.resolution.as_ref()?;
6938 let published = resolution
6939 .relationships
6940 .get(&self.type_name)
6941 .and_then(|fields| fields.iter().find(|r| r.name == name));
6942 if let Some(found) = published {
6943 return Some(std::borrow::Cow::Borrowed(found));
6944 }
6945
6946 let table = resolution.cache.get_table(&self.qualified)?;
6947
6948 if let Some(declared) = self
6954 .names
6955 .declared_relationships(&table.schema, &table.name)
6956 {
6957 if let Some(entry) = declared.iter().find(|entry| entry.name == name) {
6958 let target = entry
6961 .target(&table.schema)
6962 .map(|(_, target)| target)
6963 .unwrap_or_default();
6964 if let Some(field) = crate::schema::mapped_relationship_field(
6965 entry,
6966 table,
6967 resolution.cache,
6968 &table.schema,
6969 &target,
6970 &target,
6971 &target,
6972 ) {
6973 return Some(std::borrow::Cow::Owned(field));
6974 }
6975 if let Some(key) = entry.using.as_deref() {
6979 if let Some(found) = resolution
6980 .cache
6981 .get_relationships(&self.qualified, &table.schema)
6982 .into_iter()
6983 .flatten()
6984 .find(|rel| {
6985 crate::schema::relationship_keys(rel)
6986 .iter()
6987 .any(|found| found == key)
6988 })
6989 {
6990 return Some(std::borrow::Cow::Owned(
6991 crate::schema::relationship::RelationshipField::from_relationship_named(
6992 found,
6993 &found.foreign_table().name,
6994 Some(&entry.name),
6995 ),
6996 ));
6997 }
6998 }
6999 }
7000 }
7001
7002 resolution
7003 .cache
7004 .get_relationships(&self.qualified, &table.schema)?
7005 .iter()
7006 .find_map(|rel| {
7007 let given = crate::schema::relationship_keys(rel)
7008 .iter()
7009 .find_map(|key| self.names.relationship(&table.schema, &table.name, key));
7010 let field = RelationshipField::from_relationship_named(
7014 rel,
7015 &rel.foreign_table().name,
7016 given,
7017 );
7018 (field.name == name).then_some(std::borrow::Cow::Owned(field))
7019 })
7020 }
7021}
7022
7023fn column_comparison(op: &str) -> Option<&'static str> {
7032 Some(match op {
7033 "_ceq" => "=",
7034 "_cne" => "<>",
7035 "_cgt" => ">",
7036 "_cgte" => ">=",
7037 "_clt" => "<",
7038 "_clte" => "<=",
7039 _ => return None,
7040 })
7041}
7042
7043fn build_condition(
7045 value: &serde_json::Value,
7046 scope: &WhereScope<'_>,
7047 param_idx: &mut usize,
7048 values: &mut Vec<serde_json::Value>,
7049 alias_counter: &mut usize,
7050) -> Result<Option<String>, async_graphql::Error> {
7051 let serde_json::Value::Object(map) = value else {
7052 return Ok(None);
7053 };
7054
7055 let mut conditions: Vec<String> = Vec::new();
7056
7057 for (key, val) in map {
7058 match key.as_str() {
7059 "_and" | "_or" => {
7063 let members = val.as_array().ok_or_else(|| {
7064 async_graphql::Error::new(format!("\"{}\" takes a list of expressions", key))
7065 })?;
7066 let mut parts = Vec::new();
7067 for member in members {
7068 if let Some(sql) =
7069 build_condition(member, scope, param_idx, values, alias_counter)?
7070 {
7071 parts.push(sql);
7072 }
7073 }
7074 if parts.is_empty() {
7075 if key == "_or" {
7076 conditions.push("false".to_string());
7077 }
7078 continue;
7079 }
7080 let joiner = if key == "_and" { " AND " } else { " OR " };
7081 conditions.push(format!("({})", parts.join(joiner)));
7082 }
7083 "_not" => {
7084 if let Some(sql) = build_condition(val, scope, param_idx, values, alias_counter)? {
7085 conditions.push(format!("NOT ({})", sql));
7086 }
7087 }
7088 PERMISSION => {
7091 if let Some(sql) =
7092 build_condition(val, &scope.as_system(), param_idx, values, alias_counter)?
7093 {
7094 conditions.push(sql);
7095 }
7096 }
7097 "_exists" => {
7101 conditions.push(table_exists_sql(
7102 val,
7103 scope,
7104 param_idx,
7105 values,
7106 alias_counter,
7107 )?);
7108 }
7109 name if scope.relationship(name).is_some() => {
7115 let relationship = scope.relationship(name).expect("just checked");
7116 conditions.push(exists_sql(
7117 &relationship,
7118 val,
7119 scope,
7120 param_idx,
7121 values,
7122 alias_counter,
7123 )?);
7124 }
7125 name if scope.column_type(name).is_none()
7130 && name
7131 .strip_suffix("_aggregate")
7132 .and_then(|rel| scope.relationship(rel))
7133 .is_some_and(|rel| rel.is_list) =>
7134 {
7135 let relationship = name
7136 .strip_suffix("_aggregate")
7137 .and_then(|rel| scope.relationship(rel))
7138 .expect("just checked");
7139 conditions.push(aggregate_predicate_sql(
7140 &relationship,
7141 val,
7142 scope,
7143 param_idx,
7144 values,
7145 alias_counter,
7146 )?);
7147 }
7148 column => {
7149 let quoted = scope.column(column);
7150 match val {
7151 serde_json::Value::Object(ops) => {
7152 let column_type = scope.column_type(column);
7153 for (op, operand) in ops {
7154 if let Some(other) = column_comparison(op) {
7160 conditions.push(format!(
7161 "{} {} {}",
7162 quoted,
7163 other,
7164 scope.other_column(operand, op)?
7165 ));
7166 continue;
7167 }
7168 conditions.push(comparison_sql(
7169 "ed,
7170 column,
7171 column_type.as_deref(),
7172 op,
7173 operand,
7174 param_idx,
7175 values,
7176 )?);
7177 }
7178 }
7179 other => {
7183 conditions.push(format!("{} = ${}", quoted, param_idx));
7184 values.push(other.clone());
7185 *param_idx += 1;
7186 }
7187 }
7188 }
7189 }
7190 }
7191
7192 Ok(if conditions.is_empty() {
7193 None
7194 } else if conditions.len() == 1 {
7195 conditions.pop()
7196 } else {
7197 Some(conditions.join(" AND "))
7198 })
7199}
7200
7201fn exists_sql(
7208 relationship: &RelationshipField,
7209 child_expression: &serde_json::Value,
7210 scope: &WhereScope<'_>,
7211 param_idx: &mut usize,
7212 values: &mut Vec<serde_json::Value>,
7213 alias_counter: &mut usize,
7214) -> Result<String, async_graphql::Error> {
7215 let cache = scope.resolution.as_ref().map(|r| r.cache).ok_or_else(|| {
7216 async_graphql::Error::new(format!(
7217 "filtering on the relationship \"{}\" is not available here",
7218 relationship.name
7219 ))
7220 })?;
7221
7222 let plan = postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, cache)
7223 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
7224
7225 if plan.junction.is_some() || (plan.function.is_none() && plan.columns.is_empty()) {
7226 return Err(async_graphql::Error::new(format!(
7227 "filtering on \"{}\" is not supported: it is reached through a junction \
7228 rather than by a key",
7229 relationship.name
7230 )));
7231 }
7232
7233 *alias_counter += 1;
7234 let alias = format!("pgrst_rel_{}", alias_counter);
7235 let child_scope = WhereScope::aliased(
7236 &plan.foreign_schema,
7237 &plan.foreign_table,
7238 &alias,
7239 &relationship.target_type,
7240 scope,
7241 );
7242
7243 let (source, mut correlation) = match &plan.function {
7246 Some(function) => (
7247 format!(
7248 "{}.{}({})",
7249 postrust_sql::escape_ident(&function.schema),
7250 postrust_sql::escape_ident(&function.name),
7251 scope.row_ref
7252 ),
7253 Vec::new(),
7254 ),
7255 None => {
7256 let mut columns = Vec::with_capacity(plan.columns.len());
7257 for (parent_column, child_column) in &plan.columns {
7258 columns.push(format!(
7259 "{} = {}",
7260 scope.column(parent_column),
7261 child_scope.column(child_column)
7262 ));
7263 }
7264 (
7265 format!(
7266 "{}.{}",
7267 postrust_sql::escape_ident(&plan.foreign_schema),
7268 postrust_sql::escape_ident(&plan.foreign_table)
7269 ),
7270 columns,
7271 )
7272 }
7273 };
7274
7275 let child_condition = build_condition(
7276 child_expression,
7277 &child_scope,
7278 param_idx,
7279 values,
7280 alias_counter,
7281 )?;
7282 if let Some(sql) = child_condition {
7283 correlation.push(format!("({})", sql));
7284 }
7285
7286 if let Some(caller) = &child_scope.caller {
7291 let permission = permission_predicate(
7298 caller,
7299 child_scope.names,
7300 &plan.foreign_schema,
7301 &plan.foreign_table,
7302 )?;
7303 if let Some(predicate) = permission {
7304 if let Some(sql) =
7305 build_condition(&predicate, &child_scope, param_idx, values, alias_counter)?
7306 {
7307 correlation.push(format!("({})", sql));
7308 }
7309 }
7310 }
7311 if correlation.is_empty() {
7312 correlation.push("true".to_string());
7313 }
7314
7315 Ok(format!(
7316 "EXISTS (SELECT 1 FROM {} AS {} WHERE {})",
7317 source,
7318 postrust_sql::escape_ident(&alias),
7319 correlation.join(" AND ")
7320 ))
7321}
7322
7323fn table_exists_sql(
7348 spec: &serde_json::Value,
7349 scope: &WhereScope<'_>,
7350 param_idx: &mut usize,
7351 values: &mut Vec<serde_json::Value>,
7352 alias_counter: &mut usize,
7353) -> Result<String, async_graphql::Error> {
7354 let Some((schema, table)) = crate::role::exists_target(spec, &scope.qualified.schema) else {
7355 return Err(async_graphql::Error::new(
7356 "\"_exists\" needs a \"_table\" to look in",
7357 ));
7358 };
7359
7360 let qualified = postrust_core::api_request::QualifiedIdentifier::new(&schema, &table);
7364 if scope
7365 .resolution
7366 .as_ref()
7367 .is_some_and(|r| r.cache.get_table(&qualified).is_none())
7368 {
7369 return Err(async_graphql::Error::new(format!(
7370 "\"_exists\" names a table this server does not have: \"{}.{}\"",
7371 schema, table
7372 )));
7373 }
7374
7375 *alias_counter += 1;
7376 let alias = format!("pgrst_exists_{}", alias_counter);
7377 let type_name = scope
7381 .names
7382 .base_name(&schema, &table)
7383 .unwrap_or(&table)
7384 .to_string();
7385 let mut inner = WhereScope::aliased(&schema, &table, &alias, &type_name, scope);
7386 inner.caller = None;
7389
7390 let condition = match spec.get("_where") {
7391 Some(predicate) => build_condition(predicate, &inner, param_idx, values, alias_counter)?,
7392 None => None,
7393 };
7394
7395 Ok(format!(
7396 "EXISTS (SELECT 1 FROM {}.{} AS {} WHERE {})",
7397 postrust_sql::escape_ident(&schema),
7398 postrust_sql::escape_ident(&table),
7399 postrust_sql::escape_ident(&alias),
7400 condition.unwrap_or_else(|| "true".to_string())
7401 ))
7402}
7403
7404fn aggregate_predicate_sql(
7419 relationship: &RelationshipField,
7420 expression: &serde_json::Value,
7421 scope: &WhereScope<'_>,
7422 param_idx: &mut usize,
7423 values: &mut Vec<serde_json::Value>,
7424 alias_counter: &mut usize,
7425) -> Result<String, async_graphql::Error> {
7426 let serde_json::Value::Object(over) = expression else {
7427 return Ok("true".to_string());
7428 };
7429
7430 let cache = scope.resolution.as_ref().map(|r| r.cache).ok_or_else(|| {
7431 async_graphql::Error::new(format!(
7432 "filtering on the relationship \"{}\" is not available here",
7433 relationship.name
7434 ))
7435 })?;
7436 let plan = postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, cache)
7437 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
7438 if plan.junction.is_some() || (plan.function.is_none() && plan.columns.is_empty()) {
7439 return Err(async_graphql::Error::new(format!(
7440 "aggregating over \"{}\" is not supported: it is reached through a junction \
7441 rather than by a key",
7442 relationship.name
7443 )));
7444 }
7445
7446 let mut conditions: Vec<String> = Vec::new();
7447 for (function, spec) in over {
7448 if spec.is_null() {
7449 continue;
7450 }
7451 let serde_json::Value::Object(spec) = spec else {
7452 continue;
7453 };
7454 let Some(predicate) = spec.get("predicate").filter(|p| !p.is_null()) else {
7455 return Err(validation_error(format!(
7456 "\"{}\" over \"{}\" needs a predicate",
7457 function, relationship.name
7458 )));
7459 };
7460
7461 *alias_counter += 1;
7462 let alias = format!("pgrst_agg_{}", alias_counter);
7463 let child_scope = WhereScope::aliased(
7464 &plan.foreign_schema,
7465 &plan.foreign_table,
7466 &alias,
7467 &relationship.target_type,
7468 scope,
7469 );
7470
7471 let (source, mut correlation) = match &plan.function {
7474 Some(routine) => (
7475 format!(
7476 "{}.{}({})",
7477 postrust_sql::escape_ident(&routine.schema),
7478 postrust_sql::escape_ident(&routine.name),
7479 scope.row_ref
7480 ),
7481 Vec::new(),
7482 ),
7483 None => {
7484 let mut columns = Vec::with_capacity(plan.columns.len());
7485 for (parent_column, child_column) in &plan.columns {
7486 columns.push(format!(
7487 "{} = {}",
7488 scope.column(parent_column),
7489 child_scope.column(child_column)
7490 ));
7491 }
7492 (
7493 format!(
7494 "{}.{}",
7495 postrust_sql::escape_ident(&plan.foreign_schema),
7496 postrust_sql::escape_ident(&plan.foreign_table)
7497 ),
7498 columns,
7499 )
7500 }
7501 };
7502 if let Some(filter) = spec.get("filter").filter(|f| !f.is_null()) {
7505 if let Some(sql) =
7506 build_condition(filter, &child_scope, param_idx, values, alias_counter)?
7507 {
7508 correlation.push(format!("({})", sql));
7509 }
7510 }
7511 if correlation.is_empty() {
7512 correlation.push("true".to_string());
7513 }
7514
7515 let arguments = spec.get("arguments").filter(|a| !a.is_null());
7516 let distinct = matches!(spec.get("distinct"), Some(serde_json::Value::Bool(true)));
7517 let (aggregate, operand_type) = match function.as_str() {
7518 "count" => {
7519 let columns: Vec<String> = match arguments {
7520 Some(serde_json::Value::Array(items)) => items
7521 .iter()
7522 .filter_map(|item| item.as_str())
7523 .map(|column| child_scope.column(column))
7524 .collect(),
7525 Some(serde_json::Value::String(one)) => vec![child_scope.column(one)],
7526 _ => Vec::new(),
7527 };
7528 let counted = match columns.len() {
7529 0 => "*".to_string(),
7530 1 => columns.into_iter().next().unwrap_or_default(),
7531 _ => format!("({})", columns.join(", ")),
7532 };
7533 let counted = match distinct && counted != "*" {
7534 true => format!("DISTINCT {}", counted),
7535 false => counted,
7536 };
7537 (format!("count({})", counted), "integer")
7538 }
7539 "bool_and" | "bool_or" => {
7540 let Some(column) = arguments.and_then(|a| a.as_str()) else {
7541 return Err(validation_error(format!(
7542 "\"{}\" over \"{}\" needs the column to fold",
7543 function, relationship.name
7544 )));
7545 };
7546 (
7547 format!("{}({})", function, child_scope.column(column)),
7548 "boolean",
7549 )
7550 }
7551 other => {
7552 return Err(validation_error(format!(
7553 "\"{}\" is not an aggregate a predicate can be written over",
7554 other
7555 )))
7556 }
7557 };
7558
7559 let subselect = format!(
7560 "(SELECT {} FROM {} AS {} WHERE {})",
7561 aggregate,
7562 source,
7563 postrust_sql::escape_ident(&alias),
7564 correlation.join(" AND ")
7565 );
7566 let serde_json::Value::Object(operators) = predicate else {
7567 return Err(validation_error(format!(
7568 "the predicate on \"{}\" is not a comparison",
7569 function
7570 )));
7571 };
7572 for (operator, operand) in operators {
7573 conditions.push(comparison_sql(
7574 &subselect,
7575 function,
7576 Some(operand_type),
7577 operator,
7578 operand,
7579 param_idx,
7580 values,
7581 )?);
7582 }
7583 }
7584
7585 Ok(match conditions.is_empty() {
7586 true => "true".to_string(),
7587 false => format!("({})", conditions.join(" AND ")),
7588 })
7589}
7590
7591#[allow(clippy::too_many_arguments)]
7599fn postgis_sql(
7600 quoted: &str,
7601 column_type: Option<&str>,
7602 function: &str,
7603 op: &str,
7604 operand: &serde_json::Value,
7605 param_idx: &mut usize,
7606 values: &mut Vec<serde_json::Value>,
7607) -> Result<String, async_graphql::Error> {
7608 let is_geography = column_type == Some("geography");
7609 let mut shape = |value: &serde_json::Value, param_idx: &mut usize| -> String {
7610 let placeholder = format!("${}", param_idx);
7611 *param_idx += 1;
7612 values.push(value.clone());
7613 match is_geography {
7614 true => format!("ST_GeomFromGeoJSON({})::geography", placeholder),
7615 false => format!("ST_GeomFromGeoJSON({})", placeholder),
7616 }
7617 };
7618
7619 match op {
7620 "_st_d_within" | "_st_3d_d_within" => {
7622 let serde_json::Value::Object(spec) = operand else {
7623 return Err(async_graphql::Error::new(format!(
7624 "\"{}\" takes {{distance, from}}",
7625 op
7626 )));
7627 };
7628 let Some(from) = spec.get("from") else {
7629 return Err(async_graphql::Error::new(format!(
7630 "\"{}\" needs a shape to measure from",
7631 op
7632 )));
7633 };
7634 let Some(distance) = spec.get("distance") else {
7635 return Err(async_graphql::Error::new(format!(
7636 "\"{}\" needs a distance",
7637 op
7638 )));
7639 };
7640 let from_sql = shape(from, param_idx);
7641 let distance_sql = format!("${}", param_idx);
7642 *param_idx += 1;
7643 values.push(distance.clone());
7644 let spheroid = match (is_geography, spec.get("use_spheroid")) {
7649 (true, Some(use_spheroid)) if !use_spheroid.is_null() => {
7650 let placeholder = format!("${}", param_idx);
7651 *param_idx += 1;
7652 values.push(use_spheroid.clone());
7653 format!(", {}::boolean", placeholder)
7654 }
7655 _ => String::new(),
7656 };
7657 Ok(format!(
7658 "{}({}, {}, {}::float8{})",
7659 function, quoted, from_sql, distance_sql, spheroid
7660 ))
7661 }
7662 "_st_intersects_rast" => {
7664 let placeholder = format!("${}", param_idx);
7665 *param_idx += 1;
7666 values.push(operand.clone());
7667 Ok(format!("{}({}, {}::raster)", function, quoted, placeholder))
7668 }
7669 "_st_intersects_geom_nband" | "_st_intersects_nband_geom" => {
7671 let serde_json::Value::Object(spec) = operand else {
7672 return Err(async_graphql::Error::new(format!(
7673 "\"{}\" takes an object",
7674 op
7675 )));
7676 };
7677 let Some(geometry) = spec.get("geommin") else {
7678 return Err(async_graphql::Error::new(format!(
7679 "\"{}\" needs a shape",
7680 op
7681 )));
7682 };
7683 let band = spec.get("nband").filter(|v| !v.is_null());
7684 let geometry_sql = shape(geometry, param_idx);
7685 Ok(match band {
7686 None => format!("{}({}, {})", function, quoted, geometry_sql),
7687 Some(band) => {
7688 let placeholder = format!("${}", param_idx);
7689 *param_idx += 1;
7690 values.push(band.clone());
7691 format!(
7695 "{}({}, {}::int, {})",
7696 function, quoted, placeholder, geometry_sql
7697 )
7698 }
7699 })
7700 }
7701 _ => {
7703 let other = shape(operand, param_idx);
7704 Ok(format!("{}({}, {})", function, quoted, other))
7705 }
7706 }
7707}
7708
7709fn sql_array(
7715 items: &[serde_json::Value],
7716 cast: &str,
7717 param_idx: &mut usize,
7718 values: &mut Vec<serde_json::Value>,
7719) -> String {
7720 if items.is_empty() {
7721 return format!("ARRAY[]::{}", cast);
7722 }
7723 let placeholders: Vec<String> = items
7724 .iter()
7725 .map(|item| {
7726 let placeholder = format!("${}", param_idx);
7727 *param_idx += 1;
7728 values.push(item.clone());
7729 placeholder
7730 })
7731 .collect();
7732 format!("ARRAY[{}]::{}", placeholders.join(", "), cast)
7733}
7734
7735#[allow(clippy::too_many_arguments)]
7737fn comparison_sql(
7738 quoted: &str,
7739 column: &str,
7740 column_type: Option<&str>,
7741 op: &str,
7742 operand: &serde_json::Value,
7743 param_idx: &mut usize,
7744 values: &mut Vec<serde_json::Value>,
7745) -> Result<String, async_graphql::Error> {
7746 if op == "_cast" {
7752 let serde_json::Value::Object(casts) = operand else {
7753 return Err(async_graphql::Error::new(
7754 "_cast takes an object naming the type to compare as",
7755 ));
7756 };
7757 let mut conditions = Vec::new();
7758 for (target, comparisons) in casts {
7759 let pg_type = match target.as_str() {
7763 "geometry" | "geography" => target.as_str(),
7764 "String" => "text",
7765 _ => {
7766 return Err(async_graphql::Error::new(format!(
7767 "cannot compare \"{}\" as \"{}\"",
7768 column, target
7769 )))
7770 }
7771 };
7772 let serde_json::Value::Object(ops) = comparisons else {
7773 continue;
7774 };
7775 let cast = format!("{}::{}", quoted, pg_type);
7776 for (nested_op, nested_operand) in ops {
7777 conditions.push(comparison_sql(
7778 &cast,
7779 column,
7780 Some(pg_type),
7781 nested_op,
7782 nested_operand,
7783 param_idx,
7784 values,
7785 )?);
7786 }
7787 }
7788 return Ok(match conditions.len() {
7789 0 => "true".to_string(),
7790 1 => conditions.pop().expect("just counted"),
7791 _ => format!("({})", conditions.join(" AND ")),
7792 });
7793 }
7794
7795 if let Some(function) = crate::input::bool_exp::postgis_function(op) {
7798 return postgis_sql(
7799 quoted,
7800 column_type,
7801 function,
7802 op,
7803 operand,
7804 param_idx,
7805 values,
7806 );
7807 }
7808
7809 if let Some((operator, cast)) = crate::input::bool_exp::ltree_operator(op) {
7813 if cast.ends_with("[]") {
7814 let items = operand.as_array().ok_or_else(|| {
7815 async_graphql::Error::new(format!(
7816 "the \"{}\" comparison on \"{}\" takes a list",
7817 op, column
7818 ))
7819 })?;
7820 return Ok(format!(
7821 "{} {} {}",
7822 quoted,
7823 operator,
7824 sql_array(items, cast, param_idx, values)
7825 ));
7826 }
7827 let placeholder = format!("${}", param_idx);
7828 *param_idx += 1;
7829 values.push(operand.clone());
7830 return Ok(format!("{} {} {}::{}", quoted, operator, placeholder, cast));
7831 }
7832
7833 if let Some(function) = match op {
7838 "_jsonb_path_exists" => Some("jsonb_path_exists"),
7839 "_jsonb_path_match" => Some("jsonb_path_match"),
7840 _ => None,
7841 } {
7842 let placeholder = format!("${}", param_idx);
7843 *param_idx += 1;
7844 values.push(operand.clone());
7845 return Ok(format!(
7846 "{}({}, {}::jsonpath)",
7847 function, quoted, placeholder
7848 ));
7849 }
7850
7851 let binary = match op {
7853 "_eq" => Some("="),
7854 "_neq" => Some("<>"),
7855 "_gt" => Some(">"),
7856 "_gte" => Some(">="),
7857 "_lt" => Some("<"),
7858 "_lte" => Some("<="),
7859 "_like" => Some("LIKE"),
7860 "_nlike" => Some("NOT LIKE"),
7861 "_ilike" => Some("ILIKE"),
7862 "_nilike" => Some("NOT ILIKE"),
7863 "_similar" => Some("SIMILAR TO"),
7864 "_nsimilar" => Some("NOT SIMILAR TO"),
7865 "_regex" => Some("~"),
7866 "_nregex" => Some("!~"),
7867 "_iregex" => Some("~*"),
7868 "_niregex" => Some("!~*"),
7869 "_contains" => Some("@>"),
7870 "_contained_in" => Some("<@"),
7871 "_has_key" => Some("?"),
7872 _ => None,
7873 };
7874
7875 if let Some(sql_op) = binary {
7876 let placeholder = format!("${}", param_idx);
7877 *param_idx += 1;
7878 values.push(match op {
7883 "_contains" | "_contained_in" => match operand {
7884 serde_json::Value::String(_)
7885 | serde_json::Value::Number(_)
7886 | serde_json::Value::Bool(_) => serde_json::Value::String(operand.to_string()),
7887 other => other.clone(),
7888 },
7889 _ => operand.clone(),
7890 });
7891 let cast = match op {
7903 "_contains" | "_contained_in" => "::jsonb".to_string(),
7904 "_has_key" => "::text".to_string(),
7905 _ if operand.is_null() => match column_type {
7914 Some(pg_type) => format!("::{}", pg_type),
7915 None => String::new(),
7916 },
7917 _ if operand.is_string() => match column_type {
7928 Some(pg_type) => format!("::{}", pg_type),
7929 None => String::new(),
7930 },
7931 _ => String::new(),
7932 };
7933 return Ok(format!("{} {} {}{}", quoted, sql_op, placeholder, cast));
7934 }
7935
7936 match op {
7937 "_is_null" => Ok(if operand.as_bool().unwrap_or(false) {
7938 format!("{} IS NULL", quoted)
7939 } else {
7940 format!("{} IS NOT NULL", quoted)
7941 }),
7942 "_in" | "_nin" => {
7943 let items = operand.as_array().ok_or_else(|| {
7944 async_graphql::Error::new(format!(
7945 "the \"{}\" comparison on \"{}\" requires a list of values",
7946 op, column
7947 ))
7948 })?;
7949 if items.is_empty() {
7950 return Ok(if op == "_in" { "false" } else { "true" }.to_string());
7953 }
7954 let mut placeholders = Vec::with_capacity(items.len());
7955 for item in items {
7956 let cast = match (item.is_null() || item.is_string(), column_type) {
7959 (true, Some(pg_type)) => format!("::{}", pg_type),
7960 _ => String::new(),
7961 };
7962 placeholders.push(format!("${}{}", param_idx, cast));
7963 values.push(item.clone());
7964 *param_idx += 1;
7965 }
7966 Ok(format!(
7967 "{} {} ({})",
7968 quoted,
7969 if op == "_in" { "IN" } else { "NOT IN" },
7970 placeholders.join(", ")
7971 ))
7972 }
7973 "_has_keys_any" | "_has_keys_all" => {
7974 let items = operand.as_array().ok_or_else(|| {
7975 async_graphql::Error::new(format!(
7976 "the \"{}\" comparison on \"{}\" requires a list of keys",
7977 op, column
7978 ))
7979 })?;
7980 Ok(format!(
7981 "{} {} {}",
7982 quoted,
7983 if op == "_has_keys_any" { "?|" } else { "?&" },
7984 sql_array(items, "text[]", param_idx, values)
7985 ))
7986 }
7987 other => Err(async_graphql::Error::new(format!(
7988 "unsupported comparison \"{}\" on \"{}\"",
7989 other, column
7990 ))),
7991 }
7992}
7993
7994#[allow(clippy::too_many_arguments)] async fn build_order_by_clause(
8004 ctx: &ResolverContext<'_>,
8005 schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
8006 schema_name: &str,
8007 table_name: &str,
8008 type_name: &str,
8009 relationships: &HashMap<String, Vec<RelationshipField>>,
8010 reference: &str,
8011 names: &crate::names::NameOverrides,
8012) -> Result<String, async_graphql::Error> {
8013 let Ok(order_arg) = ctx.args.try_get("order_by") else {
8014 return Ok(String::new());
8015 };
8016
8017 let value = accessor_to_json(&order_arg);
8018 let entries: Vec<&serde_json::Value> = match &value {
8021 serde_json::Value::Array(items) => items.iter().collect(),
8022 serde_json::Value::Object(_) => vec![&value],
8023 serde_json::Value::Null => return Ok(String::new()),
8024 _ => {
8025 return Err(async_graphql::Error::new(
8026 "order_by takes an object or a list of them",
8027 ))
8028 }
8029 };
8030 if entries.is_empty() {
8031 return Ok(String::new());
8032 }
8033
8034 let guard = schema_cache
8035 .get()
8036 .await
8037 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8038 let cache = guard
8039 .as_ref()
8040 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
8041 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8042 let table = cache
8043 .get_table(&qi)
8044 .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8045
8046 let mut terms = Vec::new();
8047 let mut alias_counter = 0usize;
8048 for entry in entries {
8049 order_terms_into(
8050 entry,
8051 cache,
8052 relationships,
8053 type_name,
8054 table,
8055 reference,
8056 names,
8057 &mut alias_counter,
8058 &mut terms,
8059 )?;
8060 }
8061
8062 if terms.is_empty() {
8063 return Ok(String::new());
8064 }
8065 Ok(format!(" ORDER BY {}", terms.join(", ")))
8066}
8067
8068#[allow(clippy::too_many_arguments)]
8076fn order_terms_into(
8077 entry: &serde_json::Value,
8078 cache: &SchemaCache,
8079 relationships: &HashMap<String, Vec<RelationshipField>>,
8080 type_name: &str,
8081 table: &postrust_core::schema_cache::Table,
8082 reference: &str,
8083 names: &crate::names::NameOverrides,
8084 alias_counter: &mut usize,
8085 terms: &mut Vec<String>,
8086) -> Result<(), async_graphql::Error> {
8087 let serde_json::Value::Object(map) = entry else {
8088 return Err(async_graphql::Error::new(
8089 "each order_by entry is an object mapping a column to a direction",
8090 ));
8091 };
8092 let available: &[RelationshipField] = relationships
8093 .get(type_name)
8094 .map(|r| r.as_slice())
8095 .unwrap_or(&[]);
8096
8097 for (key, value) in map {
8098 if value.is_null() {
8104 continue;
8105 }
8106
8107 if let Some(name) = value.as_str() {
8109 let sql = crate::input::order_by::direction_sql(name).ok_or_else(|| {
8110 async_graphql::Error::new(format!(
8111 "\"{}\" is not a sort direction; expected one of asc, desc, \
8112 asc_nulls_first, asc_nulls_last, desc_nulls_first, desc_nulls_last",
8113 name
8114 ))
8115 })?;
8116 let column = table_column_for(names, table, key);
8117 if table.get_column(column).is_some() {
8118 terms.push(format!(
8119 "{}.{} {}",
8120 reference,
8121 postrust_sql::escape_ident(column),
8122 sql
8123 ));
8124 continue;
8125 }
8126 let function = names
8129 .computed_source(&table.schema, &table.name, key)
8130 .unwrap_or(key);
8131 if let Some(definition) = table.get_computed_column(function) {
8132 terms.push(format!(
8133 "{} {}",
8134 computed_call(definition, &format!("{}.*", reference), reference),
8135 sql
8136 ));
8137 continue;
8138 }
8139 return Err(async_graphql::Error::new(format!(
8140 "cannot order by unknown column \"{}\" on \"{}\"",
8141 key, table.name
8142 )));
8143 }
8144
8145 if let Some(rel) = key
8147 .strip_suffix("_aggregate")
8148 .and_then(|name| available.iter().find(|r| r.name == name && r.is_list))
8149 {
8150 aggregate_order_terms(value, rel, cache, reference, alias_counter, terms)?;
8151 continue;
8152 }
8153
8154 if let Some(rel) = available.iter().find(|r| r.name == *key && !r.is_list) {
8156 let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, cache)
8157 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8158 if plan.columns.is_empty() {
8159 return Err(async_graphql::Error::new(format!(
8160 "cannot order by \"{}\": it is not reached by a key",
8161 key
8162 )));
8163 }
8164 *alias_counter += 1;
8165 let alias = format!("pgrst_ord_{}", alias_counter);
8166 let quoted_alias = postrust_sql::escape_ident(&alias);
8167 let correlation = plan
8168 .columns
8169 .iter()
8170 .map(|(local, foreign)| {
8171 format!(
8172 "{} = {}.{}",
8173 format_args!("{}.{}", reference, postrust_sql::escape_ident(local)),
8174 quoted_alias,
8175 postrust_sql::escape_ident(foreign)
8176 )
8177 })
8178 .collect::<Vec<_>>()
8179 .join(" AND ");
8180
8181 let target_qi = postrust_core::api_request::QualifiedIdentifier::new(
8182 &plan.foreign_schema,
8183 &plan.foreign_table,
8184 );
8185 let Some(target) = cache.get_table(&target_qi) else {
8186 return Err(async_graphql::Error::new(format!(
8187 "unknown table \"{}\"",
8188 plan.foreign_table
8189 )));
8190 };
8191
8192 let mut nested = Vec::new();
8195 order_terms_into(
8196 value,
8197 cache,
8198 relationships,
8199 &rel.target_type,
8200 target,
8201 "ed_alias,
8202 names,
8203 alias_counter,
8204 &mut nested,
8205 )?;
8206 for term in nested {
8207 let (expression, direction) = term
8208 .rsplit_once(' ')
8209 .map(|(e, d)| (e.to_string(), d.to_string()))
8210 .unwrap_or((term.clone(), String::new()));
8211 terms.push(format!(
8212 "(SELECT {} FROM {}.{} AS {} WHERE {}) {}",
8213 expression,
8214 postrust_sql::escape_ident(&plan.foreign_schema),
8215 postrust_sql::escape_ident(&plan.foreign_table),
8216 quoted_alias,
8217 correlation,
8218 direction
8219 ));
8220 }
8221 continue;
8222 }
8223
8224 return Err(async_graphql::Error::new(format!(
8225 "cannot order by \"{}\" on \"{}\"",
8226 key, table.name
8227 )));
8228 }
8229 Ok(())
8230}
8231
8232fn aggregate_order_terms(
8234 value: &serde_json::Value,
8235 rel: &RelationshipField,
8236 cache: &SchemaCache,
8237 reference: &str,
8238 alias_counter: &mut usize,
8239 terms: &mut Vec<String>,
8240) -> Result<(), async_graphql::Error> {
8241 let serde_json::Value::Object(spec) = value else {
8242 return Err(async_graphql::Error::new(
8243 "ordering by an aggregate takes an object, such as {count: desc}",
8244 ));
8245 };
8246 let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, cache)
8247 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8248 if plan.columns.is_empty() && plan.function.is_none() {
8249 return Err(async_graphql::Error::new(format!(
8250 "cannot order by an aggregate of \"{}\": it is not reached by a key",
8251 rel.name
8252 )));
8253 }
8254 if plan.function.is_some() && !rel.arguments.is_empty() {
8257 return Err(async_graphql::Error::new(format!(
8258 "cannot order by an aggregate of \"{}\": it takes arguments, and an \
8259 ordering has nowhere to write them",
8260 rel.name
8261 )));
8262 }
8263
8264 *alias_counter += 1;
8265 let alias = postrust_sql::escape_ident(&format!("pgrst_ord_{}", alias_counter));
8266 let (source, correlation) = match &plan.function {
8269 Some(function) => {
8270 let session = plan.row_argument.as_ref().and_then(|row_argument| {
8271 computed_session_argument(cache, function, row_argument)
8272 .map(|session| (row_argument.clone(), session))
8273 });
8274 let call = match session {
8275 Some((row_argument, session)) => format!(
8276 "{} => {}, {} => {}",
8277 postrust_sql::escape_ident(&row_argument),
8278 reference,
8279 postrust_sql::escape_ident(&session),
8280 SESSION_ARGUMENT
8281 ),
8282 None => reference.to_string(),
8283 };
8284 (
8285 format!(
8286 "{}.{}({})",
8287 postrust_sql::escape_ident(&function.schema),
8288 postrust_sql::escape_ident(&function.name),
8289 call
8290 ),
8291 "true".to_string(),
8292 )
8293 }
8294 None => (
8295 format!(
8296 "{}.{}",
8297 postrust_sql::escape_ident(&plan.foreign_schema),
8298 postrust_sql::escape_ident(&plan.foreign_table)
8299 ),
8300 plan.columns
8301 .iter()
8302 .map(|(local, foreign)| {
8303 format!(
8304 "{}.{} = {}.{}",
8305 reference,
8306 postrust_sql::escape_ident(local),
8307 alias,
8308 postrust_sql::escape_ident(foreign)
8309 )
8310 })
8311 .collect::<Vec<_>>()
8312 .join(" AND "),
8313 ),
8314 };
8315
8316 let mut wanted: Vec<(String, String)> = Vec::new();
8318 for (function, argument) in spec {
8319 if argument.is_null() {
8322 continue;
8323 }
8324 if function == "count" {
8325 let name = argument.as_str().unwrap_or_default();
8326 let Some(direction) = crate::input::order_by::direction_sql(name) else {
8327 return Err(async_graphql::Error::new(format!(
8328 "\"{}\" is not a sort direction",
8329 name
8330 )));
8331 };
8332 wanted.push(("count(*)".to_string(), direction.to_string()));
8333 continue;
8334 }
8335 let serde_json::Value::Object(columns) = argument else {
8336 continue;
8337 };
8338 for (column, direction) in columns {
8339 if direction.is_null() {
8340 continue;
8341 }
8342 let name = direction.as_str().unwrap_or_default();
8343 let Some(direction) = crate::input::order_by::direction_sql(name) else {
8344 return Err(async_graphql::Error::new(format!(
8345 "\"{}\" is not a sort direction",
8346 name
8347 )));
8348 };
8349 wanted.push((
8352 format!(
8353 "{}({}.{})",
8354 function,
8355 alias,
8356 postrust_sql::escape_ident(column)
8357 ),
8358 direction.to_string(),
8359 ));
8360 }
8361 }
8362
8363 for (expression, direction) in wanted {
8364 terms.push(format!(
8365 "(SELECT {} FROM {} AS {} WHERE {}) {}",
8366 expression, source, alias, correlation, direction
8367 ));
8368 }
8369 Ok(())
8370}
8371
8372fn distinct_on_clause(
8386 distinct_on: &[String],
8387 written: Option<&str>,
8388) -> Result<(String, Option<String>), async_graphql::Error> {
8389 if distinct_on.is_empty() {
8390 return Ok((String::new(), written.map(str::to_string)));
8391 }
8392 let terms: Vec<&str> = written
8393 .map(|written| written.split(", ").collect())
8394 .unwrap_or_default();
8395 let column_of = |term: &str| {
8398 let expression = term.split_whitespace().next().unwrap_or(term);
8399 expression
8400 .rsplit_once('.')
8401 .map(|(_, name)| name)
8402 .unwrap_or(expression)
8403 .to_string()
8404 };
8405 let leading: Vec<String> = terms
8406 .iter()
8407 .take(distinct_on.len())
8408 .map(|term| column_of(term))
8409 .collect();
8410 if !terms.is_empty()
8411 && (leading.len() != distinct_on.len()
8412 || distinct_on
8413 .iter()
8414 .any(|column| !leading.contains(&column_of(column))))
8415 {
8416 return Err(validation_error(
8417 "\"distinct_on\" columns must match initial \"order_by\" columns",
8418 ));
8419 }
8420 let order = match terms.is_empty() {
8421 true => Some(distinct_on.join(", ")),
8422 false => written.map(str::to_string),
8423 };
8424 Ok((format!("DISTINCT ON ({}) ", distinct_on.join(", ")), order))
8425}
8426
8427async fn build_distinct_on(
8435 ctx: &ResolverContext<'_>,
8436 schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
8437 schema_name: &str,
8438 table_name: &str,
8439 names: &crate::names::NameOverrides,
8440) -> Result<Vec<String>, async_graphql::Error> {
8441 let Ok(arg) = ctx.args.try_get("distinct_on") else {
8442 return Ok(Vec::new());
8443 };
8444 let value = accessor_to_json(&arg);
8445 let requested: Vec<String> = match &value {
8446 serde_json::Value::Array(items) => items
8447 .iter()
8448 .filter_map(|i| i.as_str().map(|s| s.to_string()))
8449 .collect(),
8450 serde_json::Value::String(one) => vec![one.clone()],
8451 _ => Vec::new(),
8452 };
8453 if requested.is_empty() {
8454 return Ok(Vec::new());
8455 }
8456
8457 let guard = schema_cache
8458 .get()
8459 .await
8460 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8461 let cache = guard
8462 .as_ref()
8463 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
8464 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8465 let table = cache
8466 .get_table(&qi)
8467 .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8468
8469 let mut quoted = Vec::with_capacity(requested.len());
8470 for field in requested {
8471 let name = table_column_for(names, table, &field).to_string();
8472 if table.get_column(&name).is_none() {
8473 return Err(async_graphql::Error::new(format!(
8474 "cannot take distinct on unknown column \"{}\" of \"{}\"",
8475 field, table_name
8476 )));
8477 }
8478 quoted.push(postrust_sql::escape_ident(&name));
8479 }
8480 Ok(quoted)
8481}
8482
8483#[allow(clippy::too_many_arguments)] fn computed_projections<'a>(
8497 table: &postrust_core::schema_cache::Table,
8498 fields: impl IntoIterator<Item = SelectionField<'a>>,
8499 row_reference: &str,
8500 names: &crate::names::NameOverrides,
8501 schema_cache: &SchemaCache,
8502 param_idx: &mut usize,
8503 values: &mut Vec<serde_json::Value>,
8504) -> Result<Vec<String>, async_graphql::Error> {
8505 let mut projections = Vec::new();
8506 for field in fields {
8507 let name = field.name();
8508 if table
8511 .get_column(table_column_for(names, table, name))
8512 .is_some()
8513 {
8514 continue;
8515 }
8516 let function = names
8519 .computed_source(&table.schema, &table.name, name)
8520 .unwrap_or(name);
8521 let Some(computed) = table.get_computed_column(function) else {
8522 continue;
8523 };
8524 let arguments = crate::schema::computed_caller_arguments(computed, schema_cache);
8525 let given = match arguments.is_empty() {
8526 true => None,
8527 false => embed_arguments(field).remove("args"),
8528 };
8529 projections.push(format!(
8530 "{} AS {}",
8531 computed_column_call(
8532 computed,
8533 row_reference,
8534 name,
8535 &arguments,
8536 given.as_ref(),
8537 param_idx,
8538 values,
8539 )?,
8540 postrust_sql::escape_ident(name)
8541 ));
8542 }
8543 Ok(projections)
8544}
8545
8546fn computed_column_call(
8555 computed: &postrust_core::schema_cache::ComputedColumn,
8556 row: &str,
8557 field_name: &str,
8558 arguments: &[(String, String, bool)],
8559 given: Option<&serde_json::Value>,
8560 param_idx: &mut usize,
8561 values: &mut Vec<serde_json::Value>,
8562) -> Result<String, async_graphql::Error> {
8563 if arguments.is_empty() {
8564 return Ok(computed_call(computed, row, row));
8565 }
8566 let Some(row_argument) = &computed.row_argument else {
8567 return Ok(computed_call(computed, row, row));
8568 };
8569 let function = format!(
8570 "{}.{}",
8571 postrust_sql::escape_ident(&computed.function.schema),
8572 postrust_sql::escape_ident(&computed.function.name)
8573 );
8574 let mut passed = vec![format!(
8575 "{} => {}",
8576 postrust_sql::escape_ident(row_argument),
8577 row
8578 )];
8579 if let Some(session) = &computed.session_argument {
8580 passed.push(format!(
8581 "{} => {}",
8582 postrust_sql::escape_ident(session),
8583 SESSION_ARGUMENT
8584 ));
8585 }
8586 for (name, pg_type, required) in arguments {
8587 match given.and_then(|given| given.get(name)) {
8588 None if *required => {
8589 return Err(async_graphql::Error::new(format!(
8590 "{} needs the argument \"{}\"",
8591 field_name, name
8592 )))
8593 }
8594 None => continue,
8596 Some(value) => {
8597 passed.push(format!(
8598 "{} => ${}::{}",
8599 postrust_sql::escape_ident(name),
8600 param_idx,
8601 pg_type
8602 ));
8603 *param_idx += 1;
8604 values.push(value.clone());
8605 }
8606 }
8607 }
8608 Ok(format!("{}({})", function, passed.join(", ")))
8609}
8610
8611fn count_expression(
8623 field: async_graphql::SelectionField<'_>,
8624 table: (&str, &str),
8625 alias: Option<&str>,
8626 names: &crate::names::NameOverrides,
8627) -> String {
8628 let arguments = embed_arguments(field);
8629 let requested = match arguments.get("columns") {
8630 Some(serde_json::Value::Array(items)) => items
8631 .iter()
8632 .filter_map(|item| item.as_str())
8633 .collect::<Vec<_>>(),
8634 Some(serde_json::Value::String(one)) => vec![one.as_str()],
8635 _ => Vec::new(),
8636 };
8637 if requested.is_empty() {
8638 return "count(*)".to_string();
8639 }
8640 let columns: Vec<String> = requested
8641 .into_iter()
8642 .map(|column| {
8643 let (schema, name) = table;
8644 let source = column_for(names, schema, name, column);
8645 match alias {
8646 Some(alias) => format!(
8647 "{}.{}",
8648 postrust_sql::escape_ident(alias),
8649 postrust_sql::escape_ident(source)
8650 ),
8651 None => postrust_sql::escape_ident(source),
8652 }
8653 })
8654 .collect();
8655 let counted = match columns.len() {
8658 1 => columns.into_iter().next().unwrap_or_default(),
8659 _ => format!("({})", columns.join(", ")),
8660 };
8661 let distinct = matches!(
8662 arguments.get("distinct"),
8663 Some(serde_json::Value::Bool(true))
8664 );
8665 match distinct {
8666 true => format!("count(DISTINCT {})", counted),
8667 false => format!("count({})", counted),
8668 }
8669}
8670
8671#[allow(clippy::too_many_arguments)] fn nested_aggregate_select(
8679 caller: &crate::role::Caller<'_>,
8680 selection: async_graphql::SelectionField<'_>,
8681 child_alias: &str,
8682 schema_cache: &SchemaCache,
8683 relationships: &HashMap<String, Vec<RelationshipField>>,
8684 target_type: &str,
8685 child_table: Option<&postrust_core::schema_cache::Table>,
8686 max_rows: Option<i64>,
8687 alias_counter: &mut usize,
8688 param_idx: &mut usize,
8689 values: &mut Vec<serde_json::Value>,
8690 names: &crate::names::NameOverrides,
8691) -> Result<String, async_graphql::Error> {
8692 use crate::schema::aggregate as agg;
8693
8694 let mut parts: Vec<String> = Vec::new();
8695
8696 for child in selection.selection_set() {
8697 match child.name() {
8698 "aggregate" => {
8699 let of_table = child_table
8700 .map(|table| (table.schema.as_str(), table.name.as_str()))
8701 .unwrap_or(("", ""));
8702 let mut counts: Vec<(String, String)> = Vec::new();
8707 let mut wanted: BTreeMap<&str, Vec<String>> = BTreeMap::new();
8708 for function in child.selection_set() {
8709 if function.name() == "count" {
8710 counts.push((
8711 function.alias().unwrap_or("count").to_string(),
8712 count_expression(function, of_table, Some(child_alias), names),
8713 ));
8714 continue;
8715 }
8716 let sql_function = agg::NUMERIC_AGGREGATES
8717 .iter()
8718 .chain(agg::ORDERED_AGGREGATES.iter())
8719 .find(|(name, _)| *name == function.name())
8720 .map(|(name, _)| *name);
8721 let Some(sql_function) = sql_function else {
8722 continue;
8723 };
8724 let columns = wanted.entry(sql_function).or_default();
8725 for column in function.selection_set() {
8726 let name = column.name().to_string();
8727 if name != "__typename" && !columns.contains(&name) {
8729 columns.push(name);
8730 }
8731 }
8732 }
8733 let mut fields = match counts.iter().any(|(key, _)| key == "count") {
8736 true => Vec::new(),
8737 false => vec!["'count', count(*)".to_string()],
8738 };
8739 for (key, expression) in &counts {
8740 fields.push(format!(
8741 "{}, {}",
8742 postrust_sql::quote_literal(key),
8743 expression
8744 ));
8745 }
8746 for (sql_function, named) in &wanted {
8747 let columns: Vec<String> = named
8748 .iter()
8749 .map(|column| {
8750 let source = child_table
8751 .map(|table| table_column_for(names, table, column))
8752 .unwrap_or(column.as_str());
8753 format!(
8754 "{}, {}({}.{})",
8755 postrust_sql::quote_literal(column),
8756 sql_function,
8757 postrust_sql::escape_ident(child_alias),
8758 postrust_sql::escape_ident(source)
8759 )
8760 })
8761 .collect();
8762 fields.push(format!(
8765 "'{}', json_build_object({})",
8766 sql_function,
8767 columns.join(", ")
8768 ));
8769 }
8770 parts.push(format!(
8771 "json_build_object({}) AS {}",
8772 fields.join(", "),
8773 postrust_sql::escape_ident("aggregate")
8774 ));
8775 }
8776 "nodes" => {
8781 let embeds = build_embed_expressions(
8782 caller,
8783 schema_cache,
8784 relationships,
8785 target_type,
8786 child_alias,
8787 child.selection_set(),
8788 max_rows,
8789 alias_counter,
8790 param_idx,
8791 values,
8792 names,
8793 )?;
8794 let mut columns: Vec<String> = Vec::new();
8795 for column in child.selection_set() {
8796 let name = column.name();
8797 if name == "__typename" || embeds.iter().any(|(field, _)| field == name) {
8798 continue;
8799 }
8800 columns.push(format!(
8801 "{}, {}",
8802 postrust_sql::quote_literal(name),
8803 column_expression(child_table, child_alias, name, names)
8804 ));
8805 }
8806 for (field, expression) in &embeds {
8807 columns.push(format!(
8808 "{}, {}",
8809 postrust_sql::quote_literal(field),
8810 expression
8811 ));
8812 }
8813 let row = if columns.is_empty() {
8814 format!("row_to_json({})", postrust_sql::escape_ident(child_alias))
8815 } else {
8816 format!("json_build_object({})", columns.join(", "))
8817 };
8818 parts.push(format!(
8819 "COALESCE(json_agg({}), '[]'::json) AS {}",
8820 row,
8821 postrust_sql::escape_ident("nodes")
8822 ));
8823 }
8824 _ => {}
8825 }
8826 }
8827
8828 if parts.is_empty() {
8829 parts.push("count(*) AS pgrst_empty".to_string());
8832 }
8833 Ok(parts.join(", "))
8834}
8835
8836fn column_expression(
8841 table: Option<&postrust_core::schema_cache::Table>,
8842 alias: &str,
8843 name: &str,
8844 names: &crate::names::NameOverrides,
8845) -> String {
8846 let column = table
8847 .map(|t| table_column_for(names, t, name))
8848 .unwrap_or(name);
8849 let plain = format!(
8850 "{}.{}",
8851 postrust_sql::escape_ident(alias),
8852 postrust_sql::escape_ident(column)
8853 );
8854 let computed = table
8855 .filter(|t| t.get_column(column).is_none())
8856 .and_then(|t| {
8857 let function = names
8858 .computed_source(&t.schema, &t.name, name)
8859 .unwrap_or(name);
8860 t.get_computed_column(function)
8861 });
8862 match computed {
8863 Some(definition) => computed_call(
8864 definition,
8865 &format!("{}.*", postrust_sql::escape_ident(alias)),
8866 &postrust_sql::escape_ident(alias),
8867 ),
8868 None => plain,
8869 }
8870}
8871
8872fn order_terms(
8880 order: &serde_json::Value,
8881 schema_cache: &SchemaCache,
8882 schema_name: &str,
8883 table_name: &str,
8884 alias: &str,
8885 names: &crate::names::NameOverrides,
8886) -> Result<Option<String>, async_graphql::Error> {
8887 let entries: Vec<&serde_json::Value> = match order {
8888 serde_json::Value::Array(items) => items.iter().collect(),
8889 serde_json::Value::Object(_) => vec![order],
8890 _ => return Ok(None),
8891 };
8892
8893 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8894 let table = schema_cache
8895 .get_table(&qi)
8896 .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8897
8898 let mut terms = Vec::new();
8899 for entry in entries {
8900 let serde_json::Value::Object(map) = entry else {
8901 continue;
8902 };
8903 for (field, direction) in map {
8904 if direction.is_null() {
8906 continue;
8907 }
8908 let column = table_column_for(names, table, field);
8909 if table.get_column(column).is_none() {
8910 return Err(async_graphql::Error::new(format!(
8911 "cannot order by unknown column \"{}\" on \"{}\"",
8912 field, table_name
8913 )));
8914 }
8915 let name = direction.as_str().unwrap_or_default();
8916 let sql = crate::input::order_by::direction_sql(name).ok_or_else(|| {
8917 async_graphql::Error::new(format!("\"{}\" is not a sort direction", name))
8918 })?;
8919 terms.push(format!(
8920 "{}.{} {}",
8921 postrust_sql::escape_ident(alias),
8922 postrust_sql::escape_ident(column),
8923 sql
8924 ));
8925 }
8926 }
8927
8928 Ok(if terms.is_empty() {
8929 None
8930 } else {
8931 Some(terms.join(", "))
8932 })
8933}
8934
8935fn always_present(rel: &RelationshipField, table: &postrust_core::schema_cache::Table) -> bool {
8947 use postrust_core::schema_cache::{Cardinality, Relationship};
8948 let Relationship::ForeignKey { cardinality, .. } = &rel.relationship else {
8949 return false;
8950 };
8951 match cardinality {
8952 Cardinality::M2O { .. } => {}
8953 Cardinality::O2O {
8954 is_parent: false, ..
8955 } => {}
8956 _ => return false,
8957 }
8958 let columns = cardinality.columns();
8959 !columns.is_empty()
8960 && columns.iter().all(|(local, _)| {
8961 table
8962 .get_column(local)
8963 .is_some_and(|column| !column.nullable)
8964 })
8965}
8966
8967fn child_holds_the_key(relationship: &postrust_core::schema_cache::Relationship) -> bool {
8975 use postrust_core::schema_cache::{Cardinality, Relationship};
8976 match relationship {
8977 Relationship::ForeignKey { cardinality, .. } => match cardinality {
8978 Cardinality::M2O { .. } => false,
8979 Cardinality::O2O { is_parent, .. } => *is_parent,
8980 _ => true,
8981 },
8982 Relationship::Computed { .. } => true,
8983 }
8984}
8985
8986fn computed_session_argument(
8988 cache: &SchemaCache,
8989 function: &postrust_core::api_request::QualifiedIdentifier,
8990 row_argument: &str,
8991) -> Option<String> {
8992 let _ = row_argument;
8993 cache
8994 .routines
8995 .get(function)
8996 .into_iter()
8997 .flatten()
8998 .find(|routine| routine.name == function.name)?
8999 .params
9000 .iter()
9001 .find(|param| {
9002 param.name == "hasura_session" && matches!(param.param_type.as_str(), "json" | "jsonb")
9003 })
9004 .map(|param| param.name.clone())
9005}
9006
9007fn computed_args_type_name(type_name: &str, field: &str) -> String {
9009 format!("{}_{}_args", type_name, field)
9010}
9011
9012fn computed_arguments(
9019 relationship: &RelationshipField,
9020 plan: &postrust_core::embed::EmbedPlan,
9021 parent_row: &str,
9022 given: Option<&serde_json::Value>,
9023 param_idx: &mut usize,
9024 values: &mut Vec<serde_json::Value>,
9025 schema_cache: &SchemaCache,
9026) -> Result<Option<String>, async_graphql::Error> {
9027 let (Some(function), Some(row_argument)) = (&plan.function, &plan.row_argument) else {
9028 return Ok(None);
9029 };
9030 let session = schema_cache
9031 .routines
9032 .get(function)
9033 .into_iter()
9034 .flatten()
9035 .find(|routine| routine.name == function.name)
9036 .and_then(|routine| {
9037 routine
9038 .params
9039 .iter()
9040 .find(|param| {
9041 param.name == "hasura_session"
9042 && matches!(param.param_type.as_str(), "json" | "jsonb")
9043 })
9044 .map(|param| param.name.clone())
9045 });
9046 if relationship.arguments.is_empty() && session.is_none() {
9047 return Ok(None);
9048 }
9049
9050 let mut passed = vec![format!(
9051 "{} => {}",
9052 postrust_sql::escape_ident(row_argument),
9053 parent_row
9054 )];
9055 if let Some(session) = session {
9056 passed.push(format!(
9057 "{} => {}",
9058 postrust_sql::escape_ident(&session),
9059 SESSION_ARGUMENT
9060 ));
9061 }
9062 for (name, pg_type, required) in &relationship.arguments {
9063 match given.and_then(|given| given.get(name)) {
9064 None if *required => {
9065 return Err(async_graphql::Error::new(format!(
9066 "{} needs the argument \"{}\"",
9067 relationship.name, name
9068 )))
9069 }
9070 None => continue,
9072 Some(value) => {
9073 passed.push(format!(
9074 "{} => ${}::{}",
9075 postrust_sql::escape_ident(name),
9076 param_idx,
9077 pg_type
9078 ));
9079 *param_idx += 1;
9080 values.push(value.clone());
9081 }
9082 }
9083 }
9084 Ok(Some(passed.join(", ")))
9085}
9086
9087fn embed_arguments(field: async_graphql::SelectionField<'_>) -> HashMap<String, serde_json::Value> {
9089 field
9090 .arguments()
9091 .map(|args| {
9092 args.into_iter()
9093 .map(|(name, value)| {
9094 (
9095 name.to_string(),
9096 plain_numbers(value.into_json().unwrap_or(serde_json::Value::Null)),
9097 )
9098 })
9099 .collect()
9100 })
9101 .unwrap_or_default()
9102}
9103
9104type Narrowing = (String, Option<String>, Option<String>, Option<i64>, i64);
9108
9109#[allow(clippy::too_many_arguments)] fn embed_narrowing(
9116 arguments: &HashMap<String, serde_json::Value>,
9117 plan: &postrust_core::embed::EmbedPlan,
9118 schema_cache: &SchemaCache,
9119 relationships: &HashMap<String, Vec<RelationshipField>>,
9120 target_type: &str,
9121 child_alias: &str,
9122 max_rows: Option<i64>,
9123 param_idx: &mut usize,
9124 values: &mut Vec<serde_json::Value>,
9125 names: &crate::names::NameOverrides,
9126 caller: &crate::role::Caller<'_>,
9127) -> Result<Narrowing, async_graphql::Error> {
9128 let permission =
9132 permission_predicate(caller, names, &plan.foreign_schema, &plan.foreign_table)?;
9133 let requested = arguments.get("where").filter(|v| !v.is_null()).cloned();
9134 let child_where = match and_predicates(requested, permission) {
9135 Some(expression) => {
9136 let child_scope = WhereScope::for_alias(
9137 &plan.foreign_schema,
9138 &plan.foreign_table,
9139 child_alias,
9140 target_type,
9141 schema_cache,
9142 relationships,
9143 names,
9144 )
9145 .for_caller(*caller);
9146 let mut nested_alias = 0usize;
9147 build_condition(
9148 &expression,
9149 &child_scope,
9150 param_idx,
9151 values,
9152 &mut nested_alias,
9153 )?
9154 }
9155 None => None,
9156 };
9157
9158 let child_order = match arguments.get("order_by") {
9159 Some(order) if !order.is_null() => order_terms(
9160 order,
9161 schema_cache,
9162 &plan.foreign_schema,
9163 &plan.foreign_table,
9164 child_alias,
9165 names,
9166 )?,
9167 _ => None,
9168 };
9169
9170 let ceiling = match (
9175 max_rows,
9176 crate::role::read_limit(caller, names, &plan.foreign_schema, &plan.foreign_table),
9177 ) {
9178 (Some(configured), Some(granted)) => Some(configured.min(granted)),
9179 (only, None) | (None, only) => only,
9180 };
9181 let child_limit = match arguments.get("limit").and_then(|v| v.as_i64()) {
9182 Some(requested) => match ceiling {
9183 Some(ceiling) => Some(requested.min(ceiling)),
9184 None => Some(requested),
9185 },
9186 None => ceiling,
9187 };
9188 let child_offset = arguments
9189 .get("offset")
9190 .and_then(|v| v.as_i64())
9191 .unwrap_or(0);
9192
9193 let requested = match arguments.get("distinct_on") {
9197 Some(serde_json::Value::Array(items)) => items
9198 .iter()
9199 .filter_map(|item| item.as_str())
9200 .collect::<Vec<_>>(),
9201 Some(serde_json::Value::String(one)) => vec![one.as_str()],
9202 _ => Vec::new(),
9203 };
9204 let mut distinct_on = Vec::with_capacity(requested.len());
9205 if !requested.is_empty() {
9206 let qi = postrust_core::api_request::QualifiedIdentifier::new(
9207 &plan.foreign_schema,
9208 &plan.foreign_table,
9209 );
9210 let table = schema_cache.get_table(&qi).ok_or_else(|| {
9211 async_graphql::Error::new(format!("unknown table \"{}\"", plan.foreign_table))
9212 })?;
9213 for field in requested {
9214 let column = table_column_for(names, table, field).to_string();
9215 if table.get_column(&column).is_none() {
9216 return Err(async_graphql::Error::new(format!(
9217 "cannot take distinct on unknown column \"{}\" of \"{}\"",
9218 field, plan.foreign_table
9219 )));
9220 }
9221 distinct_on.push(format!(
9222 "{}.{}",
9223 postrust_sql::escape_ident(child_alias),
9224 postrust_sql::escape_ident(&column)
9225 ));
9226 }
9227 }
9228 let (distinct, child_order) = distinct_on_clause(&distinct_on, child_order.as_deref())?;
9229
9230 Ok((
9231 distinct,
9232 child_where,
9233 child_order,
9234 child_limit,
9235 child_offset,
9236 ))
9237}
9238
9239#[allow(clippy::too_many_arguments)] fn build_embed_expressions<'a>(
9241 caller: &crate::role::Caller<'_>,
9242 schema_cache: &SchemaCache,
9243 relationships: &HashMap<String, Vec<RelationshipField>>,
9244 type_name: &str,
9245 parent_alias: &str,
9246 fields: impl IntoIterator<Item = SelectionField<'a>>,
9247 max_rows: Option<i64>,
9248 alias_counter: &mut usize,
9249 param_idx: &mut usize,
9250 values: &mut Vec<serde_json::Value>,
9251 names: &crate::names::NameOverrides,
9252) -> Result<Vec<(String, String)>, async_graphql::Error> {
9253 let Some(available) = relationships.get(type_name) else {
9254 return Ok(Vec::new());
9255 };
9256
9257 let mut expressions = Vec::new();
9258
9259 for field in fields {
9260 let aggregate_of = field
9264 .name()
9265 .strip_suffix("_aggregate")
9266 .and_then(|name| available.iter().find(|r| r.name == name && r.is_list));
9267
9268 if let Some(rel) = aggregate_of {
9269 let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, schema_cache)
9270 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9271 *alias_counter += 1;
9272 let child_alias = format!("a{}", alias_counter);
9273
9274 let arguments = embed_arguments(field);
9278 let (child_distinct, child_where, child_order, child_limit, child_offset) =
9279 embed_narrowing(
9280 &arguments,
9281 &plan,
9282 schema_cache,
9283 relationships,
9284 &rel.target_type,
9285 &child_alias,
9286 max_rows,
9287 param_idx,
9288 values,
9289 names,
9290 caller,
9291 )?;
9292
9293 let child_table =
9294 schema_cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
9295 &plan.foreign_schema,
9296 &plan.foreign_table,
9297 ));
9298 let select = nested_aggregate_select(
9299 caller,
9300 field,
9301 &child_alias,
9302 schema_cache,
9303 relationships,
9304 &rel.target_type,
9305 child_table,
9306 max_rows,
9307 alias_counter,
9308 param_idx,
9309 values,
9310 names,
9311 )?;
9312
9313 let call = computed_arguments(
9314 rel,
9315 &plan,
9316 &postrust_sql::escape_ident(parent_alias),
9317 arguments.get("args"),
9318 param_idx,
9319 values,
9320 schema_cache,
9321 )?;
9322 let expression = plan
9323 .aggregate_expression(
9324 parent_alias,
9325 &postrust_sql::escape_ident(parent_alias),
9326 &child_alias,
9327 &select,
9328 child_limit,
9329 child_offset,
9330 child_where.as_deref(),
9331 child_order.as_deref(),
9332 call.as_deref(),
9333 &child_distinct,
9334 postrust_core::EmbedRendering::Verbatim,
9338 )
9339 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9340 expressions.push((field.name().to_string(), expression));
9341 continue;
9342 }
9343
9344 let Some(rel) = available.iter().find(|r| r.name == field.name()) else {
9345 continue;
9346 };
9347
9348 let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, schema_cache)
9349 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9350
9351 *alias_counter += 1;
9352 let child_alias = format!("e{}", alias_counter);
9353
9354 let nested = build_embed_expressions(
9355 caller,
9356 schema_cache,
9357 relationships,
9358 &rel.target_type,
9359 &child_alias,
9360 field.selection_set(),
9361 max_rows,
9362 alias_counter,
9363 param_idx,
9364 values,
9365 names,
9366 )?;
9367
9368 let arguments = embed_arguments(field);
9370 let (child_distinct, child_where, child_order, child_limit, child_offset) =
9371 embed_narrowing(
9372 &arguments,
9373 &plan,
9374 schema_cache,
9375 relationships,
9376 &rel.target_type,
9377 &child_alias,
9378 max_rows,
9379 param_idx,
9380 values,
9381 names,
9382 caller,
9383 )?;
9384
9385 let child_relationships = relationships.get(&rel.target_type);
9388 let child_qi = postrust_core::api_request::QualifiedIdentifier::new(
9389 &plan.foreign_schema,
9390 &plan.foreign_table,
9391 );
9392 let child_table = schema_cache.get_table(&child_qi);
9393 let mut parts: Vec<String> = Vec::new();
9394 for sub in field.selection_set() {
9395 let name = sub.name();
9396 let is_relationship = child_relationships
9397 .map(|rels| {
9398 rels.iter().any(|r| {
9399 r.name == name || (r.is_list && format!("{}_aggregate", r.name) == name)
9400 })
9401 })
9402 .unwrap_or(false);
9403 if is_relationship || name == "__typename" {
9407 continue;
9408 }
9409 let column = child_table
9412 .map(|t| table_column_for(names, t, name))
9413 .unwrap_or(name);
9414 let computed = child_table
9415 .filter(|t| t.get_column(column).is_none())
9416 .and_then(|t| {
9417 let function = names
9418 .computed_source(&t.schema, &t.name, name)
9419 .unwrap_or(name);
9420 t.get_computed_column(function)
9421 });
9422 match computed {
9423 Some(definition) => parts.push(format!(
9424 "{} AS {}",
9425 computed_call(
9426 definition,
9427 &format!("{}.*", postrust_sql::escape_ident(&child_alias)),
9428 &postrust_sql::escape_ident(&child_alias),
9429 ),
9430 postrust_sql::escape_ident(name)
9431 )),
9432 None if column != name => parts.push(format!(
9435 "{} AS {}",
9436 postrust_sql::escape_ident(column),
9437 postrust_sql::escape_ident(name)
9438 )),
9439 None => parts.push(postrust_sql::escape_ident(name)),
9440 }
9441 }
9442 if parts.is_empty() && nested.is_empty() {
9443 parts.push(
9444 child_table
9445 .and_then(|table| rename_projection(table, &child_alias, names))
9446 .unwrap_or_else(|| format!("{}.*", postrust_sql::escape_ident(&child_alias))),
9447 );
9448 }
9449 for (field_name, expression) in nested {
9450 parts.push(format!(
9451 "{} AS {}",
9452 expression,
9453 postrust_sql::escape_ident(&field_name)
9454 ));
9455 }
9456
9457 let computed_call_arguments = computed_arguments(
9458 rel,
9459 &plan,
9460 &postrust_sql::escape_ident(parent_alias),
9461 arguments.get("args"),
9462 param_idx,
9463 values,
9464 schema_cache,
9465 )?;
9466 let expression = plan
9467 .embed_expression(
9468 parent_alias,
9469 &postrust_sql::escape_ident(parent_alias),
9473 &child_alias,
9474 &format!("{}{}", child_distinct, parts.join(", ")),
9475 child_limit,
9476 child_offset,
9477 child_where.as_deref(),
9478 child_order.as_deref(),
9479 computed_call_arguments.as_deref(),
9480 postrust_core::EmbedRendering::Verbatim,
9481 )
9482 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9483
9484 expressions.push((rel.name.clone(), expression));
9485 }
9486
9487 Ok(expressions)
9488}
9489
9490struct EmbedContext<'c> {
9496 schema_cache: &'c SchemaCache,
9497 relationships: &'c HashMap<String, Vec<RelationshipField>>,
9498 max_rows: Option<i64>,
9499}
9500
9501fn embed_relationships<'f>(
9507 conn: &'f mut sqlx::PgConnection,
9508 ctx: &'f EmbedContext<'f>,
9509 type_name: &'f str,
9510 selection: async_graphql::SelectionField<'f>,
9511 rows: &'f mut [serde_json::Value],
9512) -> futures::future::BoxFuture<'f, Result<(), async_graphql::Error>> {
9513 Box::pin(async move {
9514 if rows.is_empty() {
9515 return Ok(());
9516 }
9517
9518 let Some(available) = ctx.relationships.get(type_name) else {
9519 return Ok(());
9520 };
9521
9522 for requested in selection.selection_set() {
9523 let Some(rel) = available.iter().find(|r| r.name == requested.name()) else {
9524 continue;
9525 };
9526
9527 let plan =
9528 postrust_core::embed::EmbedPlan::resolve(&rel.relationship, ctx.schema_cache)
9529 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9530
9531 let keys = postrust_core::embed::parent_keys(rows, &plan.local_column);
9532
9533 let mut child_columns: Vec<String> = Vec::new();
9543 let mut project_everything = false;
9544 let child_relationships = ctx.relationships.get(&rel.target_type);
9545 for field in requested.selection_set() {
9546 let name = field.name();
9547 match child_relationships.and_then(|rels| rels.iter().find(|r| r.name == name)) {
9548 Some(nested_rel) => {
9549 match postrust_core::embed::EmbedPlan::resolve(
9550 &nested_rel.relationship,
9551 ctx.schema_cache,
9552 ) {
9553 Ok(nested_plan) => child_columns.push(nested_plan.local_column),
9554 Err(_) => project_everything = true,
9555 }
9556 }
9557 None if name == "__typename" => {}
9559 None => child_columns.push(name.to_string()),
9560 }
9561 }
9562 if project_everything || child_columns.is_empty() {
9563 child_columns.clear();
9564 }
9565
9566 let mut grouped = if keys.is_empty() {
9567 std::collections::HashMap::new()
9568 } else {
9569 let sql = plan
9570 .children_grouped_sql(ctx.max_rows, &child_columns)
9571 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9572
9573 let fetched = sqlx::query(AssertSqlSafe(sql))
9574 .bind(&keys)
9575 .fetch_all(&mut *conn)
9576 .await
9577 .map_err(database_error)?;
9578
9579 use sqlx::Row;
9582 let pairs: Vec<(serde_json::Value, serde_json::Value)> = fetched
9583 .into_iter()
9584 .filter_map(|row| {
9585 Some((
9586 row.try_get::<serde_json::Value, _>(0).ok()?,
9587 row.try_get::<serde_json::Value, _>(1).ok()?,
9588 ))
9589 })
9590 .collect();
9591
9592 postrust_core::embed::group_from_aggregated(pairs)
9593 };
9594
9595 let has_deeper_embed = ctx
9600 .relationships
9601 .get(&rel.target_type)
9602 .map(|rels| {
9603 requested
9604 .selection_set()
9605 .any(|field| rels.iter().any(|r| r.name == field.name()))
9606 })
9607 .unwrap_or(false);
9608
9609 if has_deeper_embed {
9610 let mut order: Vec<(String, usize)> = Vec::with_capacity(grouped.len());
9611 let mut flat: Vec<serde_json::Value> = Vec::new();
9612 for (key, children) in grouped.drain() {
9613 order.push((key, children.len()));
9614 flat.extend(children);
9615 }
9616
9617 embed_relationships(&mut *conn, ctx, &rel.target_type, requested, &mut flat)
9618 .await?;
9619
9620 let mut rest = flat.into_iter();
9621 for (key, count) in order {
9622 grouped.insert(key, rest.by_ref().take(count).collect());
9623 }
9624 }
9625
9626 for row in rows.iter_mut() {
9627 postrust_core::embed::attach_to_parent(row, &rel.name, &plan, &grouped);
9628 }
9629 }
9630
9631 Ok(())
9632 })
9633}
9634
9635fn pk_where_from_args(
9640 ctx: &ResolverContext<'_>,
9641 schema_name: &str,
9642 table_name: &str,
9643 pk_columns: &[(String, String)],
9644 names: &crate::names::NameOverrides,
9645) -> Result<serde_json::Value, async_graphql::Error> {
9646 if pk_columns.is_empty() {
9647 return Err(async_graphql::Error::new(format!(
9648 "\"{}\" has no primary key, so it cannot be mutated by key",
9649 table_name
9650 )));
9651 }
9652
9653 let from_object = ctx
9657 .args
9658 .try_get("pk_columns")
9659 .ok()
9660 .map(|v| accessor_to_json(&v));
9661
9662 let mut conditions = serde_json::Map::new();
9663 for (col_name, _) in pk_columns {
9664 let field = names
9668 .column(schema_name, table_name, col_name)
9669 .unwrap_or(col_name);
9670 let value = match &from_object {
9671 Some(serde_json::Value::Object(map)) => map.get(field).cloned().ok_or_else(|| {
9672 async_graphql::Error::new(format!(
9673 "pk_columns is missing the key column \"{}\"",
9674 field
9675 ))
9676 })?,
9677 _ => {
9678 let arg = ctx.args.try_get(field).map_err(|_| {
9679 async_graphql::Error::new(format!(
9680 "missing required primary key argument \"{}\"",
9681 field
9682 ))
9683 })?;
9684 accessor_to_json(&arg)
9685 }
9686 };
9687 conditions.insert(field.to_string(), serde_json::json!({ "_eq": value }));
9688 }
9689
9690 Ok(serde_json::Value::Object(conditions))
9691}
9692
9693fn pk_argument_type(pg_type: &str) -> String {
9700 let rendered = crate::types::pg_type_to_graphql(pg_type).to_string();
9701 if rendered.starts_with('[') {
9702 "String".to_string()
9703 } else {
9704 rendered
9705 }
9706}
9707
9708fn exposed_pk_argument_type(
9713 names: &crate::names::NameOverrides,
9714 schema: &str,
9715 table: &str,
9716 column: &str,
9717 pg_type: &str,
9718) -> String {
9719 names
9720 .column_type(schema, table, column)
9721 .map(|given| given.to_string())
9722 .unwrap_or_else(|| pk_argument_type(pg_type))
9723}
9724
9725fn graphql_type_ref(type_str: &str) -> TypeRef {
9727 let is_list = type_str.starts_with('[');
9729 let is_nn = type_str.ends_with('!');
9730
9731 let inner = if is_list {
9733 let stripped = type_str
9734 .trim_end_matches('!') .trim_start_matches('[') .trim_end_matches(']'); stripped
9738 } else {
9739 type_str.trim_end_matches('!')
9740 };
9741
9742 let inner_nn = inner.ends_with('!');
9743 let base_type = inner.trim_end_matches('!');
9744
9745 if is_list {
9746 if is_nn {
9747 if inner_nn {
9748 TypeRef::named_nn_list_nn(base_type)
9749 } else {
9750 TypeRef::named_list_nn(base_type)
9751 }
9752 } else if inner_nn {
9753 TypeRef::named_nn_list(base_type)
9754 } else {
9755 TypeRef::named_list(base_type)
9756 }
9757 } else if is_nn {
9758 TypeRef::named_nn(base_type)
9759 } else {
9760 TypeRef::named(base_type)
9761 }
9762}
9763
9764const NUMBER_AS_TEXT: &str = "$serde_json::private::Number";
9774
9775fn number_kept_as_text(
9778 map: &serde_json::Map<String, serde_json::Value>,
9779) -> Option<serde_json::Value> {
9780 if map.len() != 1 {
9781 return None;
9782 }
9783 let text = map.get(NUMBER_AS_TEXT)?.as_str()?;
9784 serde_json::from_str::<serde_json::Value>(text)
9785 .ok()
9786 .filter(|value| value.is_number())
9787}
9788
9789fn plain_numbers(value: serde_json::Value) -> serde_json::Value {
9791 match value {
9792 serde_json::Value::Object(map) => match number_kept_as_text(&map) {
9793 Some(number) => number,
9794 None => serde_json::Value::Object(
9795 map.into_iter()
9796 .map(|(k, v)| (k, plain_numbers(v)))
9797 .collect(),
9798 ),
9799 },
9800 serde_json::Value::Array(items) => {
9801 serde_json::Value::Array(items.into_iter().map(plain_numbers).collect())
9802 }
9803 other => other,
9804 }
9805}
9806
9807fn accessor_to_json(accessor: &ValueAccessor<'_>) -> serde_json::Value {
9809 if accessor.is_null() {
9811 serde_json::Value::Null
9812 } else if let Ok(b) = accessor.boolean() {
9813 serde_json::Value::Bool(b)
9814 } else if let Ok(i) = accessor.i64() {
9815 serde_json::Value::Number(i.into())
9816 } else if let Ok(f) = accessor.f64() {
9817 serde_json::Number::from_f64(f)
9818 .map(serde_json::Value::Number)
9819 .unwrap_or(serde_json::Value::Null)
9820 } else if let Ok(s) = accessor.string() {
9821 serde_json::Value::String(s.to_string())
9822 } else if let Ok(name) = accessor.enum_name() {
9823 serde_json::Value::String(name.to_string())
9826 } else if let Ok(list) = accessor.list() {
9827 serde_json::Value::Array(list.iter().map(|v| accessor_to_json(&v)).collect())
9828 } else if let Ok(obj) = accessor.object() {
9829 let map: serde_json::Map<String, serde_json::Value> = obj
9830 .iter()
9831 .map(|(k, v)| (k.to_string(), accessor_to_json(&v)))
9832 .collect();
9833 match number_kept_as_text(&map) {
9834 Some(number) => number,
9835 None => serde_json::Value::Object(map),
9836 }
9837 } else {
9838 serde_json::Value::Null
9839 }
9840}
9841
9842fn value_to_json(value: &Value) -> serde_json::Value {
9844 match value {
9845 Value::Null => serde_json::Value::Null,
9846 Value::Boolean(b) => serde_json::Value::Bool(*b),
9847 Value::Number(n) => {
9848 if let Some(i) = n.as_i64() {
9849 serde_json::Value::Number(i.into())
9850 } else if let Some(f) = n.as_f64() {
9851 serde_json::Value::Number(serde_json::Number::from_f64(f).unwrap())
9852 } else {
9853 serde_json::Value::Null
9854 }
9855 }
9856 Value::String(s) => serde_json::Value::String(s.clone()),
9857 Value::List(arr) => serde_json::Value::Array(arr.iter().map(value_to_json).collect()),
9858 Value::Object(obj) => {
9859 let map: serde_json::Map<String, serde_json::Value> = obj
9860 .iter()
9861 .map(|(k, v)| (k.to_string(), value_to_json(v)))
9862 .collect();
9863 serde_json::Value::Object(map)
9864 }
9865 Value::Binary(b) => serde_json::Value::String(base64::Engine::encode(
9866 &base64::engine::general_purpose::STANDARD,
9867 b,
9868 )),
9869 Value::Enum(e) => serde_json::Value::String(e.to_string()),
9870 }
9871}
9872
9873fn json_to_value(json: serde_json::Value) -> Value {
9875 match json {
9876 serde_json::Value::Null => Value::Null,
9877 serde_json::Value::Bool(b) => Value::Boolean(b),
9878 serde_json::Value::Number(n) => {
9879 if let Some(i) = n.as_i64() {
9880 Value::Number(i.into())
9881 } else if let Some(f) = n.as_f64() {
9882 Value::Number(async_graphql::Number::from_f64(f).unwrap())
9883 } else {
9884 Value::Null
9885 }
9886 }
9887 serde_json::Value::String(s) => Value::String(s),
9888 serde_json::Value::Array(arr) => Value::List(arr.into_iter().map(json_to_value).collect()),
9889 serde_json::Value::Object(obj) => {
9890 let map: indexmap::IndexMap<async_graphql::Name, Value> = obj
9891 .into_iter()
9892 .map(|(k, v)| (async_graphql::Name::new(k), json_to_value(v)))
9893 .collect();
9894 Value::Object(map)
9895 }
9896 }
9897}
9898
9899#[cfg(test)]
9909mod tests {
9910 use super::*;
9911 use indexmap::IndexMap;
9912 use postrust_core::schema_cache::{Cardinality, Column, Relationship, Table};
9913 use postrust_core::QualifiedIdentifier;
9914 use std::collections::{HashMap, HashSet};
9915
9916 fn entity_key_column(pg_type: &str, explicit_id: bool) -> EntityKeyColumn {
9917 EntityKeyColumn {
9918 field_name: "id".to_string(),
9919 column_name: "id".to_string(),
9920 pg_type: pg_type.to_string(),
9921 explicit_id,
9922 }
9923 }
9924
9925 #[test]
9926 fn federation_integer_keys_reject_strings() {
9927 let column = entity_key_column("int4", false);
9928
9929 assert_eq!(
9930 normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap(),
9931 serde_json::json!(2)
9932 );
9933 let error = normalize_entity_key_value("users", &column, &serde_json::json!("2"))
9934 .expect_err("a GraphQL Int cannot be a string");
9935 assert_eq!(
9936 error.message,
9937 "entity representation for \"users\" has invalid key field \"id\": expected a value compatible with PostgreSQL type \"int4\", found a string"
9938 );
9939 }
9940
9941 #[test]
9942 fn federation_bigint_keys_accept_exact_decimal_strings() {
9943 let column = entity_key_column("int8", false);
9944
9945 assert_eq!(
9946 normalize_entity_key_value("users", &column, &serde_json::json!(7)).unwrap(),
9947 serde_json::json!(7)
9948 );
9949 assert_eq!(
9950 normalize_entity_key_value("users", &column, &serde_json::json!("9007199254740993"))
9951 .unwrap(),
9952 serde_json::json!(9_007_199_254_740_993_i64)
9953 );
9954 assert!(normalize_entity_key_value(
9955 "users",
9956 &column,
9957 &serde_json::json!("9223372036854775808")
9958 )
9959 .is_err());
9960 assert!(normalize_entity_key_value("users", &column, &serde_json::json!("7.5")).is_err());
9961 }
9962
9963 #[test]
9964 fn federation_numeric_keys_accept_exact_decimal_strings() {
9965 let column = entity_key_column("numeric", false);
9966
9967 assert_eq!(
9968 normalize_entity_key_value("users", &column, &serde_json::json!(7.5)).unwrap(),
9969 serde_json::json!("7.5")
9970 );
9971 assert_eq!(
9972 normalize_entity_key_value(
9973 "users",
9974 &column,
9975 &serde_json::json!("9007199254740993.123456789")
9976 )
9977 .unwrap(),
9978 serde_json::json!("9007199254740993.123456789")
9979 );
9980 assert!(
9981 normalize_entity_key_value("users", &column, &serde_json::json!("not-a-number"))
9982 .is_err()
9983 );
9984 }
9985
9986 #[test]
9987 fn federation_integer_backed_ids_have_one_normal_form() {
9988 let column = entity_key_column("int4", true);
9989
9990 let number = normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap();
9991 let string = normalize_entity_key_value("users", &column, &serde_json::json!("2")).unwrap();
9992 assert_eq!(number, serde_json::json!(2));
9993 assert_eq!(string, number);
9994 assert!(normalize_entity_key_value("users", &column, &serde_json::json!("two")).is_err());
9995 }
9996
9997 #[test]
9998 fn federation_text_backed_ids_normalize_integer_input_to_text() {
9999 let column = entity_key_column("text", true);
10000
10001 let number = normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap();
10002 let string = normalize_entity_key_value("users", &column, &serde_json::json!("2")).unwrap();
10003 assert_eq!(number, serde_json::json!("2"));
10004 assert_eq!(string, number);
10005 }
10006
10007 #[test]
10008 fn federation_uuid_backed_ids_are_validated_and_canonicalized() {
10009 let column = entity_key_column("uuid", true);
10010
10011 assert_eq!(
10012 normalize_entity_key_value(
10013 "users",
10014 &column,
10015 &serde_json::json!("550E8400-E29B-41D4-A716-446655440000")
10016 )
10017 .unwrap(),
10018 serde_json::json!("550e8400-e29b-41d4-a716-446655440000")
10019 );
10020 assert!(
10021 normalize_entity_key_value("users", &column, &serde_json::json!("not-a-uuid")).is_err()
10022 );
10023 }
10024
10025 fn create_test_table(name: &str) -> Table {
10026 let mut columns = IndexMap::new();
10027 columns.insert(
10028 "id".into(),
10029 Column {
10030 name: "id".into(),
10031 description: None,
10032 nullable: false,
10033 data_type: "integer".into(),
10034 nominal_type: "int4".into(),
10035 max_len: None,
10036 default: Some("nextval('id_seq')".into()),
10037 enum_values: vec![],
10038 is_pk: true,
10039 position: 1,
10040 always_generated: false,
10041 domain_type: None,
10042 },
10043 );
10044 columns.insert(
10045 "name".into(),
10046 Column {
10047 name: "name".into(),
10048 description: None,
10049 nullable: false,
10050 data_type: "text".into(),
10051 nominal_type: "text".into(),
10052 max_len: None,
10053 default: None,
10054 enum_values: vec![],
10055 is_pk: false,
10056 position: 2,
10057 always_generated: false,
10058 domain_type: None,
10059 },
10060 );
10061
10062 Table {
10063 schema: "public".into(),
10064 name: name.into(),
10065 description: None,
10066 is_view: false,
10067 insertable: true,
10068 updatable: true,
10069 deletable: true,
10070 pk_cols: vec!["id".into()],
10071 unique_constraints: Vec::new(),
10072 columns,
10073 computed_columns: Default::default(),
10074 is_partitioned: false,
10075 }
10076 }
10077
10078 fn create_test_schema_cache() -> SchemaCache {
10079 let mut tables = HashMap::new();
10080 let users = create_test_table("users");
10081 tables.insert(users.qualified_identifier(), users);
10082
10083 SchemaCache {
10084 tables,
10085 relationships: HashMap::new(),
10086 routines: HashMap::new(),
10087 timezones: HashSet::new(),
10088 media_handlers: HashMap::new(),
10089 pg_version: 150000,
10090 representations: Default::default(),
10091 }
10092 }
10093
10094 fn add_test_table(cache: &mut SchemaCache, name: &str) {
10095 let table = create_test_table(name);
10096 cache.tables.insert(table.qualified_identifier(), table);
10097 }
10098
10099 fn add_test_posts_relationship(cache: &mut SchemaCache) {
10100 let users = QualifiedIdentifier::new("public", "users");
10101 cache.relationships.insert(
10102 (users.clone(), "public".into()),
10103 vec![Relationship::ForeignKey {
10104 table: users,
10105 foreign_table: QualifiedIdentifier::new("public", "posts"),
10106 is_self: false,
10107 cardinality: Cardinality::O2M {
10108 constraint: "posts_user_id_fkey".into(),
10109 columns: vec![("id".into(), "user_id".into())],
10110 },
10111 table_is_view: false,
10112 foreign_table_is_view: false,
10113 constraint_name: "posts_user_id_fkey".into(),
10114 }],
10115 );
10116 }
10117
10118 #[test]
10123 fn test_graphql_type_ref_simple() {
10124 let _type_ref = graphql_type_ref("String");
10125 }
10127
10128 #[test]
10129 fn test_graphql_type_ref_non_null() {
10130 let _type_ref = graphql_type_ref("String!");
10131 }
10132
10133 #[test]
10134 fn test_graphql_type_ref_list() {
10135 let _type_ref = graphql_type_ref("[String]");
10136 }
10137
10138 #[test]
10139 fn test_graphql_type_ref_list_non_null() {
10140 let _type_ref = graphql_type_ref("[String!]!");
10141 }
10142
10143 #[test]
10148 fn test_value_to_json_null() {
10149 let value = Value::Null;
10150 let json = value_to_json(&value);
10151 assert_eq!(json, serde_json::Value::Null);
10152 }
10153
10154 #[test]
10155 fn test_value_to_json_boolean() {
10156 let value = Value::Boolean(true);
10157 let json = value_to_json(&value);
10158 assert_eq!(json, serde_json::Value::Bool(true));
10159 }
10160
10161 #[test]
10162 fn test_value_to_json_number() {
10163 let value = Value::Number(42.into());
10164 let json = value_to_json(&value);
10165 assert_eq!(json, serde_json::json!(42));
10166 }
10167
10168 #[test]
10169 fn test_value_to_json_string() {
10170 let value = Value::String("hello".to_string());
10171 let json = value_to_json(&value);
10172 assert_eq!(json, serde_json::Value::String("hello".to_string()));
10173 }
10174
10175 #[test]
10176 fn test_value_to_json_list() {
10177 let value = Value::List(vec![Value::Number(1.into()), Value::Number(2.into())]);
10178 let json = value_to_json(&value);
10179 assert_eq!(json, serde_json::json!([1, 2]));
10180 }
10181
10182 #[test]
10183 fn test_json_to_value_null() {
10184 let json = serde_json::Value::Null;
10185 let value = json_to_value(json);
10186 assert!(matches!(value, Value::Null));
10187 }
10188
10189 #[test]
10190 fn test_json_to_value_boolean() {
10191 let json = serde_json::Value::Bool(false);
10192 let value = json_to_value(json);
10193 assert!(matches!(value, Value::Boolean(false)));
10194 }
10195
10196 #[test]
10197 fn test_json_to_value_number() {
10198 let json = serde_json::json!(123);
10199 let value = json_to_value(json);
10200 assert!(matches!(value, Value::Number(_)));
10201 }
10202
10203 #[test]
10204 fn test_json_to_value_string() {
10205 let json = serde_json::Value::String("test".to_string());
10206 let value = json_to_value(json);
10207 assert!(matches!(value, Value::String(_)));
10208 }
10209
10210 #[test]
10211 fn test_json_to_value_array() {
10212 let json = serde_json::json!([1, 2, 3]);
10213 let value = json_to_value(json);
10214 assert!(matches!(value, Value::List(_)));
10215 }
10216
10217 #[test]
10218 fn test_json_to_value_object() {
10219 let json = serde_json::json!({"key": "value"});
10220 let value = json_to_value(json);
10221 assert!(matches!(value, Value::Object(_)));
10222 }
10223
10224 #[test]
10229 fn test_build_dynamic_schema() {
10230 let cache = create_test_schema_cache();
10231 let config = SchemaConfig::default();
10232 let generated = build_schema(&cache, &config);
10233
10234 let result = build_dynamic_schema(
10235 &generated,
10236 &cache,
10237 None,
10238 None,
10239 Arc::new(Default::default()),
10240 std::time::Duration::from_secs(30),
10241 None,
10242 );
10243 if let Err(ref e) = result {
10244 eprintln!("Schema build error: {:?}", e);
10245 }
10246 assert!(result.is_ok(), "Schema build failed: {:?}", result.err());
10247 }
10248
10249 #[test]
10250 fn a_column_type_override_reaches_fields_and_key_arguments() {
10251 let cache = create_test_schema_cache();
10252 let names = crate::names::NameOverrides::parse(
10253 r#"{"tables": {"public.users": {"column_types": {"id": "ID"}}}}"#,
10254 )
10255 .unwrap();
10256 let config = SchemaConfig {
10257 names: names.clone(),
10258 ..SchemaConfig::default()
10259 };
10260 let generated = build_schema(&cache, &config);
10261 let schema = build_dynamic_schema(
10262 &generated,
10263 &cache,
10264 None,
10265 None,
10266 Arc::new(names),
10267 std::time::Duration::from_secs(30),
10268 None,
10269 )
10270 .expect("schema with an ID override should build");
10271 let sdl = schema.sdl();
10272
10273 let input_body = |name: &str| {
10274 sdl.split_once(&format!("input {name} {{"))
10275 .and_then(|(_, rest)| rest.split_once('}'))
10276 .map(|(body, _)| body.to_string())
10277 .unwrap_or_else(|| panic!("missing input {name}:\n{sdl}"))
10278 };
10279
10280 assert!(sdl.contains("id: ID!"), "object and input fields:\n{sdl}");
10281 assert!(
10282 sdl.contains("users_by_pk(id: ID!): users"),
10283 "query key argument:\n{sdl}"
10284 );
10285 assert!(
10286 sdl.contains("delete_users_by_pk(id: ID!): users"),
10287 "delete key argument:\n{sdl}"
10288 );
10289 assert!(
10290 input_body("users_pk_columns_input").contains("id: ID!"),
10291 "update key input:\n{sdl}"
10292 );
10293 assert!(
10294 input_body("users_bool_exp").contains("id: ID_comparison_exp"),
10295 "comparison input:\n{sdl}"
10296 );
10297 assert!(
10298 input_body("users_insert_input").contains("id: ID"),
10299 "write input:\n{sdl}"
10300 );
10301 }
10302
10303 #[test]
10304 fn a_type_prefix_names_the_complete_dynamic_schema() {
10305 let cache = create_test_schema_cache();
10306 let config = SchemaConfig {
10307 type_prefix: Some("test".into()),
10308 ..SchemaConfig::default()
10309 };
10310 let generated = build_schema(&cache, &config);
10311 let schema = build_dynamic_schema(
10312 &generated,
10313 &cache,
10314 None,
10315 None,
10316 Arc::new(Default::default()),
10317 std::time::Duration::from_secs(30),
10318 None,
10319 )
10320 .expect("a prefixed schema should build");
10321 let sdl = schema.sdl();
10322
10323 assert!(sdl.contains("type test_users "), "object type:\n{sdl}");
10324 assert!(sdl.contains("test_users("), "query root:\n{sdl}");
10325 assert!(sdl.contains("test_users_by_pk("), "by-PK root:\n{sdl}");
10326 assert!(sdl.contains("test_users_bool_exp"), "derived input:\n{sdl}");
10327 assert!(
10328 sdl.contains("test_users_aggregate"),
10329 "aggregate type:\n{sdl}"
10330 );
10331 assert!(sdl.contains("test_insert_users("), "mutation root:\n{sdl}");
10332 }
10333
10334 #[test]
10335 fn federation_is_absent_by_default() {
10336 let cache = create_test_schema_cache();
10337 let generated = build_schema(&cache, &SchemaConfig::default());
10338 let schema = build_dynamic_schema(
10339 &generated,
10340 &cache,
10341 None,
10342 None,
10343 Arc::new(Default::default()),
10344 std::time::Duration::from_secs(30),
10345 None,
10346 )
10347 .expect("a non-federated schema should build");
10348 let sdl = schema.sdl();
10349
10350 assert!(!sdl.contains("_Service"), "service type:\n{sdl}");
10351 assert!(!sdl.contains("_service"), "service field:\n{sdl}");
10352 assert!(!sdl.contains("@key"), "federation key:\n{sdl}");
10353 }
10354
10355 #[test]
10356 fn federation_entity_selections_respect_fragment_type_conditions() {
10357 let document = async_graphql::parser::parse_query(
10358 r#"
10359 query {
10360 _entities(representations: []) {
10361 __typename
10362 ... on authors { id items { title } }
10363 ...ShopFields
10364 ... { common }
10365 ...EntityName
10366 }
10367 }
10368 fragment ShopFields on shops { id items { sku } }
10369 fragment EntityName on _Entity { __typename }
10370 "#,
10371 )
10372 .expect("query parses");
10373 let (_, operation) = document.operations.iter().next().expect("one operation");
10374 let entity = operation
10375 .node
10376 .selection_set
10377 .node
10378 .items
10379 .iter()
10380 .find_map(|selection| match &selection.node {
10381 Selection::Field(field) if field.node.name.node == "_entities" => Some(&field.node),
10382 _ => None,
10383 })
10384 .expect("_entities field");
10385
10386 assert_eq!(
10387 entity_field_applicability(&entity.selection_set.node, &document.fragments, "authors"),
10388 vec![true, true, true, false, false, true, true]
10389 );
10390 assert_eq!(
10391 entity_field_applicability(&entity.selection_set.node, &document.fragments, "shops"),
10392 vec![true, false, false, true, true, true, true]
10393 );
10394 }
10395
10396 #[tokio::test]
10397 async fn federation_entity_lists_allow_null_members() {
10398 let entity =
10399 Object::new("widgets").field(Field::new("id", TypeRef::named_nn(TypeRef::INT), |_| {
10400 FieldFuture::new(async { Ok(Some(Value::from(2))) })
10401 }));
10402 let union = Union::new("_Entity").possible_type("widgets");
10403 let query = Object::new("Query").field(Field::new(
10404 "_entities",
10405 TypeRef::named_list_nn("_Entity"),
10406 |_| {
10407 FieldFuture::new(async {
10408 Ok(Some(FieldValue::list([
10409 FieldValue::NULL,
10410 FieldValue::NULL.with_type("widgets"),
10411 ])))
10412 })
10413 },
10414 ));
10415 let schema = Schema::build("Query", None, None)
10416 .extension(NullableFederationEntity)
10417 .register(entity)
10418 .register(union)
10419 .register(query)
10420 .finish()
10421 .expect("schema builds");
10422
10423 let response = schema
10424 .execute("{ _entities { ... on widgets { id } } }")
10425 .await;
10426
10427 assert!(response.errors.is_empty(), "{:?}", response.errors);
10428 assert_eq!(
10429 response.data,
10430 async_graphql::value!({ "_entities": [null, { "id": 2 }] })
10431 );
10432 }
10433
10434 #[test]
10435 fn federation_metadata_is_byte_for_byte_inert_when_disabled() {
10436 let cache = create_test_schema_cache();
10437 let sdl_for = |config: SchemaConfig| {
10438 let generated = build_schema(&cache, &config);
10439 build_dynamic_schema(
10440 &generated,
10441 &cache,
10442 None,
10443 None,
10444 Arc::new(config.names.clone()),
10445 std::time::Duration::from_secs(30),
10446 None,
10447 )
10448 .expect("schema should build")
10449 .sdl()
10450 };
10451
10452 let baseline = sdl_for(SchemaConfig {
10453 type_prefix: Some("test".into()),
10454 ..SchemaConfig::default()
10455 });
10456 let with_disabled_federation_metadata = sdl_for(SchemaConfig {
10457 enable_federation: false,
10458 type_prefix: Some("test".into()),
10459 names: crate::names::NameOverrides::parse(
10460 r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10461 )
10462 .expect("metadata"),
10463 ..SchemaConfig::default()
10464 });
10465
10466 assert_eq!(with_disabled_federation_metadata, baseline);
10467 assert!(
10468 with_disabled_federation_metadata.contains("type test_users "),
10469 "prefixed object type remains when federation is disabled:\n{with_disabled_federation_metadata}"
10470 );
10471 assert!(
10472 !with_disabled_federation_metadata.contains("_Service"),
10473 "service type:\n{with_disabled_federation_metadata}"
10474 );
10475 assert!(
10476 !with_disabled_federation_metadata.contains("@key"),
10477 "federation key:\n{with_disabled_federation_metadata}"
10478 );
10479 }
10480
10481 #[test]
10482 fn shared_entities_are_shareable_at_the_type_level() {
10483 let federation_sdl = |shared: bool| {
10484 let mut cache = create_test_schema_cache();
10485 add_test_table(&mut cache, "posts");
10486 add_test_posts_relationship(&mut cache);
10487 let names = match shared {
10488 true => crate::names::NameOverrides::parse(
10489 r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10490 )
10491 .expect("metadata"),
10492 false => crate::names::NameOverrides::default(),
10493 };
10494 let config = SchemaConfig {
10495 enable_federation: true,
10496 type_prefix: Some("test".into()),
10497 names: names.clone(),
10498 ..SchemaConfig::default()
10499 };
10500 let generated = build_schema(&cache, &config);
10501 build_dynamic_schema(
10502 &generated,
10503 &cache,
10504 None,
10505 None,
10506 Arc::new(names),
10507 std::time::Duration::from_secs(30),
10508 None,
10509 )
10510 .expect("federated schema should build")
10511 .sdl_with_options(async_graphql::SDLExportOptions::new().federation())
10512 };
10513
10514 let shared = federation_sdl(true);
10517 assert!(
10518 shared.contains("type users @key(fields: \"id\") @shareable"),
10519 "shared entity type:\n{shared}"
10520 );
10521 assert!(
10522 shared.contains("): [test_posts!]!") && shared.contains("): test_posts_aggregate!"),
10523 "shared relationship fields:\n{shared}"
10524 );
10525 assert!(
10526 !shared.contains("): [test_posts!]! @shareable")
10527 && !shared.contains("): test_posts_aggregate! @shareable"),
10528 "field-level @shareable is redundant under a shareable type:\n{shared}"
10529 );
10530
10531 let not_shared = federation_sdl(false);
10532 assert!(
10533 not_shared.contains("type test_users @key(fields: \"id\") {"),
10534 "non-shared entity type must not be shareable:\n{not_shared}"
10535 );
10536 assert!(
10537 !not_shared.contains(" @shareable"),
10538 "nothing in a schema without shared entities is shareable:\n{not_shared}"
10539 );
10540 }
10541
10542 #[tokio::test]
10543 async fn federation_exposes_service_sdl_and_entity_keys() {
10544 let mut cache = create_test_schema_cache();
10545 add_test_table(&mut cache, "posts");
10546 let config = SchemaConfig {
10547 enable_federation: true,
10548 type_prefix: Some("test".into()),
10549 names: crate::names::NameOverrides::parse(
10550 r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10551 )
10552 .expect("metadata"),
10553 ..SchemaConfig::default()
10554 };
10555 let generated = build_schema(&cache, &config);
10556 let schema = build_dynamic_schema(
10557 &generated,
10558 &cache,
10559 None,
10560 None,
10561 Arc::new(Default::default()),
10562 std::time::Duration::from_secs(30),
10563 None,
10564 )
10565 .expect("a federated schema should build");
10566 let sdl = schema.sdl();
10567 let federation_sdl =
10568 schema.sdl_with_options(async_graphql::SDLExportOptions::new().federation());
10569
10570 assert!(sdl.contains("_Service"), "service type:\n{sdl}");
10571 assert!(sdl.contains("_service"), "service field:\n{sdl}");
10572 assert!(
10573 federation_sdl.contains("type users @key(fields: \"id\") @shareable"),
10574 "users key and type-level @shareable:\n{federation_sdl}"
10575 );
10576 assert!(
10577 federation_sdl.contains("@shareable"),
10578 "shared field directive:\n{federation_sdl}"
10579 );
10580 assert!(sdl.contains("type users "), "shared object type:\n{sdl}");
10581 assert!(
10582 !sdl.contains("type test_users "),
10583 "prefixed shared object type:\n{sdl}"
10584 );
10585 assert!(sdl.contains("test_users("), "query root:\n{sdl}");
10586 assert!(sdl.contains("test_users_by_pk("), "by-PK root:\n{sdl}");
10587 assert!(sdl.contains("test_users_bool_exp"), "derived input:\n{sdl}");
10588 assert!(
10589 !sdl.contains("input users_bool_exp "),
10590 "unprefixed derived input:\n{sdl}"
10591 );
10592 assert!(
10593 sdl.contains("test_users_aggregate"),
10594 "aggregate type:\n{sdl}"
10595 );
10596 assert!(
10597 !sdl.contains("type users_aggregate "),
10598 "unprefixed aggregate type:\n{sdl}"
10599 );
10600 assert!(
10601 sdl.contains("test_users_mutation_response"),
10602 "mutation response type:\n{sdl}"
10603 );
10604 assert!(
10605 !sdl.contains("type users_mutation_response "),
10606 "unprefixed mutation response type:\n{sdl}"
10607 );
10608 assert!(
10609 sdl.contains("type test_posts {"),
10610 "non-shared object type remains prefixed:\n{sdl}"
10611 );
10612 assert!(
10613 !sdl.contains("type posts {"),
10614 "non-shared object type must not become unprefixed:\n{sdl}"
10615 );
10616 assert!(sdl.contains("test_posts("), "prefixed posts root:\n{sdl}");
10617 assert!(
10618 sdl.contains("test_posts_bool_exp"),
10619 "prefixed posts bool_exp:\n{sdl}"
10620 );
10621
10622 let response = schema.execute("{ _service { sdl } }").await;
10623 assert!(
10624 response.errors.is_empty(),
10625 "service query errors: {:?}",
10626 response.errors
10627 );
10628 let service = response.data.into_json().expect("service response JSON");
10629 let service_sdl = service
10630 .get("_service")
10631 .and_then(|value| value.get("sdl"))
10632 .and_then(serde_json::Value::as_str)
10633 .expect("service SDL string");
10634 assert!(
10635 service_sdl.contains("type Query"),
10636 "federation root type:\n{service_sdl}"
10637 );
10638 assert!(
10639 service_sdl.contains("test_users("),
10640 "query fields are on the federation root:\n{service_sdl}"
10641 );
10642 assert!(
10643 service_sdl.contains("test_posts("),
10644 "non-shared query fields are on the federation root:\n{service_sdl}"
10645 );
10646 assert!(
10647 !service_sdl.contains("type query_root"),
10648 "Apollo composition treats query_root as an ordinary object without a schema definition:\n{service_sdl}"
10649 );
10650 assert!(
10651 service_sdl.contains("type users @key(fields: \"id\")"),
10652 "{service_sdl}"
10653 );
10654 assert!(
10655 service_sdl.contains("type test_posts @key(fields: \"id\")"),
10656 "{service_sdl}"
10657 );
10658 }
10659
10660 #[test]
10663 fn exists_is_a_subselect_over_another_table() {
10664 let cache = create_test_schema_cache();
10665 let names = crate::names::NameOverrides::default();
10666 let relationships: HashMap<String, Vec<RelationshipField>> = HashMap::new();
10667 let scope = WhereScope::table("public", "users", "users", &names)
10668 .with_resolution(&cache, &relationships);
10669
10670 let mut param_idx = 1usize;
10671 let mut values: Vec<serde_json::Value> = Vec::new();
10672 let mut aliases = 0usize;
10673 let sql = build_condition(
10674 &serde_json::json!({
10675 "_exists": {"_table": "users", "_where": {"name": {"_eq": "Ann"}}}
10676 }),
10677 &scope,
10678 &mut param_idx,
10679 &mut values,
10680 &mut aliases,
10681 )
10682 .expect("compiles")
10683 .expect("constrains something");
10684
10685 assert_eq!(
10686 sql,
10687 "EXISTS (SELECT 1 FROM \"public\".\"users\" AS \"pgrst_exists_1\" \
10688 WHERE \"pgrst_exists_1\".\"name\" = $1::text)"
10689 );
10690 assert_eq!(values, vec![serde_json::json!("Ann")]);
10691 }
10692
10693 #[test]
10695 fn exists_names_a_table_the_server_has() {
10696 let cache = create_test_schema_cache();
10697 let names = crate::names::NameOverrides::default();
10698 let relationships: HashMap<String, Vec<RelationshipField>> = HashMap::new();
10699 let scope = WhereScope::table("public", "users", "users", &names)
10700 .with_resolution(&cache, &relationships);
10701 let error = build_condition(
10702 &serde_json::json!({"_exists": {"_table": "nowhere", "_where": {}}}),
10703 &scope,
10704 &mut 1,
10705 &mut Vec::new(),
10706 &mut 0,
10707 )
10708 .expect_err("a table that is not there is an error");
10709 assert!(
10710 error.message.contains("public.nowhere"),
10711 "{}",
10712 error.message
10713 );
10714 }
10715
10716 #[test]
10723 fn a_table_a_role_may_count_and_not_read_has_a_count_and_no_rows() {
10724 let cache = create_test_schema_cache();
10725 let names = crate::names::NameOverrides::parse(
10726 r#"{"tables": {"public.users": {"permissions":
10727 {"counter": {"select": {"columns": [], "filter": {},
10728 "allow_aggregations": true}}}}}}"#,
10729 )
10730 .unwrap();
10731 let view = crate::role::cache_for_role(&cache, &names, "counter", false);
10732 assert!(!view.tables.is_empty(), "the table is there to be counted");
10733
10734 let config = SchemaConfig {
10735 names: names.clone(),
10736 role: Some("counter".to_string()),
10737 ..SchemaConfig::default()
10738 };
10739 let generated = build_schema(&view, &config);
10740 let schema = build_dynamic_schema(
10741 &generated,
10742 &view,
10743 None,
10744 None,
10745 Arc::new(names),
10746 std::time::Duration::from_secs(30),
10747 Some("counter"),
10748 )
10749 .expect("a role that may only count still has a buildable schema");
10750 let sdl = schema.sdl();
10751
10752 assert!(
10753 sdl.contains("users_aggregate"),
10754 "the count is there:\n{}",
10755 sdl
10756 );
10757 assert!(sdl.contains("count: Int!"), "and it is a count:\n{}", sdl);
10758 assert!(!sdl.contains("type users "), "no row type:\n{}", sdl);
10760 assert!(
10761 !sdl.contains("nodes"),
10762 "and no rows beside the numbers:\n{}",
10763 sdl
10764 );
10765 assert!(
10766 !sdl.contains("users_select_column"),
10767 "no column enum to order by or count over:\n{}",
10768 sdl
10769 );
10770 assert!(!sdl.contains("users_max_fields"), "no max:\n{}", sdl);
10772 }
10773
10774 #[test]
10781 fn a_table_a_role_may_only_write_gets_the_write_and_no_type() {
10782 let cache = create_test_schema_cache();
10783 let names = crate::names::NameOverrides::parse(
10784 r#"{"tables": {"public.users": {"permissions":
10785 {"writer": {"insert": {"columns": "*", "check": {}}}}}}}"#,
10786 )
10787 .unwrap();
10788 let view = crate::role::cache_for_role(&cache, &names, "writer", false);
10789 let config = SchemaConfig {
10790 names: names.clone(),
10791 role: Some("writer".to_string()),
10792 ..SchemaConfig::default()
10793 };
10794 let generated = build_schema(&view, &config);
10795
10796 let schema = build_dynamic_schema(
10797 &generated,
10798 &view,
10799 None,
10800 None,
10801 Arc::new(names),
10802 std::time::Duration::from_secs(30),
10803 Some("writer"),
10804 )
10805 .expect("a role that may only write still has a buildable schema");
10806 let sdl = schema.sdl();
10807
10808 assert!(
10809 sdl.contains("insert_users("),
10810 "the write is there:\n{}",
10811 sdl
10812 );
10813 assert!(
10814 sdl.contains("users_insert_input"),
10815 "and its input:\n{}",
10816 sdl
10817 );
10818 assert!(!sdl.contains("type users "), "no row type:\n{}", sdl);
10820 assert!(!sdl.contains("insert_users_one"), "no insert_one:\n{}", sdl);
10821 assert!(
10822 !sdl.contains("returning"),
10823 "and nothing to return:\n{}",
10824 sdl
10825 );
10826 assert!(
10827 sdl.contains("users_mutation_response"),
10828 "the count is still answered:\n{}",
10829 sdl
10830 );
10831 assert!(
10832 !sdl.contains("_mutation_response_mutation_response"),
10833 "and no type is named twice over:\n{}",
10834 sdl
10835 );
10836 }
10837
10838 fn cache_with_a_mutation_function() -> SchemaCache {
10841 use postrust_core::schema_cache::{FuncVolatility, RetType, Routine};
10842
10843 let mut cache = create_test_schema_cache();
10844 let routine = Routine {
10845 schema: "public".into(),
10846 name: "add_to_score".into(),
10847 description: None,
10848 params: Vec::new(),
10849 return_type: RetType::SetOf("users".into()),
10850 returns_composite: true,
10851 volatility: FuncVolatility::Volatile,
10852 has_variadic: false,
10853 isolation_level: None,
10854 settings: Vec::new(),
10855 is_procedure: false,
10856 media_type: None,
10857 media_base_type: None,
10858 output_columns: Vec::new(),
10859 };
10860 cache
10861 .routines
10862 .insert(routine.qualified_identifier(), vec![routine]);
10863 cache
10864 }
10865
10866 #[test]
10871 fn a_mutation_function_needs_the_role_to_be_named() {
10872 let cache = cache_with_a_mutation_function();
10873 let withheld = crate::names::NameOverrides::parse(
10874 r#"{"tables": {"public.users": {"permissions":
10875 {"reader": {"select": {"columns": "*", "filter": {}}}}}},
10876 "functions": {"public.add_to_score": {"exposed_as": "mutation"}}}"#,
10877 )
10878 .unwrap();
10879 let granted = crate::names::NameOverrides::parse(
10880 r#"{"tables": {"public.users": {"permissions":
10881 {"reader": {"select": {"columns": "*", "filter": {}}}}}},
10882 "functions": {"public.add_to_score":
10883 {"exposed_as": "mutation", "roles": ["reader"]}}}"#,
10884 )
10885 .unwrap();
10886
10887 let sdl_for = |names: &crate::names::NameOverrides| {
10888 let view = crate::role::cache_for_role(&cache, names, "reader", false);
10889 let config = SchemaConfig {
10890 names: names.clone(),
10891 role: Some("reader".to_string()),
10892 ..SchemaConfig::default()
10893 };
10894 let generated = build_schema(&view, &config);
10895 build_dynamic_schema(
10896 &generated,
10897 &view,
10898 None,
10899 None,
10900 Arc::new(names.clone()),
10901 std::time::Duration::from_secs(30),
10902 Some("reader"),
10903 )
10904 .expect("schema builds")
10905 .sdl()
10906 };
10907
10908 let without = sdl_for(&withheld);
10909 assert!(
10910 !without.contains("add_to_score"),
10911 "not granted, so not there:\n{}",
10912 without
10913 );
10914 assert!(
10917 !without.contains("mutation: mutation_root"),
10918 "and no mutation root at all:\n{}",
10919 without
10920 );
10921
10922 let with = sdl_for(&granted);
10923 assert!(
10924 with.contains("add_to_score"),
10925 "named by a function permission, so it is:\n{}",
10926 with
10927 );
10928 }
10929
10930 #[test]
10932 fn a_role_the_document_never_names_is_granted_nothing() {
10933 let cache = Arc::new(create_test_schema_cache());
10934 let config = SchemaConfig {
10935 names: crate::names::NameOverrides::parse(
10936 r#"{"tables": {"public.users": {"permissions":
10937 {"reader": {"select": {"columns": "*", "filter": {}}}}}}}"#,
10938 )
10939 .unwrap(),
10940 ..SchemaConfig::default()
10941 };
10942 let empty = build_ungranted_schema(&cache, &config).expect("it builds");
10943 let sdl = empty.sdl();
10944 assert!(
10945 sdl.contains("no_queries_available"),
10946 "nothing to read:\n{}",
10947 sdl
10948 );
10949 assert!(!sdl.contains("type users "), "and no table:\n{}", sdl);
10950 assert!(build_ungranted_schema(&cache, &SchemaConfig::default()).is_none());
10952 }
10953
10954 #[test]
10957 fn a_column_a_role_may_set_without_seeing_is_in_the_input_alone() {
10958 let cache = create_test_schema_cache();
10959 let names = crate::names::NameOverrides::parse(
10960 r#"{"tables": {"public.users": {"permissions":
10961 {"user": {"select": {"columns": ["id"], "filter": {}},
10962 "insert": {"columns": "*", "check": {}}}}}}}"#,
10963 )
10964 .unwrap();
10965 let view = crate::role::cache_for_role(&cache, &names, "user", false);
10966 let config = SchemaConfig {
10967 names: names.clone(),
10968 role: Some("user".to_string()),
10969 ..SchemaConfig::default()
10970 };
10971 let generated = build_schema(&view, &config);
10972 let object = &generated.object_types["users"];
10973 assert_eq!(
10974 object
10975 .fields
10976 .iter()
10977 .map(|f| f.name.as_str())
10978 .collect::<Vec<_>>(),
10979 vec!["id"],
10980 "the type shows what may be read"
10981 );
10982 assert!(
10983 object.writable_fields.iter().any(|f| f.name == "name"),
10984 "and the input keeps what may be written"
10985 );
10986
10987 let schema = build_dynamic_schema(
10988 &generated,
10989 &view,
10990 None,
10991 None,
10992 Arc::new(names),
10993 std::time::Duration::from_secs(30),
10994 Some("user"),
10995 )
10996 .expect("schema builds");
10997 let sdl = schema.sdl();
10998 let input = sdl
10999 .split("input users_insert_input")
11000 .nth(1)
11001 .and_then(|rest| rest.split('}').next())
11002 .expect("the insert input is registered");
11003 assert!(input.contains("name:"), "settable without being readable");
11004 }
11005
11006 #[test]
11010 fn a_generated_column_is_readable_and_not_writable() {
11011 let mut cache = create_test_schema_cache();
11012 cache
11013 .tables
11014 .get_mut(&postrust_core::api_request::QualifiedIdentifier::new(
11015 "public", "users",
11016 ))
11017 .expect("the fixture has users")
11018 .columns
11019 .get_mut("id")
11020 .expect("with an id")
11021 .always_generated = true;
11022
11023 let names = crate::names::NameOverrides::default();
11024 let config = SchemaConfig {
11025 names: names.clone(),
11026 ..SchemaConfig::default()
11027 };
11028 let generated = build_schema(&cache, &config);
11029 let schema = build_dynamic_schema(
11030 &generated,
11031 &cache,
11032 None,
11033 None,
11034 Arc::new(names),
11035 std::time::Duration::from_secs(30),
11036 None,
11037 )
11038 .expect("schema builds");
11039 let sdl = schema.sdl();
11040
11041 let block = |header: &str| {
11042 sdl.split(header)
11043 .nth(1)
11044 .and_then(|rest| rest.split('}').next())
11045 .unwrap_or_else(|| panic!("{} is registered:\n{}", header, sdl))
11046 .to_string()
11047 };
11048 assert!(
11049 block("type users ").contains("id:"),
11050 "still readable:\n{}",
11051 sdl
11052 );
11053 for header in ["input users_insert_input", "input users_set_input"] {
11054 assert!(
11055 !block(header).contains("id:"),
11056 "{} may not name it:\n{}",
11057 header,
11058 block(header)
11059 );
11060 }
11061 assert!(
11064 !sdl.contains("users_inc_input"),
11065 "and nothing is left to increment:\n{}",
11066 sdl
11067 );
11068 assert!(
11069 block("input users_insert_input").contains("name:"),
11070 "and the rest of the table is untouched",
11071 );
11072 }
11073
11074 #[test]
11075 fn test_create_object_type() {
11076 let table = create_test_table("users");
11077 let obj = TableObjectType::from_table(&table);
11078 let _gql_obj = create_object_type(&obj, &[], None);
11079 }
11080
11081 #[test]
11082 fn test_create_query_type() {
11083 let cache = create_test_schema_cache();
11084 let config = SchemaConfig::default();
11085 let generated = build_schema(&cache, &config);
11086
11087 let _query = create_query_type(
11088 &generated,
11089 "query_root",
11090 None,
11091 Arc::new(HashMap::new()),
11092 Arc::new(Default::default()),
11093 );
11094 }
11095
11096 #[test]
11097 fn test_create_mutation_type() {
11098 let cache = create_test_schema_cache();
11099 let config = SchemaConfig::default();
11100 let generated = build_schema(&cache, &config);
11101
11102 let _mutation = create_mutation_type(
11103 &generated,
11104 "mutation_root",
11105 Arc::new(HashMap::new()),
11106 Arc::new(HashMap::new()),
11107 Arc::new(Default::default()),
11108 None,
11109 None,
11110 );
11111 }
11112
11113 #[test]
11118 fn a_scalar_is_named_the_way_a_client_declares_it() {
11119 use crate::types::{pg_type_to_graphql, GraphQLType};
11120
11121 assert_eq!(pg_type_to_graphql("jsonb").to_string(), "jsonb");
11126 assert_eq!(pg_type_to_graphql("json").to_string(), "json");
11127 assert_eq!(pg_type_to_graphql("int8").to_string(), "bigint");
11128 assert_eq!(pg_type_to_graphql("numeric").to_string(), "numeric");
11129 assert_eq!(pg_type_to_graphql("timestamptz").to_string(), "timestamptz");
11130 assert_eq!(pg_type_to_graphql("timestamp").to_string(), "timestamp");
11131 assert_eq!(pg_type_to_graphql("uuid").to_string(), "uuid");
11132
11133 assert_eq!(pg_type_to_graphql("geometry").to_string(), "geometry");
11136 assert_eq!(
11137 pg_type_to_graphql("colors_enum"),
11138 GraphQLType::Custom("colors_enum".to_string())
11139 );
11140
11141 assert_eq!(
11143 leaf_scalar_name(&pg_type_to_graphql("_text")),
11144 "String".to_string()
11145 );
11146 }
11147
11148 #[test]
11153 fn every_table_gets_a_boolean_expression() {
11154 let cache = create_test_schema_cache();
11155 let config = SchemaConfig::default();
11156 let generated = build_schema(&cache, &config);
11157
11158 let (inputs, _) = crate::input::bool_exp::build_inputs(
11159 &generated.object_types,
11160 &generated.relationship_fields,
11161 );
11162 let names: HashSet<String> = inputs.iter().map(|i| i.type_name().to_string()).collect();
11163
11164 for table in generated.object_types.keys() {
11165 let expected = format!("{}_bool_exp", table);
11166 assert!(
11167 names.contains(&expected),
11168 "no {} among {:?}",
11169 expected,
11170 names
11171 );
11172 }
11173 assert!(names.contains("String_comparison_exp"));
11175 assert!(names.contains("Int_comparison_exp"));
11176 }
11177
11178 #[test]
11179 fn a_schema_carrying_the_boolean_expressions_still_builds() {
11180 let cache = create_test_schema_cache();
11181 let config = SchemaConfig::default();
11182 let generated = build_schema(&cache, &config);
11183
11184 let schema = build_dynamic_schema(
11185 &generated,
11186 &cache,
11187 None,
11188 None,
11189 Arc::new(Default::default()),
11190 std::time::Duration::from_secs(30),
11191 None,
11192 );
11193 assert!(schema.is_ok(), "{:?}", schema.err());
11194
11195 let sdl = schema.unwrap().sdl();
11196 assert!(
11197 sdl.contains("_bool_exp"),
11198 "no boolean expressions in:\n{}",
11199 sdl
11200 );
11201 assert!(sdl.contains("_and"), "no _and in the generated expressions");
11202 }
11203
11204 #[test]
11209 fn test_build_schema_with_subscriptions() {
11210 let cache = create_test_schema_cache();
11211 let config = SchemaConfig {
11212 enable_subscriptions: true,
11213 ..SchemaConfig::default()
11214 };
11215 let generated = build_schema(&cache, &config);
11216
11217 let sub_fields = generate_subscription_fields(&cache, &generated);
11219 assert!(!sub_fields.is_empty(), "Should have subscription fields");
11220
11221 let result = build_dynamic_schema(
11223 &generated,
11224 &cache,
11225 Some(&sub_fields),
11226 None,
11227 Arc::new(Default::default()),
11228 std::time::Duration::from_secs(30),
11229 None,
11230 );
11231 assert!(result.is_ok(), "Schema with subscriptions should build");
11232 }
11233
11234 #[test]
11235 fn test_subscription_field_generation() {
11236 let cache = create_test_schema_cache();
11237 let config = SchemaConfig::default();
11238 let generated = build_schema(&cache, &config);
11239
11240 let fields = generate_subscription_fields(&cache, &generated);
11241
11242 assert_eq!(fields.len(), 1);
11244 assert_eq!(fields[0].name, "users");
11245 assert_eq!(fields[0].table_name, "users");
11246 assert_eq!(fields[0].channel_name(), "postrust_public_users");
11247 }
11248
11249 #[test]
11250 fn test_create_subscription_type() {
11251 let cache = create_test_schema_cache();
11252 let config = SchemaConfig::default();
11253 let generated = build_schema(&cache, &config);
11254 let _subscription = create_subscription_type(
11257 &generated,
11258 "subscription_root",
11259 None,
11260 Arc::new(Default::default()),
11261 Arc::new(Default::default()),
11262 std::time::Duration::from_secs(30),
11263 );
11264 }
11265}
11266
11267#[derive(Debug, PartialEq, Eq)]
11269enum PathStep {
11270 Key(String),
11271 Index(usize),
11272}
11273
11274fn walk_json_path(value: &Value, path: &str) -> Result<Value, async_graphql::Error> {
11281 let mut at = value;
11282 for step in parse_json_path(path)? {
11283 let next = match (&step, at) {
11284 (PathStep::Key(key), Value::Object(map)) => map.get(key.as_str()),
11285 (PathStep::Index(index), Value::List(items)) => items.get(*index),
11286 _ => None,
11289 };
11290 match next {
11291 Some(next) => at = next,
11292 None => return Ok(Value::Null),
11293 }
11294 }
11295 Ok(at.clone())
11296}
11297
11298fn unclosed_bracket(path: &str) -> async_graphql::Error {
11300 let message = format!("\"{}\" is not a JSON path: a bracket is never closed", path);
11301 validation_error(&message)
11302}
11303
11304fn parse_json_path(path: &str) -> Result<Vec<PathStep>, async_graphql::Error> {
11311 let mut steps = Vec::new();
11312 let mut chars = path.chars().peekable();
11313 if chars.peek() == Some(&'$') {
11315 chars.next();
11316 }
11317 while let Some(&c) = chars.peek() {
11318 match c {
11319 '.' => {
11321 chars.next();
11322 }
11323 '[' => {
11324 chars.next();
11325 let quote = match chars.peek() {
11326 Some(&q @ ('\'' | '"')) => {
11327 chars.next();
11328 Some(q)
11329 }
11330 _ => None,
11331 };
11332 let mut inner = String::new();
11333 loop {
11334 let Some(c) = chars.next() else {
11335 return Err(unclosed_bracket(path));
11336 };
11337 match (quote, c) {
11338 (Some(quote), c) if c == quote => break,
11339 (None, ']') => break,
11340 _ => inner.push(c),
11341 }
11342 }
11343 if quote.is_some() {
11345 match chars.next() {
11346 Some(']') => {}
11347 _ => return Err(unclosed_bracket(path)),
11348 }
11349 }
11350 match (quote, inner.parse::<usize>()) {
11353 (None, Ok(index)) => steps.push(PathStep::Index(index)),
11354 _ => steps.push(PathStep::Key(inner)),
11355 }
11356 }
11357 _ => {
11358 let mut key = String::new();
11359 while let Some(&c) = chars.peek() {
11360 if matches!(c, '.' | '[') {
11361 break;
11362 }
11363 key.push(c);
11364 chars.next();
11365 }
11366 steps.push(PathStep::Key(key));
11367 }
11368 }
11369 }
11370 Ok(steps)
11371}
11372
11373#[cfg(test)]
11374mod json_path_tests {
11375 use super::*;
11376
11377 fn steps(path: &str) -> Vec<PathStep> {
11378 parse_json_path(path).expect("the path parses")
11379 }
11380
11381 fn key(name: &str) -> PathStep {
11382 PathStep::Key(name.to_string())
11383 }
11384
11385 #[test]
11386 fn the_document_itself_has_no_steps() {
11387 assert_eq!(steps("$"), vec![]);
11388 assert_eq!(steps(""), vec![]);
11389 }
11390
11391 #[test]
11392 fn a_key_is_written_bare_or_after_a_dot() {
11393 assert_eq!(steps("a"), vec![key("a")]);
11394 assert_eq!(steps(".obj.c1"), vec![key("obj"), key("c1")]);
11395 assert_eq!(steps("._underscore"), vec![key("_underscore")]);
11396 }
11397
11398 #[test]
11399 fn a_bracket_holds_an_index_or_a_quoted_key() {
11400 assert_eq!(steps("arr[0]"), vec![key("arr"), PathStep::Index(0)]);
11401 assert_eq!(steps("['!@#$%^']"), vec![key("!@#$%^")]);
11402 assert_eq!(
11403 steps("translations['hello world!']"),
11404 vec![key("translations"), key("hello world!")]
11405 );
11406 }
11407
11408 #[test]
11410 fn a_dot_before_a_bracket_changes_nothing() {
11411 let expected = vec![key("objs"), PathStep::Index(0), key("\u{4f60}\u{597d}")];
11412 for spelling in [
11413 "objs[0]['\u{4f60}\u{597d}']",
11414 "objs[0][\"\u{4f60}\u{597d}\"]",
11415 "objs[0].[\"\u{4f60}\u{597d}\"]",
11416 "objs.[0].[\"\u{4f60}\u{597d}\"]",
11417 ] {
11418 assert_eq!(steps(spelling), expected, "{}", spelling);
11419 }
11420 }
11421
11422 #[test]
11423 fn a_bracket_that_never_closes_is_refused() {
11424 assert!(parse_json_path("arr[0").is_err());
11425 assert!(parse_json_path("['key'").is_err());
11426 }
11427
11428 #[test]
11429 fn a_step_the_document_does_not_have_reads_null() {
11430 let document = Value::from_json(serde_json::json!({
11431 "obj": {"c1": "c2"},
11432 "arr": [1, 2, 3],
11433 }))
11434 .expect("a document");
11435 let at = |path| walk_json_path(&document, path).expect("the path parses");
11436 assert_eq!(at(".obj.c1"), Value::String("c2".to_string()));
11437 assert_eq!(at("arr[1]"), Value::Number(2.into()));
11438 assert_eq!(at("arr[9]"), Value::Null);
11439 assert_eq!(at(".obj.nothing"), Value::Null);
11440 assert_eq!(at("obj[0]"), Value::Null);
11443 assert_eq!(at("arr.first"), Value::Null);
11444 }
11445}