ignis_db/dsl/
typed_query.rs1use super::{OrderBy, Source, TypedColumn, WhereCondition};
4use crate::schema::{Table, View};
5
6pub trait ColumnLike {
8 fn qualified_name(&self) -> String;
10}
11
12impl<T> ColumnLike for TypedColumn<T> {
13 fn qualified_name(&self) -> String {
14 self.qualified_name()
15 }
16}
17
18#[derive(Debug, Clone)]
20pub struct TypedQuery {
21 pub source: Option<Source>,
23 pub select_columns: Vec<String>,
25 pub where_conditions: Option<WhereCondition>,
27 pub order_by: Vec<String>,
29 pub limit: Option<usize>,
31 pub offset: Option<usize>,
33}
34
35impl TypedQuery {
36 pub fn new() -> Self {
38 Self {
39 source: None,
40 select_columns: Vec::new(),
41 where_conditions: None,
42 order_by: Vec::new(),
43 limit: None,
44 offset: None,
45 }
46 }
47
48 pub fn from_table(mut self, table: Table) -> Self {
50 self.source = Some(Source::Table(table));
51 self
52 }
53
54 pub fn from_view(mut self, view: View) -> Self {
56 self.source = Some(Source::View(view));
57 self
58 }
59
60 pub fn select_columns_from<I>(mut self, columns: I) -> Self
62 where
63 I: IntoIterator,
64 I::Item: Into<String>,
65 {
66 self.select_columns = columns.into_iter().map(|c| c.into()).collect();
67 self
68 }
69
70 pub fn select_column<T>(mut self, column: TypedColumn<T>) -> Self {
72 self.select_columns.push(column.qualified_name());
73 self
74 }
75
76 pub fn where_clause(mut self, condition: WhereCondition) -> Self {
78 self.where_conditions = Some(condition);
79 self
80 }
81
82 pub fn order_by<T>(mut self, order: OrderBy<T>) -> Self {
84 self.order_by.push(order.to_sql());
85 self
86 }
87
88 pub fn limit(mut self, limit: usize) -> Self {
90 self.limit = Some(limit);
91 self
92 }
93
94 pub fn offset(mut self, offset: usize) -> Self {
96 self.offset = Some(offset);
97 self
98 }
99
100 pub fn to_sql(&self) -> String {
102 let mut sql = String::from("SELECT ");
103
104 if self.select_columns.is_empty() {
106 sql.push('*');
107 } else {
108 sql.push_str(&self.select_columns.join(", "));
109 }
110
111 if let Some(ref source) = self.source {
113 sql.push_str(" FROM ");
114 sql.push_str(&source.qualified_name());
115 }
116
117 if let Some(ref conditions) = self.where_conditions {
119 sql.push_str(" WHERE ");
120 sql.push_str(&conditions.to_sql());
121 }
122
123 if !self.order_by.is_empty() {
125 sql.push_str(" ORDER BY ");
126 sql.push_str(&self.order_by.join(", "));
127 }
128
129 if let Some(_limit) = self.limit {
131 sql.push_str(" LIMIT ?");
132 }
133
134 if let Some(_offset) = self.offset {
136 sql.push_str(" OFFSET ?");
137 }
138
139 sql
140 }
141}
142
143pub trait TypedQueryBuilder {
145 fn query() -> TypedQuery;
147}