1use crate::error::{Error, Result};
19use crate::schema_cache::{Relationship, SchemaCache, Table};
20use std::collections::HashMap;
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum EmbedRendering {
35 Verbatim,
39 Normalised,
48}
49
50impl EmbedRendering {
51 fn cast(self) -> &'static str {
53 match self {
54 Self::Verbatim => "::json",
55 Self::Normalised => "::jsonb",
56 }
57 }
58}
59
60#[derive(Clone, Debug)]
62pub struct EmbedPlan {
63 pub local_column: String,
65 pub foreign_column: String,
67 pub foreign_column_type: String,
69 pub foreign_schema: String,
71 pub foreign_table: String,
73 pub is_list: bool,
75 pub columns: Vec<(String, String)>,
81 pub junction: Option<EmbedJunction>,
86 pub function: Option<crate::api_request::QualifiedIdentifier>,
93 pub row_argument: Option<String>,
96}
97
98#[derive(Clone, Debug)]
100pub struct EmbedJunction {
101 pub schema: String,
103 pub table: String,
105 pub parent_columns: Vec<(String, String)>,
112 pub child_columns: Vec<(String, String)>,
114}
115
116impl EmbedJunction {
117 fn child_join(&self, junction_alias: &str, child_alias: &str) -> String {
119 Self::equalities(&self.child_columns, junction_alias, child_alias, true)
120 }
121
122 fn parent_correlation(&self, junction_alias: &str, parent_alias: &str) -> String {
124 Self::equalities(&self.parent_columns, junction_alias, parent_alias, false)
125 }
126
127 fn equalities(
133 pairs: &[(String, String)],
134 junction_alias: &str,
135 other_alias: &str,
136 junction_first: bool,
137 ) -> String {
138 pairs
139 .iter()
140 .map(|(left, right)| {
141 let (junction_column, other_column) = match junction_first {
142 true => (left, right),
143 false => (right, left),
144 };
145 format!(
146 "{}.{} = {}.{}",
147 postrust_sql::escape_ident(junction_alias),
148 postrust_sql::escape_ident(junction_column),
149 postrust_sql::escape_ident(other_alias),
150 postrust_sql::escape_ident(other_column),
151 )
152 })
153 .collect::<Vec<_>>()
154 .join(" AND ")
155 }
156}
157
158impl EmbedPlan {
159 pub fn resolve(relationship: &Relationship, schema_cache: &SchemaCache) -> Result<Self> {
164 let foreign_table_qi = relationship.foreign_table().clone();
165
166 if let Relationship::Computed {
169 function,
170 foreign_table,
171 to_one,
172 row_argument,
173 ..
174 } = relationship
175 {
176 return Ok(Self {
177 local_column: String::new(),
178 foreign_column: String::new(),
179 foreign_column_type: String::new(),
180 foreign_schema: foreign_table.schema.clone(),
181 foreign_table: foreign_table.name.clone(),
182 is_list: !to_one,
183 columns: Vec::new(),
184 junction: None,
185 function: Some(function.clone()),
186 row_argument: row_argument.clone(),
187 });
188 }
189
190 if let Relationship::ForeignKey {
191 cardinality: crate::schema_cache::Cardinality::M2M(junction),
192 ..
193 } = relationship
194 {
195 let (local_column, _) =
200 junction.source_columns.first().cloned().ok_or_else(|| {
201 Error::EmbeddingError("junction has no source columns".into())
202 })?;
203 let (_, foreign_column) =
204 junction.target_columns.first().cloned().ok_or_else(|| {
205 Error::EmbeddingError("junction has no target columns".into())
206 })?;
207
208 return Ok(Self {
209 local_column,
210 foreign_column,
211 foreign_column_type: String::new(),
212 foreign_schema: foreign_table_qi.schema.clone(),
213 foreign_table: foreign_table_qi.name.clone(),
214 is_list: true,
216 columns: Vec::new(),
217 row_argument: None,
218 junction: Some(EmbedJunction {
219 schema: junction.table.schema.clone(),
220 table: junction.table.name.clone(),
221 parent_columns: junction.source_columns.clone(),
222 child_columns: junction.target_columns.clone(),
223 }),
224 function: None,
225 });
226 }
227
228 let columns = match relationship {
229 Relationship::ForeignKey { cardinality, .. } => cardinality.columns(),
230 Relationship::Computed { .. } => unreachable!("handled above"),
231 };
232
233 let (local_column, foreign_column) = columns
234 .first()
235 .cloned()
236 .ok_or_else(|| Error::EmbeddingError("relationship joins on no columns".into()))?;
237
238 let foreign_table: &Table = schema_cache.get_table(&foreign_table_qi).ok_or_else(|| {
239 Error::EmbeddingError(format!(
240 "cannot embed \"{}\": it is not in an exposed schema",
241 foreign_table_qi
242 ))
243 })?;
244
245 let foreign_column_type = foreign_table
246 .get_column(&foreign_column)
247 .map(|c| c.nominal_type.clone())
248 .ok_or_else(|| {
249 Error::EmbeddingError(format!(
250 "cannot embed \"{}\": join column \"{}\" not found",
251 foreign_table_qi, foreign_column
252 ))
253 })?;
254
255 Ok(Self {
256 local_column,
257 foreign_column,
258 foreign_column_type,
259 foreign_schema: foreign_table_qi.schema.clone(),
260 foreign_table: foreign_table_qi.name.clone(),
261 is_list: !relationship.is_to_one(),
262 columns,
263 junction: None,
264 function: None,
265 row_argument: None,
266 })
267 }
268
269 fn correlation(&self, parent_alias: &str, child_alias: &str) -> String {
274 let pairs = if self.columns.is_empty() {
275 vec![(self.local_column.clone(), self.foreign_column.clone())]
276 } else {
277 self.columns.clone()
278 };
279
280 pairs
281 .iter()
282 .map(|(local, foreign)| {
283 format!(
284 "{}.{} = {}.{}",
285 postrust_sql::escape_ident(child_alias),
286 postrust_sql::escape_ident(foreign),
287 postrust_sql::escape_ident(parent_alias),
288 postrust_sql::escape_ident(local),
289 )
290 })
291 .collect::<Vec<_>>()
292 .join(" AND ")
293 }
294
295 pub fn children_sql(&self, limit: Option<i64>, columns: &[String]) -> Result<String> {
309 let type_name = castable_type_name(&self.foreign_column_type).ok_or_else(|| {
310 Error::EmbeddingError(format!(
311 "cannot embed \"{}\": join column type \"{}\" is not a plain type name",
312 self.foreign_table, self.foreign_column_type
313 ))
314 })?;
315
316 let projection = self.projection(columns);
317
318 let mut inner = format!(
319 "SELECT {} FROM {}.{} WHERE {} = ANY($1::{}[])",
320 projection,
321 postrust_sql::escape_ident(&self.foreign_schema),
322 postrust_sql::escape_ident(&self.foreign_table),
323 postrust_sql::escape_ident(&self.foreign_column),
324 type_name
325 );
326
327 if let Some(limit) = limit {
328 inner.push_str(&format!(" LIMIT {}", limit));
329 }
330
331 Ok(format!("SELECT row_to_json(t) FROM ({}) t", inner))
332 }
333
334 pub fn children_grouped_sql(&self, limit: Option<i64>, columns: &[String]) -> Result<String> {
349 if self
350 .junction
351 .as_ref()
352 .is_some_and(|j| j.parent_columns.len() > 1)
353 {
354 return Err(Error::EmbeddingError(format!(
355 "embedding \"{}\" this way is not supported: it joins through a junction \
356 keyed on several columns, and grouping children by key needs a single one",
357 self.foreign_table,
358 )));
359 }
360
361 if self.columns.len() > 1 {
362 return Err(Error::EmbeddingError(format!(
363 "embedding \"{}\" this way is not supported: it joins on {} columns, and \
364 grouping children by key needs a single one",
365 self.foreign_table,
366 self.columns.len()
367 )));
368 }
369
370 let type_name = castable_type_name(&self.foreign_column_type).ok_or_else(|| {
371 Error::EmbeddingError(format!(
372 "cannot embed \"{}\": join column type \"{}\" is not a plain type name",
373 self.foreign_table, self.foreign_column_type
374 ))
375 })?;
376
377 let key = postrust_sql::escape_ident(&self.foreign_column);
378
379 let mut inner = format!(
380 "SELECT {} FROM {}.{} WHERE {} = ANY($1::{}[])",
381 self.projection(columns),
382 postrust_sql::escape_ident(&self.foreign_schema),
383 postrust_sql::escape_ident(&self.foreign_table),
384 key,
385 type_name
386 );
387
388 if let Some(limit) = limit {
389 inner.push_str(&format!(" LIMIT {}", limit));
390 }
391
392 Ok(format!(
393 "SELECT to_jsonb(c.{key}) AS k, json_agg(row_to_json(c)) AS v \
394 FROM ({inner}) c GROUP BY c.{key}",
395 key = key,
396 inner = inner
397 ))
398 }
399
400 #[allow(clippy::too_many_arguments)] pub fn correlated_rows(
417 &self,
418 parent_alias: &str,
419 parent_row: &str,
420 child_alias: &str,
421 inner_select: &str,
422 limit: Option<i64>,
423 offset: i64,
427 child_where: Option<&str>,
428 order_by: Option<&str>,
432 function_arguments: Option<&str>,
435 ) -> Result<String> {
436 let mut inner = match &self.function {
444 Some(function) => format!(
445 "SELECT {} FROM {}.{}({}) AS {} WHERE true",
446 inner_select,
447 postrust_sql::escape_ident(&function.schema),
448 postrust_sql::escape_ident(&function.name),
449 function_arguments.unwrap_or(parent_row),
454 postrust_sql::escape_ident(child_alias),
455 ),
456 None => match &self.junction {
457 Some(junction) => format!(
460 "SELECT {} FROM {}",
461 inner_select,
462 self.junction_source(junction, parent_alias, child_alias),
463 ),
464 None => format!(
465 "SELECT {} FROM {}.{} AS {} WHERE {}",
466 inner_select,
467 postrust_sql::escape_ident(&self.foreign_schema),
468 postrust_sql::escape_ident(&self.foreign_table),
469 postrust_sql::escape_ident(child_alias),
470 self.correlation(parent_alias, child_alias),
471 ),
472 },
473 };
474
475 if let Some(child_where) = child_where {
479 inner.push_str(" AND ");
480 inner.push_str(child_where);
481 }
482
483 if let Some(order_by) = order_by {
484 inner.push_str(" ORDER BY ");
485 inner.push_str(order_by);
486 }
487
488 if let Some(limit) = limit {
493 inner.push_str(&format!(" LIMIT {}", limit));
494 } else if !self.is_list {
495 inner.push_str(" LIMIT 1");
496 }
497
498 if offset > 0 {
499 inner.push_str(&format!(" OFFSET {}", offset));
500 }
501
502 Ok(inner)
503 }
504
505 fn junction_source(
517 &self,
518 junction: &EmbedJunction,
519 parent_alias: &str,
520 child_alias: &str,
521 ) -> String {
522 let junction_alias = format!("{}_jx", child_alias);
523 let lateral_alias = format!("{}_jl", child_alias);
524 format!(
525 "{}.{} AS {} CROSS JOIN LATERAL (SELECT 1 FROM {}.{} AS {} WHERE {} AND {}) AS {} WHERE true",
526 postrust_sql::escape_ident(&self.foreign_schema),
527 postrust_sql::escape_ident(&self.foreign_table),
528 postrust_sql::escape_ident(child_alias),
529 postrust_sql::escape_ident(&junction.schema),
530 postrust_sql::escape_ident(&junction.table),
531 postrust_sql::escape_ident(&junction_alias),
532 junction.child_join(&junction_alias, child_alias),
533 junction.parent_correlation(&junction_alias, parent_alias),
534 postrust_sql::escape_ident(&lateral_alias),
535 )
536 }
537
538 #[allow(clippy::too_many_arguments)] pub fn embed_expression(
545 &self,
546 parent_alias: &str,
547 parent_row: &str,
548 child_alias: &str,
549 inner_select: &str,
550 limit: Option<i64>,
551 offset: i64,
552 child_where: Option<&str>,
553 order_by: Option<&str>,
554 function_arguments: Option<&str>,
555 rendering: EmbedRendering,
556 ) -> Result<String> {
557 let inner = self.correlated_rows(
558 parent_alias,
559 parent_row,
560 child_alias,
561 inner_select,
562 limit,
563 offset,
564 child_where,
565 order_by,
566 function_arguments,
567 )?;
568
569 let alias = postrust_sql::escape_ident(&format!("{}_j", child_alias));
570
571 Ok(if self.is_list {
572 format!(
575 "COALESCE((SELECT json_agg(row_to_json({alias})) FROM ({inner}) {alias}), '[]'::json){cast}",
576 alias = alias,
577 inner = inner,
578 cast = rendering.cast()
579 )
580 } else {
581 format!(
582 "(SELECT row_to_json({alias}) FROM ({inner}) {alias}){cast}",
583 alias = alias,
584 inner = inner,
585 cast = rendering.cast()
586 )
587 })
588 }
589
590 #[allow(clippy::too_many_arguments)] pub fn aggregate_expression(
606 &self,
607 parent_alias: &str,
608 parent_row: &str,
609 child_alias: &str,
610 aggregate_select: &str,
611 limit: Option<i64>,
612 offset: i64,
613 child_where: Option<&str>,
614 order_by: Option<&str>,
615 function_arguments: Option<&str>,
616 distinct_on: &str,
620 rendering: EmbedRendering,
621 ) -> Result<String> {
622 let child = postrust_sql::escape_ident(child_alias);
623 let rows = self.correlated_rows(
624 parent_alias,
625 parent_row,
626 child_alias,
627 &format!("{}{}.*", distinct_on, child),
628 limit,
629 offset,
630 child_where,
631 order_by,
632 function_arguments,
633 )?;
634 let alias = postrust_sql::escape_ident(&format!("{}_a", child_alias));
635 Ok(format!(
636 "(SELECT row_to_json({alias}) FROM \
637 (SELECT {select} FROM ({rows}) AS {child}) {alias}){cast}",
638 alias = alias,
639 select = aggregate_select,
640 rows = rows,
641 child = child,
642 cast = rendering.cast()
643 ))
644 }
645
646 pub fn order_expression(
654 &self,
655 parent_alias: &str,
656 parent_row: &str,
657 child_alias: &str,
658 column_sql: &str,
659 ) -> String {
660 let source = match (&self.function, &self.junction) {
661 (Some(function), _) => format!(
662 "{}.{}({}) AS {} WHERE true",
663 postrust_sql::escape_ident(&function.schema),
664 postrust_sql::escape_ident(&function.name),
665 parent_row,
666 postrust_sql::escape_ident(child_alias),
667 ),
668 (None, Some(junction)) => self.junction_source(junction, parent_alias, child_alias),
669 (None, None) => format!(
670 "{}.{} AS {} WHERE {}",
671 postrust_sql::escape_ident(&self.foreign_schema),
672 postrust_sql::escape_ident(&self.foreign_table),
673 postrust_sql::escape_ident(child_alias),
674 self.correlation(parent_alias, child_alias),
675 ),
676 };
677
678 format!("(SELECT {} FROM {} LIMIT 1)", column_sql, source)
679 }
680
681 pub fn inner_join_predicate(
690 &self,
691 parent_alias: &str,
692 parent_row: &str,
693 child_alias: &str,
694 child_where: Option<&str>,
695 ) -> String {
696 let mut predicate = match &self.function {
697 Some(function) => format!(
698 "EXISTS (SELECT 1 FROM {}.{}({}) AS {} WHERE true",
699 postrust_sql::escape_ident(&function.schema),
700 postrust_sql::escape_ident(&function.name),
701 parent_row,
702 postrust_sql::escape_ident(child_alias),
703 ),
704 None => match &self.junction {
705 Some(junction) => format!(
706 "EXISTS (SELECT 1 FROM {}",
707 self.junction_source(junction, parent_alias, child_alias),
708 ),
709 None => format!(
710 "EXISTS (SELECT 1 FROM {}.{} AS {} WHERE {}",
711 postrust_sql::escape_ident(&self.foreign_schema),
712 postrust_sql::escape_ident(&self.foreign_table),
713 postrust_sql::escape_ident(child_alias),
714 self.correlation(parent_alias, child_alias),
715 ),
716 },
717 };
718
719 if let Some(child_where) = child_where {
720 predicate.push_str(" AND ");
721 predicate.push_str(child_where);
722 }
723
724 predicate.push(')');
725 predicate
726 }
727
728 fn projection(&self, columns: &[String]) -> String {
734 if columns.is_empty() {
735 return "*".to_string();
736 }
737
738 let mut wanted: Vec<&str> = Vec::with_capacity(columns.len() + 1);
739 for column in columns {
740 if !wanted.contains(&column.as_str()) {
741 wanted.push(column);
742 }
743 }
744 if !wanted.contains(&self.foreign_column.as_str()) {
745 wanted.push(&self.foreign_column);
746 }
747
748 wanted
749 .into_iter()
750 .map(postrust_sql::escape_ident)
751 .collect::<Vec<_>>()
752 .join(", ")
753 }
754}
755
756fn castable_type_name(pg_type: &str) -> Option<&str> {
758 if pg_type.is_empty() {
759 return None;
760 }
761 if pg_type
762 .chars()
763 .all(|c| c.is_ascii_alphanumeric() || c == '_')
764 {
765 Some(pg_type)
766 } else {
767 None
768 }
769}
770
771pub fn key_to_text(value: &serde_json::Value) -> Option<String> {
776 match value {
777 serde_json::Value::Null => None,
778 serde_json::Value::String(s) => Some(s.clone()),
779 other => Some(other.to_string()),
780 }
781}
782
783pub fn group_from_aggregated(
790 rows: Vec<(serde_json::Value, serde_json::Value)>,
791) -> HashMap<String, Vec<serde_json::Value>> {
792 let mut grouped: HashMap<String, Vec<serde_json::Value>> = HashMap::with_capacity(rows.len());
793
794 for (key, children) in rows {
795 let key = key_to_text(&key).unwrap_or_default();
796 let children = match children {
797 serde_json::Value::Array(items) => items,
798 _ => Vec::new(),
800 };
801 grouped.entry(key).or_default().extend(children);
802 }
803
804 grouped
805}
806
807pub fn group_by_key(
813 children: Vec<serde_json::Value>,
814 foreign_column: &str,
815) -> HashMap<String, Vec<serde_json::Value>> {
816 let mut grouped: HashMap<String, Vec<serde_json::Value>> = HashMap::new();
817
818 for child in children {
819 let key = child
820 .get(foreign_column)
821 .and_then(key_to_text)
822 .unwrap_or_default();
823 grouped.entry(key).or_default().push(child);
824 }
825
826 grouped
827}
828
829pub fn attach_to_parent(
835 parent: &mut serde_json::Value,
836 field_name: &str,
837 plan: &EmbedPlan,
838 grouped: &HashMap<String, Vec<serde_json::Value>>,
839) {
840 let key = parent.get(&plan.local_column).and_then(key_to_text);
841
842 let matches = key
843 .as_ref()
844 .and_then(|k| grouped.get(k))
845 .cloned()
846 .unwrap_or_default();
847
848 let value = if plan.is_list {
849 serde_json::Value::Array(matches)
850 } else {
851 matches
852 .into_iter()
853 .next()
854 .unwrap_or(serde_json::Value::Null)
855 };
856
857 if let Some(object) = parent.as_object_mut() {
858 object.insert(field_name.to_string(), value);
859 }
860}
861
862pub fn spread_into_parent(
881 parent: &mut serde_json::Value,
882 plan: &EmbedPlan,
883 grouped: &HashMap<String, Vec<serde_json::Value>>,
884 columns: &[(String, String)],
885) {
886 let key = parent.get(&plan.local_column).and_then(key_to_text);
887 let matches = key
888 .as_ref()
889 .and_then(|k| grouped.get(k))
890 .cloned()
891 .unwrap_or_default();
892
893 let Some(object) = parent.as_object_mut() else {
894 return;
895 };
896
897 for (source, output) in columns {
898 let value = if plan.is_list {
899 serde_json::Value::Array(
900 matches
901 .iter()
902 .map(|child| {
903 child
904 .get(source)
905 .cloned()
906 .unwrap_or(serde_json::Value::Null)
907 })
908 .collect(),
909 )
910 } else {
911 matches
912 .first()
913 .and_then(|child| child.get(source).cloned())
914 .unwrap_or(serde_json::Value::Null)
915 };
916 object.insert(output.clone(), value);
917 }
918}
919
920pub fn parent_keys(parents: &[serde_json::Value], local_column: &str) -> Vec<String> {
922 let mut seen = std::collections::HashSet::new();
923 let mut keys = Vec::new();
924
925 for parent in parents {
926 if let Some(key) = parent.get(local_column).and_then(key_to_text) {
927 if seen.insert(key.clone()) {
928 keys.push(key);
929 }
930 }
931 }
932
933 keys
934}
935
936#[cfg(test)]
937mod tests {
938 use super::*;
939
940 fn plan(is_list: bool) -> EmbedPlan {
941 EmbedPlan {
942 row_argument: None,
943 local_column: "id".into(),
944 foreign_column: "user_id".into(),
945 foreign_column_type: "int4".into(),
946 foreign_schema: "public".into(),
947 foreign_table: "posts".into(),
948 is_list,
949 columns: vec![("id".into(), "user_id".into())],
950 junction: None,
951 function: None,
952 }
953 }
954
955 #[test]
956 fn a_junction_hop_keeps_only_the_childs_columns_in_scope() {
957 let mut p = plan(true);
958 p.foreign_table = "jobs".into();
959 p.junction = Some(EmbedJunction {
960 schema: "public".into(),
961 table: "big_projects".into(),
962 parent_columns: vec![("id".into(), "project_id".into())],
963 child_columns: vec![("job_id".into(), "id".into())],
964 });
965 let rows = p
966 .correlated_rows("p", "\"p\"", "jobs", "jobs.*", None, 0, None, None, None)
967 .unwrap();
968 assert!(
971 rows.contains("CROSS JOIN LATERAL (SELECT 1 FROM"),
972 "{}",
973 rows
974 );
975 assert!(
976 !rows.contains(" JOIN \"public\".\"big_projects\" AS"),
977 "{}",
978 rows
979 );
980 assert!(
981 !rows.contains("EXISTS") && !rows.contains(" IN ("),
982 "{}",
983 rows
984 );
985 assert!(
986 rows.contains(r#""jobs_jx"."project_id" = "p"."id""#),
987 "{}",
988 rows
989 );
990 assert!(rows.ends_with("WHERE true"), "{}", rows);
991 let order = p.order_expression("p", "\"p\"", "jobs", "\"name\"");
992 assert!(order.contains("CROSS JOIN LATERAL"), "{}", order);
993 let inner = p.inner_join_predicate("p", "\"p\"", "jobs", None);
994 assert!(
995 inner.starts_with(
996 "EXISTS (SELECT 1 FROM \"public\".\"jobs\" AS \"jobs\" CROSS JOIN LATERAL"
997 ),
998 "{}",
999 inner
1000 );
1001 }
1002
1003 #[test]
1004 fn children_sql_binds_keys_as_a_cast_array() {
1005 let sql = plan(true).children_sql(None, &[]).unwrap();
1006 assert_eq!(
1007 sql,
1008 "SELECT row_to_json(t) FROM (SELECT * FROM \"public\".\"posts\" \
1009 WHERE \"user_id\" = ANY($1::int4[])) t"
1010 );
1011 }
1012
1013 #[test]
1014 fn embed_expression_aggregates_a_to_many_relation() {
1015 let sql = plan(true)
1016 .embed_expression(
1017 "p",
1018 "\"p\"",
1019 "posts",
1020 r#""id", "title""#,
1021 None,
1022 0,
1023 None,
1024 None,
1025 None,
1026 EmbedRendering::Verbatim,
1027 )
1028 .unwrap();
1029
1030 assert!(sql.starts_with("COALESCE((SELECT json_agg("), "{}", sql);
1031 assert!(sql.contains(r#""posts"."user_id" = "p"."id""#), "{}", sql);
1034 assert!(
1035 sql.contains(r#"AS "posts""#),
1036 "the child table is aliased: {}",
1037 sql
1038 );
1039 assert!(!sql.contains("ANY("), "{}", sql);
1040 assert!(sql.contains("'[]'::json"), "{}", sql);
1042 }
1043
1044 #[test]
1045 fn embed_expression_takes_one_row_for_a_to_one_relation() {
1046 let sql = plan(false)
1047 .embed_expression(
1048 "p",
1049 "\"p\"",
1050 "author",
1051 r#""id""#,
1052 None,
1053 0,
1054 None,
1055 None,
1056 None,
1057 EmbedRendering::Verbatim,
1058 )
1059 .unwrap();
1060
1061 assert!(sql.contains("row_to_json"), "{}", sql);
1062 assert!(!sql.contains("json_agg"), "{}", sql);
1063 assert!(
1064 sql.contains("LIMIT 1"),
1065 "a to-one relation yields one row: {}",
1066 sql
1067 );
1068 }
1069
1070 #[test]
1071 fn embed_expression_limits_rows_per_parent() {
1072 let sql = plan(true)
1073 .embed_expression(
1074 "p",
1075 "\"p\"",
1076 "posts",
1077 r#""id""#,
1078 Some(25),
1079 0,
1080 None,
1081 None,
1082 None,
1083 EmbedRendering::Verbatim,
1084 )
1085 .unwrap();
1086 assert!(sql.contains("LIMIT 25"), "{}", sql);
1087 }
1088
1089 #[test]
1090 fn children_sql_projects_only_the_requested_columns() {
1091 let sql = plan(true)
1092 .children_sql(None, &["title".to_string(), "body".to_string()])
1093 .unwrap();
1094
1095 assert!(
1096 sql.contains(r#"SELECT "title", "body", "user_id" FROM"#),
1097 "{}",
1098 sql
1099 );
1100 assert!(
1101 !sql.contains("SELECT *"),
1102 "an unrequested column should not be read at all: {}",
1103 sql
1104 );
1105 }
1106
1107 #[test]
1108 fn children_sql_always_includes_the_join_column() {
1109 let sql = plan(true)
1112 .children_sql(None, &["title".to_string()])
1113 .unwrap();
1114 assert!(sql.contains(r#""user_id""#), "{}", sql);
1115 }
1116
1117 #[test]
1118 fn children_sql_does_not_repeat_the_join_column() {
1119 let sql = plan(true)
1120 .children_sql(None, &["user_id".to_string(), "title".to_string()])
1121 .unwrap();
1122 assert_eq!(
1123 sql.matches(r#""user_id""#).count(),
1124 2,
1125 "expected the column once in the projection and once in the WHERE: {}",
1126 sql
1127 );
1128 }
1129
1130 #[test]
1131 fn children_sql_escapes_column_names() {
1132 let sql = plan(true)
1134 .children_sql(None, &[r#"ev"il"#.to_string()])
1135 .unwrap();
1136 assert!(sql.contains(r#""ev""il""#), "{}", sql);
1137 }
1138
1139 #[test]
1140 fn children_sql_falls_back_to_every_column() {
1141 let sql = plan(true).children_sql(None, &[]).unwrap();
1142 assert!(sql.contains("SELECT * FROM"), "{}", sql);
1143 }
1144
1145 #[test]
1146 fn children_sql_applies_a_limit() {
1147 let sql = plan(true).children_sql(Some(25), &[]).unwrap();
1148 assert!(sql.contains("LIMIT 25"), "{}", sql);
1149 }
1150
1151 #[test]
1152 fn children_sql_rejects_a_non_plain_type_name() {
1153 let mut p = plan(true);
1154 p.foreign_column_type = "int4; DROP TABLE users".into();
1155 assert!(p.children_sql(None, &[]).is_err());
1156 }
1157
1158 #[test]
1159 fn keys_are_rendered_without_json_quoting() {
1160 assert_eq!(key_to_text(&serde_json::json!(7)), Some("7".to_string()));
1161 assert_eq!(
1162 key_to_text(&serde_json::json!("abc")),
1163 Some("abc".to_string())
1164 );
1165 assert_eq!(key_to_text(&serde_json::Value::Null), None);
1166 }
1167
1168 #[test]
1169 fn parent_keys_are_distinct_and_skip_nulls() {
1170 let parents = vec![
1171 serde_json::json!({"id": 1}),
1172 serde_json::json!({"id": 2}),
1173 serde_json::json!({"id": 1}),
1174 serde_json::json!({"id": null}),
1175 ];
1176 assert_eq!(parent_keys(&parents, "id"), vec!["1", "2"]);
1177 }
1178
1179 #[test]
1180 fn to_many_attaches_an_array_and_empty_when_absent() {
1181 let grouped = group_by_key(vec![serde_json::json!({"id": 10, "user_id": 1})], "user_id");
1182
1183 let mut matched = serde_json::json!({"id": 1});
1184 attach_to_parent(&mut matched, "posts", &plan(true), &grouped);
1185 assert_eq!(matched["posts"].as_array().map(|a| a.len()), Some(1));
1186
1187 let mut unmatched = serde_json::json!({"id": 2});
1188 attach_to_parent(&mut unmatched, "posts", &plan(true), &grouped);
1189 assert_eq!(
1190 unmatched["posts"],
1191 serde_json::json!([]),
1192 "a to-many with no matches must still be an array"
1193 );
1194 }
1195
1196 #[test]
1197 fn to_one_attaches_an_object_or_null() {
1198 let grouped = group_by_key(vec![serde_json::json!({"id": 10, "user_id": 1})], "user_id");
1199
1200 let mut matched = serde_json::json!({"id": 1});
1201 attach_to_parent(&mut matched, "author", &plan(false), &grouped);
1202 assert_eq!(matched["author"]["id"], serde_json::json!(10));
1203
1204 let mut unmatched = serde_json::json!({"id": 2});
1205 attach_to_parent(&mut unmatched, "author", &plan(false), &grouped);
1206 assert_eq!(unmatched["author"], serde_json::Value::Null);
1207 }
1208
1209 #[test]
1210 fn spread_lifts_a_to_one_relation_into_the_parent() {
1211 let mut grouped = HashMap::new();
1212 grouped.insert(
1213 "1".to_string(),
1214 vec![serde_json::json!({"first_name": "Ada", "last_name": "L"})],
1215 );
1216
1217 let mut parent = serde_json::json!({"id": 1, "title": "Notes"});
1218 spread_into_parent(
1219 &mut parent,
1220 &plan(false),
1221 &grouped,
1222 &[
1223 ("first_name".into(), "first_name".into()),
1224 ("last_name".into(), "last_name".into()),
1225 ],
1226 );
1227
1228 assert_eq!(parent["first_name"], "Ada");
1230 assert_eq!(parent["last_name"], "L");
1231 assert_eq!(parent["title"], "Notes");
1232 assert!(parent.get("posts").is_none());
1233 }
1234
1235 #[test]
1236 fn spread_without_a_match_still_carries_the_requested_keys() {
1237 let mut parent = serde_json::json!({"id": 9});
1238 spread_into_parent(
1239 &mut parent,
1240 &plan(false),
1241 &HashMap::new(),
1242 &[("first_name".into(), "first_name".into())],
1243 );
1244 assert_eq!(parent["first_name"], serde_json::Value::Null);
1245 }
1246
1247 #[test]
1248 fn spread_of_a_to_many_relation_gives_a_column_per_array() {
1249 let mut grouped = HashMap::new();
1250 grouped.insert(
1251 "1".to_string(),
1252 vec![
1253 serde_json::json!({"title": "a"}),
1254 serde_json::json!({"title": "b"}),
1255 ],
1256 );
1257
1258 let mut parent = serde_json::json!({"id": 1});
1259 spread_into_parent(
1260 &mut parent,
1261 &plan(true),
1262 &grouped,
1263 &[("title".into(), "title".into())],
1264 );
1265
1266 assert_eq!(parent["title"], serde_json::json!(["a", "b"]));
1267 }
1268
1269 #[test]
1270 fn spread_without_a_column_list_adds_nothing() {
1271 let mut grouped = HashMap::new();
1274 grouped.insert("1".to_string(), vec![serde_json::json!({"id": 7, "b": 2})]);
1275
1276 let mut parent = serde_json::json!({"id": 1});
1277 spread_into_parent(&mut parent, &plan(false), &grouped, &[]);
1278
1279 assert_eq!(parent, serde_json::json!({"id": 1}));
1280 }
1281}