1use crate::input::mutation::InputValue;
6use crate::resolver::query::TableFilter;
7use bytes::Bytes;
8use postrust_core::plan::{CoercibleField, CoercibleLogicTree, MutatePlan};
9use postrust_core::schema_cache::Table;
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12
13#[derive(Debug, Clone, Default)]
15pub struct InsertArgs {
16 pub objects: Vec<HashMap<String, InputValue>>,
18 pub on_conflict: Option<OnConflictArgs>,
20 pub returning: Vec<String>,
22}
23
24impl InsertArgs {
25 pub fn new() -> Self {
27 Self::default()
28 }
29
30 pub fn with_object(mut self, object: HashMap<String, InputValue>) -> Self {
32 self.objects.push(object);
33 self
34 }
35
36 pub fn with_objects(mut self, objects: Vec<HashMap<String, InputValue>>) -> Self {
38 self.objects = objects;
39 self
40 }
41
42 pub fn with_on_conflict(mut self, on_conflict: OnConflictArgs) -> Self {
44 self.on_conflict = Some(on_conflict);
45 self
46 }
47
48 pub fn with_returning(mut self, returning: Vec<String>) -> Self {
50 self.returning = returning;
51 self
52 }
53
54 pub fn has_objects(&self) -> bool {
56 !self.objects.is_empty()
57 }
58
59 pub fn object_count(&self) -> usize {
61 self.objects.len()
62 }
63
64 pub fn to_json_bytes(&self) -> Option<Bytes> {
66 if self.objects.is_empty() {
67 return None;
68 }
69
70 let json_objects: Vec<serde_json::Value> = self
72 .objects
73 .iter()
74 .map(|obj| {
75 let map: serde_json::Map<String, serde_json::Value> = obj
76 .iter()
77 .map(|(k, v)| (k.clone(), input_value_to_json(v)))
78 .collect();
79 serde_json::Value::Object(map)
80 })
81 .collect();
82
83 let json = if json_objects.len() == 1 {
84 serde_json::to_vec(&json_objects[0]).ok()
85 } else {
86 serde_json::to_vec(&json_objects).ok()
87 };
88
89 json.map(Bytes::from)
90 }
91
92 pub fn column_names(&self) -> Vec<String> {
94 self.objects
95 .first()
96 .map(|obj| obj.keys().cloned().collect())
97 .unwrap_or_default()
98 }
99}
100
101#[derive(Debug, Clone, Default, Serialize, Deserialize)]
103pub struct OnConflictArgs {
104 pub constraint: Vec<String>,
106 pub update_columns: Vec<String>,
108 pub where_filter: Option<TableFilter>,
110}
111
112impl OnConflictArgs {
113 pub fn new(constraint: Vec<String>) -> Self {
115 Self {
116 constraint,
117 update_columns: vec![],
118 where_filter: None,
119 }
120 }
121
122 pub fn with_update_columns(mut self, columns: Vec<String>) -> Self {
124 self.update_columns = columns;
125 self
126 }
127
128 pub fn with_where(mut self, filter: TableFilter) -> Self {
130 self.where_filter = Some(filter);
131 self
132 }
133}
134
135#[derive(Debug, Clone, Default)]
137pub struct UpdateArgs {
138 pub filter: Option<TableFilter>,
140 pub set: HashMap<String, InputValue>,
142 pub returning: Vec<String>,
144}
145
146impl UpdateArgs {
147 pub fn new() -> Self {
149 Self::default()
150 }
151
152 pub fn with_filter(mut self, filter: TableFilter) -> Self {
154 self.filter = Some(filter);
155 self
156 }
157
158 pub fn with_set(mut self, set: HashMap<String, InputValue>) -> Self {
160 self.set = set;
161 self
162 }
163
164 pub fn with_returning(mut self, returning: Vec<String>) -> Self {
166 self.returning = returning;
167 self
168 }
169
170 pub fn has_filter(&self) -> bool {
172 self.filter.is_some()
173 }
174
175 pub fn has_set(&self) -> bool {
177 !self.set.is_empty()
178 }
179
180 pub fn to_json_bytes(&self) -> Option<Bytes> {
182 if self.set.is_empty() {
183 return None;
184 }
185
186 let map: serde_json::Map<String, serde_json::Value> = self
187 .set
188 .iter()
189 .map(|(k, v)| (k.clone(), input_value_to_json(v)))
190 .collect();
191
192 serde_json::to_vec(&serde_json::Value::Object(map))
193 .ok()
194 .map(Bytes::from)
195 }
196
197 pub fn column_names(&self) -> Vec<String> {
199 self.set.keys().cloned().collect()
200 }
201}
202
203#[derive(Debug, Clone, Default)]
205pub struct DeleteArgs {
206 pub filter: Option<TableFilter>,
208 pub returning: Vec<String>,
210}
211
212impl DeleteArgs {
213 pub fn new() -> Self {
215 Self::default()
216 }
217
218 pub fn with_filter(mut self, filter: TableFilter) -> Self {
220 self.filter = Some(filter);
221 self
222 }
223
224 pub fn with_returning(mut self, returning: Vec<String>) -> Self {
226 self.returning = returning;
227 self
228 }
229
230 pub fn has_filter(&self) -> bool {
232 self.filter.is_some()
233 }
234}
235
236fn input_value_to_json(value: &InputValue) -> serde_json::Value {
238 match value {
239 InputValue::Null => serde_json::Value::Null,
240 InputValue::Bool(b) => serde_json::Value::Bool(*b),
241 InputValue::Int(i) => serde_json::Value::Number((*i).into()),
242 InputValue::Float(f) => serde_json::Number::from_f64(*f)
243 .map(serde_json::Value::Number)
244 .unwrap_or(serde_json::Value::Null),
245 InputValue::String(s) => serde_json::Value::String(s.clone()),
246 InputValue::Object(obj) => {
247 let map: serde_json::Map<String, serde_json::Value> = obj
248 .iter()
249 .map(|(k, v)| (k.clone(), input_value_to_json(v)))
250 .collect();
251 serde_json::Value::Object(map)
252 }
253 InputValue::Array(arr) => {
254 serde_json::Value::Array(arr.iter().map(input_value_to_json).collect())
255 }
256 }
257}
258
259fn build_coercible_fields(columns: &[String], table: &Table) -> Vec<CoercibleField> {
261 columns
262 .iter()
263 .filter_map(|name| {
264 table
265 .columns
266 .get(name)
267 .map(|col| CoercibleField::simple(name, &col.data_type))
268 })
269 .collect()
270}
271
272fn build_where_clauses(filter: &Option<TableFilter>, table: &Table) -> Vec<CoercibleLogicTree> {
274 let Some(filter) = filter else {
275 return vec![];
276 };
277
278 let type_resolver = |name: &str| -> String {
279 table
280 .get_column(name)
281 .map(|c| c.data_type.clone())
282 .unwrap_or_else(|| "text".to_string())
283 };
284
285 filter
286 .to_logic_tree()
287 .map(|tree| vec![CoercibleLogicTree::from_logic_tree(&tree, type_resolver)])
288 .unwrap_or_default()
289}
290
291pub fn build_insert_plan(args: &InsertArgs, table: &Table) -> MutatePlan {
293 let columns = build_coercible_fields(&args.column_names(), table);
294 let body = args.to_json_bytes();
295 let returning = if args.returning.is_empty() {
296 table.pk_cols.clone()
297 } else {
298 args.returning.clone()
299 };
300
301 let on_conflict = args.on_conflict.as_ref().map(|oc| {
302 (
303 postrust_core::api_request::PreferResolution::MergeDuplicates,
304 oc.constraint.clone(),
305 )
306 });
307
308 MutatePlan::Insert {
309 target: table.qualified_identifier(),
310 columns,
311 body,
312 on_conflict,
313 where_clauses: vec![],
314 returning,
315 pk_cols: table.pk_cols.clone(),
316 apply_defaults: true,
317 reports_inserted: false,
318 counts_inserted: false,
319 }
320}
321
322pub fn build_update_plan(args: &UpdateArgs, table: &Table) -> MutatePlan {
324 let columns = build_coercible_fields(&args.column_names(), table);
325 let body = args.to_json_bytes();
326 let where_clauses = build_where_clauses(&args.filter, table);
327 let returning = if args.returning.is_empty() {
328 table.pk_cols.clone()
329 } else {
330 args.returning.clone()
331 };
332
333 MutatePlan::Update {
334 target: table.qualified_identifier(),
335 columns,
336 body,
337 where_clauses,
338 returning,
339 apply_defaults: false,
340 }
341}
342
343pub fn build_delete_plan(args: &DeleteArgs, table: &Table) -> MutatePlan {
345 let where_clauses = build_where_clauses(&args.filter, table);
346 let returning = if args.returning.is_empty() {
347 table.pk_cols.clone()
348 } else {
349 args.returning.clone()
350 };
351
352 MutatePlan::Delete {
353 target: table.qualified_identifier(),
354 where_clauses,
355 returning,
356 }
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362 use crate::input::filter::IntFilterInput;
363 use crate::resolver::query::FieldFilter;
364 use indexmap::IndexMap;
365 use postrust_core::schema_cache::Column;
366 use pretty_assertions::assert_eq;
367
368 fn create_test_table() -> Table {
369 let mut columns = IndexMap::new();
370 columns.insert(
371 "id".into(),
372 Column {
373 name: "id".into(),
374 description: None,
375 nullable: false,
376 data_type: "integer".into(),
377 nominal_type: "int4".into(),
378 max_len: None,
379 default: Some("nextval('users_id_seq')".into()),
380 enum_values: vec![],
381 is_pk: true,
382 position: 1,
383 always_generated: false,
384 domain_type: None,
385 },
386 );
387 columns.insert(
388 "name".into(),
389 Column {
390 name: "name".into(),
391 description: None,
392 nullable: false,
393 data_type: "text".into(),
394 nominal_type: "text".into(),
395 max_len: None,
396 default: None,
397 enum_values: vec![],
398 is_pk: false,
399 position: 2,
400 always_generated: false,
401 domain_type: None,
402 },
403 );
404 columns.insert(
405 "email".into(),
406 Column {
407 name: "email".into(),
408 description: None,
409 nullable: true,
410 data_type: "text".into(),
411 nominal_type: "text".into(),
412 max_len: None,
413 default: None,
414 enum_values: vec![],
415 is_pk: false,
416 position: 3,
417 always_generated: false,
418 domain_type: None,
419 },
420 );
421
422 Table {
423 schema: "public".into(),
424 name: "users".into(),
425 description: None,
426 is_view: false,
427 insertable: true,
428 updatable: true,
429 deletable: true,
430 pk_cols: vec!["id".into()],
431 unique_constraints: Vec::new(),
432 columns,
433 computed_columns: Default::default(),
434 is_partitioned: false,
435 }
436 }
437
438 #[test]
443 fn test_insert_args_default() {
444 let args = InsertArgs::new();
445 assert!(!args.has_objects());
446 assert_eq!(args.object_count(), 0);
447 }
448
449 #[test]
450 fn test_insert_args_with_object() {
451 let mut object = HashMap::new();
452 object.insert("name".to_string(), InputValue::String("Alice".to_string()));
453 object.insert(
454 "email".to_string(),
455 InputValue::String("alice@example.com".to_string()),
456 );
457
458 let args = InsertArgs::new().with_object(object);
459 assert!(args.has_objects());
460 assert_eq!(args.object_count(), 1);
461 }
462
463 #[test]
464 fn test_insert_args_with_multiple_objects() {
465 let obj1: HashMap<String, InputValue> =
466 [("name".to_string(), InputValue::String("Alice".to_string()))]
467 .into_iter()
468 .collect();
469 let obj2: HashMap<String, InputValue> =
470 [("name".to_string(), InputValue::String("Bob".to_string()))]
471 .into_iter()
472 .collect();
473
474 let args = InsertArgs::new().with_objects(vec![obj1, obj2]);
475 assert_eq!(args.object_count(), 2);
476 }
477
478 #[test]
479 fn test_insert_args_column_names() {
480 let object: HashMap<String, InputValue> = [
481 ("name".to_string(), InputValue::String("Alice".to_string())),
482 (
483 "email".to_string(),
484 InputValue::String("alice@example.com".to_string()),
485 ),
486 ]
487 .into_iter()
488 .collect();
489
490 let args = InsertArgs::new().with_object(object);
491 let columns = args.column_names();
492 assert_eq!(columns.len(), 2);
493 assert!(columns.contains(&"name".to_string()));
494 assert!(columns.contains(&"email".to_string()));
495 }
496
497 #[test]
498 fn test_insert_args_to_json_bytes() {
499 let object: HashMap<String, InputValue> =
500 [("name".to_string(), InputValue::String("Alice".to_string()))]
501 .into_iter()
502 .collect();
503
504 let args = InsertArgs::new().with_object(object);
505 let bytes = args.to_json_bytes().unwrap();
506 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
507 assert_eq!(json["name"], "Alice");
508 }
509
510 #[test]
511 fn test_insert_args_with_returning() {
512 let args = InsertArgs::new().with_returning(vec!["id".to_string(), "name".to_string()]);
513 assert_eq!(args.returning.len(), 2);
514 }
515
516 #[test]
517 fn test_insert_args_with_on_conflict() {
518 let on_conflict = OnConflictArgs::new(vec!["email".to_string()])
519 .with_update_columns(vec!["name".to_string()]);
520
521 let args = InsertArgs::new().with_on_conflict(on_conflict);
522 assert!(args.on_conflict.is_some());
523 }
524
525 #[test]
530 fn test_on_conflict_args() {
531 let args = OnConflictArgs::new(vec!["id".to_string()])
532 .with_update_columns(vec!["name".to_string(), "email".to_string()]);
533
534 assert_eq!(args.constraint, vec!["id".to_string()]);
535 assert_eq!(args.update_columns.len(), 2);
536 }
537
538 #[test]
543 fn test_update_args_default() {
544 let args = UpdateArgs::new();
545 assert!(!args.has_filter());
546 assert!(!args.has_set());
547 }
548
549 #[test]
550 fn test_update_args_with_set() {
551 let set: HashMap<String, InputValue> = [(
552 "name".to_string(),
553 InputValue::String("Updated".to_string()),
554 )]
555 .into_iter()
556 .collect();
557
558 let args = UpdateArgs::new().with_set(set);
559 assert!(args.has_set());
560 assert_eq!(args.column_names().len(), 1);
561 }
562
563 #[test]
564 fn test_update_args_with_filter() {
565 let filter = TableFilter::new().with_field(
566 "id",
567 FieldFilter::int(IntFilterInput {
568 eq: Some(1),
569 ..Default::default()
570 }),
571 );
572
573 let args = UpdateArgs::new().with_filter(filter);
574 assert!(args.has_filter());
575 }
576
577 #[test]
578 fn test_update_args_to_json_bytes() {
579 let set: HashMap<String, InputValue> = [
580 (
581 "name".to_string(),
582 InputValue::String("Updated".to_string()),
583 ),
584 ("active".to_string(), InputValue::Bool(true)),
585 ]
586 .into_iter()
587 .collect();
588
589 let args = UpdateArgs::new().with_set(set);
590 let bytes = args.to_json_bytes().unwrap();
591 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
592 assert_eq!(json["name"], "Updated");
593 assert_eq!(json["active"], true);
594 }
595
596 #[test]
601 fn test_delete_args_default() {
602 let args = DeleteArgs::new();
603 assert!(!args.has_filter());
604 }
605
606 #[test]
607 fn test_delete_args_with_filter() {
608 let filter = TableFilter::new().with_field(
609 "id",
610 FieldFilter::int(IntFilterInput {
611 eq: Some(1),
612 ..Default::default()
613 }),
614 );
615
616 let args = DeleteArgs::new().with_filter(filter);
617 assert!(args.has_filter());
618 }
619
620 #[test]
621 fn test_delete_args_with_returning() {
622 let args = DeleteArgs::new().with_returning(vec!["id".to_string(), "name".to_string()]);
623 assert_eq!(args.returning.len(), 2);
624 }
625
626 #[test]
631 fn test_input_value_to_json_null() {
632 let json = input_value_to_json(&InputValue::Null);
633 assert!(json.is_null());
634 }
635
636 #[test]
637 fn test_input_value_to_json_bool() {
638 let json = input_value_to_json(&InputValue::Bool(true));
639 assert_eq!(json, serde_json::Value::Bool(true));
640 }
641
642 #[test]
643 fn test_input_value_to_json_int() {
644 let json = input_value_to_json(&InputValue::Int(42));
645 assert_eq!(json, serde_json::json!(42));
646 }
647
648 #[test]
649 fn test_input_value_to_json_float() {
650 let json = input_value_to_json(&InputValue::Float(1.5));
651 assert_eq!(json, serde_json::json!(1.5));
652 }
653
654 #[test]
655 fn test_input_value_to_json_string() {
656 let json = input_value_to_json(&InputValue::String("hello".to_string()));
657 assert_eq!(json, serde_json::json!("hello"));
658 }
659
660 #[test]
661 fn test_input_value_to_json_array() {
662 let arr = vec![InputValue::Int(1), InputValue::Int(2), InputValue::Int(3)];
663 let json = input_value_to_json(&InputValue::Array(arr));
664 assert_eq!(json, serde_json::json!([1, 2, 3]));
665 }
666
667 #[test]
668 fn test_input_value_to_json_object() {
669 let obj: HashMap<String, InputValue> = [
670 ("name".to_string(), InputValue::String("test".to_string())),
671 ("count".to_string(), InputValue::Int(5)),
672 ]
673 .into_iter()
674 .collect();
675 let json = input_value_to_json(&InputValue::Object(obj));
676 assert_eq!(json["name"], "test");
677 assert_eq!(json["count"], 5);
678 }
679
680 #[test]
685 fn test_build_insert_plan_basic() {
686 let table = create_test_table();
687 let object: HashMap<String, InputValue> =
688 [("name".to_string(), InputValue::String("Alice".to_string()))]
689 .into_iter()
690 .collect();
691
692 let args = InsertArgs::new().with_object(object);
693 let plan = build_insert_plan(&args, &table);
694
695 match plan {
696 MutatePlan::Insert {
697 target,
698 body,
699 returning,
700 ..
701 } => {
702 assert_eq!(target.name, "users");
703 assert!(body.is_some());
704 assert_eq!(returning, vec!["id".to_string()]);
705 }
706 _ => panic!("Expected Insert plan"),
707 }
708 }
709
710 #[test]
711 fn test_build_insert_plan_with_returning() {
712 let table = create_test_table();
713 let object: HashMap<String, InputValue> =
714 [("name".to_string(), InputValue::String("Alice".to_string()))]
715 .into_iter()
716 .collect();
717
718 let args = InsertArgs::new()
719 .with_object(object)
720 .with_returning(vec!["id".to_string(), "name".to_string()]);
721 let plan = build_insert_plan(&args, &table);
722
723 match plan {
724 MutatePlan::Insert { returning, .. } => {
725 assert_eq!(returning.len(), 2);
726 }
727 _ => panic!("Expected Insert plan"),
728 }
729 }
730
731 #[test]
732 fn test_build_insert_plan_with_on_conflict() {
733 let table = create_test_table();
734 let object: HashMap<String, InputValue> =
735 [("name".to_string(), InputValue::String("Alice".to_string()))]
736 .into_iter()
737 .collect();
738
739 let on_conflict = OnConflictArgs::new(vec!["id".to_string()]);
740 let args = InsertArgs::new()
741 .with_object(object)
742 .with_on_conflict(on_conflict);
743 let plan = build_insert_plan(&args, &table);
744
745 match plan {
746 MutatePlan::Insert { on_conflict, .. } => {
747 assert!(on_conflict.is_some());
748 let (_, cols) = on_conflict.unwrap();
749 assert_eq!(cols, vec!["id".to_string()]);
750 }
751 _ => panic!("Expected Insert plan"),
752 }
753 }
754
755 #[test]
756 fn test_build_update_plan_basic() {
757 let table = create_test_table();
758 let set: HashMap<String, InputValue> = [(
759 "name".to_string(),
760 InputValue::String("Updated".to_string()),
761 )]
762 .into_iter()
763 .collect();
764
765 let filter = TableFilter::new().with_field(
766 "id",
767 FieldFilter::int(IntFilterInput {
768 eq: Some(1),
769 ..Default::default()
770 }),
771 );
772
773 let args = UpdateArgs::new().with_set(set).with_filter(filter);
774 let plan = build_update_plan(&args, &table);
775
776 match plan {
777 MutatePlan::Update {
778 target,
779 body,
780 where_clauses,
781 ..
782 } => {
783 assert_eq!(target.name, "users");
784 assert!(body.is_some());
785 assert!(!where_clauses.is_empty());
786 }
787 _ => panic!("Expected Update plan"),
788 }
789 }
790
791 #[test]
792 fn test_build_update_plan_with_returning() {
793 let table = create_test_table();
794 let set: HashMap<String, InputValue> = [(
795 "name".to_string(),
796 InputValue::String("Updated".to_string()),
797 )]
798 .into_iter()
799 .collect();
800
801 let args = UpdateArgs::new()
802 .with_set(set)
803 .with_returning(vec!["id".to_string(), "name".to_string()]);
804 let plan = build_update_plan(&args, &table);
805
806 match plan {
807 MutatePlan::Update { returning, .. } => {
808 assert_eq!(returning.len(), 2);
809 }
810 _ => panic!("Expected Update plan"),
811 }
812 }
813
814 #[test]
815 fn test_build_delete_plan_basic() {
816 let table = create_test_table();
817 let filter = TableFilter::new().with_field(
818 "id",
819 FieldFilter::int(IntFilterInput {
820 eq: Some(1),
821 ..Default::default()
822 }),
823 );
824
825 let args = DeleteArgs::new().with_filter(filter);
826 let plan = build_delete_plan(&args, &table);
827
828 match plan {
829 MutatePlan::Delete {
830 target,
831 where_clauses,
832 returning,
833 } => {
834 assert_eq!(target.name, "users");
835 assert!(!where_clauses.is_empty());
836 assert_eq!(returning, vec!["id".to_string()]);
837 }
838 _ => panic!("Expected Delete plan"),
839 }
840 }
841
842 #[test]
843 fn test_build_delete_plan_with_returning() {
844 let table = create_test_table();
845 let args = DeleteArgs::new().with_returning(vec![
846 "id".to_string(),
847 "name".to_string(),
848 "email".to_string(),
849 ]);
850 let plan = build_delete_plan(&args, &table);
851
852 match plan {
853 MutatePlan::Delete { returning, .. } => {
854 assert_eq!(returning.len(), 3);
855 }
856 _ => panic!("Expected Delete plan"),
857 }
858 }
859
860 #[test]
861 fn test_build_delete_plan_no_filter() {
862 let table = create_test_table();
863 let args = DeleteArgs::new();
864 let plan = build_delete_plan(&args, &table);
865
866 match plan {
867 MutatePlan::Delete { where_clauses, .. } => {
868 assert!(where_clauses.is_empty());
869 }
870 _ => panic!("Expected Delete plan"),
871 }
872 }
873}