1use crate::error::{Error, Result};
7use std::collections::HashMap;
8
9#[derive(Debug, Clone)]
11pub struct QueryBuilder {
12 query_type: QueryType,
13 table: Option<String>,
14 columns: Vec<String>,
15 values: Vec<QueryValue>,
16 conditions: Vec<Condition>,
17 joins: Vec<Join>,
18 group_by: Vec<String>,
19 having: Vec<Condition>,
20 order_by: Vec<OrderBy>,
21 limit: Option<usize>,
22 offset: Option<usize>,
23}
24
25#[derive(Debug, Clone)]
26enum QueryType {
27 Select,
28 Insert,
29 Update,
30 Delete,
31}
32
33#[derive(Debug, Clone)]
34pub enum QueryValue {
36 String(String),
38 Integer(i64),
40 Float(f64),
42 Boolean(bool),
44 Null,
46}
47
48#[derive(Debug, Clone)]
49pub struct Condition {
51 column: String,
52 operator: String,
53 value: QueryValue,
54 connector: String, }
56
57#[derive(Debug, Clone)]
58pub struct Join {
60 join_type: String, table: String,
62 on_condition: String,
63}
64
65#[derive(Debug, Clone)]
66pub struct OrderBy {
68 column: String,
69 direction: String, }
71
72impl QueryBuilder {
73 pub fn select() -> Self {
87 Self {
88 query_type: QueryType::Select,
89 table: None,
90 columns: Vec::new(),
91 values: Vec::new(),
92 conditions: Vec::new(),
93 joins: Vec::new(),
94 group_by: Vec::new(),
95 having: Vec::new(),
96 order_by: Vec::new(),
97 limit: None,
98 offset: None,
99 }
100 }
101
102 pub fn insert() -> Self {
116 Self {
117 query_type: QueryType::Insert,
118 table: None,
119 columns: Vec::new(),
120 values: Vec::new(),
121 conditions: Vec::new(),
122 joins: Vec::new(),
123 group_by: Vec::new(),
124 having: Vec::new(),
125 order_by: Vec::new(),
126 limit: None,
127 offset: None,
128 }
129 }
130
131 pub fn update() -> Self {
145 Self {
146 query_type: QueryType::Update,
147 table: None,
148 columns: Vec::new(),
149 values: Vec::new(),
150 conditions: Vec::new(),
151 joins: Vec::new(),
152 group_by: Vec::new(),
153 having: Vec::new(),
154 order_by: Vec::new(),
155 limit: None,
156 offset: None,
157 }
158 }
159
160 pub fn delete() -> Self {
173 Self {
174 query_type: QueryType::Delete,
175 table: None,
176 columns: Vec::new(),
177 values: Vec::new(),
178 conditions: Vec::new(),
179 joins: Vec::new(),
180 group_by: Vec::new(),
181 having: Vec::new(),
182 order_by: Vec::new(),
183 limit: None,
184 offset: None,
185 }
186 }
187
188 pub fn from(mut self, table: &str) -> Self {
190 self.table = Some(table.to_string());
191 self
192 }
193
194 pub fn into(mut self, table: &str) -> Self {
196 self.table = Some(table.to_string());
197 self
198 }
199
200 pub fn table(mut self, table: &str) -> Self {
202 self.table = Some(table.to_string());
203 self
204 }
205
206 pub fn columns(mut self, columns: &[&str]) -> Self {
208 self.columns = columns.iter().map(|s| s.to_string()).collect();
209 self
210 }
211
212 pub fn column(mut self, column: &str) -> Self {
214 self.columns.push(column.to_string());
215 self
216 }
217
218 pub fn values(mut self, values: &[&str]) -> Self {
220 for value in values {
221 self.values.push(QueryValue::String(value.to_string()));
222 }
223 self
224 }
225
226 pub fn int_values(mut self, values: &[i64]) -> Self {
228 for &value in values {
229 self.values.push(QueryValue::Integer(value));
230 }
231 self
232 }
233
234 pub fn set(mut self, column: &str, value: &str) -> Self {
236 self.columns.push(column.to_string());
237 self.values.push(QueryValue::String(value.to_string()));
238 self
239 }
240
241 pub fn set_int(mut self, column: &str, value: i64) -> Self {
243 self.columns.push(column.to_string());
244 self.values.push(QueryValue::Integer(value));
245 self
246 }
247
248 pub fn set_float(mut self, column: &str, value: f64) -> Self {
250 self.columns.push(column.to_string());
251 self.values.push(QueryValue::Float(value));
252 self
253 }
254
255 pub fn set_bool(mut self, column: &str, value: bool) -> Self {
257 self.columns.push(column.to_string());
258 self.values.push(QueryValue::Boolean(value));
259 self
260 }
261
262 pub fn where_eq(mut self, column: &str, value: impl Into<QueryValue>) -> Self {
264 self.conditions.push(Condition {
265 column: column.to_string(),
266 operator: "=".to_string(),
267 value: value.into(),
268 connector: "AND".to_string(),
269 });
270 self
271 }
272
273 pub fn where_ne(mut self, column: &str, value: impl Into<QueryValue>) -> Self {
275 self.conditions.push(Condition {
276 column: column.to_string(),
277 operator: "!=".to_string(),
278 value: value.into(),
279 connector: "AND".to_string(),
280 });
281 self
282 }
283
284 pub fn where_gt(mut self, column: &str, value: impl Into<QueryValue>) -> Self {
286 self.conditions.push(Condition {
287 column: column.to_string(),
288 operator: ">".to_string(),
289 value: value.into(),
290 connector: "AND".to_string(),
291 });
292 self
293 }
294
295 pub fn where_lt(mut self, column: &str, value: impl Into<QueryValue>) -> Self {
297 self.conditions.push(Condition {
298 column: column.to_string(),
299 operator: "<".to_string(),
300 value: value.into(),
301 connector: "AND".to_string(),
302 });
303 self
304 }
305
306 pub fn where_like(mut self, column: &str, pattern: &str) -> Self {
308 self.conditions.push(Condition {
309 column: column.to_string(),
310 operator: "LIKE".to_string(),
311 value: QueryValue::String(pattern.to_string()),
312 connector: "AND".to_string(),
313 });
314 self
315 }
316
317 pub fn where_in(mut self, column: &str, values: &[&str]) -> Self {
319 let values_str = values
320 .iter()
321 .map(|v| format!("'{}'", v.replace('\'', "''")))
322 .collect::<Vec<_>>()
323 .join(", ");
324
325 self.conditions.push(Condition {
326 column: column.to_string(),
327 operator: "IN".to_string(),
328 value: QueryValue::String(format!("({})", values_str)),
329 connector: "AND".to_string(),
330 });
331 self
332 }
333
334 pub fn or_where_eq(mut self, column: &str, value: impl Into<QueryValue>) -> Self {
336 self.conditions.push(Condition {
337 column: column.to_string(),
338 operator: "=".to_string(),
339 value: value.into(),
340 connector: "OR".to_string(),
341 });
342 self
343 }
344
345 pub fn inner_join(mut self, table: &str, on: &str) -> Self {
347 self.joins.push(Join {
348 join_type: "INNER".to_string(),
349 table: table.to_string(),
350 on_condition: on.to_string(),
351 });
352 self
353 }
354
355 pub fn left_join(mut self, table: &str, on: &str) -> Self {
357 self.joins.push(Join {
358 join_type: "LEFT".to_string(),
359 table: table.to_string(),
360 on_condition: on.to_string(),
361 });
362 self
363 }
364
365 pub fn right_join(mut self, table: &str, on: &str) -> Self {
367 self.joins.push(Join {
368 join_type: "RIGHT".to_string(),
369 table: table.to_string(),
370 on_condition: on.to_string(),
371 });
372 self
373 }
374
375 pub fn group_by(mut self, columns: &[&str]) -> Self {
377 self.group_by = columns.iter().map(|s| s.to_string()).collect();
378 self
379 }
380
381 pub fn having_eq(mut self, column: &str, value: impl Into<QueryValue>) -> Self {
383 self.having.push(Condition {
384 column: column.to_string(),
385 operator: "=".to_string(),
386 value: value.into(),
387 connector: "AND".to_string(),
388 });
389 self
390 }
391
392 pub fn order_by_asc(mut self, column: &str) -> Self {
394 self.order_by.push(OrderBy {
395 column: column.to_string(),
396 direction: "ASC".to_string(),
397 });
398 self
399 }
400
401 pub fn order_by_desc(mut self, column: &str) -> Self {
403 self.order_by.push(OrderBy {
404 column: column.to_string(),
405 direction: "DESC".to_string(),
406 });
407 self
408 }
409
410 pub fn limit(mut self, limit: usize) -> Self {
412 self.limit = Some(limit);
413 self
414 }
415
416 pub fn offset(mut self, offset: usize) -> Self {
418 self.offset = Some(offset);
419 self
420 }
421
422 pub fn build(self) -> Result<String> {
424 match self.query_type {
425 QueryType::Select => self.build_select(),
426 QueryType::Insert => self.build_insert(),
427 QueryType::Update => self.build_update(),
428 QueryType::Delete => self.build_delete(),
429 }
430 }
431
432 fn build_select(&self) -> Result<String> {
433 let mut query = String::new();
434
435 query.push_str("SELECT ");
437 if self.columns.is_empty() {
438 query.push('*');
439 } else {
440 query.push_str(&self.columns.join(", "));
441 }
442
443 if let Some(table) = &self.table {
445 query.push_str(&format!(" FROM {}", table));
446 } else {
447 return Err(Error::validation(
448 "Table name is required for SELECT query".to_string(),
449 ));
450 }
451
452 for join in &self.joins {
454 query.push_str(&format!(
455 " {} JOIN {} ON {}",
456 join.join_type, join.table, join.on_condition
457 ));
458 }
459
460 if !self.conditions.is_empty() {
462 query.push_str(" WHERE ");
463 for (i, condition) in self.conditions.iter().enumerate() {
464 if i > 0 {
465 query.push_str(&format!(" {} ", condition.connector));
466 }
467 query.push_str(&format!(
468 "{} {} {}",
469 condition.column,
470 condition.operator,
471 self.format_value(&condition.value)
472 ));
473 }
474 }
475
476 if !self.group_by.is_empty() {
478 query.push_str(&format!(" GROUP BY {}", self.group_by.join(", ")));
479 }
480
481 if !self.having.is_empty() {
483 query.push_str(" HAVING ");
484 for (i, condition) in self.having.iter().enumerate() {
485 if i > 0 {
486 query.push_str(&format!(" {} ", condition.connector));
487 }
488 query.push_str(&format!(
489 "{} {} {}",
490 condition.column,
491 condition.operator,
492 self.format_value(&condition.value)
493 ));
494 }
495 }
496
497 if !self.order_by.is_empty() {
499 query.push_str(" ORDER BY ");
500 let order_parts: Vec<String> = self
501 .order_by
502 .iter()
503 .map(|order| format!("{} {}", order.column, order.direction))
504 .collect();
505 query.push_str(&order_parts.join(", "));
506 }
507
508 if let Some(limit) = self.limit {
510 query.push_str(&format!(" LIMIT {}", limit));
511 }
512
513 if let Some(offset) = self.offset {
515 query.push_str(&format!(" OFFSET {}", offset));
516 }
517
518 Ok(query)
519 }
520
521 fn build_insert(&self) -> Result<String> {
522 let table = self.table.as_ref().ok_or_else(|| {
523 Error::validation("Table name is required for INSERT query".to_string())
524 })?;
525
526 if self.columns.is_empty() {
527 return Err(Error::validation(
528 "Columns are required for INSERT query".to_string(),
529 ));
530 }
531
532 if self.values.len() != self.columns.len() {
533 return Err(Error::validation(
534 "Number of values must match number of columns".to_string(),
535 ));
536 }
537
538 let mut query = format!("INSERT INTO {} ({})", table, self.columns.join(", "));
539
540 let values_str: Vec<String> = self
541 .values
542 .iter()
543 .map(|value| self.format_value(value))
544 .collect();
545
546 query.push_str(&format!(" VALUES ({})", values_str.join(", ")));
547
548 Ok(query)
549 }
550
551 fn build_update(&self) -> Result<String> {
552 let table = self.table.as_ref().ok_or_else(|| {
553 Error::validation("Table name is required for UPDATE query".to_string())
554 })?;
555
556 if self.columns.is_empty() {
557 return Err(Error::validation(
558 "SET clause is required for UPDATE query".to_string(),
559 ));
560 }
561
562 if self.values.len() != self.columns.len() {
563 return Err(Error::validation(
564 "Number of values must match number of columns".to_string(),
565 ));
566 }
567
568 let mut query = format!("UPDATE {}", table);
569
570 query.push_str(" SET ");
572 let set_parts: Vec<String> = self
573 .columns
574 .iter()
575 .zip(self.values.iter())
576 .map(|(col, val)| format!("{} = {}", col, self.format_value(val)))
577 .collect();
578 query.push_str(&set_parts.join(", "));
579
580 if !self.conditions.is_empty() {
582 query.push_str(" WHERE ");
583 for (i, condition) in self.conditions.iter().enumerate() {
584 if i > 0 {
585 query.push_str(&format!(" {} ", condition.connector));
586 }
587 query.push_str(&format!(
588 "{} {} {}",
589 condition.column,
590 condition.operator,
591 self.format_value(&condition.value)
592 ));
593 }
594 }
595
596 Ok(query)
597 }
598
599 fn build_delete(&self) -> Result<String> {
600 let table = self.table.as_ref().ok_or_else(|| {
601 Error::validation("Table name is required for DELETE query".to_string())
602 })?;
603
604 let mut query = format!("DELETE FROM {}", table);
605
606 if !self.conditions.is_empty() {
608 query.push_str(" WHERE ");
609 for (i, condition) in self.conditions.iter().enumerate() {
610 if i > 0 {
611 query.push_str(&format!(" {} ", condition.connector));
612 }
613 query.push_str(&format!(
614 "{} {} {}",
615 condition.column,
616 condition.operator,
617 self.format_value(&condition.value)
618 ));
619 }
620 }
621
622 Ok(query)
623 }
624
625 fn format_value(&self, value: &QueryValue) -> String {
626 match value {
627 QueryValue::String(s) => {
628 if s.starts_with('(') && s.ends_with(')') {
629 s.clone()
631 } else {
632 format!("'{}'", s.replace('\'', "''"))
633 }
634 }
635 QueryValue::Integer(i) => i.to_string(),
636 QueryValue::Float(f) => f.to_string(),
637 QueryValue::Boolean(b) => if *b { "TRUE" } else { "FALSE" }.to_string(),
638 QueryValue::Null => "NULL".to_string(),
639 }
640 }
641}
642
643impl From<&str> for QueryValue {
645 fn from(s: &str) -> Self {
646 QueryValue::String(s.to_string())
647 }
648}
649
650impl From<String> for QueryValue {
651 fn from(s: String) -> Self {
652 QueryValue::String(s)
653 }
654}
655
656impl From<i32> for QueryValue {
657 fn from(i: i32) -> Self {
658 QueryValue::Integer(i as i64)
659 }
660}
661
662impl From<i64> for QueryValue {
663 fn from(i: i64) -> Self {
664 QueryValue::Integer(i)
665 }
666}
667
668impl From<f32> for QueryValue {
669 fn from(f: f32) -> Self {
670 QueryValue::Float(f as f64)
671 }
672}
673
674impl From<f64> for QueryValue {
675 fn from(f: f64) -> Self {
676 QueryValue::Float(f)
677 }
678}
679
680impl From<bool> for QueryValue {
681 fn from(b: bool) -> Self {
682 QueryValue::Boolean(b)
683 }
684}
685
686pub struct QueryExecutor;
688
689impl QueryExecutor {
690 pub fn format_query_result(rows: Vec<HashMap<String, serde_json::Value>>) -> Result<String> {
692 if rows.is_empty() {
693 return Ok("No results found.".to_string());
694 }
695
696 let mut result = String::new();
697
698 let columns: Vec<String> = rows[0].keys().cloned().collect();
700
701 let mut widths: HashMap<String, usize> = HashMap::new();
703 for col in &columns {
704 widths.insert(col.clone(), col.len());
705 }
706
707 for row in &rows {
708 for (col, value) in row {
709 let value_str = match value {
710 serde_json::Value::String(s) => s.clone(),
711 _ => value.to_string(),
712 };
713 let current_width = widths.get(col).unwrap_or(&0);
714 if value_str.len() > *current_width {
715 widths.insert(col.clone(), value_str.len());
716 }
717 }
718 }
719
720 result.push('|');
722 for col in &columns {
723 let width = widths.get(col).unwrap_or(&0);
724 result.push_str(&format!(" {:width$} |", col, width = width));
725 }
726 result.push('\n');
727
728 result.push('|');
730 for col in &columns {
731 let width = widths.get(col).unwrap_or(&0);
732 result.push_str(&format!("{:-<width$}|", "", width = width + 2));
733 }
734 result.push('\n');
735
736 for row in &rows {
738 result.push('|');
739 for col in &columns {
740 let width = widths.get(col).unwrap_or(&0);
741 let value = row.get(col).unwrap_or(&serde_json::Value::Null);
742 let value_str = match value {
743 serde_json::Value::String(s) => s.clone(),
744 serde_json::Value::Null => "NULL".to_string(),
745 _ => value.to_string(),
746 };
747 result.push_str(&format!(" {:width$} |", value_str, width = width));
748 }
749 result.push('\n');
750 }
751
752 Ok(result)
753 }
754
755 pub fn to_csv(rows: Vec<HashMap<String, serde_json::Value>>) -> Result<String> {
757 if rows.is_empty() {
758 return Ok(String::new());
759 }
760
761 let mut result = String::new();
762
763 let columns: Vec<String> = rows[0].keys().cloned().collect();
765
766 result.push_str(&columns.join(","));
768 result.push('\n');
769
770 for row in &rows {
772 let values: Vec<String> = columns
773 .iter()
774 .map(|col| {
775 let value = row.get(col).unwrap_or(&serde_json::Value::Null);
776 match value {
777 serde_json::Value::String(s) => {
778 if s.contains(',') || s.contains('"') || s.contains('\n') {
779 format!("\"{}\"", s.replace('"', "\"\""))
780 } else {
781 s.clone()
782 }
783 }
784 serde_json::Value::Null => String::new(),
785 _ => value.to_string(),
786 }
787 })
788 .collect();
789
790 result.push_str(&values.join(","));
791 result.push('\n');
792 }
793
794 Ok(result)
795 }
796}
797
798#[cfg(test)]
799mod tests {
800 use super::*;
801
802 #[test]
803 fn test_select_query_builder() {
804 let query = QueryBuilder::select()
805 .columns(&["id", "name", "email"])
806 .from("users")
807 .where_eq("active", true)
808 .where_gt("age", 18)
809 .order_by_asc("name")
810 .limit(10)
811 .build()
812 .unwrap();
813
814 let expected = "SELECT id, name, email FROM users WHERE active = TRUE AND age > 18 ORDER BY name ASC LIMIT 10";
815 assert_eq!(query, expected);
816 }
817
818 #[test]
819 fn test_insert_query_builder() {
820 let query = QueryBuilder::insert()
821 .into("users")
822 .columns(&["name", "email"])
823 .values(&["Alice", "alice@example.com"])
824 .build()
825 .unwrap();
826
827 let expected = "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')";
828 assert_eq!(query, expected);
829 }
830
831 #[test]
832 fn test_update_query_builder() {
833 let query = QueryBuilder::update()
834 .table("users")
835 .set("name", "Bob")
836 .set_int("age", 25)
837 .where_eq("id", 1)
838 .build()
839 .unwrap();
840
841 let expected = "UPDATE users SET name = 'Bob', age = 25 WHERE id = 1";
842 assert_eq!(query, expected);
843 }
844
845 #[test]
846 fn test_delete_query_builder() {
847 let query = QueryBuilder::delete()
848 .from("users")
849 .where_eq("active", false)
850 .build()
851 .unwrap();
852
853 let expected = "DELETE FROM users WHERE active = FALSE";
854 assert_eq!(query, expected);
855 }
856
857 #[test]
858 fn test_complex_select_with_joins() {
859 let query = QueryBuilder::select()
860 .columns(&["u.name", "p.title"])
861 .from("users u")
862 .inner_join("posts p", "u.id = p.user_id")
863 .where_like("u.name", "%John%")
864 .order_by_desc("p.created_at")
865 .build()
866 .unwrap();
867
868 let expected = "SELECT u.name, p.title FROM users u INNER JOIN posts p ON u.id = p.user_id WHERE u.name LIKE '%John%' ORDER BY p.created_at DESC";
869 assert_eq!(query, expected);
870 }
871
872 #[test]
873 fn test_where_in_clause() {
874 let query = QueryBuilder::select()
875 .from("users")
876 .where_in("status", &["active", "pending"])
877 .build()
878 .unwrap();
879
880 let expected = "SELECT * FROM users WHERE status IN ('active', 'pending')";
881 assert_eq!(query, expected);
882 }
883
884 #[test]
885 fn test_group_by_having() {
886 let query = QueryBuilder::select()
887 .columns(&["department", "COUNT(*)"])
888 .from("employees")
889 .group_by(&["department"])
890 .having_eq("COUNT(*)", "> 5")
891 .build()
892 .unwrap();
893
894 let expected = "SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) = '> 5'";
895 assert_eq!(query, expected);
896 }
897
898 #[test]
899 fn test_query_value_conversions() {
900 let str_val: QueryValue = "test".into();
901 let int_val: QueryValue = 42i32.into();
902 let int64_val: QueryValue = 42i64.into();
903 let float_val: QueryValue = 3.14f32.into();
904 let float64_val: QueryValue = 3.14f64.into();
905 let bool_val: QueryValue = true.into();
906
907 assert!(matches!(str_val, QueryValue::String(_)));
908 assert!(matches!(int_val, QueryValue::Integer(42)));
909 assert!(matches!(int64_val, QueryValue::Integer(42)));
910 assert!(matches!(float_val, QueryValue::Float(_)));
911 assert!(matches!(float64_val, QueryValue::Float(_)));
912 assert!(matches!(bool_val, QueryValue::Boolean(true)));
913 }
914
915 #[test]
916 fn test_query_executor_format() {
917 let mut rows = Vec::new();
918 let mut row1 = HashMap::new();
919 row1.insert(
920 "id".to_string(),
921 serde_json::Value::Number(serde_json::Number::from(1)),
922 );
923 row1.insert(
924 "name".to_string(),
925 serde_json::Value::String("Alice".to_string()),
926 );
927 rows.push(row1);
928
929 let mut row2 = HashMap::new();
930 row2.insert(
931 "id".to_string(),
932 serde_json::Value::Number(serde_json::Number::from(2)),
933 );
934 row2.insert(
935 "name".to_string(),
936 serde_json::Value::String("Bob".to_string()),
937 );
938 rows.push(row2);
939
940 let result = QueryExecutor::format_query_result(rows).unwrap();
941 assert!(result.contains("Alice"));
942 assert!(result.contains("Bob"));
943 assert!(result.contains("|"));
944 }
945
946 #[test]
947 fn test_query_executor_csv() {
948 let mut rows = Vec::new();
949 let mut row1 = HashMap::new();
950 row1.insert(
951 "id".to_string(),
952 serde_json::Value::Number(serde_json::Number::from(1)),
953 );
954 row1.insert(
955 "name".to_string(),
956 serde_json::Value::String("Alice".to_string()),
957 );
958 rows.push(row1);
959
960 let csv = QueryExecutor::to_csv(rows).unwrap();
961 assert!(csv.contains("id"));
962 assert!(csv.contains("name"));
963 assert!(csv.contains("1"));
964 assert!(csv.contains("Alice"));
965 }
966
967 #[test]
968 fn test_error_cases() {
969 let result = QueryBuilder::select().build();
971 assert!(result.is_err());
972
973 let result = QueryBuilder::insert().into("users").build();
975 assert!(result.is_err());
976
977 let result = QueryBuilder::insert()
979 .into("users")
980 .columns(&["name"])
981 .values(&["Alice", "Bob"])
982 .build();
983 assert!(result.is_err());
984 }
985}