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 let gql_field = if entity_is_shared && !field.is_pk {
1821 gql_field.shareable()
1822 } else {
1823 gql_field
1824 };
1825
1826 fields.push((field.name.clone(), gql_field));
1827 }
1828
1829 for rel in relationships {
1833 if !taken.insert(rel.name.clone()) {
1834 tracing::warn!(
1835 "{}: not exposing the relationship to \"{}\" as `{}` -- the table \
1836 already has a column of that name",
1837 obj.name,
1838 rel.target_type,
1839 rel.name
1840 );
1841 continue;
1842 }
1843 let field_name = rel.name.clone();
1844 let field_type = if rel.is_list {
1845 TypeRef::named_nn_list_nn(&rel.target_type)
1846 } else if always_present(rel, &obj.table) {
1847 TypeRef::named_nn(&rel.target_type)
1848 } else {
1849 TypeRef::named(&rel.target_type)
1850 };
1851
1852 let is_list = rel.is_list;
1853 let mut gql_field = Field::new(&rel.name, field_type, move |ctx| {
1854 let field_name = field_name.clone();
1855 FieldFuture::new(async move {
1856 if let Some(Value::Object(map)) = ctx.parent_value.as_value() {
1857 let key = async_graphql::Name::new(&field_name);
1858 match map.get(&key) {
1859 Some(Value::Null) if !is_list => return Ok(None),
1864 Some(val) => return Ok(Some(FieldValue::value(val.clone()))),
1865 None => {}
1866 }
1867 }
1868 Ok(None)
1869 })
1870 });
1871
1872 if !rel.arguments.is_empty() {
1883 gql_field = gql_field.argument(InputValue::new(
1884 "args",
1885 TypeRef::named_nn(computed_args_type_name(&obj.local_name, &rel.name)),
1886 ));
1887 }
1888 if rel.is_list {
1889 gql_field = gql_field
1890 .argument(InputValue::new(
1891 "distinct_on",
1892 TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
1893 &rel.target_local_name,
1894 )),
1895 ))
1896 .argument(InputValue::new(
1897 "where",
1898 TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
1899 &rel.target_local_name,
1900 )),
1901 ))
1902 .argument(InputValue::new(
1903 "order_by",
1904 TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
1905 &rel.target_local_name,
1906 )),
1907 ))
1908 .argument(InputValue::new("limit", TypeRef::named("Int")))
1909 .argument(InputValue::new("offset", TypeRef::named("Int")));
1910 }
1911
1912 let gql_field = if let Some(desc) = &rel.description {
1913 gql_field.description(desc)
1914 } else {
1915 gql_field
1916 };
1917 let gql_field = if entity_is_shared {
1918 gql_field.shareable()
1919 } else {
1920 gql_field
1921 };
1922
1923 fields.push((rel.name.clone(), gql_field));
1924
1925 if rel.is_list {
1930 let aggregate_field = format!("{}_aggregate", rel.name);
1931 if taken.insert(aggregate_field.clone()) {
1932 let key = aggregate_field.clone();
1933 fields.push((
1934 aggregate_field.clone(),
1935 Field::new(
1936 &aggregate_field,
1937 TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
1938 &rel.target_local_name,
1939 )),
1940 move |ctx| {
1941 let key = key.clone();
1942 FieldFuture::new(async move {
1943 Ok(Some(FieldValue::value(
1947 child_value(&ctx, &key).unwrap_or(Value::Null),
1948 )))
1949 })
1950 },
1951 )
1952 .argument(InputValue::new(
1957 "distinct_on",
1958 TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
1959 &rel.target_local_name,
1960 )),
1961 ))
1962 .argument(InputValue::new(
1963 "where",
1964 TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
1965 &rel.target_local_name,
1966 )),
1967 ))
1968 .argument(InputValue::new(
1969 "order_by",
1970 TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
1971 &rel.target_local_name,
1972 )),
1973 ))
1974 .argument(InputValue::new("limit", TypeRef::named("Int")))
1975 .argument(InputValue::new("offset", TypeRef::named("Int")))
1976 .description(format!("Aggregates over {}.", rel.name)),
1977 ));
1978 if !rel.arguments.is_empty() {
1981 let last = fields.len() - 1;
1982 let (name, field) = fields.remove(last);
1983 fields.push((
1984 name,
1985 field.argument(InputValue::new(
1986 "args",
1987 TypeRef::named_nn(computed_args_type_name(&obj.local_name, &rel.name)),
1988 )),
1989 ));
1990 }
1991 if entity_is_shared {
1992 let last = fields.len() - 1;
1993 let (name, field) = fields.remove(last);
1994 fields.push((name, field.shareable()));
1995 }
1996 }
1997 }
1998 }
1999
2000 fields.sort_by(|(a, _), (b, _)| a.cmp(b));
2001 for (_, field) in fields {
2002 object = object.field(field);
2003 }
2004
2005 object
2006}
2007
2008trait RootField: Sized {
2015 fn with_argument(self, value: InputValue) -> Self;
2016}
2017
2018impl RootField for Field {
2019 fn with_argument(self, value: InputValue) -> Self {
2020 self.argument(value)
2021 }
2022}
2023
2024impl RootField for SubscriptionField {
2025 fn with_argument(self, value: InputValue) -> Self {
2026 self.argument(value)
2027 }
2028}
2029
2030fn with_row_arguments<F: RootField>(field: F, type_name: &str) -> F {
2033 with_row_arguments_named(field, type_name, true)
2034}
2035
2036fn with_row_arguments_named<F: RootField>(field: F, type_name: &str, columns: bool) -> F {
2044 let mut field = field;
2045 if columns {
2046 field = field.with_argument(InputValue::new(
2047 "distinct_on",
2048 TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(type_name)),
2049 ));
2050 }
2051 field = field
2052 .with_argument(InputValue::new("limit", TypeRef::named("Int")))
2053 .with_argument(InputValue::new("offset", TypeRef::named("Int")));
2054 if columns {
2055 field = field.with_argument(InputValue::new(
2056 "order_by",
2057 TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(type_name)),
2058 ));
2059 }
2060 field.with_argument(InputValue::new(
2061 "where",
2062 TypeRef::named(crate::input::bool_exp::bool_exp_type_name(type_name)),
2063 ))
2064}
2065
2066fn with_key_arguments<F: RootField>(
2069 field: F,
2070 schema_name: &str,
2071 table_name: &str,
2072 pk_columns: &[(String, String)],
2073 names: &crate::names::NameOverrides,
2074) -> F {
2075 let mut field = field;
2076 for (column, pg_type) in pk_columns {
2077 field = field.with_argument(InputValue::new(
2078 names
2079 .column(schema_name, table_name, column)
2080 .unwrap_or(column),
2081 TypeRef::named_nn(exposed_pk_argument_type(
2082 names,
2083 schema_name,
2084 table_name,
2085 column,
2086 pg_type,
2087 )),
2088 ));
2089 }
2090 field
2091}
2092
2093fn create_query_type(
2095 generated: &GeneratedSchema,
2096 root_name: &str,
2097 max_rows: Option<i64>,
2098 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2099 names: Arc<crate::names::NameOverrides>,
2100) -> Object {
2101 let mut roots: Vec<(String, Field)> = Vec::new();
2106
2107 for field in &generated.query_fields {
2108 let table_name = field.table_name.clone();
2109 let schema_name = field.schema_name.clone();
2110 let type_name = field.type_name.clone();
2111 let local_type_name = field.local_type_name.clone();
2112 let is_by_pk = field.is_by_pk;
2113 let pk_columns = field.pk_columns.clone();
2114 let return_type = graphql_type_ref(&field.return_type);
2115
2116 let spec_type_name = local_type_name.clone();
2117 let spec = Arc::new(QueryFieldSpec {
2118 schema_name,
2119 table_name,
2120 type_name,
2121 is_by_pk,
2122 pk_columns: pk_columns.clone(),
2123 max_rows,
2124 relationships: Arc::clone(&relationships),
2125 names: Arc::clone(&names),
2126 call: None,
2127 });
2128
2129 let mut gql_field = Field::new(&field.name, return_type, move |ctx| {
2130 let spec = Arc::clone(&spec);
2131 FieldFuture::new(async move { resolve_query(&ctx, &spec).await })
2132 });
2133
2134 gql_field = match is_by_pk {
2136 false => with_row_arguments(gql_field, &spec_type_name),
2137 true => with_key_arguments(
2138 gql_field,
2139 &field.schema_name,
2140 &field.table_name,
2141 &pk_columns,
2142 names.as_ref(),
2143 ),
2144 };
2145
2146 if let Some(desc) = &field.description {
2147 gql_field = gql_field.description(desc);
2148 }
2149
2150 if field.rows {
2155 roots.push((field.name.clone(), gql_field));
2156 }
2157
2158 if !is_by_pk && field.aggregates {
2166 let agg_spec = Arc::new(AggregateSpec {
2167 schema_name: field.schema_name.clone(),
2168 table_name: field.table_name.clone(),
2169 type_name: field.type_name.clone(),
2170 max_rows,
2171 relationships: Arc::clone(&relationships),
2172 names: Arc::clone(&names),
2173 call: None,
2174 });
2175 let aggregate_field_name = field.aggregate_name.clone().unwrap_or_else(|| {
2176 crate::schema::aggregate::aggregate_type_name(&field.local_type_name)
2177 });
2178 let aggregate_field_name_for_sorting = aggregate_field_name.clone();
2179 let mut agg_field = Field::new(
2180 aggregate_field_name,
2181 TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
2182 &field.local_type_name,
2183 )),
2184 move |ctx| {
2185 let agg_spec = Arc::clone(&agg_spec);
2186 FieldFuture::new(async move { resolve_aggregate(&ctx, &agg_spec).await })
2187 },
2188 );
2189 agg_field = with_row_arguments_named(agg_field, &spec_type_name, field.rows);
2190 agg_field = match field.aggregate_description.as_deref() {
2191 Some("") => agg_field,
2192 Some(given) => agg_field.description(given),
2193 None => agg_field.description(format!(
2194 "fetch aggregated fields from the table: \"{}\"",
2195 field.table_name
2196 )),
2197 };
2198 roots.push((aggregate_field_name_for_sorting, agg_field));
2199 }
2200 }
2201
2202 roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2203 let mut query = Object::new(root_name);
2204 if roots.is_empty() {
2208 return query.field(
2209 Field::new("no_queries_available", TypeRef::named("String"), |_| {
2210 FieldFuture::new(async move { Ok(None::<Value>) })
2211 })
2212 .description("There are no queries available to the current role."),
2213 );
2214 }
2215 for (_, field) in roots {
2216 query = query.field(field);
2217 }
2218
2219 query
2220}
2221
2222type JsonbOperator = (&'static str, fn() -> TypeRef);
2224
2225const JSONB_OPERATORS: &[JsonbOperator] = &[
2232 ("_append", || TypeRef::named("jsonb")),
2233 ("_delete_at_path", || TypeRef::named_nn_list("String")),
2234 ("_delete_elem", || TypeRef::named("Int")),
2235 ("_delete_key", || TypeRef::named("String")),
2236 ("_prepend", || TypeRef::named("jsonb")),
2237];
2238
2239fn jsonb_operator_input(type_name: &str, operator: &str) -> String {
2241 format!("{}{}_input", type_name, operator)
2242}
2243
2244fn with_update_operators(
2251 field: Field,
2252 base_name: &str,
2253 has_numeric: bool,
2254 has_jsonb: bool,
2255) -> Field {
2256 let mut field = field;
2257 if has_jsonb {
2260 for (operator, _) in JSONB_OPERATORS {
2261 field = field.argument(InputValue::new(
2262 *operator,
2263 TypeRef::named(jsonb_operator_input(base_name, operator)),
2264 ));
2265 }
2266 }
2267 if has_numeric {
2268 field = field.argument(InputValue::new(
2269 "_inc",
2270 TypeRef::named(format!("{}_inc_input", base_name)),
2271 ));
2272 }
2273 field.argument(InputValue::new(
2274 "_set",
2275 TypeRef::named(format!("{}_set_input", base_name)),
2276 ))
2277}
2278
2279fn write_fields<'a>(
2289 object: &'a crate::schema::object::TableObjectType,
2290 names: &crate::names::NameOverrides,
2291 role: Option<&str>,
2292 verb: crate::role::Verb,
2293) -> Vec<&'a crate::schema::object::GraphQLField> {
2294 let allowed = role.and_then(|role| {
2295 names
2296 .permissions(&object.table.schema, &object.table.name, role)
2297 .and_then(|granted| granted.write_columns(verb))
2298 });
2299 object
2300 .writable_fields
2301 .iter()
2302 .filter(|field| {
2303 let column = table_column_for(names, &object.table, &field.name);
2304 object
2312 .table
2313 .get_column(column)
2314 .is_some_and(|c| !c.always_generated)
2315 && allowed.is_none_or(|set| set.allows(column))
2316 })
2317 .collect()
2318}
2319
2320fn update_inputs(
2322 object: &crate::schema::object::TableObjectType,
2323 names: &crate::names::NameOverrides,
2324 role: Option<&str>,
2325) -> (bool, bool) {
2326 let fields = write_fields(object, names, role, crate::role::Verb::Update);
2327 (
2328 fields
2329 .iter()
2330 .any(|f| crate::schema::aggregate::is_incrementable(&f.graphql_type)),
2331 fields
2332 .iter()
2333 .any(|f| matches!(&f.graphql_type, crate::types::GraphQLType::Json)),
2334 )
2335}
2336
2337fn create_mutation_type(
2338 generated: &GeneratedSchema,
2339 root_name: &str,
2340 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2341 type_names: Arc<HashMap<(String, String), String>>,
2342 names: Arc<crate::names::NameOverrides>,
2343 max_rows: Option<i64>,
2344 role: Option<&str>,
2345) -> Object {
2346 let mut mutation = Object::new(root_name);
2347 let mut roots: Vec<(String, Field)> = Vec::new();
2349
2350 let mut has_numeric_column: HashSet<String> = HashSet::new();
2357 let mut has_jsonb_column: HashSet<String> = HashSet::new();
2358 for object in generated.object_types.values() {
2359 let (numeric, jsonb) = update_inputs(object, &names, role);
2360 if numeric {
2361 has_numeric_column.insert(object.local_name.clone());
2362 }
2363 if jsonb {
2364 has_jsonb_column.insert(object.local_name.clone());
2365 }
2366 }
2367
2368 let has_conflict_target: HashSet<String> = generated
2369 .object_types
2370 .iter()
2371 .filter(|(_, object)| !object.table.unique_constraints.is_empty())
2372 .map(|(_, object)| object.local_name.clone())
2373 .collect();
2374
2375 for field in &generated.mutation_fields {
2376 let table_name = field.table_name.clone();
2377 let schema_name = field.schema_name.clone();
2378 let mutation_type = field.mutation_type;
2379 let pk_columns = field.pk_columns.clone();
2380 let return_type = graphql_type_ref(&field.return_type);
2381
2382 let where_type = field.local_type_name.clone();
2386
2387 let resolver_pk_columns = pk_columns.clone();
2388 let field_relationships = Arc::clone(&relationships);
2389 let field_type_names = Arc::clone(&type_names);
2390 let field_names = Arc::clone(&names);
2391 let mut gql_field = Field::new(&field.name, return_type, move |ctx| {
2392 let table_name = table_name.clone();
2393 let schema_name = schema_name.clone();
2394 let pk_columns = resolver_pk_columns.clone();
2395 let relationships = Arc::clone(&field_relationships);
2396 let type_names = Arc::clone(&field_type_names);
2397 let names = Arc::clone(&field_names);
2398 FieldFuture::new(async move {
2399 resolve_mutation(
2400 &ctx,
2401 &schema_name,
2402 &table_name,
2403 mutation_type,
2404 &pk_columns,
2405 &relationships,
2406 &type_names,
2407 &names,
2408 max_rows,
2409 )
2410 .await
2411 })
2412 });
2413
2414 match mutation_type {
2420 MutationType::Insert | MutationType::InsertOne => {
2421 let insert_input = format!("{}_insert_input", where_type);
2422 gql_field = if mutation_type == MutationType::Insert {
2423 gql_field.argument(InputValue::new(
2424 "objects",
2425 TypeRef::named_nn_list_nn(&insert_input),
2426 ))
2427 } else {
2428 gql_field.argument(InputValue::new("object", TypeRef::named_nn(&insert_input)))
2431 };
2432 if has_conflict_target.contains(&where_type) {
2433 gql_field = gql_field.argument(InputValue::new(
2434 "on_conflict",
2435 TypeRef::named(format!("{}_on_conflict", where_type)),
2436 ));
2437 }
2438 }
2439 MutationType::UpdateByPk => {
2440 gql_field = gql_field.argument(InputValue::new(
2441 "pk_columns",
2442 TypeRef::named_nn(format!("{}_pk_columns_input", where_type)),
2443 ));
2444 gql_field = with_update_operators(
2445 gql_field,
2446 &where_type,
2447 has_numeric_column.contains(&where_type),
2448 has_jsonb_column.contains(&where_type),
2449 );
2450 }
2451 MutationType::Update => {
2452 gql_field = gql_field.argument(InputValue::new(
2453 "where",
2454 TypeRef::named_nn(crate::input::bool_exp::bool_exp_type_name(&where_type)),
2455 ));
2456 gql_field = with_update_operators(
2457 gql_field,
2458 &where_type,
2459 has_numeric_column.contains(&where_type),
2460 has_jsonb_column.contains(&where_type),
2461 );
2462 }
2463 MutationType::UpdateMany => {
2464 gql_field = gql_field.argument(InputValue::new(
2465 "updates",
2466 TypeRef::named_nn_list_nn(format!("{}_updates", where_type)),
2467 ));
2468 }
2469 MutationType::DeleteByPk => {
2470 for (col_name, pg_type) in &pk_columns {
2471 gql_field = gql_field.argument(InputValue::new(
2472 names
2473 .column(&field.schema_name, &field.table_name, col_name)
2474 .unwrap_or(col_name),
2475 TypeRef::named_nn(exposed_pk_argument_type(
2476 names.as_ref(),
2477 &field.schema_name,
2478 &field.table_name,
2479 col_name,
2480 pg_type,
2481 )),
2482 ));
2483 }
2484 }
2485 MutationType::Delete => {
2486 gql_field = gql_field.argument(InputValue::new(
2493 "where",
2494 TypeRef::named_nn(crate::input::bool_exp::bool_exp_type_name(&where_type)),
2495 ));
2496 }
2497 }
2498
2499 if let Some(desc) = &field.description {
2500 gql_field = gql_field.description(desc);
2501 }
2502
2503 roots.push((field.name.clone(), gql_field));
2504 }
2505
2506 roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2507 for (_, field) in roots {
2508 mutation = mutation.field(field);
2509 }
2510
2511 mutation
2512}
2513
2514fn create_subscription_type(
2531 generated: &GeneratedSchema,
2532 root_name: &str,
2533 max_rows: Option<i64>,
2534 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2535 names: Arc<crate::names::NameOverrides>,
2536 refresh: std::time::Duration,
2537) -> Subscription {
2538 let mut roots: Vec<(String, SubscriptionField)> = Vec::new();
2539
2540 for field in &generated.query_fields {
2541 let spec_type_name = field.local_type_name.clone();
2542 let pk_columns = field.pk_columns.clone();
2543 let is_by_pk = field.is_by_pk;
2544 let return_type = graphql_type_ref(&field.return_type);
2545 let watched = vec![crate::subscription::table_channel_name(
2546 &field.schema_name,
2547 &field.table_name,
2548 )];
2549
2550 let spec = Arc::new(QueryFieldSpec {
2551 schema_name: field.schema_name.clone(),
2552 table_name: field.table_name.clone(),
2553 type_name: field.type_name.clone(),
2554 is_by_pk,
2555 pk_columns: pk_columns.clone(),
2556 max_rows,
2557 relationships: Arc::clone(&relationships),
2558 names: Arc::clone(&names),
2559 call: None,
2560 });
2561
2562 let mut gql_field = SubscriptionField::new(&field.name, return_type, move |ctx| {
2563 let spec = Arc::clone(&spec);
2564 let watched = watched.clone();
2565 SubscriptionFieldFuture::new(async move {
2566 let wake = wake_on(&ctx, &watched, refresh).await;
2567 Ok(live(ctx, LiveSource::Rows(spec), wake))
2568 })
2569 });
2570
2571 gql_field = match is_by_pk {
2572 false => with_row_arguments(gql_field, &spec_type_name),
2573 true => with_key_arguments(
2574 gql_field,
2575 &field.schema_name,
2576 &field.table_name,
2577 &pk_columns,
2578 names.as_ref(),
2579 ),
2580 };
2581 if let Some(desc) = &field.description {
2582 gql_field = gql_field.description(desc);
2583 }
2584 if field.rows {
2586 roots.push((field.name.clone(), gql_field));
2587 }
2588
2589 if is_by_pk || !field.aggregates {
2592 continue;
2593 }
2594
2595 let agg_spec = Arc::new(AggregateSpec {
2597 schema_name: field.schema_name.clone(),
2598 table_name: field.table_name.clone(),
2599 type_name: field.type_name.clone(),
2600 max_rows,
2601 relationships: Arc::clone(&relationships),
2602 names: Arc::clone(&names),
2603 call: None,
2604 });
2605 let agg_watched = vec![crate::subscription::table_channel_name(
2606 &field.schema_name,
2607 &field.table_name,
2608 )];
2609 let agg_name = field.aggregate_name.clone().unwrap_or_else(|| {
2610 crate::schema::aggregate::aggregate_type_name(&field.local_type_name)
2611 });
2612 let mut agg_field = SubscriptionField::new(
2613 agg_name.clone(),
2614 TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
2615 &field.local_type_name,
2616 )),
2617 move |ctx| {
2618 let agg_spec = Arc::clone(&agg_spec);
2619 let watched = agg_watched.clone();
2620 SubscriptionFieldFuture::new(async move {
2621 let wake = wake_on(&ctx, &watched, refresh).await;
2622 Ok(live(ctx, LiveSource::Aggregate(agg_spec), wake))
2623 })
2624 },
2625 );
2626 agg_field = with_row_arguments_named(agg_field, &spec_type_name, field.rows);
2627 agg_field = match field.aggregate_description.as_deref() {
2628 Some("") => agg_field,
2629 Some(given) => agg_field.description(given),
2630 None => agg_field.description(format!(
2631 "fetch aggregated fields from the table: \"{}\"",
2632 field.table_name
2633 )),
2634 };
2635 roots.push((agg_name, agg_field));
2636 }
2637
2638 roots.sort_by(|(a, _), (b, _)| a.cmp(b));
2639 let mut subscription = Subscription::new(root_name);
2640 if roots.is_empty() {
2643 return subscription.field(SubscriptionField::new(
2644 "no_subscriptions_available",
2645 TypeRef::named("String"),
2646 |_| {
2647 SubscriptionFieldFuture::new(async move {
2648 Ok(futures::stream::empty::<
2649 Result<FieldValue, async_graphql::Error>,
2650 >())
2651 })
2652 },
2653 ));
2654 }
2655 for (_, field) in roots {
2656 subscription = subscription.field(field);
2657 }
2658 subscription
2659}
2660
2661async fn wake_on(
2667 ctx: &ResolverContext<'_>,
2668 channels: &[String],
2669 refresh: std::time::Duration,
2670) -> futures::stream::BoxStream<'static, ()> {
2671 use futures::StreamExt;
2672
2673 let mut streams: Vec<futures::stream::BoxStream<'static, ()>> =
2674 Vec::with_capacity(channels.len() + 1);
2675 streams.push(
2678 tokio_stream::wrappers::IntervalStream::new({
2679 let mut interval = tokio::time::interval(refresh);
2680 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
2681 interval
2682 })
2683 .map(|_| ())
2684 .boxed(),
2685 );
2686
2687 if let Ok(broker_arc) = ctx.data::<Arc<RwLock<Option<NotifyBroker>>>>() {
2688 let guard = broker_arc.read().await;
2689 if let Some(broker) = guard.as_ref() {
2690 for channel in channels {
2691 streams.push(
2695 broker
2696 .subscribe_or_create(channel)
2697 .await
2698 .map(|_| ())
2699 .boxed(),
2700 );
2701 }
2702 }
2703 }
2704
2705 futures::stream::select_all(streams).boxed()
2706}
2707
2708enum LiveSource {
2714 Rows(Arc<QueryFieldSpec>),
2715 Aggregate(Arc<AggregateSpec>),
2716}
2717
2718async fn read_live<'a>(
2720 ctx: &ResolverContext<'a>,
2721 source: &LiveSource,
2722) -> Result<(serde_json::Value, Option<FieldValue<'a>>), async_graphql::Error> {
2723 match source {
2724 LiveSource::Rows(spec) => {
2725 let rows = query_rows(ctx, spec).await?;
2726 Ok((
2727 serde_json::Value::Array(rows.clone()),
2728 rows_as_field_value(rows, spec.is_by_pk),
2729 ))
2730 }
2731 LiveSource::Aggregate(spec) => {
2732 let value = aggregate_value(ctx, spec).await?;
2733 let seen = serde_json::to_value(&value).unwrap_or_default();
2734 Ok((seen, Some(FieldValue::value(value))))
2735 }
2736 }
2737}
2738
2739fn live<'a>(
2747 ctx: ResolverContext<'a>,
2748 source: LiveSource,
2749 wake: futures::stream::BoxStream<'static, ()>,
2750) -> impl futures::Stream<Item = Result<FieldValue<'a>, async_graphql::Error>> + Send + 'a {
2751 use futures::StreamExt;
2752
2753 struct Live<'a> {
2754 ctx: ResolverContext<'a>,
2755 source: LiveSource,
2756 wake: futures::stream::BoxStream<'static, ()>,
2757 sent: Option<serde_json::Value>,
2758 started: bool,
2759 failed: bool,
2761 _active: crate::subscription::ActiveSubscription,
2763 }
2764
2765 futures::stream::unfold(
2766 Live {
2767 ctx,
2768 source,
2769 wake,
2770 sent: None,
2771 started: false,
2772 failed: false,
2773 _active: crate::subscription::ActiveSubscription::open(),
2774 },
2775 |mut live: Live<'a>| async move {
2776 if live.failed {
2777 return None;
2778 }
2779 loop {
2780 if live.started {
2781 live.wake.next().await?;
2782 } else {
2783 live.started = true;
2784 }
2785 let read = read_live(&live.ctx, &live.source).await;
2786 match read {
2787 Err(e) => {
2795 live.failed = true;
2796 return Some((Err(e), live));
2797 }
2798 Ok((seen, value)) => {
2799 if live.sent.as_ref() == Some(&seen) {
2800 continue;
2801 }
2802 live.sent = Some(seen);
2803 let value = value.unwrap_or_else(|| FieldValue::value(Value::Null));
2804 return Some((Ok(value), live));
2805 }
2806 }
2807 }
2808 },
2809 )
2810}
2811
2812struct QueryFieldSpec {
2814 schema_name: String,
2815 table_name: String,
2816 type_name: String,
2817 is_by_pk: bool,
2818 pk_columns: Vec<(String, String)>,
2819 max_rows: Option<i64>,
2820 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2821 names: Arc<crate::names::NameOverrides>,
2822 call: Option<Arc<FunctionCall>>,
2825}
2826
2827#[derive(Clone)]
2829struct EntityLookup {
2830 schema_name: String,
2831 table_name: String,
2832 type_name: String,
2833 key_columns: Vec<EntityKeyColumn>,
2834 row_column_types: HashMap<String, String>,
2835}
2836
2837#[derive(Clone)]
2838struct EntityKeyColumn {
2839 field_name: String,
2840 column_name: String,
2841 pg_type: String,
2842 explicit_id: bool,
2843}
2844
2845struct EntityResolverState {
2847 entities: HashMap<String, EntityLookup>,
2848 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2849 names: Arc<crate::names::NameOverrides>,
2850 max_rows: Option<i64>,
2851}
2852
2853impl EntityResolverState {
2854 fn new(
2855 generated: &GeneratedSchema,
2856 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
2857 names: Arc<crate::names::NameOverrides>,
2858 max_rows: Option<i64>,
2859 ) -> Self {
2860 let mut entities = HashMap::new();
2861 for (type_name, entity) in &generated.federation_entities {
2862 let Some(object) = generated.object_types.get(type_name) else {
2863 continue;
2864 };
2865 let mut key_columns = Vec::with_capacity(entity.key_fields.len());
2866 for field_name in &entity.key_fields {
2867 let column_name = names
2868 .column_source(&object.table.schema, &object.table.name, field_name)
2869 .unwrap_or(field_name);
2870 let Some(column) = object.table.get_column(column_name) else {
2871 continue;
2872 };
2873 key_columns.push(EntityKeyColumn {
2874 field_name: field_name.clone(),
2875 column_name: column.name.clone(),
2876 pg_type: column.nominal_type.clone(),
2877 explicit_id: matches!(
2878 names.column_type(&object.table.schema, &object.table.name, &column.name),
2879 Some(crate::types::GraphQLType::Id)
2880 ),
2881 });
2882 }
2883 if key_columns.len() != entity.key_fields.len() {
2884 continue;
2885 }
2886 entities.insert(
2887 type_name.clone(),
2888 EntityLookup {
2889 schema_name: object.table.schema.clone(),
2890 table_name: object.table.name.clone(),
2891 type_name: type_name.clone(),
2892 key_columns,
2893 row_column_types: exposed_column_types(&object.table, names.as_ref()),
2894 },
2895 );
2896 }
2897 Self {
2898 entities,
2899 relationships,
2900 names,
2901 max_rows,
2902 }
2903 }
2904}
2905
2906struct EntityRepresentation {
2907 index: usize,
2908 type_name: String,
2909 values: serde_json::Map<String, serde_json::Value>,
2910}
2911
2912fn entity_field_applicability(
2919 selection_set: &SelectionSet,
2920 fragments: &HashMap<Name, Positioned<FragmentDefinition>>,
2921 type_name: &str,
2922) -> Vec<bool> {
2923 fn condition_matches(condition: Option<&Positioned<TypeCondition>>, type_name: &str) -> bool {
2924 condition.is_none_or(|condition| {
2925 let condition = condition.node.on.node.as_str();
2926 condition == type_name || condition == "_Entity"
2927 })
2928 }
2929
2930 fn collect(
2931 selection_set: &SelectionSet,
2932 fragments: &HashMap<Name, Positioned<FragmentDefinition>>,
2933 type_name: &str,
2934 parent_matches: bool,
2935 applicability: &mut Vec<bool>,
2936 ) {
2937 for selection in &selection_set.items {
2938 match &selection.node {
2939 Selection::Field(_) => applicability.push(parent_matches),
2940 Selection::FragmentSpread(spread) => {
2941 let Some(fragment) = fragments.get(&spread.node.fragment_name.node) else {
2942 continue;
2943 };
2944 collect(
2945 &fragment.node.selection_set.node,
2946 fragments,
2947 type_name,
2948 parent_matches
2949 && condition_matches(Some(&fragment.node.type_condition), type_name),
2950 applicability,
2951 );
2952 }
2953 Selection::InlineFragment(fragment) => collect(
2954 &fragment.node.selection_set.node,
2955 fragments,
2956 type_name,
2957 parent_matches
2958 && condition_matches(fragment.node.type_condition.as_ref(), type_name),
2959 applicability,
2960 ),
2961 }
2962 }
2963 }
2964
2965 let mut applicability = Vec::new();
2966 collect(
2967 selection_set,
2968 fragments,
2969 type_name,
2970 true,
2971 &mut applicability,
2972 );
2973 applicability
2974}
2975
2976fn entity_selection_fields<'ctx, 'a>(
2977 ctx: &'ctx ResolverContext<'a>,
2978 type_name: &str,
2979) -> Vec<SelectionField<'ctx>> {
2980 let applicability = entity_field_applicability(
2981 &ctx.ctx.item.node.selection_set.node,
2982 &ctx.ctx.query_env.fragments,
2983 type_name,
2984 );
2985 let fields: Vec<_> = ctx.field().selection_set().collect();
2986 debug_assert_eq!(fields.len(), applicability.len());
2987 fields
2988 .into_iter()
2989 .zip(applicability)
2990 .filter_map(|(field, applies)| applies.then_some(field))
2991 .collect()
2992}
2993
2994async fn resolve_entities<'a>(
2995 ctx: &ResolverContext<'a>,
2996 state: &EntityResolverState,
2997) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
2998 let representations = ctx.args.try_get("representations")?.list()?;
2999 let mut grouped: HashMap<String, Vec<EntityRepresentation>> = HashMap::new();
3000 let mut count = 0;
3001 for (index, representation) in representations.iter().enumerate() {
3002 count += 1;
3003 let value = accessor_to_json(&representation);
3004 let serde_json::Value::Object(values) = value else {
3005 return Err(async_graphql::Error::new(
3006 "entity representation must be an object",
3007 ));
3008 };
3009 let type_name = values
3010 .get("__typename")
3011 .and_then(serde_json::Value::as_str)
3012 .ok_or_else(|| {
3013 async_graphql::Error::new("entity representation is missing __typename")
3014 })?
3015 .to_string();
3016 grouped
3017 .entry(type_name.clone())
3018 .or_default()
3019 .push(EntityRepresentation {
3020 index,
3021 type_name,
3022 values,
3023 });
3024 }
3025
3026 let mut resolved: Vec<Option<FieldValue<'a>>> =
3027 std::iter::repeat_with(|| None).take(count).collect();
3028 for (type_name, representations) in grouped {
3029 let lookup = state.entities.get(&type_name).ok_or_else(|| {
3030 async_graphql::Error::new(format!("unknown federation entity \"{}\"", type_name))
3031 })?;
3032 let rows = resolve_entity_group(ctx, lookup, &representations, state).await?;
3033 for (ordinality, representation) in representations.into_iter().enumerate() {
3034 resolved[representation.index] = Some(match &rows[ordinality] {
3035 Some(row) => FieldValue::value(json_to_value(row.clone()))
3036 .with_type(representation.type_name),
3037 None => FieldValue::NULL,
3038 });
3039 }
3040 }
3041
3042 Ok(Some(FieldValue::list(resolved.into_iter().map(|value| {
3043 value.expect("every representation was resolved or errored")
3044 }))))
3045}
3046
3047async fn resolve_entity_group(
3048 ctx: &ResolverContext<'_>,
3049 lookup: &EntityLookup,
3050 representations: &[EntityRepresentation],
3051 state: &EntityResolverState,
3052) -> Result<Vec<Option<serde_json::Value>>, async_graphql::Error> {
3053 if representations.is_empty() {
3054 return Ok(Vec::new());
3055 }
3056
3057 let pool = ctx.data::<PgPool>()?;
3058 let gql_ctx = ctx.data::<GraphQLContext>()?;
3059 let mut bound_values = Vec::new();
3060 let mut value_rows = Vec::with_capacity(representations.len());
3061 for (ordinality, representation) in representations.iter().enumerate() {
3062 let normalized_values = normalized_entity_key_values(
3063 &representation.values,
3064 &lookup.key_columns,
3065 &lookup.type_name,
3066 )?;
3067 let mut values = Vec::with_capacity(lookup.key_columns.len() + 1);
3068 for (key_column, value) in lookup.key_columns.iter().zip(normalized_values) {
3069 values.push(format!(
3070 "${}::{}",
3071 bound_values.len() + 1,
3072 key_column.pg_type
3073 ));
3074 bound_values.push(value);
3075 }
3076 values.push(ordinality.to_string());
3077 value_rows.push(format!("({})", values.join(", ")));
3078 }
3079
3080 let representation_alias = "pgrst_entity_representation";
3081 let ordinality_column = "pgrst_entity_ordinality";
3082 let key_aliases: Vec<String> = (0..lookup.key_columns.len())
3083 .map(|index| format!("pgrst_entity_key_{index}"))
3084 .collect();
3085 let mut representation_columns: Vec<String> = key_aliases
3086 .iter()
3087 .map(|column| postrust_sql::escape_ident(column))
3088 .collect();
3089 representation_columns.push(postrust_sql::escape_ident(ordinality_column));
3090 let representations_sql = format!(
3091 "(VALUES {}) AS {} ({})",
3092 value_rows.join(", "),
3093 postrust_sql::escape_ident(representation_alias),
3094 representation_columns.join(", ")
3095 );
3096 let key_predicate = lookup
3097 .key_columns
3098 .iter()
3099 .zip(&key_aliases)
3100 .map(|(key_column, key_alias)| {
3101 format!(
3102 "{}.{} = {}.{}",
3103 postrust_sql::escape_ident(READ_ROW),
3104 postrust_sql::escape_ident(&key_column.column_name),
3105 postrust_sql::escape_ident(representation_alias),
3106 postrust_sql::escape_ident(key_alias)
3107 )
3108 })
3109 .collect::<Vec<_>>()
3110 .join(" AND ");
3111 let mut where_sql = format!(" WHERE ({key_predicate})");
3112
3113 let permission = permission_predicate(
3114 &gql_ctx.caller(),
3115 state.names.as_ref(),
3116 &lookup.schema_name,
3117 &lookup.table_name,
3118 )?;
3119 if let Some(predicate) = permission {
3120 let guard = gql_ctx
3121 .schema_cache
3122 .get()
3123 .await
3124 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3125 let cache = guard
3126 .as_ref()
3127 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3128 let scope = WhereScope::table(
3129 &lookup.schema_name,
3130 &lookup.table_name,
3131 &lookup.type_name,
3132 state.names.as_ref(),
3133 )
3134 .under_alias(READ_ROW)
3135 .with_resolution(cache, state.relationships.as_ref())
3136 .for_caller(gql_ctx.caller());
3137 let (filter_sql, filter_values) =
3138 build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
3139 if !filter_sql.is_empty() {
3140 where_sql = format!(
3141 "{} AND ({})",
3142 where_sql,
3143 filter_sql.trim_start_matches("WHERE ")
3144 );
3145 bound_values.extend(filter_values);
3146 }
3147 }
3148
3149 let source = format!(
3150 "{}.{} AS {}",
3151 postrust_sql::escape_ident(&lookup.schema_name),
3152 postrust_sql::escape_ident(&lookup.table_name),
3153 postrust_sql::escape_ident(READ_ROW)
3154 );
3155 let source_rows = format!(
3156 "SELECT {}.* FROM {}{}",
3157 postrust_sql::escape_ident(READ_ROW),
3158 source,
3159 where_sql
3160 );
3161 let mut projection = {
3162 let guard = gql_ctx
3163 .schema_cache
3164 .get()
3165 .await
3166 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3167 guard
3168 .as_ref()
3169 .and_then(|cache| {
3170 cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
3171 &lookup.schema_name,
3172 &lookup.table_name,
3173 ))
3174 })
3175 .and_then(|table| rename_projection(table, "src", state.names.as_ref()))
3176 .unwrap_or_else(|| "src.*".to_string())
3177 };
3178 let projected_rows = {
3179 let guard = gql_ctx
3180 .schema_cache
3181 .get()
3182 .await
3183 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3184 let cache = guard
3185 .as_ref()
3186 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3187 let table = cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
3188 &lookup.schema_name,
3189 &lookup.table_name,
3190 ));
3191 let selected_fields = entity_selection_fields(ctx, &lookup.type_name);
3192 let mut param_idx = bound_values.len() + 1;
3193 let computed = match table {
3194 Some(table) => computed_projections(
3195 table,
3196 selected_fields.iter().copied(),
3197 "src",
3198 state.names.as_ref(),
3199 cache,
3200 &mut param_idx,
3201 &mut bound_values,
3202 )?,
3203 None => Vec::new(),
3204 };
3205 let embeds = build_embed_expressions(
3206 &gql_ctx.caller(),
3207 cache,
3208 state.relationships.as_ref(),
3209 &lookup.type_name,
3210 "src",
3211 selected_fields,
3212 state.max_rows,
3213 &mut 0,
3214 &mut param_idx,
3215 &mut bound_values,
3216 state.names.as_ref(),
3217 )?;
3218 for expression in &computed {
3219 projection.push_str(", ");
3220 projection.push_str(expression);
3221 }
3222 for (field_name, expression) in &embeds {
3223 projection.push_str(", ");
3224 projection.push_str(expression);
3225 projection.push_str(" AS ");
3226 projection.push_str(&postrust_sql::escape_ident(field_name));
3227 }
3228 format!("SELECT {} FROM ({}) AS src", projection, source_rows)
3229 };
3230 let sql = format!(
3235 "SELECT json_build_array({}.{}, {}) FROM {} CROSS JOIN LATERAL ({}) AS t",
3236 postrust_sql::escape_ident(representation_alias),
3237 postrust_sql::escape_ident(ordinality_column),
3238 row_json("t", &lookup.row_column_types),
3239 representations_sql,
3240 projected_rows,
3241 );
3242 let mut tx = begin_with_session(pool, gql_ctx).await?;
3243 let rows = execute_query_on(&mut tx, &sql, &bound_values).await?;
3244 tx.commit().await?;
3245
3246 let mut by_ordinal = std::iter::repeat_with(|| None)
3247 .take(representations.len())
3248 .collect::<Vec<_>>();
3249 for result in rows {
3250 let serde_json::Value::Array(mut pair) = result else {
3251 return Err(async_graphql::Error::new(
3252 "entity query returned an invalid result",
3253 ));
3254 };
3255 if pair.len() != 2 {
3256 return Err(async_graphql::Error::new(
3257 "entity query returned an invalid result",
3258 ));
3259 }
3260 let row = pair.pop().expect("the result pair has two values");
3261 let ordinality = pair
3262 .pop()
3263 .and_then(|value| value.as_u64())
3264 .and_then(|value| usize::try_from(value).ok())
3265 .filter(|value| *value < by_ordinal.len())
3266 .ok_or_else(|| async_graphql::Error::new("entity query returned an invalid ordinal"))?;
3267 by_ordinal[ordinality] = Some(row);
3268 }
3269 Ok(by_ordinal)
3270}
3271
3272fn normalized_entity_key_values(
3276 values: &serde_json::Map<String, serde_json::Value>,
3277 key_columns: &[EntityKeyColumn],
3278 type_name: &str,
3279) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
3280 let mut key = Vec::with_capacity(key_columns.len());
3281 for key_column in key_columns {
3282 let value = values.get(&key_column.field_name).ok_or_else(|| {
3283 async_graphql::Error::new(format!(
3284 "entity representation for \"{}\" is missing key field \"{}\"",
3285 type_name, key_column.field_name
3286 ))
3287 })?;
3288 key.push(normalize_entity_key_value(type_name, key_column, value)?);
3289 }
3290 Ok(key)
3291}
3292
3293fn normalize_entity_key_value(
3294 type_name: &str,
3295 key_column: &EntityKeyColumn,
3296 value: &serde_json::Value,
3297) -> Result<serde_json::Value, async_graphql::Error> {
3298 let invalid = |expected: &str| {
3299 async_graphql::Error::new(format!(
3300 "entity representation for \"{}\" has invalid key field \"{}\": expected {}, found {}",
3301 type_name,
3302 key_column.field_name,
3303 expected,
3304 json_value_kind(value)
3305 ))
3306 };
3307
3308 if key_column.explicit_id {
3309 return normalize_graphql_id(value, &key_column.pg_type).ok_or_else(|| {
3310 invalid(&format!(
3311 "an ID compatible with PostgreSQL type \"{}\"",
3312 key_column.pg_type
3313 ))
3314 });
3315 }
3316
3317 let pg_type = key_column.pg_type.trim().to_ascii_lowercase();
3318 let normalized = if matches!(pg_type.as_str(), "int8" | "bigint") {
3319 match value {
3320 serde_json::Value::Number(number) => number.as_i64(),
3321 serde_json::Value::String(text) => text.parse::<i64>().ok(),
3322 _ => None,
3323 }
3324 .map(serde_json::Value::from)
3325 } else if integer_bounds(&pg_type).is_some() {
3326 value.as_i64().and_then(|integer| {
3327 let (min, max) = integer_bounds(&pg_type)?;
3328 (min..=max)
3329 .contains(&integer)
3330 .then(|| serde_json::Value::from(integer))
3331 })
3332 } else if matches!(
3333 pg_type.as_str(),
3334 "float4" | "float8" | "real" | "double precision"
3335 ) {
3336 value
3337 .as_f64()
3338 .and_then(serde_json::Number::from_f64)
3339 .map(serde_json::Value::Number)
3340 } else if matches!(pg_type.as_str(), "numeric" | "decimal") {
3341 match value {
3342 serde_json::Value::Number(number) => {
3343 Some(serde_json::Value::String(number.to_string()))
3344 }
3345 serde_json::Value::String(text) if text.parse::<sqlx::types::BigDecimal>().is_ok() => {
3346 Some(serde_json::Value::String(text.clone()))
3347 }
3348 _ => None,
3349 }
3350 } else if matches!(pg_type.as_str(), "bool" | "boolean") {
3351 value.as_bool().map(serde_json::Value::Bool)
3352 } else if matches!(pg_type.as_str(), "json" | "jsonb") {
3353 Some(value.clone())
3354 } else if is_array_type(&pg_type) {
3355 value.is_array().then(|| value.clone())
3356 } else {
3357 value
3358 .as_str()
3359 .map(|text| serde_json::Value::String(text.to_string()))
3360 };
3361
3362 normalized.ok_or_else(|| {
3363 invalid(&format!(
3364 "a value compatible with PostgreSQL type \"{}\"",
3365 key_column.pg_type
3366 ))
3367 })
3368}
3369
3370fn normalize_graphql_id(value: &serde_json::Value, pg_type: &str) -> Option<serde_json::Value> {
3371 if integer_bounds(pg_type).is_some() {
3372 let integer = match value {
3373 serde_json::Value::Number(number) => number.as_i64(),
3374 serde_json::Value::String(text) => text.parse::<i64>().ok(),
3375 _ => None,
3376 }?;
3377 let (min, max) = integer_bounds(pg_type)?;
3378 return (min..=max)
3379 .contains(&integer)
3380 .then(|| serde_json::Value::from(integer));
3381 }
3382 if pg_type.eq_ignore_ascii_case("uuid") {
3383 return normalize_uuid(value).map(serde_json::Value::String);
3384 }
3385 if is_text_type(pg_type) {
3386 return match value {
3387 serde_json::Value::String(s) => Some(serde_json::Value::String(s.clone())),
3388 serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => {
3389 Some(serde_json::Value::String(n.to_string()))
3390 }
3391 _ => None,
3392 };
3393 }
3394 None
3395}
3396
3397fn integer_bounds(pg_type: &str) -> Option<(i64, i64)> {
3398 match pg_type.trim().to_ascii_lowercase().as_str() {
3399 "int2" | "smallint" => Some((i16::MIN.into(), i16::MAX.into())),
3400 "int4" | "int" | "integer" => Some((i32::MIN.into(), i32::MAX.into())),
3401 "int8" | "bigint" => Some((i64::MIN, i64::MAX)),
3402 _ => None,
3403 }
3404}
3405
3406fn is_text_type(pg_type: &str) -> bool {
3407 matches!(
3408 pg_type.trim().to_ascii_lowercase().as_str(),
3409 "text" | "varchar" | "character varying" | "char" | "character" | "bpchar" | "citext"
3410 )
3411}
3412
3413fn normalize_uuid(value: &serde_json::Value) -> Option<String> {
3414 sqlx::types::Uuid::parse_str(value.as_str()?)
3415 .ok()
3416 .map(|uuid| uuid.to_string())
3417}
3418
3419fn json_value_kind(value: &serde_json::Value) -> &'static str {
3420 match value {
3421 serde_json::Value::Null => "null",
3422 serde_json::Value::Bool(_) => "a boolean",
3423 serde_json::Value::Number(_) => "a number",
3424 serde_json::Value::String(_) => "a string",
3425 serde_json::Value::Array(_) => "an array",
3426 serde_json::Value::Object(_) => "an object",
3427 }
3428}
3429
3430fn add_function_fields(
3437 mut root: Object,
3438 generated: &GeneratedSchema,
3439 volatile: bool,
3440 max_rows: Option<i64>,
3441 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
3442 names: Arc<crate::names::NameOverrides>,
3443) -> Object {
3444 let taken: HashSet<&str> = if volatile {
3449 generated
3450 .mutation_fields
3451 .iter()
3452 .map(|f| f.name.as_str())
3453 .collect()
3454 } else {
3455 generated
3456 .query_fields
3457 .iter()
3458 .map(|f| f.name.as_str())
3459 .collect()
3460 };
3461
3462 for function in &generated.function_fields {
3463 if function.volatile != volatile {
3464 continue;
3465 }
3466 if taken.contains(function.name.as_str()) {
3467 tracing::warn!(
3468 "not exposing {}.{}({}) -- a table already has a root field \
3469 called {}",
3470 function.schema_name,
3471 function.function_name,
3472 function.argument_signature(),
3473 function.name,
3474 );
3475 continue;
3476 }
3477 let spec = Arc::new(QueryFieldSpec {
3478 schema_name: function.returns_table.0.clone(),
3479 table_name: function.returns_table.1.clone(),
3480 type_name: function.returns.clone(),
3481 is_by_pk: false,
3482 pk_columns: Vec::new(),
3483 max_rows,
3484 relationships: Arc::clone(&relationships),
3485 names: Arc::clone(&names),
3486 call: Some(Arc::new(FunctionCall {
3487 schema: function.schema_name.clone(),
3488 name: function.function_name.clone(),
3489 arguments: function.arguments.clone(),
3490 session_argument: function.session_argument.clone(),
3491 })),
3492 });
3493
3494 let mut field = Field::new(
3495 &function.name,
3496 TypeRef::named_nn_list_nn(&function.returns),
3497 move |ctx| {
3498 let spec = Arc::clone(&spec);
3499 FieldFuture::new(async move { resolve_query(&ctx, &spec).await })
3500 },
3501 );
3502 if !function.arguments.is_empty() {
3503 field = field.argument(InputValue::new(
3504 "args",
3505 TypeRef::named_nn(format!("{}_args", function.name)),
3506 ));
3507 }
3508 field = field
3509 .argument(InputValue::new(
3510 "where",
3511 TypeRef::named(crate::input::bool_exp::bool_exp_type_name(
3512 &function.local_returns,
3513 )),
3514 ))
3515 .argument(InputValue::new(
3516 "order_by",
3517 TypeRef::named_nn_list(crate::input::order_by::order_by_type_name(
3518 &function.local_returns,
3519 )),
3520 ))
3521 .argument(InputValue::new(
3522 "distinct_on",
3523 TypeRef::named_nn_list(crate::input::order_by::select_column_type_name(
3524 &function.local_returns,
3525 )),
3526 ))
3527 .argument(InputValue::new("limit", TypeRef::named("Int")))
3528 .argument(InputValue::new("offset", TypeRef::named("Int")));
3529 if let Some(description) = &function.description {
3530 field = field.description(description);
3531 }
3532 root = root.field(field);
3533
3534 let agg_spec = Arc::new(AggregateSpec {
3539 schema_name: function.returns_table.0.clone(),
3540 table_name: function.returns_table.1.clone(),
3541 type_name: function.returns.clone(),
3542 max_rows,
3543 relationships: Arc::clone(&relationships),
3544 names: Arc::clone(&names),
3545 call: Some(Arc::new(FunctionCall {
3546 schema: function.schema_name.clone(),
3547 name: function.function_name.clone(),
3548 arguments: function.arguments.clone(),
3549 session_argument: function.session_argument.clone(),
3550 })),
3551 });
3552 let mut aggregate = Field::new(
3553 format!("{}_aggregate", function.name),
3554 TypeRef::named_nn(crate::schema::aggregate::aggregate_type_name(
3555 &function.local_returns,
3556 )),
3557 move |ctx| {
3558 let agg_spec = Arc::clone(&agg_spec);
3559 FieldFuture::new(async move { resolve_aggregate(&ctx, &agg_spec).await })
3560 },
3561 );
3562 if !function.arguments.is_empty() {
3563 aggregate = aggregate.argument(InputValue::new(
3564 "args",
3565 TypeRef::named_nn(format!("{}_args", function.name)),
3566 ));
3567 }
3568 aggregate = with_row_arguments(aggregate, &function.local_returns).description(format!(
3569 "fetch aggregated fields from the table: \"{}\"",
3570 function.returns_table.1
3571 ));
3572 root = root.field(aggregate);
3573 }
3574 root
3575}
3576
3577fn function_source(
3585 ctx: &ResolverContext<'_>,
3586 call: &FunctionCall,
3587 alias: &str,
3588 bound_values: &mut Vec<serde_json::Value>,
3589) -> Result<String, async_graphql::Error> {
3590 let given = ctx
3591 .args
3592 .try_get("args")
3593 .ok()
3594 .map(|v| accessor_to_json(&v))
3595 .unwrap_or_else(|| serde_json::json!({}));
3596 let mut passed = Vec::new();
3597 for (name, _, required) in &call.arguments {
3598 match given.get(name) {
3599 None if *required => {
3600 return Err(async_graphql::Error::new(format!(
3601 "{} needs the argument \"{}\"",
3602 call.name, name
3603 )))
3604 }
3605 None => continue,
3608 Some(value) => {
3609 let (_, pg_type, _) = call
3616 .arguments
3617 .iter()
3618 .find(|(argument, _, _)| argument == name)
3619 .expect("iterating the arguments");
3620 passed.push(format!(
3621 "{} => ${}::{}",
3622 postrust_sql::escape_ident(name),
3623 bound_values.len() + 1,
3624 pg_type
3625 ));
3626 bound_values.push(value.clone());
3627 }
3628 }
3629 }
3630 if let Some(session) = &call.session_argument {
3634 passed.push(format!(
3635 "{} => {}",
3636 postrust_sql::escape_ident(session),
3637 SESSION_ARGUMENT
3638 ));
3639 }
3640 Ok(format!(
3641 "{}.{}({}) AS {}",
3642 postrust_sql::escape_ident(&call.schema),
3643 postrust_sql::escape_ident(&call.name),
3644 passed.join(", "),
3645 postrust_sql::escape_ident(alias)
3646 ))
3647}
3648
3649struct FunctionCall {
3651 schema: String,
3652 name: String,
3653 arguments: Vec<(String, String, bool)>,
3654 session_argument: Option<String>,
3657}
3658
3659struct AggregateSpec {
3661 schema_name: String,
3662 table_name: String,
3663 type_name: String,
3664 max_rows: Option<i64>,
3665 relationships: Arc<HashMap<String, Vec<RelationshipField>>>,
3666 names: Arc<crate::names::NameOverrides>,
3667 call: Option<Arc<FunctionCall>>,
3671}
3672
3673async fn resolve_aggregate<'a>(
3680 ctx: &ResolverContext<'a>,
3681 spec: &AggregateSpec,
3682) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
3683 Ok(Some(FieldValue::value(aggregate_value(ctx, spec).await?)))
3684}
3685
3686async fn aggregate_value(
3691 ctx: &ResolverContext<'_>,
3692 spec: &AggregateSpec,
3693) -> Result<Value, async_graphql::Error> {
3694 use crate::schema::aggregate as agg;
3695
3696 let pool = ctx.data::<PgPool>()?;
3697 let gql_ctx = ctx.data::<GraphQLContext>()?;
3698
3699 let mut bound_values: Vec<serde_json::Value> = Vec::new();
3700 let source = match &spec.call {
3704 None => format!(
3705 "{}.{}",
3706 postrust_sql::escape_ident(&spec.schema_name),
3707 postrust_sql::escape_ident(&spec.table_name)
3708 ),
3709 Some(call) => function_source(ctx, call, &spec.table_name, &mut bound_values)?,
3710 };
3711
3712 let mut where_sql = String::new();
3713 {
3714 let requested = ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v));
3718 let permission = permission_predicate(
3719 &gql_ctx.caller(),
3720 spec.names.as_ref(),
3721 &spec.schema_name,
3722 &spec.table_name,
3723 )?;
3724 if let Some(predicate) = and_predicates(requested, permission) {
3725 let guard = gql_ctx
3726 .schema_cache
3727 .get()
3728 .await
3729 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3730 let cache = guard
3731 .as_ref()
3732 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3733 let scope = match &spec.call {
3740 None => WhereScope::table(
3741 &spec.schema_name,
3742 &spec.table_name,
3743 &spec.type_name,
3744 spec.names.as_ref(),
3745 )
3746 .with_resolution(cache, spec.relationships.as_ref()),
3747 Some(_) => WhereScope::for_alias(
3748 &spec.schema_name,
3749 &spec.table_name,
3750 &spec.table_name,
3751 &spec.type_name,
3752 cache,
3753 spec.relationships.as_ref(),
3754 spec.names.as_ref(),
3755 ),
3756 }
3757 .for_caller(gql_ctx.caller());
3758 let (sql, values) =
3759 build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
3760 if !sql.is_empty() {
3761 where_sql = format!(" {}", sql);
3762 bound_values.extend(values);
3763 }
3764 }
3765 }
3766
3767 let order_sql = build_order_by_clause(
3768 ctx,
3769 &gql_ctx.schema_cache,
3770 &spec.schema_name,
3771 &spec.table_name,
3772 &spec.type_name,
3773 spec.relationships.as_ref(),
3774 &format!(
3775 "{}.{}",
3776 postrust_sql::escape_ident(&spec.schema_name),
3777 postrust_sql::escape_ident(&spec.table_name)
3778 ),
3779 spec.names.as_ref(),
3780 )
3781 .await?;
3782
3783 let requested_limit = ctx.args.try_get("limit").ok().and_then(|v| v.i64().ok());
3784 let offset = ctx.args.try_get("offset").ok().and_then(|v| v.i64().ok());
3785 let ceiling = match (
3786 spec.max_rows,
3787 permission_limit(
3788 &gql_ctx.caller(),
3789 spec.names.as_ref(),
3790 &spec.schema_name,
3791 &spec.table_name,
3792 ),
3793 ) {
3794 (Some(configured), Some(granted)) => Some(configured.min(granted)),
3795 (only, None) | (None, only) => only,
3796 };
3797 let limit = match (requested_limit, ceiling) {
3798 (Some(requested), Some(ceiling)) => Some(requested.min(ceiling)),
3799 (Some(requested), None) => Some(requested),
3800 (None, ceiling) => ceiling,
3801 };
3802
3803 let rows = format!("SELECT * FROM {}{}{}", source, where_sql, order_sql);
3804
3805 let mut inner = rows.clone();
3807 if let Some(limit) = limit {
3808 inner.push_str(&format!(" LIMIT {}", limit));
3809 }
3810 if let Some(offset) = offset {
3811 inner.push_str(&format!(" OFFSET {}", offset));
3812 }
3813
3814 let mut counted = rows;
3828 if let Some(limit) = requested_limit {
3829 counted.push_str(&format!(" LIMIT {}", limit));
3830 }
3831 if let Some(offset) = offset {
3832 counted.push_str(&format!(" OFFSET {}", offset));
3833 }
3834
3835 let mut wants_nodes = false;
3840 let mut wants_aggregate = false;
3841 let mut wanted: BTreeMap<String, Vec<String>> = BTreeMap::new();
3842 let mut counts: Vec<(String, String)> = Vec::new();
3845 for selection in ctx.field().selection_set() {
3846 match selection.name() {
3847 "nodes" => wants_nodes = true,
3848 "aggregate" => {
3849 wants_aggregate = true;
3850 for function in selection.selection_set() {
3851 if function.name() == "__typename" {
3853 continue;
3854 }
3855 if function.name() == "count" {
3856 counts.push((
3857 function.alias().unwrap_or("count").to_string(),
3858 count_expression(
3859 function,
3860 (&spec.schema_name, &spec.table_name),
3861 None,
3862 spec.names.as_ref(),
3863 ),
3864 ));
3865 continue;
3866 }
3867 let columns = wanted.entry(function.name().to_string()).or_default();
3870 for column in function.selection_set() {
3871 let name = column.name().to_string();
3872 if name != "__typename" && !columns.contains(&name) {
3873 columns.push(name);
3874 }
3875 }
3876 }
3877 }
3878 _ => {}
3879 }
3880 }
3881
3882 let mut result = async_graphql::indexmap::IndexMap::new();
3883
3884 if wants_aggregate {
3887 let mut parts = match counts.iter().any(|(key, _)| key == "count") {
3891 true => Vec::new(),
3892 false => vec!["'count', count(*)".to_string()],
3893 };
3894 for (key, expression) in &counts {
3895 parts.push(format!(
3896 "{}, {}",
3897 postrust_sql::quote_literal(key),
3898 expression
3899 ));
3900 }
3901 for (function, columns) in &wanted {
3902 let sql_function = agg::NUMERIC_AGGREGATES
3906 .iter()
3907 .chain(agg::ORDERED_AGGREGATES.iter())
3908 .find(|(name, _)| name == function)
3909 .map(|(name, _)| *name)
3910 .ok_or_else(|| {
3911 async_graphql::Error::new(format!("unknown aggregate \"{}\"", function))
3912 })?;
3913 let per_column: Vec<String> = columns
3914 .iter()
3915 .map(|field| {
3916 let source = spec
3917 .names
3918 .column_source(&spec.schema_name, &spec.table_name, field)
3919 .unwrap_or(field);
3920 format!(
3921 "{}, {}({})",
3922 postrust_sql::quote_literal(field),
3923 sql_function,
3924 postrust_sql::escape_ident(source)
3925 )
3926 })
3927 .collect();
3928 parts.push(format!(
3929 "'{}', json_build_object({})",
3930 sql_function,
3931 per_column.join(", ")
3932 ));
3933 }
3934
3935 let sql = format!(
3936 "SELECT json_build_object({}) FROM ({}) AS pgrst_agg",
3937 parts.join(", "),
3938 counted
3939 );
3940 let mut conn = begin_with_session(pool, gql_ctx).await?;
3941 let rows = execute_query_on(&mut conn, &sql, &bound_values).await?;
3942 conn.commit().await?;
3943 if let Some(first) = rows.into_iter().next() {
3944 if let Value::Object(map) = json_to_value(first) {
3945 result.insert(async_graphql::Name::new("aggregate"), Value::Object(map));
3946 }
3947 }
3948 }
3949
3950 if wants_nodes {
3951 let nodes = ctx
3957 .field()
3958 .selection_set()
3959 .find(|selection| selection.name() == "nodes")
3960 .ok_or_else(|| async_graphql::Error::new("nodes was asked for and then was not"))?;
3961
3962 let mut node_values = bound_values.clone();
3966 let (projection, row_column_types) = {
3967 let guard = gql_ctx
3968 .schema_cache
3969 .get()
3970 .await
3971 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
3972 let cache = guard
3973 .as_ref()
3974 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
3975 let qi = postrust_core::api_request::QualifiedIdentifier::new(
3976 &spec.schema_name,
3977 &spec.table_name,
3978 );
3979 let table = cache.get_table(&qi);
3980 let mut param_idx = node_values.len() + 1;
3981 let computed = match table {
3982 Some(table) => computed_projections(
3983 table,
3984 nodes.selection_set(),
3985 "src",
3986 spec.names.as_ref(),
3987 cache,
3988 &mut param_idx,
3989 &mut node_values,
3990 )?,
3991 None => Vec::new(),
3992 };
3993 let embeds = build_embed_expressions(
3994 &gql_ctx.caller(),
3995 cache,
3996 spec.relationships.as_ref(),
3997 &spec.type_name,
3998 "src",
3999 nodes.selection_set(),
4000 spec.max_rows,
4001 &mut 0,
4002 &mut param_idx,
4003 &mut node_values,
4004 spec.names.as_ref(),
4005 )?;
4006 let mut projection = table
4010 .and_then(|table| rename_projection(table, "src", spec.names.as_ref()))
4011 .unwrap_or_else(|| "src.*".to_string());
4012 for expression in &computed {
4013 projection.push_str(", ");
4014 projection.push_str(expression);
4015 }
4016 for (field_name, expression) in &embeds {
4017 projection.push_str(", ");
4018 projection.push_str(expression);
4019 projection.push_str(" AS ");
4020 projection.push_str(&postrust_sql::escape_ident(field_name));
4021 }
4022 (
4023 projection,
4024 table
4025 .map(|table| exposed_column_types(table, spec.names.as_ref()))
4026 .unwrap_or_default(),
4027 )
4028 };
4029
4030 let sql = format!(
4031 "SELECT {} FROM (SELECT {} FROM ({}) AS src) AS pgrst_nodes",
4032 row_json("pgrst_nodes", &row_column_types),
4033 projection,
4034 inner
4035 );
4036 let mut conn = begin_with_session(pool, gql_ctx).await?;
4037 let rows = execute_query_on(&mut conn, &sql, &node_values).await?;
4038 conn.commit().await?;
4039 result.insert(
4040 async_graphql::Name::new("nodes"),
4041 Value::List(rows.into_iter().map(json_to_value).collect()),
4042 );
4043 }
4044
4045 let _ = &spec.type_name;
4046 Ok(Value::Object(result))
4047}
4048
4049async fn resolve_query<'a>(
4051 ctx: &ResolverContext<'a>,
4052 spec: &QueryFieldSpec,
4053) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
4054 Ok(rows_as_field_value(
4055 query_rows(ctx, spec).await?,
4056 spec.is_by_pk,
4057 ))
4058}
4059
4060async fn query_rows(
4066 ctx: &ResolverContext<'_>,
4067 spec: &QueryFieldSpec,
4068) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
4069 let schema_name = spec.schema_name.as_str();
4070 let table_name = spec.table_name.as_str();
4071 let type_name = spec.type_name.as_str();
4072 let is_by_pk = spec.is_by_pk;
4073 let pk_columns = spec.pk_columns.as_slice();
4074 let max_rows = spec.max_rows;
4075 let relationships = spec.relationships.as_ref();
4076
4077 let pool = ctx.data::<PgPool>()?;
4078 let gql_ctx = ctx.data::<GraphQLContext>()?;
4079
4080 debug!("Resolving query for table: {}", table_name);
4081
4082 let requested_limit: Option<i64> = ctx.args.try_get("limit").ok().and_then(|v| v.i64().ok());
4084
4085 let offset: Option<i64> = ctx.args.try_get("offset").ok().and_then(|v| v.i64().ok());
4086
4087 let limit: Option<i64> = if is_by_pk {
4092 Some(1)
4093 } else {
4094 let ceiling = match (
4098 max_rows,
4099 permission_limit(
4100 &gql_ctx.caller(),
4101 spec.names.as_ref(),
4102 schema_name,
4103 table_name,
4104 ),
4105 ) {
4106 (Some(configured), Some(granted)) => Some(configured.min(granted)),
4107 (only, None) | (None, only) => only,
4108 };
4109 match (requested_limit, ceiling) {
4110 (Some(requested), Some(ceiling)) => Some(requested.min(ceiling)),
4111 (Some(requested), None) => Some(requested),
4112 (None, ceiling) => ceiling,
4113 }
4114 };
4115
4116 let mut where_sql = String::new();
4124 let mut bound_values: Vec<serde_json::Value> = Vec::new();
4125
4126 let source = match &spec.call {
4130 None => format!(
4136 "{}.{} AS {}",
4137 postrust_sql::escape_ident(schema_name),
4138 postrust_sql::escape_ident(table_name),
4139 postrust_sql::escape_ident(READ_ROW)
4140 ),
4141 Some(call) => function_source(ctx, call, table_name, &mut bound_values)?,
4142 };
4143
4144 let source_ref = match &spec.call {
4147 None => postrust_sql::escape_ident(READ_ROW),
4148 Some(_) => postrust_sql::escape_ident(table_name),
4149 };
4150
4151 if is_by_pk {
4152 if pk_columns.is_empty() {
4153 return Err(async_graphql::Error::new(format!(
4154 "\"{}\" has no primary key, so it cannot be queried by key",
4155 table_name
4156 )));
4157 }
4158
4159 let mut conditions = Vec::with_capacity(pk_columns.len());
4160 for (idx, (col_name, pg_type)) in pk_columns.iter().enumerate() {
4161 let field = spec
4162 .names
4163 .column(schema_name, table_name, col_name)
4164 .unwrap_or(col_name);
4165 let value = ctx.args.try_get(field).map_err(|_| {
4166 async_graphql::Error::new(format!(
4167 "missing required primary key argument \"{}\"",
4168 field
4169 ))
4170 })?;
4171
4172 conditions.push(format!(
4173 "{} = ${}::{}",
4174 postrust_sql::escape_ident(col_name),
4175 idx + 1,
4176 pg_type
4177 ));
4178 bound_values.push(accessor_to_json(&value));
4179 }
4180 where_sql = format!(" WHERE {}", conditions.join(" AND "));
4181 }
4182
4183 {
4188 let requested = match is_by_pk {
4189 true => None,
4190 false => ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v)),
4191 };
4192 let permission = permission_predicate(
4193 &gql_ctx.caller(),
4194 spec.names.as_ref(),
4195 schema_name,
4196 table_name,
4197 )?;
4198
4199 if let Some(predicate) = and_predicates(requested, permission) {
4200 let guard = gql_ctx
4201 .schema_cache
4202 .get()
4203 .await
4204 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4205 let cache = guard
4206 .as_ref()
4207 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4208 let scope = match &spec.call {
4209 None => WhereScope::table(schema_name, table_name, type_name, spec.names.as_ref())
4210 .under_alias(READ_ROW)
4211 .with_resolution(cache, relationships)
4212 .for_caller(gql_ctx.caller()),
4213 Some(_) => WhereScope::for_alias(
4216 schema_name,
4217 table_name,
4218 table_name,
4219 type_name,
4220 cache,
4221 relationships,
4222 spec.names.as_ref(),
4223 )
4224 .for_caller(gql_ctx.caller()),
4225 };
4226 let (filter_sql, filter_values) =
4227 build_where_clause(Some(&predicate), bound_values.len() + 1, &scope)?;
4228 if !filter_sql.is_empty() {
4229 where_sql = match where_sql.is_empty() {
4232 true => format!(" {}", filter_sql),
4233 false => format!(
4234 "{} AND ({})",
4235 where_sql,
4236 filter_sql.trim_start_matches("WHERE ")
4237 ),
4238 };
4239 bound_values.extend(filter_values);
4240 }
4241 }
4242 }
4243
4244 let (order_sql, distinct_on) = if is_by_pk {
4247 (String::new(), Vec::new())
4248 } else {
4249 (
4250 build_order_by_clause(
4251 ctx,
4252 &gql_ctx.schema_cache,
4253 schema_name,
4254 table_name,
4255 type_name,
4256 relationships,
4257 &source_ref,
4258 spec.names.as_ref(),
4259 )
4260 .await?,
4261 build_distinct_on(
4262 ctx,
4263 &gql_ctx.schema_cache,
4264 schema_name,
4265 table_name,
4266 spec.names.as_ref(),
4267 )
4268 .await?,
4269 )
4270 };
4271
4272 let (distinct_sql, order_sql) = {
4280 let written = order_sql.strip_prefix(" ORDER BY ");
4281 let (prefix, order) = distinct_on_clause(&distinct_on, written).map_err(|error| {
4284 at_path(
4285 error,
4286 &format!(
4287 "$.selectionSet.{}.args",
4288 ctx.ctx.field().alias().unwrap_or(ctx.ctx.field().name())
4289 ),
4290 )
4291 })?;
4292 (
4293 prefix,
4294 match order {
4295 Some(order) => format!(" ORDER BY {}", order),
4296 None => String::new(),
4297 },
4298 )
4299 };
4300
4301 let (computed, row_column_types) = {
4304 let guard = gql_ctx
4305 .schema_cache
4306 .get()
4307 .await
4308 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4309 match guard.as_ref() {
4310 Some(cache) => {
4311 let qi =
4312 postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
4313 match cache.get_table(&qi) {
4314 Some(table) => {
4315 let mut param_idx = bound_values.len() + 1;
4316 (
4317 computed_projections(
4318 table,
4319 ctx.field().selection_set(),
4320 "src",
4321 spec.names.as_ref(),
4322 cache,
4323 &mut param_idx,
4324 &mut bound_values,
4325 )?,
4326 exposed_column_types(table, spec.names.as_ref()),
4327 )
4328 }
4329 None => (Vec::new(), HashMap::new()),
4330 }
4331 }
4332 None => (Vec::new(), HashMap::new()),
4333 }
4334 };
4335 let mut inner = format!(
4339 "SELECT {}* FROM {}{}{}",
4340 distinct_sql, source, where_sql, order_sql
4341 );
4342
4343 if let Some(limit) = limit {
4344 inner.push_str(&format!(" LIMIT {}", limit));
4345 }
4346
4347 if let Some(offset) = offset {
4348 inner.push_str(&format!(" OFFSET {}", offset));
4349 }
4350
4351 let embed_expressions = {
4354 let guard = gql_ctx
4355 .schema_cache
4356 .get()
4357 .await
4358 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4359 match guard.as_ref() {
4360 Some(cache) => {
4361 let mut param_idx = bound_values.len() + 1;
4366 build_embed_expressions(
4367 &gql_ctx.caller(),
4368 cache,
4369 relationships,
4370 type_name,
4371 "src",
4372 ctx.field().selection_set(),
4373 max_rows,
4374 &mut 0,
4375 &mut param_idx,
4376 &mut bound_values,
4377 spec.names.as_ref(),
4378 )?
4379 }
4380 None => Vec::new(),
4381 }
4382 };
4383
4384 let renamed = {
4392 let guard = gql_ctx
4393 .schema_cache
4394 .get()
4395 .await
4396 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4397 guard
4398 .as_ref()
4399 .and_then(|cache| {
4400 cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
4401 schema_name,
4402 table_name,
4403 ))
4404 })
4405 .and_then(|table| rename_projection(table, "src", spec.names.as_ref()))
4406 };
4407 let inner = if embed_expressions.is_empty() && computed.is_empty() && renamed.is_none() {
4408 inner
4409 } else {
4410 let mut projection = renamed.unwrap_or_else(|| "src.*".to_string());
4411 for expression in &computed {
4412 projection.push_str(", ");
4413 projection.push_str(expression);
4414 }
4415 for (field_name, expression) in &embed_expressions {
4416 projection.push_str(", ");
4417 projection.push_str(expression);
4418 projection.push_str(" AS ");
4419 projection.push_str(&postrust_sql::escape_ident(field_name));
4420 }
4421 format!("SELECT {} FROM ({}) AS src", projection, inner)
4422 };
4423
4424 let sql = format!(
4425 "SELECT {} FROM ({}) t",
4426 row_json("t", &row_column_types),
4427 inner
4428 );
4429
4430 let mut tx = begin_with_session(pool, gql_ctx).await?;
4434
4435 let mut result = execute_query_on(&mut tx, &sql, &bound_values).await?;
4437
4438 if embed_expressions.is_empty() {
4440 let guard = gql_ctx
4441 .schema_cache
4442 .get()
4443 .await
4444 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4445 let cache = guard
4446 .as_ref()
4447 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4448
4449 let embed_ctx = EmbedContext {
4450 schema_cache: cache,
4451 relationships,
4452 max_rows,
4453 };
4454
4455 embed_relationships(&mut tx, &embed_ctx, type_name, ctx.field(), &mut result).await?;
4456 }
4457
4458 tx.commit().await?;
4459
4460 Ok(result)
4461}
4462
4463fn rows_as_field_value<'a>(rows: Vec<serde_json::Value>, is_by_pk: bool) -> Option<FieldValue<'a>> {
4468 match is_by_pk {
4469 true => rows
4470 .into_iter()
4471 .next()
4472 .map(|v| FieldValue::value(json_to_value(v))),
4473 false => Some(FieldValue::list(
4474 rows.into_iter()
4475 .map(|v| FieldValue::value(json_to_value(v))),
4476 )),
4477 }
4478}
4479
4480#[allow(clippy::too_many_arguments)]
4482async fn resolve_mutation<'a>(
4483 ctx: &ResolverContext<'a>,
4484 schema_name: &str,
4485 table_name: &str,
4486 mutation_type: MutationType,
4487 pk_columns: &[(String, String)],
4488 relationships: &Arc<HashMap<String, Vec<RelationshipField>>>,
4489 type_names: &Arc<HashMap<(String, String), String>>,
4490 names: &Arc<crate::names::NameOverrides>,
4491 max_rows: Option<i64>,
4492) -> Result<Option<FieldValue<'a>>, async_graphql::Error> {
4493 let pool = ctx.data::<PgPool>()?;
4494 let gql_ctx = ctx.data::<GraphQLContext>()?;
4495
4496 debug!(
4497 "Resolving mutation for table: {} type: {:?}",
4498 table_name, mutation_type
4499 );
4500
4501 let type_name = type_names
4507 .get(&(schema_name.to_string(), table_name.to_string()))
4508 .cloned()
4509 .unwrap_or_else(|| table_name.to_string());
4510
4511 let by_key = matches!(
4512 mutation_type,
4513 MutationType::InsertOne | MutationType::UpdateByPk | MutationType::DeleteByPk
4514 );
4515 let returning = if by_key {
4516 Some(ctx.field())
4517 } else {
4518 ctx.field()
4519 .selection_set()
4520 .find(|selection| selection.name() == "returning")
4521 };
4522
4523 if mutation_type == MutationType::UpdateMany {
4528 let updates = ctx
4529 .args
4530 .try_get("updates")
4531 .ok()
4532 .map(|v| accessor_to_json(&v))
4533 .unwrap_or(serde_json::Value::Null);
4534 let serde_json::Value::Array(entries) = updates else {
4535 return Err(async_graphql::Error::new(
4536 "\"updates\" takes a list of {where, _set, …} objects",
4537 ));
4538 };
4539 let column_types = column_types_of(&gql_ctx.schema_cache, schema_name, table_name).await;
4540 let mut answers: Vec<FieldValue<'_>> = Vec::with_capacity(entries.len());
4541 for entry in entries {
4542 let serde_json::Value::Object(entry) = entry else {
4543 return Err(async_graphql::Error::new(
4544 "each update is an object of {where, _set, …}",
4545 ));
4546 };
4547 let operators: Vec<(&'static str, serde_json::Value)> = UPDATE_OPERATORS
4548 .iter()
4549 .filter_map(|name| entry.get(*name).map(|value| (*name, value.clone())))
4550 .filter(|(_, value)| !value.is_null())
4551 .collect();
4552 let rows = execute_update(
4553 pool,
4554 gql_ctx,
4555 schema_name,
4556 table_name,
4557 &type_name,
4558 operators,
4559 column_types.clone(),
4560 entry.get("where").cloned(),
4561 relationships.as_ref(),
4562 names.as_ref(),
4563 )
4564 .await?;
4565 let affected = rows.len();
4566 let rows = match returning {
4567 Some(returning) if !rows.is_empty() => {
4568 reread_returning(
4569 pool,
4570 gql_ctx,
4571 schema_name,
4572 table_name,
4573 &type_name,
4574 rows,
4575 returning,
4576 relationships.as_ref(),
4577 names.as_ref(),
4578 max_rows,
4579 )
4580 .await?
4581 }
4582 _ => rows,
4583 };
4584 answers.extend(mutation_result(rows, affected, false));
4585 }
4586 return Ok(Some(FieldValue::list(answers)));
4587 }
4588
4589 let (result, affected) = match mutation_type {
4590 MutationType::Insert | MutationType::InsertOne => {
4591 let objects = ctx
4592 .args
4593 .try_get("objects")
4594 .ok()
4595 .map(|v| accessor_to_json(&v))
4596 .or_else(|| {
4597 ctx.args
4600 .try_get("object")
4601 .ok()
4602 .map(|v| serde_json::Value::Array(vec![accessor_to_json(&v)]))
4603 })
4604 .unwrap_or_else(|| serde_json::Value::Array(vec![]));
4605
4606 let guard = gql_ctx
4607 .schema_cache
4608 .get()
4609 .await
4610 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
4611 let cache = guard
4612 .as_ref()
4613 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
4614 let here = format!(
4618 "$.selectionSet.{}",
4619 ctx.ctx.field().alias().unwrap_or(ctx.ctx.field().name())
4620 );
4621 let named = match mutation_type {
4624 MutationType::InsertOne => "object",
4625 _ => "objects",
4626 };
4627 let context = InsertContext {
4628 on_conflict: ctx
4629 .args
4630 .try_get("on_conflict")
4631 .ok()
4632 .map(|v| accessor_to_json(&v))
4633 .filter(|v| !v.is_null()),
4634 cache,
4635 relationships: relationships.as_ref(),
4636 type_names: type_names.as_ref(),
4637 names: names.as_ref(),
4638 caller: gql_ctx.caller(),
4639 row: String::new(),
4642 objects: format!("{}.args.{}", here, named),
4643 conflict: format!("{}.args.on_conflict", here),
4644 };
4645
4646 execute_insert(
4647 pool,
4648 gql_ctx,
4649 schema_name,
4650 table_name,
4651 objects,
4652 &context,
4653 mutation_type == MutationType::InsertOne,
4654 )
4655 .await?
4656 }
4657 MutationType::UpdateMany | MutationType::Update | MutationType::UpdateByPk => {
4660 let operators: Vec<(&'static str, serde_json::Value)> = UPDATE_OPERATORS
4664 .iter()
4665 .filter_map(|name| {
4666 ctx.args
4667 .try_get(name)
4668 .ok()
4669 .map(|v| (*name, accessor_to_json(&v)))
4670 })
4671 .filter(|(_, value)| !value.is_null())
4672 .collect();
4673
4674 let where_clause = if mutation_type == MutationType::UpdateByPk {
4675 Some(pk_where_from_args(
4676 ctx,
4677 schema_name,
4678 table_name,
4679 pk_columns,
4680 names.as_ref(),
4681 )?)
4682 } else {
4683 ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v))
4684 };
4685 let where_clause = and_predicates(
4689 where_clause,
4690 permission_filter(
4691 &gql_ctx.caller(),
4692 names.as_ref(),
4693 schema_name,
4694 table_name,
4695 crate::role::Verb::Update,
4696 )?,
4697 );
4698
4699 execute_update(
4700 pool,
4701 gql_ctx,
4702 schema_name,
4703 table_name,
4704 &type_name,
4705 operators,
4706 column_types_of(&gql_ctx.schema_cache, schema_name, table_name).await,
4707 where_clause,
4708 relationships.as_ref(),
4709 names.as_ref(),
4710 )
4711 .await
4712 .map(|rows| {
4713 let count = rows.len();
4714 (rows, count)
4715 })?
4716 }
4717 MutationType::Delete | MutationType::DeleteByPk => {
4718 let where_clause = if mutation_type == MutationType::DeleteByPk {
4719 Some(pk_where_from_args(
4720 ctx,
4721 schema_name,
4722 table_name,
4723 pk_columns,
4724 names.as_ref(),
4725 )?)
4726 } else {
4727 ctx.args.try_get("where").ok().map(|v| accessor_to_json(&v))
4728 };
4729 let where_clause = and_predicates(
4730 where_clause,
4731 permission_filter(
4732 &gql_ctx.caller(),
4733 names.as_ref(),
4734 schema_name,
4735 table_name,
4736 crate::role::Verb::Delete,
4737 )?,
4738 );
4739
4740 execute_delete(
4741 pool,
4742 gql_ctx,
4743 schema_name,
4744 table_name,
4745 &type_name,
4746 where_clause,
4747 returning,
4748 relationships.as_ref(),
4749 names.as_ref(),
4750 max_rows,
4751 )
4752 .await
4753 .map(|rows| {
4754 let count = rows.len();
4755 (rows, count)
4756 })?
4757 }
4758 };
4759
4760 let is_delete = matches!(
4761 mutation_type,
4762 MutationType::Delete | MutationType::DeleteByPk
4763 );
4764 let result = match returning {
4765 Some(returning) if !result.is_empty() && !is_delete => {
4766 reread_returning(
4767 pool,
4768 gql_ctx,
4769 schema_name,
4770 table_name,
4771 &type_name,
4772 result,
4773 returning,
4774 relationships.as_ref(),
4775 names.as_ref(),
4776 max_rows,
4777 )
4778 .await?
4779 }
4780 _ => result,
4781 };
4782
4783 Ok(mutation_result(result, affected, by_key))
4784}
4785
4786async fn write_tx<'a>(
4794 gql_ctx: &'a GraphQLContext,
4795 pool: &PgPool,
4796) -> Result<
4797 tokio::sync::MutexGuard<'a, Option<sqlx::Transaction<'static, sqlx::Postgres>>>,
4798 async_graphql::Error,
4799> {
4800 let mut guard = gql_ctx.write.lock().await;
4801 if guard.is_none() {
4802 *guard = Some(begin_with_session(pool, gql_ctx).await?);
4803 }
4804 Ok(guard)
4805}
4806
4807async fn begin_with_session(
4824 pool: &PgPool,
4825 gql_ctx: &GraphQLContext,
4826) -> Result<sqlx::Transaction<'static, sqlx::Postgres>, async_graphql::Error> {
4827 let mut tx = pool.begin().await?;
4828 gql_ctx.session().apply_sqlx(&mut tx).await?;
4829 Ok(tx)
4830}
4831
4832fn row_json(expr: &str, column_types: &HashMap<String, String>) -> String {
4843 let mut shapes: Vec<(&String, &String)> = column_types
4844 .iter()
4845 .filter(|(_, pg_type)| matches!(pg_type.as_str(), "geometry" | "geography"))
4846 .collect();
4847 if shapes.is_empty() {
4848 return format!("row_to_json({})", expr);
4849 }
4850 shapes.sort();
4851
4852 let overrides: Vec<String> = shapes
4853 .iter()
4854 .map(|(name, _)| {
4855 format!(
4856 "{}, ST_AsGeoJSON({}.{}, 9, 4)::jsonb",
4862 postrust_sql::quote_literal(name),
4863 expr,
4864 postrust_sql::escape_ident(name)
4865 )
4866 })
4867 .collect();
4868 format!(
4869 "(to_jsonb({}) || jsonb_build_object({}))",
4870 expr,
4871 overrides.join(", ")
4872 )
4873}
4874
4875async fn execute_query_on(
4878 conn: &mut sqlx::PgConnection,
4879 sql: &str,
4880 params: &[serde_json::Value],
4881) -> Result<Vec<serde_json::Value>, async_graphql::Error> {
4882 use sqlx::Row;
4883
4884 trace!("Executing SQL: {}", sql);
4885
4886 let mut query = sqlx::query(AssertSqlSafe(sql));
4888 for param in params {
4889 query = bind_json_value(query, param);
4890 }
4891 let rows = query.fetch_all(&mut *conn).await.map_err(database_error)?;
4892
4893 let results: Vec<serde_json::Value> = rows
4896 .into_iter()
4897 .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
4898 .collect();
4899
4900 Ok(results)
4901}
4902
4903fn check_geojson(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4916 fn refuse<T>(message: &str) -> Result<T, async_graphql::Error> {
4917 Err(coded_error("parse-failed", message))
4918 }
4919
4920 fn position(
4921 value: &serde_json::Value,
4922 ) -> Result<&Vec<serde_json::Value>, async_graphql::Error> {
4923 match value.as_array() {
4924 Some(items) if items.len() >= 2 && items.iter().all(|i| i.is_number()) => Ok(items),
4925 _ => refuse("A Position needs at least 2 elements"),
4926 }
4927 }
4928
4929 fn positions(
4930 value: Option<&serde_json::Value>,
4931 least: usize,
4932 what: &str,
4933 ) -> Result<Vec<Vec<serde_json::Value>>, async_graphql::Error> {
4934 let items = match value.and_then(|v| v.as_array()) {
4935 Some(items) => items,
4936 None => return refuse(&format!("A {} needs at least {} Positions", what, least)),
4937 };
4938 if items.len() < least {
4939 return refuse(&format!("A {} needs at least {} Positions", what, least));
4940 }
4941 items.iter().map(|item| position(item).cloned()).collect()
4942 }
4943
4944 fn ring(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4945 let points = positions(Some(value), 4, "LinearRing")?;
4946 match (points.first(), points.last()) {
4947 (Some(first), Some(last)) if first == last => Ok(()),
4948 _ => refuse("the first and last locations have to be equal for a LinearRing"),
4949 }
4950 }
4951
4952 fn polygon(value: &serde_json::Value) -> Result<(), async_graphql::Error> {
4953 let Some(rings) = value.as_array() else {
4954 return refuse("A LinearRing needs at least 4 Positions");
4955 };
4956 rings.iter().try_for_each(ring)
4957 }
4958
4959 let serde_json::Value::Object(map) = value else {
4960 return Ok(());
4961 };
4962 let Some(kind) = map.get("type").and_then(|v| v.as_str()) else {
4963 return Ok(());
4964 };
4965 let coordinates = map.get("coordinates");
4966 match kind {
4967 "Point" => {
4968 position(coordinates.unwrap_or(&serde_json::Value::Null))?;
4969 }
4970 "MultiPoint" => {
4971 positions(coordinates, 0, "MultiPoint")?;
4972 }
4973 "LineString" => {
4974 positions(coordinates, 2, "LineString")?;
4975 }
4976 "MultiLineString" => {
4977 for line in coordinates.and_then(|v| v.as_array()).into_iter().flatten() {
4978 positions(Some(line), 2, "LineString")?;
4979 }
4980 }
4981 "Polygon" => polygon(coordinates.unwrap_or(&serde_json::Value::Null))?,
4982 "MultiPolygon" => {
4983 for one in coordinates.and_then(|v| v.as_array()).into_iter().flatten() {
4984 polygon(one)?;
4985 }
4986 }
4987 "GeometryCollection" => {
4988 for geometry in map
4989 .get("geometries")
4990 .and_then(|v| v.as_array())
4991 .into_iter()
4992 .flatten()
4993 {
4994 check_geojson(geometry)?;
4995 }
4996 }
4997 other => return refuse(&format!("unexpected geometry type: {}", other)),
4998 }
4999 Ok(())
5000}
5001
5002fn computed_call(
5010 definition: &postrust_core::schema_cache::ComputedColumn,
5011 row: &str,
5012 row_by_name: &str,
5013) -> String {
5014 let function = format!(
5015 "{}.{}",
5016 postrust_sql::escape_ident(&definition.function.schema),
5017 postrust_sql::escape_ident(&definition.function.name)
5018 );
5019 match (&definition.session_argument, &definition.row_argument) {
5020 (Some(session), Some(row_argument)) => format!(
5021 "{}({} => {}, {} => {})",
5022 function,
5023 postrust_sql::escape_ident(row_argument),
5024 row_by_name,
5025 postrust_sql::escape_ident(session),
5026 SESSION_ARGUMENT
5027 ),
5028 _ => format!("{}({})", function, row),
5029 }
5030}
5031
5032const SESSION_ARGUMENT: &str = "coalesce(current_setting('hasura.session', true), '{}')::json";
5039
5040const UPDATE_OPERATORS: [&str; 7] = [
5043 "_set",
5044 "_inc",
5045 "_append",
5046 "_prepend",
5047 "_delete_key",
5048 "_delete_elem",
5049 "_delete_at_path",
5050];
5051
5052const READ_ROW: &str = "pgrst_src";
5058
5059const WRITTEN_ROW: &str = "pgrst_row";
5064
5065fn write_cast(column_types: &HashMap<String, String>, column: &str) -> String {
5073 match column_types.get(column) {
5074 Some(pg_type) => format!("::{}", pg_type),
5075 None => String::new(),
5076 }
5077}
5078
5079fn write_operand(
5086 column_types: &HashMap<String, String>,
5087 column: &str,
5088 value: &serde_json::Value,
5089) -> serde_json::Value {
5090 match column_types.get(column).map(String::as_str) {
5091 Some("json") | Some("jsonb") => match value {
5092 serde_json::Value::String(_)
5093 | serde_json::Value::Number(_)
5094 | serde_json::Value::Bool(_) => serde_json::Value::String(value.to_string()),
5095 other => other.clone(),
5096 },
5097 Some(pg_type) if is_array_type(pg_type) => match value {
5102 serde_json::Value::Array(_) => serde_json::Value::String(array_literal(value)),
5103 other => other.clone(),
5104 },
5105 _ => value.clone(),
5106 }
5107}
5108
5109fn is_array_type(pg_type: &str) -> bool {
5114 pg_type.ends_with("[]") || pg_type.starts_with('_')
5115}
5116
5117fn array_literal(value: &serde_json::Value) -> String {
5123 fn element(value: &serde_json::Value) -> String {
5124 match value {
5125 serde_json::Value::Null => "NULL".to_string(),
5126 serde_json::Value::Array(_) => array_literal(value),
5127 serde_json::Value::String(text) => {
5128 format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
5129 }
5130 other => format!("\"{}\"", other.to_string().replace('"', "\\\"")),
5131 }
5132 }
5133 let items = match value {
5134 serde_json::Value::Array(items) => items,
5135 other => return element(other),
5136 };
5137 format!(
5138 "{{{}}}",
5139 items.iter().map(element).collect::<Vec<_>>().join(",")
5140 )
5141}
5142
5143fn write_expression(
5154 column_types: &HashMap<String, String>,
5155 column: &str,
5156 value: &serde_json::Value,
5157 placeholder: &str,
5158) -> String {
5159 let pg_type = column_types.get(column).map(String::as_str);
5160 if value.is_object() && matches!(pg_type, Some("geometry") | Some("geography")) {
5161 return match pg_type {
5162 Some("geography") => format!("ST_GeomFromGeoJSON({})::geography", placeholder),
5163 _ => format!("ST_GeomFromGeoJSON({})", placeholder),
5164 };
5165 }
5166 if pg_type == Some("money") && value.is_number() {
5172 return format!("{}::numeric::money", placeholder);
5173 }
5174 format!("{}{}", placeholder, write_cast(column_types, column))
5175}
5176
5177async fn column_types_of(
5179 schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
5180 schema_name: &str,
5181 table_name: &str,
5182) -> HashMap<String, String> {
5183 let Ok(guard) = schema_cache.get().await else {
5184 return HashMap::new();
5185 };
5186 let Some(cache) = guard.as_ref() else {
5187 return HashMap::new();
5188 };
5189 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5190 match cache.get_table(&qi) {
5191 Some(table) => table
5192 .columns
5193 .values()
5194 .map(|c| (c.name.clone(), c.nominal_type.clone()))
5195 .collect(),
5196 None => HashMap::new(),
5197 }
5198}
5199
5200fn insert_row<'life>(
5218 conn: &'life mut sqlx::PgConnection,
5219 schema_name: &'life str,
5220 table_name: &'life str,
5221 object: serde_json::Map<String, serde_json::Value>,
5222 context: &'life InsertContext<'life>,
5223 written_count: &'life mut usize,
5224) -> std::pin::Pin<
5225 Box<
5226 dyn std::future::Future<Output = Result<serde_json::Value, async_graphql::Error>>
5227 + Send
5228 + 'life,
5229 >,
5230> {
5231 Box::pin(async move {
5232 use sqlx::Row;
5233
5234 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5235 let table = context.cache.get_table(&qi).ok_or_else(|| {
5236 async_graphql::Error::new(format!("unknown table \"{}\"", table_name))
5237 })?;
5238 let column_types: HashMap<String, String> = table
5239 .columns
5240 .values()
5241 .map(|c| (c.name.clone(), c.nominal_type.clone()))
5242 .collect();
5243
5244 let type_name = context
5246 .type_names
5247 .get(&(schema_name.to_string(), table_name.to_string()));
5248 let relationships: &[RelationshipField] = type_name
5249 .and_then(|name| context.relationships.get(name))
5250 .map(|r| r.as_slice())
5251 .unwrap_or(&[]);
5252
5253 let mut columns = serde_json::Map::new();
5254 type Nested<'r> = (
5255 &'r RelationshipField,
5256 serde_json::Value,
5257 Option<serde_json::Value>,
5258 );
5259 let mut to_one: Vec<Nested> = Vec::new();
5260 let mut to_many: Vec<Nested> = Vec::new();
5261
5262 for (key, value) in object {
5263 match relationships.iter().find(|r| r.name == key) {
5264 None => {
5265 columns.insert(
5268 table_column_for(context.names, table, &key).to_string(),
5269 value,
5270 );
5271 }
5272 Some(_) if value.is_null() => {
5273 continue;
5277 }
5278 Some(relationship) => {
5279 let (data, conflict) = match &value {
5283 serde_json::Value::Object(map) => (
5284 map.get("data").cloned().unwrap_or(value.clone()),
5285 map.get("on_conflict").cloned().filter(|v| !v.is_null()),
5286 ),
5287 other => (other.clone(), None),
5288 };
5289 if child_holds_the_key(&relationship.relationship) {
5296 to_many.push((relationship, data, conflict));
5297 } else {
5298 to_one.push((relationship, data, conflict));
5299 }
5300 }
5301 }
5302 }
5303
5304 for (column, value) in &columns {
5307 if matches!(
5308 column_types.get(column).map(String::as_str),
5309 Some("geometry") | Some("geography")
5310 ) {
5311 check_geojson(value).map_err(|error| {
5314 let field = context
5315 .names
5316 .column(schema_name, table_name, column)
5317 .unwrap_or(column);
5318 at_path(error, &format!("{}.{}", context.row, field))
5319 })?;
5320 }
5321 }
5322
5323 for (relationship, data, conflict) in to_one {
5326 let plan =
5327 postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, context.cache)
5328 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5329 let serde_json::Value::Object(child) = data else {
5330 return Err(async_graphql::Error::new(format!(
5331 "\"{}\" takes an object to insert",
5332 relationship.name
5333 )));
5334 };
5335 for (local, _) in &plan.columns {
5339 if columns.get(local).is_some_and(|v| !v.is_null()) {
5340 return Err(at_path(
5341 validation_error(format!(
5342 "cannot insert object relationship \"{}\" as \"{}\" column \
5343 values are already determined",
5344 relationship.name, local
5345 )),
5346 &format!("{}.{}", context.row, relationship.name),
5347 ));
5348 }
5349 }
5350 let under = format!("{}.{}", context.row, relationship.name);
5353 let nested = InsertContext {
5354 on_conflict: conflict,
5355 cache: context.cache,
5356 relationships: context.relationships,
5357 type_names: context.type_names,
5358 names: context.names,
5359 caller: context.caller,
5360 row: format!("{}.data", under),
5361 objects: format!("{}.data", under),
5362 conflict: format!("{}.on_conflict", under),
5363 };
5364 let written = insert_row(
5365 conn,
5366 &plan.foreign_schema,
5367 &plan.foreign_table,
5368 child,
5369 &nested,
5370 written_count,
5371 )
5372 .await?;
5373 for (local, foreign) in &plan.columns {
5374 if let Some(value) = written.get(foreign) {
5375 columns.insert(local.clone(), value.clone());
5376 }
5377 }
5378 }
5379
5380 for (column, value) in crate::role::presets(
5386 &context.caller,
5387 context.names,
5388 schema_name,
5389 table_name,
5390 crate::role::Verb::Insert,
5391 )
5392 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?
5393 {
5394 columns.insert(column, value);
5395 }
5396
5397 let column_names: Vec<&str> = columns.keys().map(|k| k.as_str()).collect();
5403 let mut conflict_values: Vec<serde_json::Value> = Vec::new();
5404 let conflict_sql = match &context.on_conflict {
5405 Some(serde_json::Value::Object(spec)) => {
5406 let constraint = spec.get("constraint").and_then(|v| v.as_str());
5407 let Some(constraint) = constraint else {
5408 return Err(async_graphql::Error::new(
5409 "on_conflict needs a constraint to resolve against",
5410 ));
5411 };
5412 if !table
5413 .unique_constraints
5414 .iter()
5415 .any(|(name, _)| name == constraint)
5416 {
5417 return Err(async_graphql::Error::new(format!(
5418 "\"{}\" is not a unique constraint of \"{}\"",
5419 constraint, table_name
5420 )));
5421 }
5422 let updates: Vec<&str> = spec
5423 .get("update_columns")
5424 .and_then(|v| v.as_array())
5425 .map(|items| items.iter().filter_map(|i| i.as_str()).collect())
5426 .unwrap_or_default();
5427 if updates.contains(&PLACEHOLDER_COLUMN) {
5431 return Err(at_path(
5432 coded_error("validation-failed", "erroneous column name"),
5433 &context.conflict,
5434 ));
5435 }
5436
5437 if updates.is_empty() {
5438 format!(
5439 " ON CONFLICT ON CONSTRAINT {} DO NOTHING",
5440 postrust_sql::escape_ident(constraint)
5441 )
5442 } else {
5443 let preset = crate::role::presets(
5449 &context.caller,
5450 context.names,
5451 schema_name,
5452 table_name,
5453 crate::role::Verb::Update,
5454 )
5455 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
5456
5457 let mut param_idx = column_names.len() + 1;
5461 let mut assignments: Vec<String> =
5462 Vec::with_capacity(preset.len() + updates.len());
5463 for (column, value) in &preset {
5464 assignments.push(format!(
5465 "{} = {}",
5466 postrust_sql::escape_ident(column),
5467 write_expression(
5468 &column_types,
5469 column,
5470 value,
5471 &format!("${}", param_idx)
5472 )
5473 ));
5474 conflict_values.push(write_operand(&column_types, column, value));
5475 param_idx += 1;
5476 }
5477 for field in &updates {
5478 let column = table_column_for(context.names, table, field);
5479 if preset.iter().any(|(written, _)| written == column) {
5480 continue;
5481 }
5482 assignments.push(format!(
5483 "{} = EXCLUDED.{}",
5484 postrust_sql::escape_ident(column),
5485 postrust_sql::escape_ident(column)
5486 ));
5487 }
5488 let granted = permission_filter(
5501 &context.caller,
5502 context.names,
5503 schema_name,
5504 table_name,
5505 crate::role::Verb::Update,
5506 )?;
5507 let requested = spec.get("where").filter(|f| !f.is_null()).cloned();
5508 let condition = match and_predicates(requested, granted) {
5509 Some(filter) => {
5510 let filter = &filter;
5511 let type_name = context
5512 .type_names
5513 .get(&(schema_name.to_string(), table_name.to_string()))
5514 .map(String::as_str)
5515 .unwrap_or(table_name);
5516 let scope = WhereScope::table(
5517 schema_name,
5518 table_name,
5519 type_name,
5520 context.names,
5521 )
5522 .under_alias(WRITTEN_ROW)
5523 .with_resolution(context.cache, context.relationships);
5524 let mut alias_counter = 0usize;
5525 build_condition(
5526 filter,
5527 &scope,
5528 &mut param_idx,
5529 &mut conflict_values,
5530 &mut alias_counter,
5531 )?
5532 .map(|sql| format!(" WHERE {}", sql))
5533 .unwrap_or_default()
5534 }
5535 None => String::new(),
5536 };
5537 format!(
5538 " ON CONFLICT ON CONSTRAINT {} DO UPDATE SET {}{}",
5539 postrust_sql::escape_ident(constraint),
5540 assignments.join(", "),
5541 condition
5542 )
5543 }
5544 }
5545 _ => String::new(),
5546 };
5547
5548 let qualified_table = postrust_sql::escape_ident(WRITTEN_ROW);
5554
5555 let check_scope = WhereScope::for_alias(
5560 schema_name,
5561 table_name,
5562 WRITTEN_ROW,
5563 context
5564 .type_names
5565 .get(&(schema_name.to_string(), table_name.to_string()))
5566 .map(String::as_str)
5567 .unwrap_or(table_name),
5568 context.cache,
5569 context.relationships,
5570 context.names,
5571 );
5572 let (check_sql, check_values) = {
5573 let check = crate::role::write_check(
5574 &context.caller,
5575 context.names,
5576 schema_name,
5577 table_name,
5578 crate::role::Verb::Insert,
5579 )
5580 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
5581 match check {
5582 None => (String::new(), Vec::new()),
5583 Some(check) => {
5584 let mut values = Vec::new();
5585 let mut param_idx = column_names.len() + conflict_values.len() + 1;
5586 let mut alias_counter = 0usize;
5587 match build_condition(
5588 &check,
5589 &check_scope,
5590 &mut param_idx,
5591 &mut values,
5592 &mut alias_counter,
5593 )? {
5594 None => (String::new(), Vec::new()),
5595 Some(sql) => (
5596 format!(
5597 ", ({}) AS {}",
5598 sql,
5599 postrust_sql::escape_ident(CHECK_COLUMN)
5600 ),
5601 values,
5602 ),
5603 }
5604 }
5605 }
5606 };
5607
5608 let names = column_names;
5609 let written = if names.is_empty() {
5610 let sql = format!(
5613 "INSERT INTO {}.{} AS {} DEFAULT VALUES{} RETURNING {}{}",
5614 postrust_sql::escape_ident(schema_name),
5615 postrust_sql::escape_ident(table_name),
5616 qualified_table,
5617 conflict_sql,
5618 row_json(&qualified_table, &column_types),
5619 check_sql
5620 );
5621 let mut query = sqlx::query(AssertSqlSafe(sql));
5622 for value in &conflict_values {
5623 query = bind_json_value(query, value);
5624 }
5625 for value in &check_values {
5626 query = bind_json_value(query, value);
5627 }
5628 query
5629 .fetch_optional(&mut *conn)
5630 .await
5631 .map_err(|error| at_path(database_error(error), &context.objects))?
5634 } else {
5635 let placeholders: Vec<String> = names
5636 .iter()
5637 .enumerate()
5638 .map(|(i, column)| {
5639 let placeholder = format!("${}", i + 1);
5640 match columns.get(*column) {
5641 Some(value) => write_expression(&column_types, column, value, &placeholder),
5642 None => placeholder,
5643 }
5644 })
5645 .collect();
5646 let sql = format!(
5647 "INSERT INTO {}.{} AS {} ({}) VALUES ({}){} RETURNING {}{}",
5648 postrust_sql::escape_ident(schema_name),
5649 postrust_sql::escape_ident(table_name),
5650 qualified_table,
5651 names
5652 .iter()
5653 .map(|c| postrust_sql::escape_ident(c))
5654 .collect::<Vec<_>>()
5655 .join(", "),
5656 placeholders.join(", "),
5657 conflict_sql,
5658 row_json(&qualified_table, &column_types),
5659 check_sql
5660 );
5661 trace!("Executing INSERT SQL: {}", sql);
5662 let mut query = sqlx::query(AssertSqlSafe(sql));
5663 for column in &names {
5664 if let Some(value) = columns.get(*column) {
5665 query = bind_json_value(query, &write_operand(&column_types, column, value));
5666 }
5667 }
5668 for value in &conflict_values {
5669 query = bind_json_value(query, value);
5670 }
5671 for value in &check_values {
5672 query = bind_json_value(query, value);
5673 }
5674 query
5675 .fetch_optional(&mut *conn)
5676 .await
5677 .map_err(|error| at_path(database_error(error), &context.objects))?
5680 };
5681
5682 let Some(written) = written else {
5685 return Ok(serde_json::Value::Null);
5686 };
5687 refuse_unchecked_rows(std::slice::from_ref(&written), !check_sql.is_empty())
5688 .map_err(|error| at_path(error, &context.objects))?;
5689 let row: serde_json::Value = written.try_get(0).unwrap_or(serde_json::Value::Null);
5690 *written_count += 1;
5691
5692 for (relationship, data, conflict) in to_many {
5694 let plan =
5695 postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, context.cache)
5696 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5697 let children = match data {
5698 serde_json::Value::Array(items) => items,
5699 serde_json::Value::Object(map) => vec![serde_json::Value::Object(map)],
5700 serde_json::Value::Null => Vec::new(),
5701 _ => {
5702 return Err(async_graphql::Error::new(format!(
5703 "\"{}\" takes objects to insert",
5704 relationship.name
5705 )))
5706 }
5707 };
5708 for (child_index, child) in children.into_iter().enumerate() {
5709 let serde_json::Value::Object(mut child) = child else {
5710 continue;
5711 };
5712 for (local, foreign) in &plan.columns {
5713 if child.get(foreign).is_some_and(|v| !v.is_null()) {
5717 return Err(at_path(
5718 validation_error(format!(
5719 "cannot insert \"{}\" columns as their values are already \
5720 being determined by parent insert",
5721 foreign
5722 )),
5723 &format!(
5724 "{}.{}{}",
5725 context.row,
5726 relationship.name,
5727 match relationship.is_list {
5728 true => format!(".data[{}]", child_index),
5729 false => ".data".to_string(),
5730 }
5731 ),
5732 ));
5733 }
5734 if let Some(value) = row.get(local) {
5735 child.insert(foreign.clone(), value.clone());
5736 }
5737 }
5738 let at = match relationship.is_list {
5744 true => format!(".data[{}]", child_index),
5745 false => ".data".to_string(),
5746 };
5747 let under = format!("{}.{}", context.row, relationship.name);
5748 let nested = InsertContext {
5749 on_conflict: conflict.clone(),
5750 cache: context.cache,
5751 relationships: context.relationships,
5752 type_names: context.type_names,
5753 names: context.names,
5754 caller: context.caller,
5755 row: format!("{}{}", under, at),
5756 objects: format!("{}.data", under),
5757 conflict: format!("{}.on_conflict", under),
5758 };
5759 insert_row(
5760 conn,
5761 &plan.foreign_schema,
5762 &plan.foreign_table,
5763 child,
5764 &nested,
5765 written_count,
5766 )
5767 .await?;
5768 }
5769 }
5770
5771 Ok(row)
5772 })
5773}
5774
5775#[derive(Clone)]
5781struct InsertContext<'a> {
5782 on_conflict: Option<serde_json::Value>,
5785 cache: &'a SchemaCache,
5786 relationships: &'a HashMap<String, Vec<RelationshipField>>,
5787 type_names: &'a HashMap<(String, String), String>,
5791 names: &'a crate::names::NameOverrides,
5794 caller: crate::role::Caller<'a>,
5798 row: String,
5803 objects: String,
5807 conflict: String,
5809}
5810
5811#[allow(clippy::too_many_arguments)]
5824async fn reread_returning(
5825 pool: &PgPool,
5826 gql_ctx: &GraphQLContext,
5827 schema_name: &str,
5828 table_name: &str,
5829 type_name: &str,
5830 rows: Vec<Value>,
5831 returning: async_graphql::SelectionField<'_>,
5832 relationships: &HashMap<String, Vec<RelationshipField>>,
5833 names: &crate::names::NameOverrides,
5834 max_rows: Option<i64>,
5835) -> Result<Vec<Value>, async_graphql::Error> {
5836 let guard = gql_ctx
5837 .schema_cache
5838 .get()
5839 .await
5840 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
5841 let Some(cache) = guard.as_ref() else {
5842 return Ok(rows);
5843 };
5844 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
5845 let Some(table) = cache.get_table(&qi) else {
5846 return Ok(rows);
5847 };
5848 if table.pk_cols.is_empty() {
5849 return Ok(rows);
5851 }
5852
5853 let mut param_idx = 1usize;
5854 let mut values: Vec<serde_json::Value> = Vec::new();
5855 let mut alias_counter = 0usize;
5856 let embeds = build_embed_expressions(
5857 &gql_ctx.caller(),
5858 cache,
5859 relationships,
5860 type_name,
5861 "src",
5862 returning.selection_set(),
5863 max_rows,
5864 &mut alias_counter,
5865 &mut param_idx,
5866 &mut values,
5867 names,
5868 )?;
5869 let computed = computed_projections(
5870 table,
5871 returning.selection_set(),
5872 "src",
5873 names,
5874 cache,
5875 &mut param_idx,
5876 &mut values,
5877 )?;
5878 let renames = names.renames_columns(&table.schema, &table.name);
5882 if embeds.is_empty() && computed.is_empty() && !renames {
5883 return Ok(rows);
5884 }
5885
5886 let mut conditions = Vec::with_capacity(rows.len());
5888 for row in &rows {
5889 let mut parts = Vec::with_capacity(table.pk_cols.len());
5890 for column in &table.pk_cols {
5891 let Value::Object(map) = row else {
5892 return Ok(rows);
5893 };
5894 let Some(value) = map.get(&async_graphql::Name::new(column)) else {
5895 return Ok(rows);
5896 };
5897 parts.push(format!(
5898 "{} = ${}",
5899 postrust_sql::escape_ident(column),
5900 param_idx
5901 ));
5902 values.push(value_to_json(value));
5903 param_idx += 1;
5904 }
5905 conditions.push(format!("({})", parts.join(" AND ")));
5906 }
5907 if conditions.is_empty() {
5908 return Ok(rows);
5909 }
5910
5911 let mut projection =
5912 rename_projection(table, "src", names).unwrap_or_else(|| "src.*".to_string());
5913 for expression in &computed {
5914 projection.push_str(", ");
5915 projection.push_str(expression);
5916 }
5917 for (name, expression) in &embeds {
5918 projection.push_str(", ");
5919 projection.push_str(expression);
5920 projection.push_str(" AS ");
5921 projection.push_str(&postrust_sql::escape_ident(name));
5922 }
5923
5924 let sql = format!(
5925 "SELECT {} FROM (SELECT {} FROM (SELECT * FROM {}.{} WHERE {}) AS src) AS pgrst_r",
5926 row_json("pgrst_r", &exposed_column_types(table, names)),
5927 projection,
5928 postrust_sql::escape_ident(schema_name),
5929 postrust_sql::escape_ident(table_name),
5930 conditions.join(" OR ")
5931 );
5932
5933 let mut guard = write_tx(gql_ctx, pool).await?;
5936 let conn = guard.as_mut().expect("write_tx opens one");
5937 let reread = execute_query_on(conn, &sql, &values).await?;
5938 drop(guard);
5939
5940 if reread.is_empty() {
5941 return Ok(rows);
5942 }
5943 Ok(reread.into_iter().map(json_to_value).collect())
5944}
5945
5946async fn execute_insert(
5948 pool: &PgPool,
5949 gql_ctx: &GraphQLContext,
5950 schema_name: &str,
5951 table_name: &str,
5952 objects: serde_json::Value,
5953 context: &InsertContext<'_>,
5954 single: bool,
5958) -> Result<(Vec<Value>, usize), async_graphql::Error> {
5959 trace!("Insert mutation for {}: {:?}", table_name, objects);
5960
5961 let objects_array = match objects {
5963 serde_json::Value::Array(arr) => arr,
5964 serde_json::Value::Object(obj) => vec![serde_json::Value::Object(obj)],
5965 _ => {
5966 return Err(async_graphql::Error::new(
5967 "objects must be an array or object",
5968 ))
5969 }
5970 };
5971
5972 if objects_array.is_empty() {
5973 return Err(async_graphql::Error::new("objects cannot be empty"));
5974 }
5975
5976 let mut guard = write_tx(gql_ctx, pool).await?;
5977 let conn = guard.as_mut().expect("write_tx opens one");
5978
5979 let mut inserted: Vec<Value> = Vec::new();
5980 let mut written = 0usize;
5981
5982 for (index, object) in objects_array.into_iter().enumerate() {
5983 let serde_json::Value::Object(map) = object else {
5984 return Err(async_graphql::Error::new(
5985 "each object to insert is an object",
5986 ));
5987 };
5988 let context = InsertContext {
5991 row: match single {
5992 true => context.objects.clone(),
5993 false => format!("{}[{}]", context.objects, index),
5994 },
5995 ..context.clone()
5996 };
5997 let row = insert_row(conn, schema_name, table_name, map, &context, &mut written).await?;
5998 if !row.is_null() {
6002 inserted.push(json_to_value(row));
6003 }
6004 }
6005
6006 Ok((inserted, written))
6007}
6008
6009fn mutation_result<'a>(rows: Vec<Value>, affected: usize, by_key: bool) -> Option<FieldValue<'a>> {
6021 if by_key {
6022 return rows.into_iter().next().map(FieldValue::value);
6023 }
6024 let mut response = async_graphql::indexmap::IndexMap::new();
6025 response.insert(
6026 async_graphql::Name::new("affected_rows"),
6027 Value::from(affected),
6028 );
6029 response.insert(async_graphql::Name::new("returning"), Value::List(rows));
6030 Some(FieldValue::value(Value::Object(response)))
6031}
6032
6033fn bind_json_value<'q>(
6045 query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
6046 value: &serde_json::Value,
6047) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
6048 match value {
6049 serde_json::Value::Null => query.bind(None::<String>),
6050 serde_json::Value::Bool(b) => query.bind(*b),
6051 serde_json::Value::Number(n) => {
6052 if let Some(i) = n.as_i64() {
6053 query.bind(i)
6054 } else if let Some(f) = n.as_f64() {
6055 query.bind(f)
6056 } else {
6057 query.bind(n.to_string())
6058 }
6059 }
6060 serde_json::Value::String(s) => query.bind(s.clone()),
6061 _ => query.bind(value.to_string()),
6062 }
6063}
6064
6065#[allow(clippy::too_many_arguments)] async fn execute_update(
6068 pool: &PgPool,
6069 gql_ctx: &GraphQLContext,
6070 schema_name: &str,
6071 table_name: &str,
6072 type_name: &str,
6073 operators: Vec<(&'static str, serde_json::Value)>,
6074 column_types: HashMap<String, String>,
6075 where_clause: Option<serde_json::Value>,
6076 relationships: &HashMap<String, Vec<RelationshipField>>,
6077 names: &crate::names::NameOverrides,
6078) -> Result<Vec<Value>, async_graphql::Error> {
6079 use sqlx::Row;
6080
6081 trace!("Update mutation for {}: {:?}", table_name, operators);
6082
6083 let mut set_parts: Vec<String> = Vec::new();
6088 let mut set_values: Vec<serde_json::Value> = Vec::new();
6089 let mut param_idx = 1;
6090 let mut written: HashSet<String> = HashSet::new();
6091
6092 let preset = crate::role::presets(
6102 &gql_ctx.caller(),
6103 names,
6104 schema_name,
6105 table_name,
6106 crate::role::Verb::Update,
6107 )
6108 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
6109 let preset_columns: HashSet<&str> = preset.iter().map(|(name, _)| name.as_str()).collect();
6110 for (column, value) in &preset {
6111 let placeholder =
6112 write_expression(&column_types, column, value, &format!("${}", param_idx));
6113 set_parts.push(format!(
6114 "{} = {}",
6115 postrust_sql::escape_ident(column),
6116 placeholder
6117 ));
6118 set_values.push(write_operand(&column_types, column, value));
6119 param_idx += 1;
6120 }
6121
6122 for (operator, payload) in &operators {
6123 let serde_json::Value::Object(map) = payload else {
6124 return Err(async_graphql::Error::new(format!(
6125 "\"{}\" takes an object mapping columns to values",
6126 operator
6127 )));
6128 };
6129 for (field, value) in map {
6130 let column = &names
6131 .column_source(schema_name, table_name, field)
6132 .unwrap_or(field)
6133 .to_string();
6134 if preset_columns.contains(column.as_str()) {
6137 continue;
6138 }
6139 if !written.insert(column.clone()) {
6140 return Err(async_graphql::Error::new(format!(
6141 "\"{}\" is written twice in one update; a column may be \
6142 changed by one operator at a time",
6143 column
6144 )));
6145 }
6146 let quoted = postrust_sql::escape_ident(column);
6147 let placeholder = match *operator {
6156 "_set" | "_inc" => {
6157 write_expression(&column_types, column, value, &format!("${}", param_idx))
6158 }
6159 _ => format!("${}", param_idx),
6160 };
6161 let assignment = match *operator {
6164 "_set" => format!("{} = {}", quoted, placeholder),
6165 "_inc" => format!("{} = {} + {}", quoted, quoted, placeholder),
6166 "_append" => format!("{} = {} || {}::jsonb", quoted, quoted, placeholder),
6167 "_prepend" => format!("{} = {}::jsonb || {}", quoted, placeholder, quoted),
6168 "_delete_key" => format!("{} = {} - {}::text", quoted, quoted, placeholder),
6169 "_delete_elem" => format!("{} = {} - {}::int", quoted, quoted, placeholder),
6170 "_delete_at_path" => {
6176 let Some(steps) = value.as_array() else {
6177 return Err(async_graphql::Error::new(format!(
6178 "\"_delete_at_path\" on \"{}\" takes a list of keys",
6179 column
6180 )));
6181 };
6182 let path = sql_array(steps, "text[]", &mut param_idx, &mut set_values);
6183 set_parts.push(format!("{} = {} #- {}", quoted, quoted, path));
6184 continue;
6185 }
6186 other => {
6187 return Err(async_graphql::Error::new(format!(
6188 "unsupported update operator \"{}\"",
6189 other
6190 )))
6191 }
6192 };
6193 if *operator == "_set"
6194 && matches!(
6195 column_types.get(column).map(String::as_str),
6196 Some("geometry") | Some("geography")
6197 )
6198 {
6199 check_geojson(value)?;
6200 }
6201 set_parts.push(assignment);
6202 set_values.push(match *operator {
6203 "_set" => write_operand(&column_types, column, value),
6204 _ => value.clone(),
6205 });
6206 param_idx += 1;
6207 }
6208 }
6209
6210 if set_parts.is_empty() {
6215 return Ok(Vec::new());
6216 }
6217
6218 let guard = gql_ctx
6222 .schema_cache
6223 .get()
6224 .await
6225 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
6226 let cache = guard
6227 .as_ref()
6228 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
6229 let scope = WhereScope::table(schema_name, table_name, type_name, names)
6230 .under_alias(WRITTEN_ROW)
6231 .with_resolution(cache, relationships);
6232 let (where_sql, where_values) = build_where_clause(where_clause.as_ref(), param_idx, &scope)?;
6233
6234 if where_sql.is_empty() {
6237 return Err(async_graphql::Error::new(format!(
6238 "update on \"{}\" requires a `where` argument with at least one \
6239 recognised condition; refusing to update every row",
6240 table_name
6241 )));
6242 }
6243
6244 let (check_sql, check_values) = permission_check_sql(
6249 gql_ctx,
6250 names,
6251 schema_name,
6252 table_name,
6253 crate::role::Verb::Update,
6254 &scope,
6255 param_idx + where_values.len(),
6256 )?;
6257
6258 let sql = format!(
6259 "UPDATE {}.{} AS {} SET {} {} RETURNING {}{}",
6260 postrust_sql::escape_ident(schema_name),
6261 postrust_sql::escape_ident(table_name),
6262 postrust_sql::escape_ident(WRITTEN_ROW),
6263 set_parts.join(", "),
6264 where_sql,
6265 row_json(&postrust_sql::escape_ident(WRITTEN_ROW), &column_types),
6266 check_sql
6267 );
6268
6269 trace!("Executing UPDATE SQL: {}", sql);
6270
6271 let mut query = sqlx::query(AssertSqlSafe(sql));
6273
6274 for val in &set_values {
6276 query = bind_json_value(query, val);
6277 }
6278
6279 for val in &where_values {
6281 query = bind_json_value(query, val);
6282 }
6283
6284 for val in &check_values {
6286 query = bind_json_value(query, val);
6287 }
6288
6289 let mut guard = write_tx(gql_ctx, pool).await?;
6290 let conn = guard.as_mut().expect("write_tx opens one");
6291 let rows = query.fetch_all(&mut **conn).await.map_err(database_error)?;
6292
6293 refuse_unchecked_rows(&rows, !check_sql.is_empty())?;
6294
6295 let updated: Vec<Value> = rows
6296 .iter()
6297 .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
6298 .map(json_to_value)
6299 .collect();
6300
6301 Ok(updated)
6302}
6303
6304fn permission_check_sql(
6311 gql_ctx: &GraphQLContext,
6312 names: &crate::names::NameOverrides,
6313 schema_name: &str,
6314 table_name: &str,
6315 verb: crate::role::Verb,
6316 scope: &WhereScope<'_>,
6317 start_param_idx: usize,
6318) -> Result<(String, Vec<serde_json::Value>), async_graphql::Error> {
6319 let check = crate::role::write_check(&gql_ctx.caller(), names, schema_name, table_name, verb)
6320 .map_err(|fault| coded_error(fault.code(), fault.to_string()))?;
6321 let Some(check) = check else {
6322 return Ok((String::new(), Vec::new()));
6323 };
6324
6325 let mut values = Vec::new();
6326 let mut param_idx = start_param_idx;
6327 let mut alias_counter = 0usize;
6328 let condition = build_condition(
6329 &check,
6330 scope,
6331 &mut param_idx,
6332 &mut values,
6333 &mut alias_counter,
6334 )?;
6335 Ok(match condition {
6336 None => (String::new(), Vec::new()),
6339 Some(sql) => (
6340 format!(
6341 ", ({}) AS {}",
6342 sql,
6343 postrust_sql::escape_ident(CHECK_COLUMN)
6344 ),
6345 values,
6346 ),
6347 })
6348}
6349
6350const CHECK_COLUMN: &str = "pgrst_permission_check";
6352
6353fn refuse_unchecked_rows(
6360 rows: &[sqlx::postgres::PgRow],
6361 checked: bool,
6362) -> Result<(), async_graphql::Error> {
6363 if !checked {
6364 return Ok(());
6365 }
6366 use sqlx::Row;
6367 let all_passed = rows
6368 .iter()
6369 .all(|row| row.try_get::<bool, _>(CHECK_COLUMN).unwrap_or(false));
6370 match all_passed {
6371 true => Ok(()),
6372 false => Err(coded_error("permission-error", crate::role::CHECK_FAILED)),
6373 }
6374}
6375
6376#[allow(clippy::too_many_arguments)] async fn execute_delete(
6379 pool: &PgPool,
6380 gql_ctx: &GraphQLContext,
6381 schema_name: &str,
6382 table_name: &str,
6383 type_name: &str,
6384 where_clause: Option<serde_json::Value>,
6385 returning: Option<async_graphql::SelectionField<'_>>,
6386 relationships: &HashMap<String, Vec<RelationshipField>>,
6387 names: &crate::names::NameOverrides,
6388 max_rows: Option<i64>,
6389) -> Result<Vec<Value>, async_graphql::Error> {
6390 use sqlx::Row;
6391
6392 trace!("Delete mutation for {}", table_name);
6393
6394 let guard = gql_ctx
6395 .schema_cache
6396 .get()
6397 .await
6398 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
6399 let cache = guard
6400 .as_ref()
6401 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
6402 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
6403 let column_types = cache
6404 .get_table(&qi)
6405 .map(|table| exposed_column_types(table, names))
6406 .unwrap_or_default();
6407
6408 let scope = WhereScope::table(schema_name, table_name, type_name, names)
6412 .under_alias(WRITTEN_ROW)
6413 .with_resolution(cache, relationships);
6414 let (where_sql, mut values) = build_where_clause(where_clause.as_ref(), 1, &scope)?;
6415
6416 if where_sql.is_empty() {
6419 return Err(async_graphql::Error::new(format!(
6420 "delete on \"{}\" requires a `where` argument with at least one \
6421 recognised condition; refusing to delete every row",
6422 table_name
6423 )));
6424 }
6425
6426 let mut projection = String::new();
6432 let renamed = cache
6433 .get_table(&qi)
6434 .and_then(|table| rename_projection(table, "src", names));
6435 if let Some(returning) = returning {
6436 let mut param_idx = values.len() + 1;
6437 let mut alias_counter = 0usize;
6438 let embeds = build_embed_expressions(
6439 &gql_ctx.caller(),
6440 cache,
6441 relationships,
6442 type_name,
6443 "src",
6444 returning.selection_set(),
6445 max_rows,
6446 &mut alias_counter,
6447 &mut param_idx,
6448 &mut values,
6449 names,
6450 )?;
6451 let computed = match cache.get_table(&qi) {
6452 Some(table) => computed_projections(
6453 table,
6454 returning.selection_set(),
6455 "src",
6456 names,
6457 cache,
6458 &mut param_idx,
6459 &mut values,
6460 )?,
6461 None => Vec::new(),
6462 };
6463 for expression in &computed {
6464 projection.push_str(", ");
6465 projection.push_str(expression);
6466 }
6467 for (name, expression) in &embeds {
6468 projection.push_str(", ");
6469 projection.push_str(expression);
6470 projection.push_str(" AS ");
6471 projection.push_str(&postrust_sql::escape_ident(name));
6472 }
6473 }
6474
6475 let written = postrust_sql::escape_ident(WRITTEN_ROW);
6476 let sql = if projection.is_empty() && renamed.is_none() {
6477 format!(
6478 "DELETE FROM {}.{} AS {} {} RETURNING {}",
6479 postrust_sql::escape_ident(schema_name),
6480 postrust_sql::escape_ident(table_name),
6481 written,
6482 where_sql,
6483 row_json(&written, &column_types)
6484 )
6485 } else {
6486 format!(
6487 "WITH pgrst_deleted AS (DELETE FROM {}.{} AS {} {} RETURNING {}.*) \
6488 SELECT {} FROM (SELECT {}{} FROM pgrst_deleted AS src) AS pgrst_r",
6489 postrust_sql::escape_ident(schema_name),
6490 postrust_sql::escape_ident(table_name),
6491 written,
6492 where_sql,
6493 written,
6494 row_json("pgrst_r", &column_types),
6495 renamed.unwrap_or_else(|| "src.*".to_string()),
6496 projection
6497 )
6498 };
6499
6500 trace!("Executing DELETE SQL: {}", sql);
6501
6502 let mut query = sqlx::query(AssertSqlSafe(sql));
6503 for val in &values {
6504 query = bind_json_value(query, val);
6505 }
6506
6507 let mut guard = write_tx(gql_ctx, pool).await?;
6508 let conn = guard.as_mut().expect("write_tx opens one");
6509 let rows = query.fetch_all(&mut **conn).await.map_err(database_error)?;
6510
6511 let deleted: Vec<Value> = rows
6512 .iter()
6513 .filter_map(|row| row.try_get::<serde_json::Value, _>(0).ok())
6514 .map(json_to_value)
6515 .collect();
6516
6517 Ok(deleted)
6518}
6519
6520fn permission_predicate(
6528 caller: &crate::role::Caller<'_>,
6529 names: &crate::names::NameOverrides,
6530 schema: &str,
6531 table: &str,
6532) -> Result<Option<serde_json::Value>, async_graphql::Error> {
6533 permission_filter(caller, names, schema, table, crate::role::Verb::Select)
6534}
6535
6536fn permission_filter(
6538 caller: &crate::role::Caller<'_>,
6539 names: &crate::names::NameOverrides,
6540 schema: &str,
6541 table: &str,
6542 verb: crate::role::Verb,
6543) -> Result<Option<serde_json::Value>, async_graphql::Error> {
6544 crate::role::row_filter(caller, names, schema, table, verb)
6545 .map(|filter| filter.map(|predicate| serde_json::json!({ PERMISSION: predicate })))
6546 .map_err(|fault| coded_error(fault.code(), fault.to_string()))
6547}
6548
6549const PERMISSION: &str = "_permission";
6570
6571fn permission_limit(
6577 caller: &crate::role::Caller<'_>,
6578 names: &crate::names::NameOverrides,
6579 schema: &str,
6580 table: &str,
6581) -> Option<i64> {
6582 crate::role::read_limit(caller, names, schema, table)
6583}
6584
6585fn and_predicates(
6592 request: Option<serde_json::Value>,
6593 permission: Option<serde_json::Value>,
6594) -> Option<serde_json::Value> {
6595 match (request, permission) {
6596 (None, None) => None,
6597 (Some(only), None) | (None, Some(only)) => Some(only),
6598 (Some(request), Some(permission)) => {
6599 Some(serde_json::json!({ "_and": [request, permission] }))
6600 }
6601 }
6602}
6603
6604fn build_where_clause(
6614 where_value: Option<&serde_json::Value>,
6615 start_param_idx: usize,
6616 scope: &WhereScope<'_>,
6617) -> Result<(String, Vec<serde_json::Value>), async_graphql::Error> {
6618 let mut values: Vec<serde_json::Value> = Vec::new();
6619 let mut param_idx = start_param_idx;
6620 let mut alias_counter = 0usize;
6621
6622 let condition = match where_value {
6623 Some(value) => build_condition(
6624 value,
6625 scope,
6626 &mut param_idx,
6627 &mut values,
6628 &mut alias_counter,
6629 )?,
6630 None => None,
6631 };
6632
6633 Ok(match condition {
6634 Some(sql) => (format!("WHERE {}", sql), values),
6635 None => (String::new(), values),
6636 })
6637}
6638
6639pub struct WhereScope<'a> {
6651 qualified: postrust_core::api_request::QualifiedIdentifier,
6653 sql_ref: String,
6655 row_ref: String,
6659 type_name: String,
6661 root_ref: String,
6669 root_qualified: postrust_core::api_request::QualifiedIdentifier,
6670 names: &'a crate::names::NameOverrides,
6673 resolution: Option<WhereResolution<'a>>,
6674 caller: Option<crate::role::Caller<'a>>,
6681}
6682
6683struct WhereResolution<'a> {
6685 cache: &'a SchemaCache,
6686 relationships: &'a HashMap<String, Vec<RelationshipField>>,
6687}
6688
6689impl<'a> WhereScope<'a> {
6690 pub fn table(
6692 schema: &str,
6693 table: &str,
6694 type_name: &str,
6695 names: &'a crate::names::NameOverrides,
6696 ) -> Self {
6697 Self {
6698 qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6699 sql_ref: format!(
6700 "{}.{}",
6701 postrust_sql::escape_ident(schema),
6702 postrust_sql::escape_ident(table)
6703 ),
6704 row_ref: postrust_sql::escape_ident(table),
6705 type_name: type_name.to_string(),
6706 root_ref: format!(
6707 "{}.{}",
6708 postrust_sql::escape_ident(schema),
6709 postrust_sql::escape_ident(table)
6710 ),
6711 root_qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6712 names,
6713 resolution: None,
6714 caller: None,
6715 }
6716 }
6717
6718 fn under_alias(mut self, alias: &str) -> Self {
6726 if self.root_ref == self.sql_ref {
6729 self.root_ref = postrust_sql::escape_ident(alias);
6730 }
6731 self.sql_ref = postrust_sql::escape_ident(alias);
6732 self.row_ref = postrust_sql::escape_ident(alias);
6733 self
6734 }
6735
6736 fn with_resolution(
6738 mut self,
6739 cache: &'a SchemaCache,
6740 relationships: &'a HashMap<String, Vec<RelationshipField>>,
6741 ) -> Self {
6742 self.resolution = Some(WhereResolution {
6743 cache,
6744 relationships,
6745 });
6746 self
6747 }
6748
6749 #[allow(clippy::too_many_arguments)]
6751 fn for_alias(
6752 schema: &str,
6753 table: &str,
6754 alias: &str,
6755 type_name: &str,
6756 cache: &'a SchemaCache,
6757 relationships: &'a HashMap<String, Vec<RelationshipField>>,
6758 names: &'a crate::names::NameOverrides,
6759 ) -> Self {
6760 Self {
6761 qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6762 sql_ref: postrust_sql::escape_ident(alias),
6763 row_ref: postrust_sql::escape_ident(alias),
6764 type_name: type_name.to_string(),
6765 root_ref: postrust_sql::escape_ident(alias),
6766 root_qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6767 names,
6768 resolution: Some(WhereResolution {
6769 cache,
6770 relationships,
6771 }),
6772 caller: None,
6773 }
6774 }
6775
6776 fn aliased(
6783 schema: &str,
6784 table: &str,
6785 alias: &str,
6786 type_name: &str,
6787 from: &WhereScope<'a>,
6788 ) -> Self {
6789 Self {
6790 qualified: postrust_core::api_request::QualifiedIdentifier::new(schema, table),
6791 sql_ref: postrust_sql::escape_ident(alias),
6792 row_ref: postrust_sql::escape_ident(alias),
6793 type_name: type_name.to_string(),
6794 root_ref: from.root_ref.clone(),
6797 root_qualified: from.root_qualified.clone(),
6798 names: from.names,
6799 resolution: from.resolution.as_ref().map(|r| WhereResolution {
6800 cache: r.cache,
6801 relationships: r.relationships,
6802 }),
6803 caller: from.caller,
6807 }
6808 }
6809
6810 pub fn for_caller(mut self, caller: crate::role::Caller<'a>) -> Self {
6812 self.caller = Some(caller);
6813 self
6814 }
6815
6816 fn as_system(&self) -> WhereScope<'a> {
6819 WhereScope {
6820 qualified: self.qualified.clone(),
6821 sql_ref: self.sql_ref.clone(),
6822 row_ref: self.row_ref.clone(),
6823 type_name: self.type_name.clone(),
6824 root_ref: self.sql_ref.clone(),
6831 root_qualified: self.qualified.clone(),
6832 names: self.names,
6833 resolution: self.resolution.as_ref().map(|r| WhereResolution {
6834 cache: r.cache,
6835 relationships: r.relationships,
6836 }),
6837 caller: None,
6838 }
6839 }
6840
6841 fn column(&self, name: &str) -> String {
6849 let column = self.column_name(name);
6850 let plain = format!("{}.{}", self.sql_ref, postrust_sql::escape_ident(column));
6851 let Some(cache) = self.resolution.as_ref().map(|r| r.cache) else {
6852 return plain;
6853 };
6854 let Some(table) = cache.get_table(&self.qualified) else {
6855 return plain;
6856 };
6857 if table.get_column(column).is_some() {
6858 return plain;
6859 }
6860 let function = self
6861 .names
6862 .computed_source(&table.schema, &table.name, name)
6863 .unwrap_or(name);
6864 match table.get_computed_column(function) {
6865 Some(definition) => {
6866 computed_call(definition, &format!("{}.*", self.row_ref), &self.row_ref)
6867 }
6868 None => plain,
6869 }
6870 }
6871
6872 fn column_name<'n>(&'n self, name: &'n str) -> &'n str {
6874 self.names
6875 .column_source(&self.qualified.schema, &self.qualified.name, name)
6876 .unwrap_or(name)
6877 }
6878
6879 fn column_type(&self, name: &str) -> Option<String> {
6883 let cache = self.resolution.as_ref()?.cache;
6884 let table = cache.get_table(&self.qualified)?;
6885 table
6886 .get_column(self.column_name(name))
6887 .map(|c| c.nominal_type.clone())
6888 }
6889
6890 fn other_column(
6904 &self,
6905 operand: &serde_json::Value,
6906 op: &str,
6907 ) -> Result<String, async_graphql::Error> {
6908 use serde_json::Value;
6909
6910 let refused = |what: &str| {
6911 async_graphql::Error::new(format!(
6912 "the \"{}\" comparison takes the name of a column, {}",
6913 op, what
6914 ))
6915 };
6916 let (against, qualified, name) = match operand {
6917 Value::String(name) => (&self.sql_ref, &self.qualified, name.as_str()),
6918 Value::Array(path) => match path.as_slice() {
6919 [Value::String(name)] => (&self.sql_ref, &self.qualified, name.as_str()),
6920 [Value::String(root), Value::String(name)] if root == "$" => {
6921 (&self.root_ref, &self.root_qualified, name.as_str())
6922 }
6923 _ => return Err(refused("or [\"$\", \"a column\"]")),
6924 },
6925 _ => return Err(refused("written as a string")),
6926 };
6927 let column = self
6930 .names
6931 .column_source(&qualified.schema, &qualified.name, name)
6932 .unwrap_or(name);
6933 Ok(format!(
6934 "{}.{}",
6935 against,
6936 postrust_sql::escape_ident(column)
6937 ))
6938 }
6939
6940 fn relationship(&self, name: &str) -> Option<std::borrow::Cow<'a, RelationshipField>> {
6954 let resolution = self.resolution.as_ref()?;
6955 let published = resolution
6956 .relationships
6957 .get(&self.type_name)
6958 .and_then(|fields| fields.iter().find(|r| r.name == name));
6959 if let Some(found) = published {
6960 return Some(std::borrow::Cow::Borrowed(found));
6961 }
6962
6963 let table = resolution.cache.get_table(&self.qualified)?;
6964
6965 if let Some(declared) = self
6971 .names
6972 .declared_relationships(&table.schema, &table.name)
6973 {
6974 if let Some(entry) = declared.iter().find(|entry| entry.name == name) {
6975 let target = entry
6978 .target(&table.schema)
6979 .map(|(_, target)| target)
6980 .unwrap_or_default();
6981 if let Some(field) = crate::schema::mapped_relationship_field(
6982 entry,
6983 table,
6984 resolution.cache,
6985 &table.schema,
6986 &target,
6987 &target,
6988 &target,
6989 ) {
6990 return Some(std::borrow::Cow::Owned(field));
6991 }
6992 if let Some(key) = entry.using.as_deref() {
6996 if let Some(found) = resolution
6997 .cache
6998 .get_relationships(&self.qualified, &table.schema)
6999 .into_iter()
7000 .flatten()
7001 .find(|rel| {
7002 crate::schema::relationship_keys(rel)
7003 .iter()
7004 .any(|found| found == key)
7005 })
7006 {
7007 return Some(std::borrow::Cow::Owned(
7008 crate::schema::relationship::RelationshipField::from_relationship_named(
7009 found,
7010 &found.foreign_table().name,
7011 Some(&entry.name),
7012 ),
7013 ));
7014 }
7015 }
7016 }
7017 }
7018
7019 resolution
7020 .cache
7021 .get_relationships(&self.qualified, &table.schema)?
7022 .iter()
7023 .find_map(|rel| {
7024 let given = crate::schema::relationship_keys(rel)
7025 .iter()
7026 .find_map(|key| self.names.relationship(&table.schema, &table.name, key));
7027 let field = RelationshipField::from_relationship_named(
7031 rel,
7032 &rel.foreign_table().name,
7033 given,
7034 );
7035 (field.name == name).then_some(std::borrow::Cow::Owned(field))
7036 })
7037 }
7038}
7039
7040fn column_comparison(op: &str) -> Option<&'static str> {
7049 Some(match op {
7050 "_ceq" => "=",
7051 "_cne" => "<>",
7052 "_cgt" => ">",
7053 "_cgte" => ">=",
7054 "_clt" => "<",
7055 "_clte" => "<=",
7056 _ => return None,
7057 })
7058}
7059
7060fn build_condition(
7062 value: &serde_json::Value,
7063 scope: &WhereScope<'_>,
7064 param_idx: &mut usize,
7065 values: &mut Vec<serde_json::Value>,
7066 alias_counter: &mut usize,
7067) -> Result<Option<String>, async_graphql::Error> {
7068 let serde_json::Value::Object(map) = value else {
7069 return Ok(None);
7070 };
7071
7072 let mut conditions: Vec<String> = Vec::new();
7073
7074 for (key, val) in map {
7075 match key.as_str() {
7076 "_and" | "_or" => {
7080 let members = val.as_array().ok_or_else(|| {
7081 async_graphql::Error::new(format!("\"{}\" takes a list of expressions", key))
7082 })?;
7083 let mut parts = Vec::new();
7084 for member in members {
7085 if let Some(sql) =
7086 build_condition(member, scope, param_idx, values, alias_counter)?
7087 {
7088 parts.push(sql);
7089 }
7090 }
7091 if parts.is_empty() {
7092 if key == "_or" {
7093 conditions.push("false".to_string());
7094 }
7095 continue;
7096 }
7097 let joiner = if key == "_and" { " AND " } else { " OR " };
7098 conditions.push(format!("({})", parts.join(joiner)));
7099 }
7100 "_not" => {
7101 if let Some(sql) = build_condition(val, scope, param_idx, values, alias_counter)? {
7102 conditions.push(format!("NOT ({})", sql));
7103 }
7104 }
7105 PERMISSION => {
7108 if let Some(sql) =
7109 build_condition(val, &scope.as_system(), param_idx, values, alias_counter)?
7110 {
7111 conditions.push(sql);
7112 }
7113 }
7114 "_exists" => {
7118 conditions.push(table_exists_sql(
7119 val,
7120 scope,
7121 param_idx,
7122 values,
7123 alias_counter,
7124 )?);
7125 }
7126 name if scope.relationship(name).is_some() => {
7132 let relationship = scope.relationship(name).expect("just checked");
7133 conditions.push(exists_sql(
7134 &relationship,
7135 val,
7136 scope,
7137 param_idx,
7138 values,
7139 alias_counter,
7140 )?);
7141 }
7142 name if scope.column_type(name).is_none()
7147 && name
7148 .strip_suffix("_aggregate")
7149 .and_then(|rel| scope.relationship(rel))
7150 .is_some_and(|rel| rel.is_list) =>
7151 {
7152 let relationship = name
7153 .strip_suffix("_aggregate")
7154 .and_then(|rel| scope.relationship(rel))
7155 .expect("just checked");
7156 conditions.push(aggregate_predicate_sql(
7157 &relationship,
7158 val,
7159 scope,
7160 param_idx,
7161 values,
7162 alias_counter,
7163 )?);
7164 }
7165 column => {
7166 let quoted = scope.column(column);
7167 match val {
7168 serde_json::Value::Object(ops) => {
7169 let column_type = scope.column_type(column);
7170 for (op, operand) in ops {
7171 if let Some(other) = column_comparison(op) {
7177 conditions.push(format!(
7178 "{} {} {}",
7179 quoted,
7180 other,
7181 scope.other_column(operand, op)?
7182 ));
7183 continue;
7184 }
7185 conditions.push(comparison_sql(
7186 "ed,
7187 column,
7188 column_type.as_deref(),
7189 op,
7190 operand,
7191 param_idx,
7192 values,
7193 )?);
7194 }
7195 }
7196 other => {
7200 conditions.push(format!("{} = ${}", quoted, param_idx));
7201 values.push(other.clone());
7202 *param_idx += 1;
7203 }
7204 }
7205 }
7206 }
7207 }
7208
7209 Ok(if conditions.is_empty() {
7210 None
7211 } else if conditions.len() == 1 {
7212 conditions.pop()
7213 } else {
7214 Some(conditions.join(" AND "))
7215 })
7216}
7217
7218fn exists_sql(
7225 relationship: &RelationshipField,
7226 child_expression: &serde_json::Value,
7227 scope: &WhereScope<'_>,
7228 param_idx: &mut usize,
7229 values: &mut Vec<serde_json::Value>,
7230 alias_counter: &mut usize,
7231) -> Result<String, async_graphql::Error> {
7232 let cache = scope.resolution.as_ref().map(|r| r.cache).ok_or_else(|| {
7233 async_graphql::Error::new(format!(
7234 "filtering on the relationship \"{}\" is not available here",
7235 relationship.name
7236 ))
7237 })?;
7238
7239 let plan = postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, cache)
7240 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
7241
7242 if plan.junction.is_some() || (plan.function.is_none() && plan.columns.is_empty()) {
7243 return Err(async_graphql::Error::new(format!(
7244 "filtering on \"{}\" is not supported: it is reached through a junction \
7245 rather than by a key",
7246 relationship.name
7247 )));
7248 }
7249
7250 *alias_counter += 1;
7251 let alias = format!("pgrst_rel_{}", alias_counter);
7252 let child_scope = WhereScope::aliased(
7253 &plan.foreign_schema,
7254 &plan.foreign_table,
7255 &alias,
7256 &relationship.target_type,
7257 scope,
7258 );
7259
7260 let (source, mut correlation) = match &plan.function {
7263 Some(function) => (
7264 format!(
7265 "{}.{}({})",
7266 postrust_sql::escape_ident(&function.schema),
7267 postrust_sql::escape_ident(&function.name),
7268 scope.row_ref
7269 ),
7270 Vec::new(),
7271 ),
7272 None => {
7273 let mut columns = Vec::with_capacity(plan.columns.len());
7274 for (parent_column, child_column) in &plan.columns {
7275 columns.push(format!(
7276 "{} = {}",
7277 scope.column(parent_column),
7278 child_scope.column(child_column)
7279 ));
7280 }
7281 (
7282 format!(
7283 "{}.{}",
7284 postrust_sql::escape_ident(&plan.foreign_schema),
7285 postrust_sql::escape_ident(&plan.foreign_table)
7286 ),
7287 columns,
7288 )
7289 }
7290 };
7291
7292 let child_condition = build_condition(
7293 child_expression,
7294 &child_scope,
7295 param_idx,
7296 values,
7297 alias_counter,
7298 )?;
7299 if let Some(sql) = child_condition {
7300 correlation.push(format!("({})", sql));
7301 }
7302
7303 if let Some(caller) = &child_scope.caller {
7308 let permission = permission_predicate(
7315 caller,
7316 child_scope.names,
7317 &plan.foreign_schema,
7318 &plan.foreign_table,
7319 )?;
7320 if let Some(predicate) = permission {
7321 if let Some(sql) =
7322 build_condition(&predicate, &child_scope, param_idx, values, alias_counter)?
7323 {
7324 correlation.push(format!("({})", sql));
7325 }
7326 }
7327 }
7328 if correlation.is_empty() {
7329 correlation.push("true".to_string());
7330 }
7331
7332 Ok(format!(
7333 "EXISTS (SELECT 1 FROM {} AS {} WHERE {})",
7334 source,
7335 postrust_sql::escape_ident(&alias),
7336 correlation.join(" AND ")
7337 ))
7338}
7339
7340fn table_exists_sql(
7365 spec: &serde_json::Value,
7366 scope: &WhereScope<'_>,
7367 param_idx: &mut usize,
7368 values: &mut Vec<serde_json::Value>,
7369 alias_counter: &mut usize,
7370) -> Result<String, async_graphql::Error> {
7371 let Some((schema, table)) = crate::role::exists_target(spec, &scope.qualified.schema) else {
7372 return Err(async_graphql::Error::new(
7373 "\"_exists\" needs a \"_table\" to look in",
7374 ));
7375 };
7376
7377 let qualified = postrust_core::api_request::QualifiedIdentifier::new(&schema, &table);
7381 if scope
7382 .resolution
7383 .as_ref()
7384 .is_some_and(|r| r.cache.get_table(&qualified).is_none())
7385 {
7386 return Err(async_graphql::Error::new(format!(
7387 "\"_exists\" names a table this server does not have: \"{}.{}\"",
7388 schema, table
7389 )));
7390 }
7391
7392 *alias_counter += 1;
7393 let alias = format!("pgrst_exists_{}", alias_counter);
7394 let type_name = scope
7398 .names
7399 .base_name(&schema, &table)
7400 .unwrap_or(&table)
7401 .to_string();
7402 let mut inner = WhereScope::aliased(&schema, &table, &alias, &type_name, scope);
7403 inner.caller = None;
7406
7407 let condition = match spec.get("_where") {
7408 Some(predicate) => build_condition(predicate, &inner, param_idx, values, alias_counter)?,
7409 None => None,
7410 };
7411
7412 Ok(format!(
7413 "EXISTS (SELECT 1 FROM {}.{} AS {} WHERE {})",
7414 postrust_sql::escape_ident(&schema),
7415 postrust_sql::escape_ident(&table),
7416 postrust_sql::escape_ident(&alias),
7417 condition.unwrap_or_else(|| "true".to_string())
7418 ))
7419}
7420
7421fn aggregate_predicate_sql(
7436 relationship: &RelationshipField,
7437 expression: &serde_json::Value,
7438 scope: &WhereScope<'_>,
7439 param_idx: &mut usize,
7440 values: &mut Vec<serde_json::Value>,
7441 alias_counter: &mut usize,
7442) -> Result<String, async_graphql::Error> {
7443 let serde_json::Value::Object(over) = expression else {
7444 return Ok("true".to_string());
7445 };
7446
7447 let cache = scope.resolution.as_ref().map(|r| r.cache).ok_or_else(|| {
7448 async_graphql::Error::new(format!(
7449 "filtering on the relationship \"{}\" is not available here",
7450 relationship.name
7451 ))
7452 })?;
7453 let plan = postrust_core::embed::EmbedPlan::resolve(&relationship.relationship, cache)
7454 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
7455 if plan.junction.is_some() || (plan.function.is_none() && plan.columns.is_empty()) {
7456 return Err(async_graphql::Error::new(format!(
7457 "aggregating over \"{}\" is not supported: it is reached through a junction \
7458 rather than by a key",
7459 relationship.name
7460 )));
7461 }
7462
7463 let mut conditions: Vec<String> = Vec::new();
7464 for (function, spec) in over {
7465 if spec.is_null() {
7466 continue;
7467 }
7468 let serde_json::Value::Object(spec) = spec else {
7469 continue;
7470 };
7471 let Some(predicate) = spec.get("predicate").filter(|p| !p.is_null()) else {
7472 return Err(validation_error(format!(
7473 "\"{}\" over \"{}\" needs a predicate",
7474 function, relationship.name
7475 )));
7476 };
7477
7478 *alias_counter += 1;
7479 let alias = format!("pgrst_agg_{}", alias_counter);
7480 let child_scope = WhereScope::aliased(
7481 &plan.foreign_schema,
7482 &plan.foreign_table,
7483 &alias,
7484 &relationship.target_type,
7485 scope,
7486 );
7487
7488 let (source, mut correlation) = match &plan.function {
7491 Some(routine) => (
7492 format!(
7493 "{}.{}({})",
7494 postrust_sql::escape_ident(&routine.schema),
7495 postrust_sql::escape_ident(&routine.name),
7496 scope.row_ref
7497 ),
7498 Vec::new(),
7499 ),
7500 None => {
7501 let mut columns = Vec::with_capacity(plan.columns.len());
7502 for (parent_column, child_column) in &plan.columns {
7503 columns.push(format!(
7504 "{} = {}",
7505 scope.column(parent_column),
7506 child_scope.column(child_column)
7507 ));
7508 }
7509 (
7510 format!(
7511 "{}.{}",
7512 postrust_sql::escape_ident(&plan.foreign_schema),
7513 postrust_sql::escape_ident(&plan.foreign_table)
7514 ),
7515 columns,
7516 )
7517 }
7518 };
7519 if let Some(filter) = spec.get("filter").filter(|f| !f.is_null()) {
7522 if let Some(sql) =
7523 build_condition(filter, &child_scope, param_idx, values, alias_counter)?
7524 {
7525 correlation.push(format!("({})", sql));
7526 }
7527 }
7528 if correlation.is_empty() {
7529 correlation.push("true".to_string());
7530 }
7531
7532 let arguments = spec.get("arguments").filter(|a| !a.is_null());
7533 let distinct = matches!(spec.get("distinct"), Some(serde_json::Value::Bool(true)));
7534 let (aggregate, operand_type) = match function.as_str() {
7535 "count" => {
7536 let columns: Vec<String> = match arguments {
7537 Some(serde_json::Value::Array(items)) => items
7538 .iter()
7539 .filter_map(|item| item.as_str())
7540 .map(|column| child_scope.column(column))
7541 .collect(),
7542 Some(serde_json::Value::String(one)) => vec![child_scope.column(one)],
7543 _ => Vec::new(),
7544 };
7545 let counted = match columns.len() {
7546 0 => "*".to_string(),
7547 1 => columns.into_iter().next().unwrap_or_default(),
7548 _ => format!("({})", columns.join(", ")),
7549 };
7550 let counted = match distinct && counted != "*" {
7551 true => format!("DISTINCT {}", counted),
7552 false => counted,
7553 };
7554 (format!("count({})", counted), "integer")
7555 }
7556 "bool_and" | "bool_or" => {
7557 let Some(column) = arguments.and_then(|a| a.as_str()) else {
7558 return Err(validation_error(format!(
7559 "\"{}\" over \"{}\" needs the column to fold",
7560 function, relationship.name
7561 )));
7562 };
7563 (
7564 format!("{}({})", function, child_scope.column(column)),
7565 "boolean",
7566 )
7567 }
7568 other => {
7569 return Err(validation_error(format!(
7570 "\"{}\" is not an aggregate a predicate can be written over",
7571 other
7572 )))
7573 }
7574 };
7575
7576 let subselect = format!(
7577 "(SELECT {} FROM {} AS {} WHERE {})",
7578 aggregate,
7579 source,
7580 postrust_sql::escape_ident(&alias),
7581 correlation.join(" AND ")
7582 );
7583 let serde_json::Value::Object(operators) = predicate else {
7584 return Err(validation_error(format!(
7585 "the predicate on \"{}\" is not a comparison",
7586 function
7587 )));
7588 };
7589 for (operator, operand) in operators {
7590 conditions.push(comparison_sql(
7591 &subselect,
7592 function,
7593 Some(operand_type),
7594 operator,
7595 operand,
7596 param_idx,
7597 values,
7598 )?);
7599 }
7600 }
7601
7602 Ok(match conditions.is_empty() {
7603 true => "true".to_string(),
7604 false => format!("({})", conditions.join(" AND ")),
7605 })
7606}
7607
7608#[allow(clippy::too_many_arguments)]
7616fn postgis_sql(
7617 quoted: &str,
7618 column_type: Option<&str>,
7619 function: &str,
7620 op: &str,
7621 operand: &serde_json::Value,
7622 param_idx: &mut usize,
7623 values: &mut Vec<serde_json::Value>,
7624) -> Result<String, async_graphql::Error> {
7625 let is_geography = column_type == Some("geography");
7626 let mut shape = |value: &serde_json::Value, param_idx: &mut usize| -> String {
7627 let placeholder = format!("${}", param_idx);
7628 *param_idx += 1;
7629 values.push(value.clone());
7630 match is_geography {
7631 true => format!("ST_GeomFromGeoJSON({})::geography", placeholder),
7632 false => format!("ST_GeomFromGeoJSON({})", placeholder),
7633 }
7634 };
7635
7636 match op {
7637 "_st_d_within" | "_st_3d_d_within" => {
7639 let serde_json::Value::Object(spec) = operand else {
7640 return Err(async_graphql::Error::new(format!(
7641 "\"{}\" takes {{distance, from}}",
7642 op
7643 )));
7644 };
7645 let Some(from) = spec.get("from") else {
7646 return Err(async_graphql::Error::new(format!(
7647 "\"{}\" needs a shape to measure from",
7648 op
7649 )));
7650 };
7651 let Some(distance) = spec.get("distance") else {
7652 return Err(async_graphql::Error::new(format!(
7653 "\"{}\" needs a distance",
7654 op
7655 )));
7656 };
7657 let from_sql = shape(from, param_idx);
7658 let distance_sql = format!("${}", param_idx);
7659 *param_idx += 1;
7660 values.push(distance.clone());
7661 let spheroid = match (is_geography, spec.get("use_spheroid")) {
7666 (true, Some(use_spheroid)) if !use_spheroid.is_null() => {
7667 let placeholder = format!("${}", param_idx);
7668 *param_idx += 1;
7669 values.push(use_spheroid.clone());
7670 format!(", {}::boolean", placeholder)
7671 }
7672 _ => String::new(),
7673 };
7674 Ok(format!(
7675 "{}({}, {}, {}::float8{})",
7676 function, quoted, from_sql, distance_sql, spheroid
7677 ))
7678 }
7679 "_st_intersects_rast" => {
7681 let placeholder = format!("${}", param_idx);
7682 *param_idx += 1;
7683 values.push(operand.clone());
7684 Ok(format!("{}({}, {}::raster)", function, quoted, placeholder))
7685 }
7686 "_st_intersects_geom_nband" | "_st_intersects_nband_geom" => {
7688 let serde_json::Value::Object(spec) = operand else {
7689 return Err(async_graphql::Error::new(format!(
7690 "\"{}\" takes an object",
7691 op
7692 )));
7693 };
7694 let Some(geometry) = spec.get("geommin") else {
7695 return Err(async_graphql::Error::new(format!(
7696 "\"{}\" needs a shape",
7697 op
7698 )));
7699 };
7700 let band = spec.get("nband").filter(|v| !v.is_null());
7701 let geometry_sql = shape(geometry, param_idx);
7702 Ok(match band {
7703 None => format!("{}({}, {})", function, quoted, geometry_sql),
7704 Some(band) => {
7705 let placeholder = format!("${}", param_idx);
7706 *param_idx += 1;
7707 values.push(band.clone());
7708 format!(
7712 "{}({}, {}::int, {})",
7713 function, quoted, placeholder, geometry_sql
7714 )
7715 }
7716 })
7717 }
7718 _ => {
7720 let other = shape(operand, param_idx);
7721 Ok(format!("{}({}, {})", function, quoted, other))
7722 }
7723 }
7724}
7725
7726fn sql_array(
7732 items: &[serde_json::Value],
7733 cast: &str,
7734 param_idx: &mut usize,
7735 values: &mut Vec<serde_json::Value>,
7736) -> String {
7737 if items.is_empty() {
7738 return format!("ARRAY[]::{}", cast);
7739 }
7740 let placeholders: Vec<String> = items
7741 .iter()
7742 .map(|item| {
7743 let placeholder = format!("${}", param_idx);
7744 *param_idx += 1;
7745 values.push(item.clone());
7746 placeholder
7747 })
7748 .collect();
7749 format!("ARRAY[{}]::{}", placeholders.join(", "), cast)
7750}
7751
7752#[allow(clippy::too_many_arguments)]
7754fn comparison_sql(
7755 quoted: &str,
7756 column: &str,
7757 column_type: Option<&str>,
7758 op: &str,
7759 operand: &serde_json::Value,
7760 param_idx: &mut usize,
7761 values: &mut Vec<serde_json::Value>,
7762) -> Result<String, async_graphql::Error> {
7763 if op == "_cast" {
7769 let serde_json::Value::Object(casts) = operand else {
7770 return Err(async_graphql::Error::new(
7771 "_cast takes an object naming the type to compare as",
7772 ));
7773 };
7774 let mut conditions = Vec::new();
7775 for (target, comparisons) in casts {
7776 let pg_type = match target.as_str() {
7780 "geometry" | "geography" => target.as_str(),
7781 "String" => "text",
7782 _ => {
7783 return Err(async_graphql::Error::new(format!(
7784 "cannot compare \"{}\" as \"{}\"",
7785 column, target
7786 )))
7787 }
7788 };
7789 let serde_json::Value::Object(ops) = comparisons else {
7790 continue;
7791 };
7792 let cast = format!("{}::{}", quoted, pg_type);
7793 for (nested_op, nested_operand) in ops {
7794 conditions.push(comparison_sql(
7795 &cast,
7796 column,
7797 Some(pg_type),
7798 nested_op,
7799 nested_operand,
7800 param_idx,
7801 values,
7802 )?);
7803 }
7804 }
7805 return Ok(match conditions.len() {
7806 0 => "true".to_string(),
7807 1 => conditions.pop().expect("just counted"),
7808 _ => format!("({})", conditions.join(" AND ")),
7809 });
7810 }
7811
7812 if let Some(function) = crate::input::bool_exp::postgis_function(op) {
7815 return postgis_sql(
7816 quoted,
7817 column_type,
7818 function,
7819 op,
7820 operand,
7821 param_idx,
7822 values,
7823 );
7824 }
7825
7826 if let Some((operator, cast)) = crate::input::bool_exp::ltree_operator(op) {
7830 if cast.ends_with("[]") {
7831 let items = operand.as_array().ok_or_else(|| {
7832 async_graphql::Error::new(format!(
7833 "the \"{}\" comparison on \"{}\" takes a list",
7834 op, column
7835 ))
7836 })?;
7837 return Ok(format!(
7838 "{} {} {}",
7839 quoted,
7840 operator,
7841 sql_array(items, cast, param_idx, values)
7842 ));
7843 }
7844 let placeholder = format!("${}", param_idx);
7845 *param_idx += 1;
7846 values.push(operand.clone());
7847 return Ok(format!("{} {} {}::{}", quoted, operator, placeholder, cast));
7848 }
7849
7850 if let Some(function) = match op {
7855 "_jsonb_path_exists" => Some("jsonb_path_exists"),
7856 "_jsonb_path_match" => Some("jsonb_path_match"),
7857 _ => None,
7858 } {
7859 let placeholder = format!("${}", param_idx);
7860 *param_idx += 1;
7861 values.push(operand.clone());
7862 return Ok(format!(
7863 "{}({}, {}::jsonpath)",
7864 function, quoted, placeholder
7865 ));
7866 }
7867
7868 let binary = match op {
7870 "_eq" => Some("="),
7871 "_neq" => Some("<>"),
7872 "_gt" => Some(">"),
7873 "_gte" => Some(">="),
7874 "_lt" => Some("<"),
7875 "_lte" => Some("<="),
7876 "_like" => Some("LIKE"),
7877 "_nlike" => Some("NOT LIKE"),
7878 "_ilike" => Some("ILIKE"),
7879 "_nilike" => Some("NOT ILIKE"),
7880 "_similar" => Some("SIMILAR TO"),
7881 "_nsimilar" => Some("NOT SIMILAR TO"),
7882 "_regex" => Some("~"),
7883 "_nregex" => Some("!~"),
7884 "_iregex" => Some("~*"),
7885 "_niregex" => Some("!~*"),
7886 "_contains" => Some("@>"),
7887 "_contained_in" => Some("<@"),
7888 "_has_key" => Some("?"),
7889 _ => None,
7890 };
7891
7892 if let Some(sql_op) = binary {
7893 let placeholder = format!("${}", param_idx);
7894 *param_idx += 1;
7895 values.push(match op {
7900 "_contains" | "_contained_in" => match operand {
7901 serde_json::Value::String(_)
7902 | serde_json::Value::Number(_)
7903 | serde_json::Value::Bool(_) => serde_json::Value::String(operand.to_string()),
7904 other => other.clone(),
7905 },
7906 _ => operand.clone(),
7907 });
7908 let cast = match op {
7920 "_contains" | "_contained_in" => "::jsonb".to_string(),
7921 "_has_key" => "::text".to_string(),
7922 _ if operand.is_null() => match column_type {
7931 Some(pg_type) => format!("::{}", pg_type),
7932 None => String::new(),
7933 },
7934 _ if operand.is_string() => match column_type {
7945 Some(pg_type) => format!("::{}", pg_type),
7946 None => String::new(),
7947 },
7948 _ => String::new(),
7949 };
7950 return Ok(format!("{} {} {}{}", quoted, sql_op, placeholder, cast));
7951 }
7952
7953 match op {
7954 "_is_null" => Ok(if operand.as_bool().unwrap_or(false) {
7955 format!("{} IS NULL", quoted)
7956 } else {
7957 format!("{} IS NOT NULL", quoted)
7958 }),
7959 "_in" | "_nin" => {
7960 let items = operand.as_array().ok_or_else(|| {
7961 async_graphql::Error::new(format!(
7962 "the \"{}\" comparison on \"{}\" requires a list of values",
7963 op, column
7964 ))
7965 })?;
7966 if items.is_empty() {
7967 return Ok(if op == "_in" { "false" } else { "true" }.to_string());
7970 }
7971 let mut placeholders = Vec::with_capacity(items.len());
7972 for item in items {
7973 let cast = match (item.is_null() || item.is_string(), column_type) {
7976 (true, Some(pg_type)) => format!("::{}", pg_type),
7977 _ => String::new(),
7978 };
7979 placeholders.push(format!("${}{}", param_idx, cast));
7980 values.push(item.clone());
7981 *param_idx += 1;
7982 }
7983 Ok(format!(
7984 "{} {} ({})",
7985 quoted,
7986 if op == "_in" { "IN" } else { "NOT IN" },
7987 placeholders.join(", ")
7988 ))
7989 }
7990 "_has_keys_any" | "_has_keys_all" => {
7991 let items = operand.as_array().ok_or_else(|| {
7992 async_graphql::Error::new(format!(
7993 "the \"{}\" comparison on \"{}\" requires a list of keys",
7994 op, column
7995 ))
7996 })?;
7997 Ok(format!(
7998 "{} {} {}",
7999 quoted,
8000 if op == "_has_keys_any" { "?|" } else { "?&" },
8001 sql_array(items, "text[]", param_idx, values)
8002 ))
8003 }
8004 other => Err(async_graphql::Error::new(format!(
8005 "unsupported comparison \"{}\" on \"{}\"",
8006 other, column
8007 ))),
8008 }
8009}
8010
8011#[allow(clippy::too_many_arguments)] async fn build_order_by_clause(
8021 ctx: &ResolverContext<'_>,
8022 schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
8023 schema_name: &str,
8024 table_name: &str,
8025 type_name: &str,
8026 relationships: &HashMap<String, Vec<RelationshipField>>,
8027 reference: &str,
8028 names: &crate::names::NameOverrides,
8029) -> Result<String, async_graphql::Error> {
8030 let Ok(order_arg) = ctx.args.try_get("order_by") else {
8031 return Ok(String::new());
8032 };
8033
8034 let value = accessor_to_json(&order_arg);
8035 let entries: Vec<&serde_json::Value> = match &value {
8038 serde_json::Value::Array(items) => items.iter().collect(),
8039 serde_json::Value::Object(_) => vec![&value],
8040 serde_json::Value::Null => return Ok(String::new()),
8041 _ => {
8042 return Err(async_graphql::Error::new(
8043 "order_by takes an object or a list of them",
8044 ))
8045 }
8046 };
8047 if entries.is_empty() {
8048 return Ok(String::new());
8049 }
8050
8051 let guard = schema_cache
8052 .get()
8053 .await
8054 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8055 let cache = guard
8056 .as_ref()
8057 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
8058 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8059 let table = cache
8060 .get_table(&qi)
8061 .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8062
8063 let mut terms = Vec::new();
8064 let mut alias_counter = 0usize;
8065 for entry in entries {
8066 order_terms_into(
8067 entry,
8068 cache,
8069 relationships,
8070 type_name,
8071 table,
8072 reference,
8073 names,
8074 &mut alias_counter,
8075 &mut terms,
8076 )?;
8077 }
8078
8079 if terms.is_empty() {
8080 return Ok(String::new());
8081 }
8082 Ok(format!(" ORDER BY {}", terms.join(", ")))
8083}
8084
8085#[allow(clippy::too_many_arguments)]
8093fn order_terms_into(
8094 entry: &serde_json::Value,
8095 cache: &SchemaCache,
8096 relationships: &HashMap<String, Vec<RelationshipField>>,
8097 type_name: &str,
8098 table: &postrust_core::schema_cache::Table,
8099 reference: &str,
8100 names: &crate::names::NameOverrides,
8101 alias_counter: &mut usize,
8102 terms: &mut Vec<String>,
8103) -> Result<(), async_graphql::Error> {
8104 let serde_json::Value::Object(map) = entry else {
8105 return Err(async_graphql::Error::new(
8106 "each order_by entry is an object mapping a column to a direction",
8107 ));
8108 };
8109 let available: &[RelationshipField] = relationships
8110 .get(type_name)
8111 .map(|r| r.as_slice())
8112 .unwrap_or(&[]);
8113
8114 for (key, value) in map {
8115 if value.is_null() {
8121 continue;
8122 }
8123
8124 if let Some(name) = value.as_str() {
8126 let sql = crate::input::order_by::direction_sql(name).ok_or_else(|| {
8127 async_graphql::Error::new(format!(
8128 "\"{}\" is not a sort direction; expected one of asc, desc, \
8129 asc_nulls_first, asc_nulls_last, desc_nulls_first, desc_nulls_last",
8130 name
8131 ))
8132 })?;
8133 let column = table_column_for(names, table, key);
8134 if table.get_column(column).is_some() {
8135 terms.push(format!(
8136 "{}.{} {}",
8137 reference,
8138 postrust_sql::escape_ident(column),
8139 sql
8140 ));
8141 continue;
8142 }
8143 let function = names
8146 .computed_source(&table.schema, &table.name, key)
8147 .unwrap_or(key);
8148 if let Some(definition) = table.get_computed_column(function) {
8149 terms.push(format!(
8150 "{} {}",
8151 computed_call(definition, &format!("{}.*", reference), reference),
8152 sql
8153 ));
8154 continue;
8155 }
8156 return Err(async_graphql::Error::new(format!(
8157 "cannot order by unknown column \"{}\" on \"{}\"",
8158 key, table.name
8159 )));
8160 }
8161
8162 if let Some(rel) = key
8164 .strip_suffix("_aggregate")
8165 .and_then(|name| available.iter().find(|r| r.name == name && r.is_list))
8166 {
8167 aggregate_order_terms(value, rel, cache, reference, alias_counter, terms)?;
8168 continue;
8169 }
8170
8171 if let Some(rel) = available.iter().find(|r| r.name == *key && !r.is_list) {
8173 let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, cache)
8174 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8175 if plan.columns.is_empty() {
8176 return Err(async_graphql::Error::new(format!(
8177 "cannot order by \"{}\": it is not reached by a key",
8178 key
8179 )));
8180 }
8181 *alias_counter += 1;
8182 let alias = format!("pgrst_ord_{}", alias_counter);
8183 let quoted_alias = postrust_sql::escape_ident(&alias);
8184 let correlation = plan
8185 .columns
8186 .iter()
8187 .map(|(local, foreign)| {
8188 format!(
8189 "{} = {}.{}",
8190 format_args!("{}.{}", reference, postrust_sql::escape_ident(local)),
8191 quoted_alias,
8192 postrust_sql::escape_ident(foreign)
8193 )
8194 })
8195 .collect::<Vec<_>>()
8196 .join(" AND ");
8197
8198 let target_qi = postrust_core::api_request::QualifiedIdentifier::new(
8199 &plan.foreign_schema,
8200 &plan.foreign_table,
8201 );
8202 let Some(target) = cache.get_table(&target_qi) else {
8203 return Err(async_graphql::Error::new(format!(
8204 "unknown table \"{}\"",
8205 plan.foreign_table
8206 )));
8207 };
8208
8209 let mut nested = Vec::new();
8212 order_terms_into(
8213 value,
8214 cache,
8215 relationships,
8216 &rel.target_type,
8217 target,
8218 "ed_alias,
8219 names,
8220 alias_counter,
8221 &mut nested,
8222 )?;
8223 for term in nested {
8224 let (expression, direction) = term
8225 .rsplit_once(' ')
8226 .map(|(e, d)| (e.to_string(), d.to_string()))
8227 .unwrap_or((term.clone(), String::new()));
8228 terms.push(format!(
8229 "(SELECT {} FROM {}.{} AS {} WHERE {}) {}",
8230 expression,
8231 postrust_sql::escape_ident(&plan.foreign_schema),
8232 postrust_sql::escape_ident(&plan.foreign_table),
8233 quoted_alias,
8234 correlation,
8235 direction
8236 ));
8237 }
8238 continue;
8239 }
8240
8241 return Err(async_graphql::Error::new(format!(
8242 "cannot order by \"{}\" on \"{}\"",
8243 key, table.name
8244 )));
8245 }
8246 Ok(())
8247}
8248
8249fn aggregate_order_terms(
8251 value: &serde_json::Value,
8252 rel: &RelationshipField,
8253 cache: &SchemaCache,
8254 reference: &str,
8255 alias_counter: &mut usize,
8256 terms: &mut Vec<String>,
8257) -> Result<(), async_graphql::Error> {
8258 let serde_json::Value::Object(spec) = value else {
8259 return Err(async_graphql::Error::new(
8260 "ordering by an aggregate takes an object, such as {count: desc}",
8261 ));
8262 };
8263 let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, cache)
8264 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8265 if plan.columns.is_empty() && plan.function.is_none() {
8266 return Err(async_graphql::Error::new(format!(
8267 "cannot order by an aggregate of \"{}\": it is not reached by a key",
8268 rel.name
8269 )));
8270 }
8271 if plan.function.is_some() && !rel.arguments.is_empty() {
8274 return Err(async_graphql::Error::new(format!(
8275 "cannot order by an aggregate of \"{}\": it takes arguments, and an \
8276 ordering has nowhere to write them",
8277 rel.name
8278 )));
8279 }
8280
8281 *alias_counter += 1;
8282 let alias = postrust_sql::escape_ident(&format!("pgrst_ord_{}", alias_counter));
8283 let (source, correlation) = match &plan.function {
8286 Some(function) => {
8287 let session = plan.row_argument.as_ref().and_then(|row_argument| {
8288 computed_session_argument(cache, function, row_argument)
8289 .map(|session| (row_argument.clone(), session))
8290 });
8291 let call = match session {
8292 Some((row_argument, session)) => format!(
8293 "{} => {}, {} => {}",
8294 postrust_sql::escape_ident(&row_argument),
8295 reference,
8296 postrust_sql::escape_ident(&session),
8297 SESSION_ARGUMENT
8298 ),
8299 None => reference.to_string(),
8300 };
8301 (
8302 format!(
8303 "{}.{}({})",
8304 postrust_sql::escape_ident(&function.schema),
8305 postrust_sql::escape_ident(&function.name),
8306 call
8307 ),
8308 "true".to_string(),
8309 )
8310 }
8311 None => (
8312 format!(
8313 "{}.{}",
8314 postrust_sql::escape_ident(&plan.foreign_schema),
8315 postrust_sql::escape_ident(&plan.foreign_table)
8316 ),
8317 plan.columns
8318 .iter()
8319 .map(|(local, foreign)| {
8320 format!(
8321 "{}.{} = {}.{}",
8322 reference,
8323 postrust_sql::escape_ident(local),
8324 alias,
8325 postrust_sql::escape_ident(foreign)
8326 )
8327 })
8328 .collect::<Vec<_>>()
8329 .join(" AND "),
8330 ),
8331 };
8332
8333 let mut wanted: Vec<(String, String)> = Vec::new();
8335 for (function, argument) in spec {
8336 if argument.is_null() {
8339 continue;
8340 }
8341 if function == "count" {
8342 let name = argument.as_str().unwrap_or_default();
8343 let Some(direction) = crate::input::order_by::direction_sql(name) else {
8344 return Err(async_graphql::Error::new(format!(
8345 "\"{}\" is not a sort direction",
8346 name
8347 )));
8348 };
8349 wanted.push(("count(*)".to_string(), direction.to_string()));
8350 continue;
8351 }
8352 let serde_json::Value::Object(columns) = argument else {
8353 continue;
8354 };
8355 for (column, direction) in columns {
8356 if direction.is_null() {
8357 continue;
8358 }
8359 let name = direction.as_str().unwrap_or_default();
8360 let Some(direction) = crate::input::order_by::direction_sql(name) else {
8361 return Err(async_graphql::Error::new(format!(
8362 "\"{}\" is not a sort direction",
8363 name
8364 )));
8365 };
8366 wanted.push((
8369 format!(
8370 "{}({}.{})",
8371 function,
8372 alias,
8373 postrust_sql::escape_ident(column)
8374 ),
8375 direction.to_string(),
8376 ));
8377 }
8378 }
8379
8380 for (expression, direction) in wanted {
8381 terms.push(format!(
8382 "(SELECT {} FROM {} AS {} WHERE {}) {}",
8383 expression, source, alias, correlation, direction
8384 ));
8385 }
8386 Ok(())
8387}
8388
8389fn distinct_on_clause(
8403 distinct_on: &[String],
8404 written: Option<&str>,
8405) -> Result<(String, Option<String>), async_graphql::Error> {
8406 if distinct_on.is_empty() {
8407 return Ok((String::new(), written.map(str::to_string)));
8408 }
8409 let terms: Vec<&str> = written
8410 .map(|written| written.split(", ").collect())
8411 .unwrap_or_default();
8412 let column_of = |term: &str| {
8415 let expression = term.split_whitespace().next().unwrap_or(term);
8416 expression
8417 .rsplit_once('.')
8418 .map(|(_, name)| name)
8419 .unwrap_or(expression)
8420 .to_string()
8421 };
8422 let leading: Vec<String> = terms
8423 .iter()
8424 .take(distinct_on.len())
8425 .map(|term| column_of(term))
8426 .collect();
8427 if !terms.is_empty()
8428 && (leading.len() != distinct_on.len()
8429 || distinct_on
8430 .iter()
8431 .any(|column| !leading.contains(&column_of(column))))
8432 {
8433 return Err(validation_error(
8434 "\"distinct_on\" columns must match initial \"order_by\" columns",
8435 ));
8436 }
8437 let order = match terms.is_empty() {
8438 true => Some(distinct_on.join(", ")),
8439 false => written.map(str::to_string),
8440 };
8441 Ok((format!("DISTINCT ON ({}) ", distinct_on.join(", ")), order))
8442}
8443
8444async fn build_distinct_on(
8452 ctx: &ResolverContext<'_>,
8453 schema_cache: &postrust_core::schema_cache::SchemaCacheRef,
8454 schema_name: &str,
8455 table_name: &str,
8456 names: &crate::names::NameOverrides,
8457) -> Result<Vec<String>, async_graphql::Error> {
8458 let Ok(arg) = ctx.args.try_get("distinct_on") else {
8459 return Ok(Vec::new());
8460 };
8461 let value = accessor_to_json(&arg);
8462 let requested: Vec<String> = match &value {
8463 serde_json::Value::Array(items) => items
8464 .iter()
8465 .filter_map(|i| i.as_str().map(|s| s.to_string()))
8466 .collect(),
8467 serde_json::Value::String(one) => vec![one.clone()],
8468 _ => Vec::new(),
8469 };
8470 if requested.is_empty() {
8471 return Ok(Vec::new());
8472 }
8473
8474 let guard = schema_cache
8475 .get()
8476 .await
8477 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
8478 let cache = guard
8479 .as_ref()
8480 .ok_or_else(|| async_graphql::Error::new("schema cache is not loaded"))?;
8481 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8482 let table = cache
8483 .get_table(&qi)
8484 .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8485
8486 let mut quoted = Vec::with_capacity(requested.len());
8487 for field in requested {
8488 let name = table_column_for(names, table, &field).to_string();
8489 if table.get_column(&name).is_none() {
8490 return Err(async_graphql::Error::new(format!(
8491 "cannot take distinct on unknown column \"{}\" of \"{}\"",
8492 field, table_name
8493 )));
8494 }
8495 quoted.push(postrust_sql::escape_ident(&name));
8496 }
8497 Ok(quoted)
8498}
8499
8500#[allow(clippy::too_many_arguments)] fn computed_projections<'a>(
8514 table: &postrust_core::schema_cache::Table,
8515 fields: impl IntoIterator<Item = SelectionField<'a>>,
8516 row_reference: &str,
8517 names: &crate::names::NameOverrides,
8518 schema_cache: &SchemaCache,
8519 param_idx: &mut usize,
8520 values: &mut Vec<serde_json::Value>,
8521) -> Result<Vec<String>, async_graphql::Error> {
8522 let mut projections = Vec::new();
8523 for field in fields {
8524 let name = field.name();
8525 if table
8528 .get_column(table_column_for(names, table, name))
8529 .is_some()
8530 {
8531 continue;
8532 }
8533 let function = names
8536 .computed_source(&table.schema, &table.name, name)
8537 .unwrap_or(name);
8538 let Some(computed) = table.get_computed_column(function) else {
8539 continue;
8540 };
8541 let arguments = crate::schema::computed_caller_arguments(computed, schema_cache);
8542 let given = match arguments.is_empty() {
8543 true => None,
8544 false => embed_arguments(field).remove("args"),
8545 };
8546 projections.push(format!(
8547 "{} AS {}",
8548 computed_column_call(
8549 computed,
8550 row_reference,
8551 name,
8552 &arguments,
8553 given.as_ref(),
8554 param_idx,
8555 values,
8556 )?,
8557 postrust_sql::escape_ident(name)
8558 ));
8559 }
8560 Ok(projections)
8561}
8562
8563fn computed_column_call(
8572 computed: &postrust_core::schema_cache::ComputedColumn,
8573 row: &str,
8574 field_name: &str,
8575 arguments: &[(String, String, bool)],
8576 given: Option<&serde_json::Value>,
8577 param_idx: &mut usize,
8578 values: &mut Vec<serde_json::Value>,
8579) -> Result<String, async_graphql::Error> {
8580 if arguments.is_empty() {
8581 return Ok(computed_call(computed, row, row));
8582 }
8583 let Some(row_argument) = &computed.row_argument else {
8584 return Ok(computed_call(computed, row, row));
8585 };
8586 let function = format!(
8587 "{}.{}",
8588 postrust_sql::escape_ident(&computed.function.schema),
8589 postrust_sql::escape_ident(&computed.function.name)
8590 );
8591 let mut passed = vec![format!(
8592 "{} => {}",
8593 postrust_sql::escape_ident(row_argument),
8594 row
8595 )];
8596 if let Some(session) = &computed.session_argument {
8597 passed.push(format!(
8598 "{} => {}",
8599 postrust_sql::escape_ident(session),
8600 SESSION_ARGUMENT
8601 ));
8602 }
8603 for (name, pg_type, required) in arguments {
8604 match given.and_then(|given| given.get(name)) {
8605 None if *required => {
8606 return Err(async_graphql::Error::new(format!(
8607 "{} needs the argument \"{}\"",
8608 field_name, name
8609 )))
8610 }
8611 None => continue,
8613 Some(value) => {
8614 passed.push(format!(
8615 "{} => ${}::{}",
8616 postrust_sql::escape_ident(name),
8617 param_idx,
8618 pg_type
8619 ));
8620 *param_idx += 1;
8621 values.push(value.clone());
8622 }
8623 }
8624 }
8625 Ok(format!("{}({})", function, passed.join(", ")))
8626}
8627
8628fn count_expression(
8640 field: async_graphql::SelectionField<'_>,
8641 table: (&str, &str),
8642 alias: Option<&str>,
8643 names: &crate::names::NameOverrides,
8644) -> String {
8645 let arguments = embed_arguments(field);
8646 let requested = match arguments.get("columns") {
8647 Some(serde_json::Value::Array(items)) => items
8648 .iter()
8649 .filter_map(|item| item.as_str())
8650 .collect::<Vec<_>>(),
8651 Some(serde_json::Value::String(one)) => vec![one.as_str()],
8652 _ => Vec::new(),
8653 };
8654 if requested.is_empty() {
8655 return "count(*)".to_string();
8656 }
8657 let columns: Vec<String> = requested
8658 .into_iter()
8659 .map(|column| {
8660 let (schema, name) = table;
8661 let source = column_for(names, schema, name, column);
8662 match alias {
8663 Some(alias) => format!(
8664 "{}.{}",
8665 postrust_sql::escape_ident(alias),
8666 postrust_sql::escape_ident(source)
8667 ),
8668 None => postrust_sql::escape_ident(source),
8669 }
8670 })
8671 .collect();
8672 let counted = match columns.len() {
8675 1 => columns.into_iter().next().unwrap_or_default(),
8676 _ => format!("({})", columns.join(", ")),
8677 };
8678 let distinct = matches!(
8679 arguments.get("distinct"),
8680 Some(serde_json::Value::Bool(true))
8681 );
8682 match distinct {
8683 true => format!("count(DISTINCT {})", counted),
8684 false => format!("count({})", counted),
8685 }
8686}
8687
8688#[allow(clippy::too_many_arguments)] fn nested_aggregate_select(
8696 caller: &crate::role::Caller<'_>,
8697 selection: async_graphql::SelectionField<'_>,
8698 child_alias: &str,
8699 schema_cache: &SchemaCache,
8700 relationships: &HashMap<String, Vec<RelationshipField>>,
8701 target_type: &str,
8702 child_table: Option<&postrust_core::schema_cache::Table>,
8703 max_rows: Option<i64>,
8704 alias_counter: &mut usize,
8705 param_idx: &mut usize,
8706 values: &mut Vec<serde_json::Value>,
8707 names: &crate::names::NameOverrides,
8708) -> Result<String, async_graphql::Error> {
8709 use crate::schema::aggregate as agg;
8710
8711 let mut parts: Vec<String> = Vec::new();
8712
8713 for child in selection.selection_set() {
8714 match child.name() {
8715 "aggregate" => {
8716 let of_table = child_table
8717 .map(|table| (table.schema.as_str(), table.name.as_str()))
8718 .unwrap_or(("", ""));
8719 let mut counts: Vec<(String, String)> = Vec::new();
8724 let mut wanted: BTreeMap<&str, Vec<String>> = BTreeMap::new();
8725 for function in child.selection_set() {
8726 if function.name() == "count" {
8727 counts.push((
8728 function.alias().unwrap_or("count").to_string(),
8729 count_expression(function, of_table, Some(child_alias), names),
8730 ));
8731 continue;
8732 }
8733 let sql_function = agg::NUMERIC_AGGREGATES
8734 .iter()
8735 .chain(agg::ORDERED_AGGREGATES.iter())
8736 .find(|(name, _)| *name == function.name())
8737 .map(|(name, _)| *name);
8738 let Some(sql_function) = sql_function else {
8739 continue;
8740 };
8741 let columns = wanted.entry(sql_function).or_default();
8742 for column in function.selection_set() {
8743 let name = column.name().to_string();
8744 if name != "__typename" && !columns.contains(&name) {
8746 columns.push(name);
8747 }
8748 }
8749 }
8750 let mut fields = match counts.iter().any(|(key, _)| key == "count") {
8753 true => Vec::new(),
8754 false => vec!["'count', count(*)".to_string()],
8755 };
8756 for (key, expression) in &counts {
8757 fields.push(format!(
8758 "{}, {}",
8759 postrust_sql::quote_literal(key),
8760 expression
8761 ));
8762 }
8763 for (sql_function, named) in &wanted {
8764 let columns: Vec<String> = named
8765 .iter()
8766 .map(|column| {
8767 let source = child_table
8768 .map(|table| table_column_for(names, table, column))
8769 .unwrap_or(column.as_str());
8770 format!(
8771 "{}, {}({}.{})",
8772 postrust_sql::quote_literal(column),
8773 sql_function,
8774 postrust_sql::escape_ident(child_alias),
8775 postrust_sql::escape_ident(source)
8776 )
8777 })
8778 .collect();
8779 fields.push(format!(
8782 "'{}', json_build_object({})",
8783 sql_function,
8784 columns.join(", ")
8785 ));
8786 }
8787 parts.push(format!(
8788 "json_build_object({}) AS {}",
8789 fields.join(", "),
8790 postrust_sql::escape_ident("aggregate")
8791 ));
8792 }
8793 "nodes" => {
8798 let embeds = build_embed_expressions(
8799 caller,
8800 schema_cache,
8801 relationships,
8802 target_type,
8803 child_alias,
8804 child.selection_set(),
8805 max_rows,
8806 alias_counter,
8807 param_idx,
8808 values,
8809 names,
8810 )?;
8811 let mut columns: Vec<String> = Vec::new();
8812 for column in child.selection_set() {
8813 let name = column.name();
8814 if name == "__typename" || embeds.iter().any(|(field, _)| field == name) {
8815 continue;
8816 }
8817 columns.push(format!(
8818 "{}, {}",
8819 postrust_sql::quote_literal(name),
8820 column_expression(child_table, child_alias, name, names)
8821 ));
8822 }
8823 for (field, expression) in &embeds {
8824 columns.push(format!(
8825 "{}, {}",
8826 postrust_sql::quote_literal(field),
8827 expression
8828 ));
8829 }
8830 let row = if columns.is_empty() {
8831 format!("row_to_json({})", postrust_sql::escape_ident(child_alias))
8832 } else {
8833 format!("json_build_object({})", columns.join(", "))
8834 };
8835 parts.push(format!(
8836 "COALESCE(json_agg({}), '[]'::json) AS {}",
8837 row,
8838 postrust_sql::escape_ident("nodes")
8839 ));
8840 }
8841 _ => {}
8842 }
8843 }
8844
8845 if parts.is_empty() {
8846 parts.push("count(*) AS pgrst_empty".to_string());
8849 }
8850 Ok(parts.join(", "))
8851}
8852
8853fn column_expression(
8858 table: Option<&postrust_core::schema_cache::Table>,
8859 alias: &str,
8860 name: &str,
8861 names: &crate::names::NameOverrides,
8862) -> String {
8863 let column = table
8864 .map(|t| table_column_for(names, t, name))
8865 .unwrap_or(name);
8866 let plain = format!(
8867 "{}.{}",
8868 postrust_sql::escape_ident(alias),
8869 postrust_sql::escape_ident(column)
8870 );
8871 let computed = table
8872 .filter(|t| t.get_column(column).is_none())
8873 .and_then(|t| {
8874 let function = names
8875 .computed_source(&t.schema, &t.name, name)
8876 .unwrap_or(name);
8877 t.get_computed_column(function)
8878 });
8879 match computed {
8880 Some(definition) => computed_call(
8881 definition,
8882 &format!("{}.*", postrust_sql::escape_ident(alias)),
8883 &postrust_sql::escape_ident(alias),
8884 ),
8885 None => plain,
8886 }
8887}
8888
8889fn order_terms(
8897 order: &serde_json::Value,
8898 schema_cache: &SchemaCache,
8899 schema_name: &str,
8900 table_name: &str,
8901 alias: &str,
8902 names: &crate::names::NameOverrides,
8903) -> Result<Option<String>, async_graphql::Error> {
8904 let entries: Vec<&serde_json::Value> = match order {
8905 serde_json::Value::Array(items) => items.iter().collect(),
8906 serde_json::Value::Object(_) => vec![order],
8907 _ => return Ok(None),
8908 };
8909
8910 let qi = postrust_core::api_request::QualifiedIdentifier::new(schema_name, table_name);
8911 let table = schema_cache
8912 .get_table(&qi)
8913 .ok_or_else(|| async_graphql::Error::new(format!("unknown table \"{}\"", table_name)))?;
8914
8915 let mut terms = Vec::new();
8916 for entry in entries {
8917 let serde_json::Value::Object(map) = entry else {
8918 continue;
8919 };
8920 for (field, direction) in map {
8921 if direction.is_null() {
8923 continue;
8924 }
8925 let column = table_column_for(names, table, field);
8926 if table.get_column(column).is_none() {
8927 return Err(async_graphql::Error::new(format!(
8928 "cannot order by unknown column \"{}\" on \"{}\"",
8929 field, table_name
8930 )));
8931 }
8932 let name = direction.as_str().unwrap_or_default();
8933 let sql = crate::input::order_by::direction_sql(name).ok_or_else(|| {
8934 async_graphql::Error::new(format!("\"{}\" is not a sort direction", name))
8935 })?;
8936 terms.push(format!(
8937 "{}.{} {}",
8938 postrust_sql::escape_ident(alias),
8939 postrust_sql::escape_ident(column),
8940 sql
8941 ));
8942 }
8943 }
8944
8945 Ok(if terms.is_empty() {
8946 None
8947 } else {
8948 Some(terms.join(", "))
8949 })
8950}
8951
8952fn always_present(rel: &RelationshipField, table: &postrust_core::schema_cache::Table) -> bool {
8964 use postrust_core::schema_cache::{Cardinality, Relationship};
8965 let Relationship::ForeignKey { cardinality, .. } = &rel.relationship else {
8966 return false;
8967 };
8968 match cardinality {
8969 Cardinality::M2O { .. } => {}
8970 Cardinality::O2O {
8971 is_parent: false, ..
8972 } => {}
8973 _ => return false,
8974 }
8975 let columns = cardinality.columns();
8976 !columns.is_empty()
8977 && columns.iter().all(|(local, _)| {
8978 table
8979 .get_column(local)
8980 .is_some_and(|column| !column.nullable)
8981 })
8982}
8983
8984fn child_holds_the_key(relationship: &postrust_core::schema_cache::Relationship) -> bool {
8992 use postrust_core::schema_cache::{Cardinality, Relationship};
8993 match relationship {
8994 Relationship::ForeignKey { cardinality, .. } => match cardinality {
8995 Cardinality::M2O { .. } => false,
8996 Cardinality::O2O { is_parent, .. } => *is_parent,
8997 _ => true,
8998 },
8999 Relationship::Computed { .. } => true,
9000 }
9001}
9002
9003fn computed_session_argument(
9005 cache: &SchemaCache,
9006 function: &postrust_core::api_request::QualifiedIdentifier,
9007 row_argument: &str,
9008) -> Option<String> {
9009 let _ = row_argument;
9010 cache
9011 .routines
9012 .get(function)
9013 .into_iter()
9014 .flatten()
9015 .find(|routine| routine.name == function.name)?
9016 .params
9017 .iter()
9018 .find(|param| {
9019 param.name == "hasura_session" && matches!(param.param_type.as_str(), "json" | "jsonb")
9020 })
9021 .map(|param| param.name.clone())
9022}
9023
9024fn computed_args_type_name(type_name: &str, field: &str) -> String {
9026 format!("{}_{}_args", type_name, field)
9027}
9028
9029fn computed_arguments(
9036 relationship: &RelationshipField,
9037 plan: &postrust_core::embed::EmbedPlan,
9038 parent_row: &str,
9039 given: Option<&serde_json::Value>,
9040 param_idx: &mut usize,
9041 values: &mut Vec<serde_json::Value>,
9042 schema_cache: &SchemaCache,
9043) -> Result<Option<String>, async_graphql::Error> {
9044 let (Some(function), Some(row_argument)) = (&plan.function, &plan.row_argument) else {
9045 return Ok(None);
9046 };
9047 let session = schema_cache
9048 .routines
9049 .get(function)
9050 .into_iter()
9051 .flatten()
9052 .find(|routine| routine.name == function.name)
9053 .and_then(|routine| {
9054 routine
9055 .params
9056 .iter()
9057 .find(|param| {
9058 param.name == "hasura_session"
9059 && matches!(param.param_type.as_str(), "json" | "jsonb")
9060 })
9061 .map(|param| param.name.clone())
9062 });
9063 if relationship.arguments.is_empty() && session.is_none() {
9064 return Ok(None);
9065 }
9066
9067 let mut passed = vec![format!(
9068 "{} => {}",
9069 postrust_sql::escape_ident(row_argument),
9070 parent_row
9071 )];
9072 if let Some(session) = session {
9073 passed.push(format!(
9074 "{} => {}",
9075 postrust_sql::escape_ident(&session),
9076 SESSION_ARGUMENT
9077 ));
9078 }
9079 for (name, pg_type, required) in &relationship.arguments {
9080 match given.and_then(|given| given.get(name)) {
9081 None if *required => {
9082 return Err(async_graphql::Error::new(format!(
9083 "{} needs the argument \"{}\"",
9084 relationship.name, name
9085 )))
9086 }
9087 None => continue,
9089 Some(value) => {
9090 passed.push(format!(
9091 "{} => ${}::{}",
9092 postrust_sql::escape_ident(name),
9093 param_idx,
9094 pg_type
9095 ));
9096 *param_idx += 1;
9097 values.push(value.clone());
9098 }
9099 }
9100 }
9101 Ok(Some(passed.join(", ")))
9102}
9103
9104fn embed_arguments(field: async_graphql::SelectionField<'_>) -> HashMap<String, serde_json::Value> {
9106 field
9107 .arguments()
9108 .map(|args| {
9109 args.into_iter()
9110 .map(|(name, value)| {
9111 (
9112 name.to_string(),
9113 plain_numbers(value.into_json().unwrap_or(serde_json::Value::Null)),
9114 )
9115 })
9116 .collect()
9117 })
9118 .unwrap_or_default()
9119}
9120
9121type Narrowing = (String, Option<String>, Option<String>, Option<i64>, i64);
9125
9126#[allow(clippy::too_many_arguments)] fn embed_narrowing(
9133 arguments: &HashMap<String, serde_json::Value>,
9134 plan: &postrust_core::embed::EmbedPlan,
9135 schema_cache: &SchemaCache,
9136 relationships: &HashMap<String, Vec<RelationshipField>>,
9137 target_type: &str,
9138 child_alias: &str,
9139 max_rows: Option<i64>,
9140 param_idx: &mut usize,
9141 values: &mut Vec<serde_json::Value>,
9142 names: &crate::names::NameOverrides,
9143 caller: &crate::role::Caller<'_>,
9144) -> Result<Narrowing, async_graphql::Error> {
9145 let permission =
9149 permission_predicate(caller, names, &plan.foreign_schema, &plan.foreign_table)?;
9150 let requested = arguments.get("where").filter(|v| !v.is_null()).cloned();
9151 let child_where = match and_predicates(requested, permission) {
9152 Some(expression) => {
9153 let child_scope = WhereScope::for_alias(
9154 &plan.foreign_schema,
9155 &plan.foreign_table,
9156 child_alias,
9157 target_type,
9158 schema_cache,
9159 relationships,
9160 names,
9161 )
9162 .for_caller(*caller);
9163 let mut nested_alias = 0usize;
9164 build_condition(
9165 &expression,
9166 &child_scope,
9167 param_idx,
9168 values,
9169 &mut nested_alias,
9170 )?
9171 }
9172 None => None,
9173 };
9174
9175 let child_order = match arguments.get("order_by") {
9176 Some(order) if !order.is_null() => order_terms(
9177 order,
9178 schema_cache,
9179 &plan.foreign_schema,
9180 &plan.foreign_table,
9181 child_alias,
9182 names,
9183 )?,
9184 _ => None,
9185 };
9186
9187 let ceiling = match (
9192 max_rows,
9193 crate::role::read_limit(caller, names, &plan.foreign_schema, &plan.foreign_table),
9194 ) {
9195 (Some(configured), Some(granted)) => Some(configured.min(granted)),
9196 (only, None) | (None, only) => only,
9197 };
9198 let child_limit = match arguments.get("limit").and_then(|v| v.as_i64()) {
9199 Some(requested) => match ceiling {
9200 Some(ceiling) => Some(requested.min(ceiling)),
9201 None => Some(requested),
9202 },
9203 None => ceiling,
9204 };
9205 let child_offset = arguments
9206 .get("offset")
9207 .and_then(|v| v.as_i64())
9208 .unwrap_or(0);
9209
9210 let requested = match arguments.get("distinct_on") {
9214 Some(serde_json::Value::Array(items)) => items
9215 .iter()
9216 .filter_map(|item| item.as_str())
9217 .collect::<Vec<_>>(),
9218 Some(serde_json::Value::String(one)) => vec![one.as_str()],
9219 _ => Vec::new(),
9220 };
9221 let mut distinct_on = Vec::with_capacity(requested.len());
9222 if !requested.is_empty() {
9223 let qi = postrust_core::api_request::QualifiedIdentifier::new(
9224 &plan.foreign_schema,
9225 &plan.foreign_table,
9226 );
9227 let table = schema_cache.get_table(&qi).ok_or_else(|| {
9228 async_graphql::Error::new(format!("unknown table \"{}\"", plan.foreign_table))
9229 })?;
9230 for field in requested {
9231 let column = table_column_for(names, table, field).to_string();
9232 if table.get_column(&column).is_none() {
9233 return Err(async_graphql::Error::new(format!(
9234 "cannot take distinct on unknown column \"{}\" of \"{}\"",
9235 field, plan.foreign_table
9236 )));
9237 }
9238 distinct_on.push(format!(
9239 "{}.{}",
9240 postrust_sql::escape_ident(child_alias),
9241 postrust_sql::escape_ident(&column)
9242 ));
9243 }
9244 }
9245 let (distinct, child_order) = distinct_on_clause(&distinct_on, child_order.as_deref())?;
9246
9247 Ok((
9248 distinct,
9249 child_where,
9250 child_order,
9251 child_limit,
9252 child_offset,
9253 ))
9254}
9255
9256#[allow(clippy::too_many_arguments)] fn build_embed_expressions<'a>(
9258 caller: &crate::role::Caller<'_>,
9259 schema_cache: &SchemaCache,
9260 relationships: &HashMap<String, Vec<RelationshipField>>,
9261 type_name: &str,
9262 parent_alias: &str,
9263 fields: impl IntoIterator<Item = SelectionField<'a>>,
9264 max_rows: Option<i64>,
9265 alias_counter: &mut usize,
9266 param_idx: &mut usize,
9267 values: &mut Vec<serde_json::Value>,
9268 names: &crate::names::NameOverrides,
9269) -> Result<Vec<(String, String)>, async_graphql::Error> {
9270 let Some(available) = relationships.get(type_name) else {
9271 return Ok(Vec::new());
9272 };
9273
9274 let mut expressions = Vec::new();
9275
9276 for field in fields {
9277 let aggregate_of = field
9281 .name()
9282 .strip_suffix("_aggregate")
9283 .and_then(|name| available.iter().find(|r| r.name == name && r.is_list));
9284
9285 if let Some(rel) = aggregate_of {
9286 let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, schema_cache)
9287 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9288 *alias_counter += 1;
9289 let child_alias = format!("a{}", alias_counter);
9290
9291 let arguments = embed_arguments(field);
9295 let (child_distinct, child_where, child_order, child_limit, child_offset) =
9296 embed_narrowing(
9297 &arguments,
9298 &plan,
9299 schema_cache,
9300 relationships,
9301 &rel.target_type,
9302 &child_alias,
9303 max_rows,
9304 param_idx,
9305 values,
9306 names,
9307 caller,
9308 )?;
9309
9310 let child_table =
9311 schema_cache.get_table(&postrust_core::api_request::QualifiedIdentifier::new(
9312 &plan.foreign_schema,
9313 &plan.foreign_table,
9314 ));
9315 let select = nested_aggregate_select(
9316 caller,
9317 field,
9318 &child_alias,
9319 schema_cache,
9320 relationships,
9321 &rel.target_type,
9322 child_table,
9323 max_rows,
9324 alias_counter,
9325 param_idx,
9326 values,
9327 names,
9328 )?;
9329
9330 let call = computed_arguments(
9331 rel,
9332 &plan,
9333 &postrust_sql::escape_ident(parent_alias),
9334 arguments.get("args"),
9335 param_idx,
9336 values,
9337 schema_cache,
9338 )?;
9339 let expression = plan
9340 .aggregate_expression(
9341 parent_alias,
9342 &postrust_sql::escape_ident(parent_alias),
9343 &child_alias,
9344 &select,
9345 child_limit,
9346 child_offset,
9347 child_where.as_deref(),
9348 child_order.as_deref(),
9349 call.as_deref(),
9350 &child_distinct,
9351 postrust_core::EmbedRendering::Verbatim,
9355 )
9356 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9357 expressions.push((field.name().to_string(), expression));
9358 continue;
9359 }
9360
9361 let Some(rel) = available.iter().find(|r| r.name == field.name()) else {
9362 continue;
9363 };
9364
9365 let plan = postrust_core::embed::EmbedPlan::resolve(&rel.relationship, schema_cache)
9366 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9367
9368 *alias_counter += 1;
9369 let child_alias = format!("e{}", alias_counter);
9370
9371 let nested = build_embed_expressions(
9372 caller,
9373 schema_cache,
9374 relationships,
9375 &rel.target_type,
9376 &child_alias,
9377 field.selection_set(),
9378 max_rows,
9379 alias_counter,
9380 param_idx,
9381 values,
9382 names,
9383 )?;
9384
9385 let arguments = embed_arguments(field);
9387 let (child_distinct, child_where, child_order, child_limit, child_offset) =
9388 embed_narrowing(
9389 &arguments,
9390 &plan,
9391 schema_cache,
9392 relationships,
9393 &rel.target_type,
9394 &child_alias,
9395 max_rows,
9396 param_idx,
9397 values,
9398 names,
9399 caller,
9400 )?;
9401
9402 let child_relationships = relationships.get(&rel.target_type);
9405 let child_qi = postrust_core::api_request::QualifiedIdentifier::new(
9406 &plan.foreign_schema,
9407 &plan.foreign_table,
9408 );
9409 let child_table = schema_cache.get_table(&child_qi);
9410 let mut parts: Vec<String> = Vec::new();
9411 for sub in field.selection_set() {
9412 let name = sub.name();
9413 let is_relationship = child_relationships
9414 .map(|rels| {
9415 rels.iter().any(|r| {
9416 r.name == name || (r.is_list && format!("{}_aggregate", r.name) == name)
9417 })
9418 })
9419 .unwrap_or(false);
9420 if is_relationship || name == "__typename" {
9424 continue;
9425 }
9426 let column = child_table
9429 .map(|t| table_column_for(names, t, name))
9430 .unwrap_or(name);
9431 let computed = child_table
9432 .filter(|t| t.get_column(column).is_none())
9433 .and_then(|t| {
9434 let function = names
9435 .computed_source(&t.schema, &t.name, name)
9436 .unwrap_or(name);
9437 t.get_computed_column(function)
9438 });
9439 match computed {
9440 Some(definition) => parts.push(format!(
9441 "{} AS {}",
9442 computed_call(
9443 definition,
9444 &format!("{}.*", postrust_sql::escape_ident(&child_alias)),
9445 &postrust_sql::escape_ident(&child_alias),
9446 ),
9447 postrust_sql::escape_ident(name)
9448 )),
9449 None if column != name => parts.push(format!(
9452 "{} AS {}",
9453 postrust_sql::escape_ident(column),
9454 postrust_sql::escape_ident(name)
9455 )),
9456 None => parts.push(postrust_sql::escape_ident(name)),
9457 }
9458 }
9459 if parts.is_empty() && nested.is_empty() {
9460 parts.push(
9461 child_table
9462 .and_then(|table| rename_projection(table, &child_alias, names))
9463 .unwrap_or_else(|| format!("{}.*", postrust_sql::escape_ident(&child_alias))),
9464 );
9465 }
9466 for (field_name, expression) in nested {
9467 parts.push(format!(
9468 "{} AS {}",
9469 expression,
9470 postrust_sql::escape_ident(&field_name)
9471 ));
9472 }
9473
9474 let computed_call_arguments = computed_arguments(
9475 rel,
9476 &plan,
9477 &postrust_sql::escape_ident(parent_alias),
9478 arguments.get("args"),
9479 param_idx,
9480 values,
9481 schema_cache,
9482 )?;
9483 let expression = plan
9484 .embed_expression(
9485 parent_alias,
9486 &postrust_sql::escape_ident(parent_alias),
9490 &child_alias,
9491 &format!("{}{}", child_distinct, parts.join(", ")),
9492 child_limit,
9493 child_offset,
9494 child_where.as_deref(),
9495 child_order.as_deref(),
9496 computed_call_arguments.as_deref(),
9497 postrust_core::EmbedRendering::Verbatim,
9498 )
9499 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9500
9501 expressions.push((rel.name.clone(), expression));
9502 }
9503
9504 Ok(expressions)
9505}
9506
9507struct EmbedContext<'c> {
9513 schema_cache: &'c SchemaCache,
9514 relationships: &'c HashMap<String, Vec<RelationshipField>>,
9515 max_rows: Option<i64>,
9516}
9517
9518fn embed_relationships<'f>(
9524 conn: &'f mut sqlx::PgConnection,
9525 ctx: &'f EmbedContext<'f>,
9526 type_name: &'f str,
9527 selection: async_graphql::SelectionField<'f>,
9528 rows: &'f mut [serde_json::Value],
9529) -> futures::future::BoxFuture<'f, Result<(), async_graphql::Error>> {
9530 Box::pin(async move {
9531 if rows.is_empty() {
9532 return Ok(());
9533 }
9534
9535 let Some(available) = ctx.relationships.get(type_name) else {
9536 return Ok(());
9537 };
9538
9539 for requested in selection.selection_set() {
9540 let Some(rel) = available.iter().find(|r| r.name == requested.name()) else {
9541 continue;
9542 };
9543
9544 let plan =
9545 postrust_core::embed::EmbedPlan::resolve(&rel.relationship, ctx.schema_cache)
9546 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9547
9548 let keys = postrust_core::embed::parent_keys(rows, &plan.local_column);
9549
9550 let mut child_columns: Vec<String> = Vec::new();
9560 let mut project_everything = false;
9561 let child_relationships = ctx.relationships.get(&rel.target_type);
9562 for field in requested.selection_set() {
9563 let name = field.name();
9564 match child_relationships.and_then(|rels| rels.iter().find(|r| r.name == name)) {
9565 Some(nested_rel) => {
9566 match postrust_core::embed::EmbedPlan::resolve(
9567 &nested_rel.relationship,
9568 ctx.schema_cache,
9569 ) {
9570 Ok(nested_plan) => child_columns.push(nested_plan.local_column),
9571 Err(_) => project_everything = true,
9572 }
9573 }
9574 None if name == "__typename" => {}
9576 None => child_columns.push(name.to_string()),
9577 }
9578 }
9579 if project_everything || child_columns.is_empty() {
9580 child_columns.clear();
9581 }
9582
9583 let mut grouped = if keys.is_empty() {
9584 std::collections::HashMap::new()
9585 } else {
9586 let sql = plan
9587 .children_grouped_sql(ctx.max_rows, &child_columns)
9588 .map_err(|e| async_graphql::Error::new(e.to_string()))?;
9589
9590 let fetched = sqlx::query(AssertSqlSafe(sql))
9591 .bind(&keys)
9592 .fetch_all(&mut *conn)
9593 .await
9594 .map_err(database_error)?;
9595
9596 use sqlx::Row;
9599 let pairs: Vec<(serde_json::Value, serde_json::Value)> = fetched
9600 .into_iter()
9601 .filter_map(|row| {
9602 Some((
9603 row.try_get::<serde_json::Value, _>(0).ok()?,
9604 row.try_get::<serde_json::Value, _>(1).ok()?,
9605 ))
9606 })
9607 .collect();
9608
9609 postrust_core::embed::group_from_aggregated(pairs)
9610 };
9611
9612 let has_deeper_embed = ctx
9617 .relationships
9618 .get(&rel.target_type)
9619 .map(|rels| {
9620 requested
9621 .selection_set()
9622 .any(|field| rels.iter().any(|r| r.name == field.name()))
9623 })
9624 .unwrap_or(false);
9625
9626 if has_deeper_embed {
9627 let mut order: Vec<(String, usize)> = Vec::with_capacity(grouped.len());
9628 let mut flat: Vec<serde_json::Value> = Vec::new();
9629 for (key, children) in grouped.drain() {
9630 order.push((key, children.len()));
9631 flat.extend(children);
9632 }
9633
9634 embed_relationships(&mut *conn, ctx, &rel.target_type, requested, &mut flat)
9635 .await?;
9636
9637 let mut rest = flat.into_iter();
9638 for (key, count) in order {
9639 grouped.insert(key, rest.by_ref().take(count).collect());
9640 }
9641 }
9642
9643 for row in rows.iter_mut() {
9644 postrust_core::embed::attach_to_parent(row, &rel.name, &plan, &grouped);
9645 }
9646 }
9647
9648 Ok(())
9649 })
9650}
9651
9652fn pk_where_from_args(
9657 ctx: &ResolverContext<'_>,
9658 schema_name: &str,
9659 table_name: &str,
9660 pk_columns: &[(String, String)],
9661 names: &crate::names::NameOverrides,
9662) -> Result<serde_json::Value, async_graphql::Error> {
9663 if pk_columns.is_empty() {
9664 return Err(async_graphql::Error::new(format!(
9665 "\"{}\" has no primary key, so it cannot be mutated by key",
9666 table_name
9667 )));
9668 }
9669
9670 let from_object = ctx
9674 .args
9675 .try_get("pk_columns")
9676 .ok()
9677 .map(|v| accessor_to_json(&v));
9678
9679 let mut conditions = serde_json::Map::new();
9680 for (col_name, _) in pk_columns {
9681 let field = names
9685 .column(schema_name, table_name, col_name)
9686 .unwrap_or(col_name);
9687 let value = match &from_object {
9688 Some(serde_json::Value::Object(map)) => map.get(field).cloned().ok_or_else(|| {
9689 async_graphql::Error::new(format!(
9690 "pk_columns is missing the key column \"{}\"",
9691 field
9692 ))
9693 })?,
9694 _ => {
9695 let arg = ctx.args.try_get(field).map_err(|_| {
9696 async_graphql::Error::new(format!(
9697 "missing required primary key argument \"{}\"",
9698 field
9699 ))
9700 })?;
9701 accessor_to_json(&arg)
9702 }
9703 };
9704 conditions.insert(field.to_string(), serde_json::json!({ "_eq": value }));
9705 }
9706
9707 Ok(serde_json::Value::Object(conditions))
9708}
9709
9710fn pk_argument_type(pg_type: &str) -> String {
9717 let rendered = crate::types::pg_type_to_graphql(pg_type).to_string();
9718 if rendered.starts_with('[') {
9719 "String".to_string()
9720 } else {
9721 rendered
9722 }
9723}
9724
9725fn exposed_pk_argument_type(
9730 names: &crate::names::NameOverrides,
9731 schema: &str,
9732 table: &str,
9733 column: &str,
9734 pg_type: &str,
9735) -> String {
9736 names
9737 .column_type(schema, table, column)
9738 .map(|given| given.to_string())
9739 .unwrap_or_else(|| pk_argument_type(pg_type))
9740}
9741
9742fn graphql_type_ref(type_str: &str) -> TypeRef {
9744 let is_list = type_str.starts_with('[');
9746 let is_nn = type_str.ends_with('!');
9747
9748 let inner = if is_list {
9750 let stripped = type_str
9751 .trim_end_matches('!') .trim_start_matches('[') .trim_end_matches(']'); stripped
9755 } else {
9756 type_str.trim_end_matches('!')
9757 };
9758
9759 let inner_nn = inner.ends_with('!');
9760 let base_type = inner.trim_end_matches('!');
9761
9762 if is_list {
9763 if is_nn {
9764 if inner_nn {
9765 TypeRef::named_nn_list_nn(base_type)
9766 } else {
9767 TypeRef::named_list_nn(base_type)
9768 }
9769 } else if inner_nn {
9770 TypeRef::named_nn_list(base_type)
9771 } else {
9772 TypeRef::named_list(base_type)
9773 }
9774 } else if is_nn {
9775 TypeRef::named_nn(base_type)
9776 } else {
9777 TypeRef::named(base_type)
9778 }
9779}
9780
9781const NUMBER_AS_TEXT: &str = "$serde_json::private::Number";
9791
9792fn number_kept_as_text(
9795 map: &serde_json::Map<String, serde_json::Value>,
9796) -> Option<serde_json::Value> {
9797 if map.len() != 1 {
9798 return None;
9799 }
9800 let text = map.get(NUMBER_AS_TEXT)?.as_str()?;
9801 serde_json::from_str::<serde_json::Value>(text)
9802 .ok()
9803 .filter(|value| value.is_number())
9804}
9805
9806fn plain_numbers(value: serde_json::Value) -> serde_json::Value {
9808 match value {
9809 serde_json::Value::Object(map) => match number_kept_as_text(&map) {
9810 Some(number) => number,
9811 None => serde_json::Value::Object(
9812 map.into_iter()
9813 .map(|(k, v)| (k, plain_numbers(v)))
9814 .collect(),
9815 ),
9816 },
9817 serde_json::Value::Array(items) => {
9818 serde_json::Value::Array(items.into_iter().map(plain_numbers).collect())
9819 }
9820 other => other,
9821 }
9822}
9823
9824fn accessor_to_json(accessor: &ValueAccessor<'_>) -> serde_json::Value {
9826 if accessor.is_null() {
9828 serde_json::Value::Null
9829 } else if let Ok(b) = accessor.boolean() {
9830 serde_json::Value::Bool(b)
9831 } else if let Ok(i) = accessor.i64() {
9832 serde_json::Value::Number(i.into())
9833 } else if let Ok(f) = accessor.f64() {
9834 serde_json::Number::from_f64(f)
9835 .map(serde_json::Value::Number)
9836 .unwrap_or(serde_json::Value::Null)
9837 } else if let Ok(s) = accessor.string() {
9838 serde_json::Value::String(s.to_string())
9839 } else if let Ok(name) = accessor.enum_name() {
9840 serde_json::Value::String(name.to_string())
9843 } else if let Ok(list) = accessor.list() {
9844 serde_json::Value::Array(list.iter().map(|v| accessor_to_json(&v)).collect())
9845 } else if let Ok(obj) = accessor.object() {
9846 let map: serde_json::Map<String, serde_json::Value> = obj
9847 .iter()
9848 .map(|(k, v)| (k.to_string(), accessor_to_json(&v)))
9849 .collect();
9850 match number_kept_as_text(&map) {
9851 Some(number) => number,
9852 None => serde_json::Value::Object(map),
9853 }
9854 } else {
9855 serde_json::Value::Null
9856 }
9857}
9858
9859fn value_to_json(value: &Value) -> serde_json::Value {
9861 match value {
9862 Value::Null => serde_json::Value::Null,
9863 Value::Boolean(b) => serde_json::Value::Bool(*b),
9864 Value::Number(n) => {
9865 if let Some(i) = n.as_i64() {
9866 serde_json::Value::Number(i.into())
9867 } else if let Some(f) = n.as_f64() {
9868 serde_json::Value::Number(serde_json::Number::from_f64(f).unwrap())
9869 } else {
9870 serde_json::Value::Null
9871 }
9872 }
9873 Value::String(s) => serde_json::Value::String(s.clone()),
9874 Value::List(arr) => serde_json::Value::Array(arr.iter().map(value_to_json).collect()),
9875 Value::Object(obj) => {
9876 let map: serde_json::Map<String, serde_json::Value> = obj
9877 .iter()
9878 .map(|(k, v)| (k.to_string(), value_to_json(v)))
9879 .collect();
9880 serde_json::Value::Object(map)
9881 }
9882 Value::Binary(b) => serde_json::Value::String(base64::Engine::encode(
9883 &base64::engine::general_purpose::STANDARD,
9884 b,
9885 )),
9886 Value::Enum(e) => serde_json::Value::String(e.to_string()),
9887 }
9888}
9889
9890fn json_to_value(json: serde_json::Value) -> Value {
9892 match json {
9893 serde_json::Value::Null => Value::Null,
9894 serde_json::Value::Bool(b) => Value::Boolean(b),
9895 serde_json::Value::Number(n) => {
9896 if let Some(i) = n.as_i64() {
9897 Value::Number(i.into())
9898 } else if let Some(f) = n.as_f64() {
9899 Value::Number(async_graphql::Number::from_f64(f).unwrap())
9900 } else {
9901 Value::Null
9902 }
9903 }
9904 serde_json::Value::String(s) => Value::String(s),
9905 serde_json::Value::Array(arr) => Value::List(arr.into_iter().map(json_to_value).collect()),
9906 serde_json::Value::Object(obj) => {
9907 let map: indexmap::IndexMap<async_graphql::Name, Value> = obj
9908 .into_iter()
9909 .map(|(k, v)| (async_graphql::Name::new(k), json_to_value(v)))
9910 .collect();
9911 Value::Object(map)
9912 }
9913 }
9914}
9915
9916#[cfg(test)]
9926mod tests {
9927 use super::*;
9928 use indexmap::IndexMap;
9929 use postrust_core::schema_cache::{Cardinality, Column, Relationship, Table};
9930 use postrust_core::QualifiedIdentifier;
9931 use std::collections::{HashMap, HashSet};
9932
9933 fn entity_key_column(pg_type: &str, explicit_id: bool) -> EntityKeyColumn {
9934 EntityKeyColumn {
9935 field_name: "id".to_string(),
9936 column_name: "id".to_string(),
9937 pg_type: pg_type.to_string(),
9938 explicit_id,
9939 }
9940 }
9941
9942 #[test]
9943 fn federation_integer_keys_reject_strings() {
9944 let column = entity_key_column("int4", false);
9945
9946 assert_eq!(
9947 normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap(),
9948 serde_json::json!(2)
9949 );
9950 let error = normalize_entity_key_value("users", &column, &serde_json::json!("2"))
9951 .expect_err("a GraphQL Int cannot be a string");
9952 assert_eq!(
9953 error.message,
9954 "entity representation for \"users\" has invalid key field \"id\": expected a value compatible with PostgreSQL type \"int4\", found a string"
9955 );
9956 }
9957
9958 #[test]
9959 fn federation_bigint_keys_accept_exact_decimal_strings() {
9960 let column = entity_key_column("int8", false);
9961
9962 assert_eq!(
9963 normalize_entity_key_value("users", &column, &serde_json::json!(7)).unwrap(),
9964 serde_json::json!(7)
9965 );
9966 assert_eq!(
9967 normalize_entity_key_value("users", &column, &serde_json::json!("9007199254740993"))
9968 .unwrap(),
9969 serde_json::json!(9_007_199_254_740_993_i64)
9970 );
9971 assert!(normalize_entity_key_value(
9972 "users",
9973 &column,
9974 &serde_json::json!("9223372036854775808")
9975 )
9976 .is_err());
9977 assert!(normalize_entity_key_value("users", &column, &serde_json::json!("7.5")).is_err());
9978 }
9979
9980 #[test]
9981 fn federation_numeric_keys_accept_exact_decimal_strings() {
9982 let column = entity_key_column("numeric", false);
9983
9984 assert_eq!(
9985 normalize_entity_key_value("users", &column, &serde_json::json!(7.5)).unwrap(),
9986 serde_json::json!("7.5")
9987 );
9988 assert_eq!(
9989 normalize_entity_key_value(
9990 "users",
9991 &column,
9992 &serde_json::json!("9007199254740993.123456789")
9993 )
9994 .unwrap(),
9995 serde_json::json!("9007199254740993.123456789")
9996 );
9997 assert!(
9998 normalize_entity_key_value("users", &column, &serde_json::json!("not-a-number"))
9999 .is_err()
10000 );
10001 }
10002
10003 #[test]
10004 fn federation_integer_backed_ids_have_one_normal_form() {
10005 let column = entity_key_column("int4", true);
10006
10007 let number = normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap();
10008 let string = normalize_entity_key_value("users", &column, &serde_json::json!("2")).unwrap();
10009 assert_eq!(number, serde_json::json!(2));
10010 assert_eq!(string, number);
10011 assert!(normalize_entity_key_value("users", &column, &serde_json::json!("two")).is_err());
10012 }
10013
10014 #[test]
10015 fn federation_text_backed_ids_normalize_integer_input_to_text() {
10016 let column = entity_key_column("text", true);
10017
10018 let number = normalize_entity_key_value("users", &column, &serde_json::json!(2)).unwrap();
10019 let string = normalize_entity_key_value("users", &column, &serde_json::json!("2")).unwrap();
10020 assert_eq!(number, serde_json::json!("2"));
10021 assert_eq!(string, number);
10022 }
10023
10024 #[test]
10025 fn federation_uuid_backed_ids_are_validated_and_canonicalized() {
10026 let column = entity_key_column("uuid", true);
10027
10028 assert_eq!(
10029 normalize_entity_key_value(
10030 "users",
10031 &column,
10032 &serde_json::json!("550E8400-E29B-41D4-A716-446655440000")
10033 )
10034 .unwrap(),
10035 serde_json::json!("550e8400-e29b-41d4-a716-446655440000")
10036 );
10037 assert!(
10038 normalize_entity_key_value("users", &column, &serde_json::json!("not-a-uuid")).is_err()
10039 );
10040 }
10041
10042 fn create_test_table(name: &str) -> Table {
10043 let mut columns = IndexMap::new();
10044 columns.insert(
10045 "id".into(),
10046 Column {
10047 name: "id".into(),
10048 description: None,
10049 nullable: false,
10050 data_type: "integer".into(),
10051 nominal_type: "int4".into(),
10052 max_len: None,
10053 default: Some("nextval('id_seq')".into()),
10054 enum_values: vec![],
10055 is_pk: true,
10056 position: 1,
10057 always_generated: false,
10058 domain_type: None,
10059 },
10060 );
10061 columns.insert(
10062 "name".into(),
10063 Column {
10064 name: "name".into(),
10065 description: None,
10066 nullable: false,
10067 data_type: "text".into(),
10068 nominal_type: "text".into(),
10069 max_len: None,
10070 default: None,
10071 enum_values: vec![],
10072 is_pk: false,
10073 position: 2,
10074 always_generated: false,
10075 domain_type: None,
10076 },
10077 );
10078
10079 Table {
10080 schema: "public".into(),
10081 name: name.into(),
10082 description: None,
10083 is_view: false,
10084 insertable: true,
10085 updatable: true,
10086 deletable: true,
10087 pk_cols: vec!["id".into()],
10088 unique_constraints: Vec::new(),
10089 columns,
10090 computed_columns: Default::default(),
10091 is_partitioned: false,
10092 }
10093 }
10094
10095 fn create_test_schema_cache() -> SchemaCache {
10096 let mut tables = HashMap::new();
10097 let users = create_test_table("users");
10098 tables.insert(users.qualified_identifier(), users);
10099
10100 SchemaCache {
10101 tables,
10102 relationships: HashMap::new(),
10103 routines: HashMap::new(),
10104 timezones: HashSet::new(),
10105 media_handlers: HashMap::new(),
10106 pg_version: 150000,
10107 representations: Default::default(),
10108 }
10109 }
10110
10111 fn add_test_table(cache: &mut SchemaCache, name: &str) {
10112 let table = create_test_table(name);
10113 cache.tables.insert(table.qualified_identifier(), table);
10114 }
10115
10116 fn add_test_posts_relationship(cache: &mut SchemaCache) {
10117 let users = QualifiedIdentifier::new("public", "users");
10118 cache.relationships.insert(
10119 (users.clone(), "public".into()),
10120 vec![Relationship::ForeignKey {
10121 table: users,
10122 foreign_table: QualifiedIdentifier::new("public", "posts"),
10123 is_self: false,
10124 cardinality: Cardinality::O2M {
10125 constraint: "posts_user_id_fkey".into(),
10126 columns: vec![("id".into(), "user_id".into())],
10127 },
10128 table_is_view: false,
10129 foreign_table_is_view: false,
10130 constraint_name: "posts_user_id_fkey".into(),
10131 }],
10132 );
10133 }
10134
10135 #[test]
10140 fn test_graphql_type_ref_simple() {
10141 let _type_ref = graphql_type_ref("String");
10142 }
10144
10145 #[test]
10146 fn test_graphql_type_ref_non_null() {
10147 let _type_ref = graphql_type_ref("String!");
10148 }
10149
10150 #[test]
10151 fn test_graphql_type_ref_list() {
10152 let _type_ref = graphql_type_ref("[String]");
10153 }
10154
10155 #[test]
10156 fn test_graphql_type_ref_list_non_null() {
10157 let _type_ref = graphql_type_ref("[String!]!");
10158 }
10159
10160 #[test]
10165 fn test_value_to_json_null() {
10166 let value = Value::Null;
10167 let json = value_to_json(&value);
10168 assert_eq!(json, serde_json::Value::Null);
10169 }
10170
10171 #[test]
10172 fn test_value_to_json_boolean() {
10173 let value = Value::Boolean(true);
10174 let json = value_to_json(&value);
10175 assert_eq!(json, serde_json::Value::Bool(true));
10176 }
10177
10178 #[test]
10179 fn test_value_to_json_number() {
10180 let value = Value::Number(42.into());
10181 let json = value_to_json(&value);
10182 assert_eq!(json, serde_json::json!(42));
10183 }
10184
10185 #[test]
10186 fn test_value_to_json_string() {
10187 let value = Value::String("hello".to_string());
10188 let json = value_to_json(&value);
10189 assert_eq!(json, serde_json::Value::String("hello".to_string()));
10190 }
10191
10192 #[test]
10193 fn test_value_to_json_list() {
10194 let value = Value::List(vec![Value::Number(1.into()), Value::Number(2.into())]);
10195 let json = value_to_json(&value);
10196 assert_eq!(json, serde_json::json!([1, 2]));
10197 }
10198
10199 #[test]
10200 fn test_json_to_value_null() {
10201 let json = serde_json::Value::Null;
10202 let value = json_to_value(json);
10203 assert!(matches!(value, Value::Null));
10204 }
10205
10206 #[test]
10207 fn test_json_to_value_boolean() {
10208 let json = serde_json::Value::Bool(false);
10209 let value = json_to_value(json);
10210 assert!(matches!(value, Value::Boolean(false)));
10211 }
10212
10213 #[test]
10214 fn test_json_to_value_number() {
10215 let json = serde_json::json!(123);
10216 let value = json_to_value(json);
10217 assert!(matches!(value, Value::Number(_)));
10218 }
10219
10220 #[test]
10221 fn test_json_to_value_string() {
10222 let json = serde_json::Value::String("test".to_string());
10223 let value = json_to_value(json);
10224 assert!(matches!(value, Value::String(_)));
10225 }
10226
10227 #[test]
10228 fn test_json_to_value_array() {
10229 let json = serde_json::json!([1, 2, 3]);
10230 let value = json_to_value(json);
10231 assert!(matches!(value, Value::List(_)));
10232 }
10233
10234 #[test]
10235 fn test_json_to_value_object() {
10236 let json = serde_json::json!({"key": "value"});
10237 let value = json_to_value(json);
10238 assert!(matches!(value, Value::Object(_)));
10239 }
10240
10241 #[test]
10246 fn test_build_dynamic_schema() {
10247 let cache = create_test_schema_cache();
10248 let config = SchemaConfig::default();
10249 let generated = build_schema(&cache, &config);
10250
10251 let result = build_dynamic_schema(
10252 &generated,
10253 &cache,
10254 None,
10255 None,
10256 Arc::new(Default::default()),
10257 std::time::Duration::from_secs(30),
10258 None,
10259 );
10260 if let Err(ref e) = result {
10261 eprintln!("Schema build error: {:?}", e);
10262 }
10263 assert!(result.is_ok(), "Schema build failed: {:?}", result.err());
10264 }
10265
10266 #[test]
10267 fn a_column_type_override_reaches_fields_and_key_arguments() {
10268 let cache = create_test_schema_cache();
10269 let names = crate::names::NameOverrides::parse(
10270 r#"{"tables": {"public.users": {"column_types": {"id": "ID"}}}}"#,
10271 )
10272 .unwrap();
10273 let config = SchemaConfig {
10274 names: names.clone(),
10275 ..SchemaConfig::default()
10276 };
10277 let generated = build_schema(&cache, &config);
10278 let schema = build_dynamic_schema(
10279 &generated,
10280 &cache,
10281 None,
10282 None,
10283 Arc::new(names),
10284 std::time::Duration::from_secs(30),
10285 None,
10286 )
10287 .expect("schema with an ID override should build");
10288 let sdl = schema.sdl();
10289
10290 let input_body = |name: &str| {
10291 sdl.split_once(&format!("input {name} {{"))
10292 .and_then(|(_, rest)| rest.split_once('}'))
10293 .map(|(body, _)| body.to_string())
10294 .unwrap_or_else(|| panic!("missing input {name}:\n{sdl}"))
10295 };
10296
10297 assert!(sdl.contains("id: ID!"), "object and input fields:\n{sdl}");
10298 assert!(
10299 sdl.contains("users_by_pk(id: ID!): users"),
10300 "query key argument:\n{sdl}"
10301 );
10302 assert!(
10303 sdl.contains("delete_users_by_pk(id: ID!): users"),
10304 "delete key argument:\n{sdl}"
10305 );
10306 assert!(
10307 input_body("users_pk_columns_input").contains("id: ID!"),
10308 "update key input:\n{sdl}"
10309 );
10310 assert!(
10311 input_body("users_bool_exp").contains("id: ID_comparison_exp"),
10312 "comparison input:\n{sdl}"
10313 );
10314 assert!(
10315 input_body("users_insert_input").contains("id: ID"),
10316 "write input:\n{sdl}"
10317 );
10318 }
10319
10320 #[test]
10321 fn a_type_prefix_names_the_complete_dynamic_schema() {
10322 let cache = create_test_schema_cache();
10323 let config = SchemaConfig {
10324 type_prefix: Some("test".into()),
10325 ..SchemaConfig::default()
10326 };
10327 let generated = build_schema(&cache, &config);
10328 let schema = build_dynamic_schema(
10329 &generated,
10330 &cache,
10331 None,
10332 None,
10333 Arc::new(Default::default()),
10334 std::time::Duration::from_secs(30),
10335 None,
10336 )
10337 .expect("a prefixed schema should build");
10338 let sdl = schema.sdl();
10339
10340 assert!(sdl.contains("type test_users "), "object type:\n{sdl}");
10341 assert!(sdl.contains("test_users("), "query root:\n{sdl}");
10342 assert!(sdl.contains("test_users_by_pk("), "by-PK root:\n{sdl}");
10343 assert!(sdl.contains("test_users_bool_exp"), "derived input:\n{sdl}");
10344 assert!(
10345 sdl.contains("test_users_aggregate"),
10346 "aggregate type:\n{sdl}"
10347 );
10348 assert!(sdl.contains("test_insert_users("), "mutation root:\n{sdl}");
10349 }
10350
10351 #[test]
10352 fn federation_is_absent_by_default() {
10353 let cache = create_test_schema_cache();
10354 let generated = build_schema(&cache, &SchemaConfig::default());
10355 let schema = build_dynamic_schema(
10356 &generated,
10357 &cache,
10358 None,
10359 None,
10360 Arc::new(Default::default()),
10361 std::time::Duration::from_secs(30),
10362 None,
10363 )
10364 .expect("a non-federated schema should build");
10365 let sdl = schema.sdl();
10366
10367 assert!(!sdl.contains("_Service"), "service type:\n{sdl}");
10368 assert!(!sdl.contains("_service"), "service field:\n{sdl}");
10369 assert!(!sdl.contains("@key"), "federation key:\n{sdl}");
10370 }
10371
10372 #[test]
10373 fn federation_entity_selections_respect_fragment_type_conditions() {
10374 let document = async_graphql::parser::parse_query(
10375 r#"
10376 query {
10377 _entities(representations: []) {
10378 __typename
10379 ... on authors { id items { title } }
10380 ...ShopFields
10381 ... { common }
10382 ...EntityName
10383 }
10384 }
10385 fragment ShopFields on shops { id items { sku } }
10386 fragment EntityName on _Entity { __typename }
10387 "#,
10388 )
10389 .expect("query parses");
10390 let (_, operation) = document.operations.iter().next().expect("one operation");
10391 let entity = operation
10392 .node
10393 .selection_set
10394 .node
10395 .items
10396 .iter()
10397 .find_map(|selection| match &selection.node {
10398 Selection::Field(field) if field.node.name.node == "_entities" => Some(&field.node),
10399 _ => None,
10400 })
10401 .expect("_entities field");
10402
10403 assert_eq!(
10404 entity_field_applicability(&entity.selection_set.node, &document.fragments, "authors"),
10405 vec![true, true, true, false, false, true, true]
10406 );
10407 assert_eq!(
10408 entity_field_applicability(&entity.selection_set.node, &document.fragments, "shops"),
10409 vec![true, false, false, true, true, true, true]
10410 );
10411 }
10412
10413 #[tokio::test]
10414 async fn federation_entity_lists_allow_null_members() {
10415 let entity =
10416 Object::new("widgets").field(Field::new("id", TypeRef::named_nn(TypeRef::INT), |_| {
10417 FieldFuture::new(async { Ok(Some(Value::from(2))) })
10418 }));
10419 let union = Union::new("_Entity").possible_type("widgets");
10420 let query = Object::new("Query").field(Field::new(
10421 "_entities",
10422 TypeRef::named_list_nn("_Entity"),
10423 |_| {
10424 FieldFuture::new(async {
10425 Ok(Some(FieldValue::list([
10426 FieldValue::NULL,
10427 FieldValue::NULL.with_type("widgets"),
10428 ])))
10429 })
10430 },
10431 ));
10432 let schema = Schema::build("Query", None, None)
10433 .extension(NullableFederationEntity)
10434 .register(entity)
10435 .register(union)
10436 .register(query)
10437 .finish()
10438 .expect("schema builds");
10439
10440 let response = schema
10441 .execute("{ _entities { ... on widgets { id } } }")
10442 .await;
10443
10444 assert!(response.errors.is_empty(), "{:?}", response.errors);
10445 assert_eq!(
10446 response.data,
10447 async_graphql::value!({ "_entities": [null, { "id": 2 }] })
10448 );
10449 }
10450
10451 #[test]
10452 fn federation_metadata_is_byte_for_byte_inert_when_disabled() {
10453 let cache = create_test_schema_cache();
10454 let sdl_for = |config: SchemaConfig| {
10455 let generated = build_schema(&cache, &config);
10456 build_dynamic_schema(
10457 &generated,
10458 &cache,
10459 None,
10460 None,
10461 Arc::new(config.names.clone()),
10462 std::time::Duration::from_secs(30),
10463 None,
10464 )
10465 .expect("schema should build")
10466 .sdl()
10467 };
10468
10469 let baseline = sdl_for(SchemaConfig {
10470 type_prefix: Some("test".into()),
10471 ..SchemaConfig::default()
10472 });
10473 let with_disabled_federation_metadata = sdl_for(SchemaConfig {
10474 enable_federation: false,
10475 type_prefix: Some("test".into()),
10476 names: crate::names::NameOverrides::parse(
10477 r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10478 )
10479 .expect("metadata"),
10480 ..SchemaConfig::default()
10481 });
10482
10483 assert_eq!(with_disabled_federation_metadata, baseline);
10484 assert!(
10485 with_disabled_federation_metadata.contains("type test_users "),
10486 "prefixed object type remains when federation is disabled:\n{with_disabled_federation_metadata}"
10487 );
10488 assert!(
10489 !with_disabled_federation_metadata.contains("_Service"),
10490 "service type:\n{with_disabled_federation_metadata}"
10491 );
10492 assert!(
10493 !with_disabled_federation_metadata.contains("@key"),
10494 "federation key:\n{with_disabled_federation_metadata}"
10495 );
10496 }
10497
10498 #[test]
10499 fn shared_entities_make_relationship_fields_shareable() {
10500 let federation_sdl = |shared: bool| {
10501 let mut cache = create_test_schema_cache();
10502 add_test_table(&mut cache, "posts");
10503 add_test_posts_relationship(&mut cache);
10504 let names = match shared {
10505 true => crate::names::NameOverrides::parse(
10506 r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10507 )
10508 .expect("metadata"),
10509 false => crate::names::NameOverrides::default(),
10510 };
10511 let config = SchemaConfig {
10512 enable_federation: true,
10513 type_prefix: Some("test".into()),
10514 names: names.clone(),
10515 ..SchemaConfig::default()
10516 };
10517 let generated = build_schema(&cache, &config);
10518 build_dynamic_schema(
10519 &generated,
10520 &cache,
10521 None,
10522 None,
10523 Arc::new(names),
10524 std::time::Duration::from_secs(30),
10525 None,
10526 )
10527 .expect("federated schema should build")
10528 .sdl_with_options(async_graphql::SDLExportOptions::new().federation())
10529 };
10530
10531 let shared = federation_sdl(true);
10532 assert!(
10533 shared.contains("): [test_posts!]! @shareable"),
10534 "shared relationship field:\n{shared}"
10535 );
10536 assert!(
10537 shared.contains("): test_posts_aggregate! @shareable"),
10538 "shared relationship aggregate field:\n{shared}"
10539 );
10540
10541 let not_shared = federation_sdl(false);
10542 assert!(
10543 not_shared.contains("): [test_posts!]!"),
10544 "non-shared relationship field:\n{not_shared}"
10545 );
10546 assert!(
10547 !not_shared.contains("): [test_posts!]! @shareable"),
10548 "non-shared relationship field must not be shareable:\n{not_shared}"
10549 );
10550 assert!(
10551 not_shared.contains("): test_posts_aggregate!"),
10552 "non-shared relationship aggregate field:\n{not_shared}"
10553 );
10554 assert!(
10555 !not_shared.contains("): test_posts_aggregate! @shareable"),
10556 "non-shared relationship aggregate must not be shareable:\n{not_shared}"
10557 );
10558 }
10559
10560 #[tokio::test]
10561 async fn federation_exposes_service_sdl_and_entity_keys() {
10562 let mut cache = create_test_schema_cache();
10563 add_test_table(&mut cache, "posts");
10564 let config = SchemaConfig {
10565 enable_federation: true,
10566 type_prefix: Some("test".into()),
10567 names: crate::names::NameOverrides::parse(
10568 r#"{"tables": {"public.users": {"federation": {"shared": true}}}}"#,
10569 )
10570 .expect("metadata"),
10571 ..SchemaConfig::default()
10572 };
10573 let generated = build_schema(&cache, &config);
10574 let schema = build_dynamic_schema(
10575 &generated,
10576 &cache,
10577 None,
10578 None,
10579 Arc::new(Default::default()),
10580 std::time::Duration::from_secs(30),
10581 None,
10582 )
10583 .expect("a federated schema should build");
10584 let sdl = schema.sdl();
10585 let federation_sdl =
10586 schema.sdl_with_options(async_graphql::SDLExportOptions::new().federation());
10587
10588 assert!(sdl.contains("_Service"), "service type:\n{sdl}");
10589 assert!(sdl.contains("_service"), "service field:\n{sdl}");
10590 assert!(
10591 federation_sdl.contains("type users @key(fields: \"id\") @shareable"),
10592 "users key and type-level @shareable:\n{federation_sdl}"
10593 );
10594 assert!(
10595 federation_sdl.contains("@shareable"),
10596 "shared field directive:\n{federation_sdl}"
10597 );
10598 assert!(sdl.contains("type users "), "shared object type:\n{sdl}");
10599 assert!(
10600 !sdl.contains("type test_users "),
10601 "prefixed shared object type:\n{sdl}"
10602 );
10603 assert!(sdl.contains("test_users("), "query root:\n{sdl}");
10604 assert!(sdl.contains("test_users_by_pk("), "by-PK root:\n{sdl}");
10605 assert!(sdl.contains("test_users_bool_exp"), "derived input:\n{sdl}");
10606 assert!(
10607 !sdl.contains("input users_bool_exp "),
10608 "unprefixed derived input:\n{sdl}"
10609 );
10610 assert!(
10611 sdl.contains("test_users_aggregate"),
10612 "aggregate type:\n{sdl}"
10613 );
10614 assert!(
10615 !sdl.contains("type users_aggregate "),
10616 "unprefixed aggregate type:\n{sdl}"
10617 );
10618 assert!(
10619 sdl.contains("test_users_mutation_response"),
10620 "mutation response type:\n{sdl}"
10621 );
10622 assert!(
10623 !sdl.contains("type users_mutation_response "),
10624 "unprefixed mutation response type:\n{sdl}"
10625 );
10626 assert!(
10627 sdl.contains("type test_posts {"),
10628 "non-shared object type remains prefixed:\n{sdl}"
10629 );
10630 assert!(
10631 !sdl.contains("type posts {"),
10632 "non-shared object type must not become unprefixed:\n{sdl}"
10633 );
10634 assert!(sdl.contains("test_posts("), "prefixed posts root:\n{sdl}");
10635 assert!(
10636 sdl.contains("test_posts_bool_exp"),
10637 "prefixed posts bool_exp:\n{sdl}"
10638 );
10639
10640 let response = schema.execute("{ _service { sdl } }").await;
10641 assert!(
10642 response.errors.is_empty(),
10643 "service query errors: {:?}",
10644 response.errors
10645 );
10646 let service = response.data.into_json().expect("service response JSON");
10647 let service_sdl = service
10648 .get("_service")
10649 .and_then(|value| value.get("sdl"))
10650 .and_then(serde_json::Value::as_str)
10651 .expect("service SDL string");
10652 assert!(
10653 service_sdl.contains("type Query"),
10654 "federation root type:\n{service_sdl}"
10655 );
10656 assert!(
10657 service_sdl.contains("test_users("),
10658 "query fields are on the federation root:\n{service_sdl}"
10659 );
10660 assert!(
10661 service_sdl.contains("test_posts("),
10662 "non-shared query fields are on the federation root:\n{service_sdl}"
10663 );
10664 assert!(
10665 !service_sdl.contains("type query_root"),
10666 "Apollo composition treats query_root as an ordinary object without a schema definition:\n{service_sdl}"
10667 );
10668 assert!(
10669 service_sdl.contains("type users @key(fields: \"id\")"),
10670 "{service_sdl}"
10671 );
10672 assert!(
10673 service_sdl.contains("type test_posts @key(fields: \"id\")"),
10674 "{service_sdl}"
10675 );
10676 }
10677
10678 #[test]
10681 fn exists_is_a_subselect_over_another_table() {
10682 let cache = create_test_schema_cache();
10683 let names = crate::names::NameOverrides::default();
10684 let relationships: HashMap<String, Vec<RelationshipField>> = HashMap::new();
10685 let scope = WhereScope::table("public", "users", "users", &names)
10686 .with_resolution(&cache, &relationships);
10687
10688 let mut param_idx = 1usize;
10689 let mut values: Vec<serde_json::Value> = Vec::new();
10690 let mut aliases = 0usize;
10691 let sql = build_condition(
10692 &serde_json::json!({
10693 "_exists": {"_table": "users", "_where": {"name": {"_eq": "Ann"}}}
10694 }),
10695 &scope,
10696 &mut param_idx,
10697 &mut values,
10698 &mut aliases,
10699 )
10700 .expect("compiles")
10701 .expect("constrains something");
10702
10703 assert_eq!(
10704 sql,
10705 "EXISTS (SELECT 1 FROM \"public\".\"users\" AS \"pgrst_exists_1\" \
10706 WHERE \"pgrst_exists_1\".\"name\" = $1::text)"
10707 );
10708 assert_eq!(values, vec![serde_json::json!("Ann")]);
10709 }
10710
10711 #[test]
10713 fn exists_names_a_table_the_server_has() {
10714 let cache = create_test_schema_cache();
10715 let names = crate::names::NameOverrides::default();
10716 let relationships: HashMap<String, Vec<RelationshipField>> = HashMap::new();
10717 let scope = WhereScope::table("public", "users", "users", &names)
10718 .with_resolution(&cache, &relationships);
10719 let error = build_condition(
10720 &serde_json::json!({"_exists": {"_table": "nowhere", "_where": {}}}),
10721 &scope,
10722 &mut 1,
10723 &mut Vec::new(),
10724 &mut 0,
10725 )
10726 .expect_err("a table that is not there is an error");
10727 assert!(
10728 error.message.contains("public.nowhere"),
10729 "{}",
10730 error.message
10731 );
10732 }
10733
10734 #[test]
10741 fn a_table_a_role_may_count_and_not_read_has_a_count_and_no_rows() {
10742 let cache = create_test_schema_cache();
10743 let names = crate::names::NameOverrides::parse(
10744 r#"{"tables": {"public.users": {"permissions":
10745 {"counter": {"select": {"columns": [], "filter": {},
10746 "allow_aggregations": true}}}}}}"#,
10747 )
10748 .unwrap();
10749 let view = crate::role::cache_for_role(&cache, &names, "counter", false);
10750 assert!(!view.tables.is_empty(), "the table is there to be counted");
10751
10752 let config = SchemaConfig {
10753 names: names.clone(),
10754 role: Some("counter".to_string()),
10755 ..SchemaConfig::default()
10756 };
10757 let generated = build_schema(&view, &config);
10758 let schema = build_dynamic_schema(
10759 &generated,
10760 &view,
10761 None,
10762 None,
10763 Arc::new(names),
10764 std::time::Duration::from_secs(30),
10765 Some("counter"),
10766 )
10767 .expect("a role that may only count still has a buildable schema");
10768 let sdl = schema.sdl();
10769
10770 assert!(
10771 sdl.contains("users_aggregate"),
10772 "the count is there:\n{}",
10773 sdl
10774 );
10775 assert!(sdl.contains("count: Int!"), "and it is a count:\n{}", sdl);
10776 assert!(!sdl.contains("type users "), "no row type:\n{}", sdl);
10778 assert!(
10779 !sdl.contains("nodes"),
10780 "and no rows beside the numbers:\n{}",
10781 sdl
10782 );
10783 assert!(
10784 !sdl.contains("users_select_column"),
10785 "no column enum to order by or count over:\n{}",
10786 sdl
10787 );
10788 assert!(!sdl.contains("users_max_fields"), "no max:\n{}", sdl);
10790 }
10791
10792 #[test]
10799 fn a_table_a_role_may_only_write_gets_the_write_and_no_type() {
10800 let cache = create_test_schema_cache();
10801 let names = crate::names::NameOverrides::parse(
10802 r#"{"tables": {"public.users": {"permissions":
10803 {"writer": {"insert": {"columns": "*", "check": {}}}}}}}"#,
10804 )
10805 .unwrap();
10806 let view = crate::role::cache_for_role(&cache, &names, "writer", false);
10807 let config = SchemaConfig {
10808 names: names.clone(),
10809 role: Some("writer".to_string()),
10810 ..SchemaConfig::default()
10811 };
10812 let generated = build_schema(&view, &config);
10813
10814 let schema = build_dynamic_schema(
10815 &generated,
10816 &view,
10817 None,
10818 None,
10819 Arc::new(names),
10820 std::time::Duration::from_secs(30),
10821 Some("writer"),
10822 )
10823 .expect("a role that may only write still has a buildable schema");
10824 let sdl = schema.sdl();
10825
10826 assert!(
10827 sdl.contains("insert_users("),
10828 "the write is there:\n{}",
10829 sdl
10830 );
10831 assert!(
10832 sdl.contains("users_insert_input"),
10833 "and its input:\n{}",
10834 sdl
10835 );
10836 assert!(!sdl.contains("type users "), "no row type:\n{}", sdl);
10838 assert!(!sdl.contains("insert_users_one"), "no insert_one:\n{}", sdl);
10839 assert!(
10840 !sdl.contains("returning"),
10841 "and nothing to return:\n{}",
10842 sdl
10843 );
10844 assert!(
10845 sdl.contains("users_mutation_response"),
10846 "the count is still answered:\n{}",
10847 sdl
10848 );
10849 assert!(
10850 !sdl.contains("_mutation_response_mutation_response"),
10851 "and no type is named twice over:\n{}",
10852 sdl
10853 );
10854 }
10855
10856 fn cache_with_a_mutation_function() -> SchemaCache {
10859 use postrust_core::schema_cache::{FuncVolatility, RetType, Routine};
10860
10861 let mut cache = create_test_schema_cache();
10862 let routine = Routine {
10863 schema: "public".into(),
10864 name: "add_to_score".into(),
10865 description: None,
10866 params: Vec::new(),
10867 return_type: RetType::SetOf("users".into()),
10868 returns_composite: true,
10869 volatility: FuncVolatility::Volatile,
10870 has_variadic: false,
10871 isolation_level: None,
10872 settings: Vec::new(),
10873 is_procedure: false,
10874 media_type: None,
10875 media_base_type: None,
10876 output_columns: Vec::new(),
10877 };
10878 cache
10879 .routines
10880 .insert(routine.qualified_identifier(), vec![routine]);
10881 cache
10882 }
10883
10884 #[test]
10889 fn a_mutation_function_needs_the_role_to_be_named() {
10890 let cache = cache_with_a_mutation_function();
10891 let withheld = crate::names::NameOverrides::parse(
10892 r#"{"tables": {"public.users": {"permissions":
10893 {"reader": {"select": {"columns": "*", "filter": {}}}}}},
10894 "functions": {"public.add_to_score": {"exposed_as": "mutation"}}}"#,
10895 )
10896 .unwrap();
10897 let granted = crate::names::NameOverrides::parse(
10898 r#"{"tables": {"public.users": {"permissions":
10899 {"reader": {"select": {"columns": "*", "filter": {}}}}}},
10900 "functions": {"public.add_to_score":
10901 {"exposed_as": "mutation", "roles": ["reader"]}}}"#,
10902 )
10903 .unwrap();
10904
10905 let sdl_for = |names: &crate::names::NameOverrides| {
10906 let view = crate::role::cache_for_role(&cache, names, "reader", false);
10907 let config = SchemaConfig {
10908 names: names.clone(),
10909 role: Some("reader".to_string()),
10910 ..SchemaConfig::default()
10911 };
10912 let generated = build_schema(&view, &config);
10913 build_dynamic_schema(
10914 &generated,
10915 &view,
10916 None,
10917 None,
10918 Arc::new(names.clone()),
10919 std::time::Duration::from_secs(30),
10920 Some("reader"),
10921 )
10922 .expect("schema builds")
10923 .sdl()
10924 };
10925
10926 let without = sdl_for(&withheld);
10927 assert!(
10928 !without.contains("add_to_score"),
10929 "not granted, so not there:\n{}",
10930 without
10931 );
10932 assert!(
10935 !without.contains("mutation: mutation_root"),
10936 "and no mutation root at all:\n{}",
10937 without
10938 );
10939
10940 let with = sdl_for(&granted);
10941 assert!(
10942 with.contains("add_to_score"),
10943 "named by a function permission, so it is:\n{}",
10944 with
10945 );
10946 }
10947
10948 #[test]
10950 fn a_role_the_document_never_names_is_granted_nothing() {
10951 let cache = Arc::new(create_test_schema_cache());
10952 let config = SchemaConfig {
10953 names: crate::names::NameOverrides::parse(
10954 r#"{"tables": {"public.users": {"permissions":
10955 {"reader": {"select": {"columns": "*", "filter": {}}}}}}}"#,
10956 )
10957 .unwrap(),
10958 ..SchemaConfig::default()
10959 };
10960 let empty = build_ungranted_schema(&cache, &config).expect("it builds");
10961 let sdl = empty.sdl();
10962 assert!(
10963 sdl.contains("no_queries_available"),
10964 "nothing to read:\n{}",
10965 sdl
10966 );
10967 assert!(!sdl.contains("type users "), "and no table:\n{}", sdl);
10968 assert!(build_ungranted_schema(&cache, &SchemaConfig::default()).is_none());
10970 }
10971
10972 #[test]
10975 fn a_column_a_role_may_set_without_seeing_is_in_the_input_alone() {
10976 let cache = create_test_schema_cache();
10977 let names = crate::names::NameOverrides::parse(
10978 r#"{"tables": {"public.users": {"permissions":
10979 {"user": {"select": {"columns": ["id"], "filter": {}},
10980 "insert": {"columns": "*", "check": {}}}}}}}"#,
10981 )
10982 .unwrap();
10983 let view = crate::role::cache_for_role(&cache, &names, "user", false);
10984 let config = SchemaConfig {
10985 names: names.clone(),
10986 role: Some("user".to_string()),
10987 ..SchemaConfig::default()
10988 };
10989 let generated = build_schema(&view, &config);
10990 let object = &generated.object_types["users"];
10991 assert_eq!(
10992 object
10993 .fields
10994 .iter()
10995 .map(|f| f.name.as_str())
10996 .collect::<Vec<_>>(),
10997 vec!["id"],
10998 "the type shows what may be read"
10999 );
11000 assert!(
11001 object.writable_fields.iter().any(|f| f.name == "name"),
11002 "and the input keeps what may be written"
11003 );
11004
11005 let schema = build_dynamic_schema(
11006 &generated,
11007 &view,
11008 None,
11009 None,
11010 Arc::new(names),
11011 std::time::Duration::from_secs(30),
11012 Some("user"),
11013 )
11014 .expect("schema builds");
11015 let sdl = schema.sdl();
11016 let input = sdl
11017 .split("input users_insert_input")
11018 .nth(1)
11019 .and_then(|rest| rest.split('}').next())
11020 .expect("the insert input is registered");
11021 assert!(input.contains("name:"), "settable without being readable");
11022 }
11023
11024 #[test]
11028 fn a_generated_column_is_readable_and_not_writable() {
11029 let mut cache = create_test_schema_cache();
11030 cache
11031 .tables
11032 .get_mut(&postrust_core::api_request::QualifiedIdentifier::new(
11033 "public", "users",
11034 ))
11035 .expect("the fixture has users")
11036 .columns
11037 .get_mut("id")
11038 .expect("with an id")
11039 .always_generated = true;
11040
11041 let names = crate::names::NameOverrides::default();
11042 let config = SchemaConfig {
11043 names: names.clone(),
11044 ..SchemaConfig::default()
11045 };
11046 let generated = build_schema(&cache, &config);
11047 let schema = build_dynamic_schema(
11048 &generated,
11049 &cache,
11050 None,
11051 None,
11052 Arc::new(names),
11053 std::time::Duration::from_secs(30),
11054 None,
11055 )
11056 .expect("schema builds");
11057 let sdl = schema.sdl();
11058
11059 let block = |header: &str| {
11060 sdl.split(header)
11061 .nth(1)
11062 .and_then(|rest| rest.split('}').next())
11063 .unwrap_or_else(|| panic!("{} is registered:\n{}", header, sdl))
11064 .to_string()
11065 };
11066 assert!(
11067 block("type users ").contains("id:"),
11068 "still readable:\n{}",
11069 sdl
11070 );
11071 for header in ["input users_insert_input", "input users_set_input"] {
11072 assert!(
11073 !block(header).contains("id:"),
11074 "{} may not name it:\n{}",
11075 header,
11076 block(header)
11077 );
11078 }
11079 assert!(
11082 !sdl.contains("users_inc_input"),
11083 "and nothing is left to increment:\n{}",
11084 sdl
11085 );
11086 assert!(
11087 block("input users_insert_input").contains("name:"),
11088 "and the rest of the table is untouched",
11089 );
11090 }
11091
11092 #[test]
11093 fn test_create_object_type() {
11094 let table = create_test_table("users");
11095 let obj = TableObjectType::from_table(&table);
11096 let _gql_obj = create_object_type(&obj, &[], None);
11097 }
11098
11099 #[test]
11100 fn test_create_query_type() {
11101 let cache = create_test_schema_cache();
11102 let config = SchemaConfig::default();
11103 let generated = build_schema(&cache, &config);
11104
11105 let _query = create_query_type(
11106 &generated,
11107 "query_root",
11108 None,
11109 Arc::new(HashMap::new()),
11110 Arc::new(Default::default()),
11111 );
11112 }
11113
11114 #[test]
11115 fn test_create_mutation_type() {
11116 let cache = create_test_schema_cache();
11117 let config = SchemaConfig::default();
11118 let generated = build_schema(&cache, &config);
11119
11120 let _mutation = create_mutation_type(
11121 &generated,
11122 "mutation_root",
11123 Arc::new(HashMap::new()),
11124 Arc::new(HashMap::new()),
11125 Arc::new(Default::default()),
11126 None,
11127 None,
11128 );
11129 }
11130
11131 #[test]
11136 fn a_scalar_is_named_the_way_a_client_declares_it() {
11137 use crate::types::{pg_type_to_graphql, GraphQLType};
11138
11139 assert_eq!(pg_type_to_graphql("jsonb").to_string(), "jsonb");
11144 assert_eq!(pg_type_to_graphql("json").to_string(), "json");
11145 assert_eq!(pg_type_to_graphql("int8").to_string(), "bigint");
11146 assert_eq!(pg_type_to_graphql("numeric").to_string(), "numeric");
11147 assert_eq!(pg_type_to_graphql("timestamptz").to_string(), "timestamptz");
11148 assert_eq!(pg_type_to_graphql("timestamp").to_string(), "timestamp");
11149 assert_eq!(pg_type_to_graphql("uuid").to_string(), "uuid");
11150
11151 assert_eq!(pg_type_to_graphql("geometry").to_string(), "geometry");
11154 assert_eq!(
11155 pg_type_to_graphql("colors_enum"),
11156 GraphQLType::Custom("colors_enum".to_string())
11157 );
11158
11159 assert_eq!(
11161 leaf_scalar_name(&pg_type_to_graphql("_text")),
11162 "String".to_string()
11163 );
11164 }
11165
11166 #[test]
11171 fn every_table_gets_a_boolean_expression() {
11172 let cache = create_test_schema_cache();
11173 let config = SchemaConfig::default();
11174 let generated = build_schema(&cache, &config);
11175
11176 let (inputs, _) = crate::input::bool_exp::build_inputs(
11177 &generated.object_types,
11178 &generated.relationship_fields,
11179 );
11180 let names: HashSet<String> = inputs.iter().map(|i| i.type_name().to_string()).collect();
11181
11182 for table in generated.object_types.keys() {
11183 let expected = format!("{}_bool_exp", table);
11184 assert!(
11185 names.contains(&expected),
11186 "no {} among {:?}",
11187 expected,
11188 names
11189 );
11190 }
11191 assert!(names.contains("String_comparison_exp"));
11193 assert!(names.contains("Int_comparison_exp"));
11194 }
11195
11196 #[test]
11197 fn a_schema_carrying_the_boolean_expressions_still_builds() {
11198 let cache = create_test_schema_cache();
11199 let config = SchemaConfig::default();
11200 let generated = build_schema(&cache, &config);
11201
11202 let schema = build_dynamic_schema(
11203 &generated,
11204 &cache,
11205 None,
11206 None,
11207 Arc::new(Default::default()),
11208 std::time::Duration::from_secs(30),
11209 None,
11210 );
11211 assert!(schema.is_ok(), "{:?}", schema.err());
11212
11213 let sdl = schema.unwrap().sdl();
11214 assert!(
11215 sdl.contains("_bool_exp"),
11216 "no boolean expressions in:\n{}",
11217 sdl
11218 );
11219 assert!(sdl.contains("_and"), "no _and in the generated expressions");
11220 }
11221
11222 #[test]
11227 fn test_build_schema_with_subscriptions() {
11228 let cache = create_test_schema_cache();
11229 let config = SchemaConfig {
11230 enable_subscriptions: true,
11231 ..SchemaConfig::default()
11232 };
11233 let generated = build_schema(&cache, &config);
11234
11235 let sub_fields = generate_subscription_fields(&cache, &generated);
11237 assert!(!sub_fields.is_empty(), "Should have subscription fields");
11238
11239 let result = build_dynamic_schema(
11241 &generated,
11242 &cache,
11243 Some(&sub_fields),
11244 None,
11245 Arc::new(Default::default()),
11246 std::time::Duration::from_secs(30),
11247 None,
11248 );
11249 assert!(result.is_ok(), "Schema with subscriptions should build");
11250 }
11251
11252 #[test]
11253 fn test_subscription_field_generation() {
11254 let cache = create_test_schema_cache();
11255 let config = SchemaConfig::default();
11256 let generated = build_schema(&cache, &config);
11257
11258 let fields = generate_subscription_fields(&cache, &generated);
11259
11260 assert_eq!(fields.len(), 1);
11262 assert_eq!(fields[0].name, "users");
11263 assert_eq!(fields[0].table_name, "users");
11264 assert_eq!(fields[0].channel_name(), "postrust_public_users");
11265 }
11266
11267 #[test]
11268 fn test_create_subscription_type() {
11269 let cache = create_test_schema_cache();
11270 let config = SchemaConfig::default();
11271 let generated = build_schema(&cache, &config);
11272 let _subscription = create_subscription_type(
11275 &generated,
11276 "subscription_root",
11277 None,
11278 Arc::new(Default::default()),
11279 Arc::new(Default::default()),
11280 std::time::Duration::from_secs(30),
11281 );
11282 }
11283}
11284
11285#[derive(Debug, PartialEq, Eq)]
11287enum PathStep {
11288 Key(String),
11289 Index(usize),
11290}
11291
11292fn walk_json_path(value: &Value, path: &str) -> Result<Value, async_graphql::Error> {
11299 let mut at = value;
11300 for step in parse_json_path(path)? {
11301 let next = match (&step, at) {
11302 (PathStep::Key(key), Value::Object(map)) => map.get(key.as_str()),
11303 (PathStep::Index(index), Value::List(items)) => items.get(*index),
11304 _ => None,
11307 };
11308 match next {
11309 Some(next) => at = next,
11310 None => return Ok(Value::Null),
11311 }
11312 }
11313 Ok(at.clone())
11314}
11315
11316fn unclosed_bracket(path: &str) -> async_graphql::Error {
11318 let message = format!("\"{}\" is not a JSON path: a bracket is never closed", path);
11319 validation_error(&message)
11320}
11321
11322fn parse_json_path(path: &str) -> Result<Vec<PathStep>, async_graphql::Error> {
11329 let mut steps = Vec::new();
11330 let mut chars = path.chars().peekable();
11331 if chars.peek() == Some(&'$') {
11333 chars.next();
11334 }
11335 while let Some(&c) = chars.peek() {
11336 match c {
11337 '.' => {
11339 chars.next();
11340 }
11341 '[' => {
11342 chars.next();
11343 let quote = match chars.peek() {
11344 Some(&q @ ('\'' | '"')) => {
11345 chars.next();
11346 Some(q)
11347 }
11348 _ => None,
11349 };
11350 let mut inner = String::new();
11351 loop {
11352 let Some(c) = chars.next() else {
11353 return Err(unclosed_bracket(path));
11354 };
11355 match (quote, c) {
11356 (Some(quote), c) if c == quote => break,
11357 (None, ']') => break,
11358 _ => inner.push(c),
11359 }
11360 }
11361 if quote.is_some() {
11363 match chars.next() {
11364 Some(']') => {}
11365 _ => return Err(unclosed_bracket(path)),
11366 }
11367 }
11368 match (quote, inner.parse::<usize>()) {
11371 (None, Ok(index)) => steps.push(PathStep::Index(index)),
11372 _ => steps.push(PathStep::Key(inner)),
11373 }
11374 }
11375 _ => {
11376 let mut key = String::new();
11377 while let Some(&c) = chars.peek() {
11378 if matches!(c, '.' | '[') {
11379 break;
11380 }
11381 key.push(c);
11382 chars.next();
11383 }
11384 steps.push(PathStep::Key(key));
11385 }
11386 }
11387 }
11388 Ok(steps)
11389}
11390
11391#[cfg(test)]
11392mod json_path_tests {
11393 use super::*;
11394
11395 fn steps(path: &str) -> Vec<PathStep> {
11396 parse_json_path(path).expect("the path parses")
11397 }
11398
11399 fn key(name: &str) -> PathStep {
11400 PathStep::Key(name.to_string())
11401 }
11402
11403 #[test]
11404 fn the_document_itself_has_no_steps() {
11405 assert_eq!(steps("$"), vec![]);
11406 assert_eq!(steps(""), vec![]);
11407 }
11408
11409 #[test]
11410 fn a_key_is_written_bare_or_after_a_dot() {
11411 assert_eq!(steps("a"), vec![key("a")]);
11412 assert_eq!(steps(".obj.c1"), vec![key("obj"), key("c1")]);
11413 assert_eq!(steps("._underscore"), vec![key("_underscore")]);
11414 }
11415
11416 #[test]
11417 fn a_bracket_holds_an_index_or_a_quoted_key() {
11418 assert_eq!(steps("arr[0]"), vec![key("arr"), PathStep::Index(0)]);
11419 assert_eq!(steps("['!@#$%^']"), vec![key("!@#$%^")]);
11420 assert_eq!(
11421 steps("translations['hello world!']"),
11422 vec![key("translations"), key("hello world!")]
11423 );
11424 }
11425
11426 #[test]
11428 fn a_dot_before_a_bracket_changes_nothing() {
11429 let expected = vec![key("objs"), PathStep::Index(0), key("\u{4f60}\u{597d}")];
11430 for spelling in [
11431 "objs[0]['\u{4f60}\u{597d}']",
11432 "objs[0][\"\u{4f60}\u{597d}\"]",
11433 "objs[0].[\"\u{4f60}\u{597d}\"]",
11434 "objs.[0].[\"\u{4f60}\u{597d}\"]",
11435 ] {
11436 assert_eq!(steps(spelling), expected, "{}", spelling);
11437 }
11438 }
11439
11440 #[test]
11441 fn a_bracket_that_never_closes_is_refused() {
11442 assert!(parse_json_path("arr[0").is_err());
11443 assert!(parse_json_path("['key'").is_err());
11444 }
11445
11446 #[test]
11447 fn a_step_the_document_does_not_have_reads_null() {
11448 let document = Value::from_json(serde_json::json!({
11449 "obj": {"c1": "c2"},
11450 "arr": [1, 2, 3],
11451 }))
11452 .expect("a document");
11453 let at = |path| walk_json_path(&document, path).expect("the path parses");
11454 assert_eq!(at(".obj.c1"), Value::String("c2".to_string()));
11455 assert_eq!(at("arr[1]"), Value::Number(2.into()));
11456 assert_eq!(at("arr[9]"), Value::Null);
11457 assert_eq!(at(".obj.nothing"), Value::Null);
11458 assert_eq!(at("obj[0]"), Value::Null);
11461 assert_eq!(at("arr.first"), Value::Null);
11462 }
11463}