postgres_querybuilder/
prelude.rs1use postgres_types::ToSql;
2
3pub enum Join {
4 Inner(String, String),
5 Left(String, String),
6 LeftOuter(String, String),
7}
8
9impl Join {
10 pub fn to_string(&self) -> String {
11 match self {
12 Join::Inner(table, constraint) => format!("INNER JOIN {} ON {}", table, constraint),
13 Join::Left(table, constraint) => format!("LEFT JOIN {} ON {}", table, constraint),
14 Join::LeftOuter(table, constraint) => {
15 format!("LEFT OUTER JOIN {} ON {}", table, constraint)
16 }
17 }
18 }
19}
20
21pub trait QueryBuilder {
22 fn add_param<T: 'static + ToSql + Sync + Clone>(&mut self, value: T) -> usize;
23 fn get_query(&self) -> String;
24 fn get_ref_params(self) -> Vec<&'static (dyn ToSql + Sync)>;
25}
26
27pub trait QueryBuilderWithWhere: QueryBuilder {
28 fn where_condition(&mut self, raw: &str) -> &mut Self;
47
48 fn where_eq<T: 'static + ToSql + Sync + Clone>(&mut self, field: &str, value: T) -> &mut Self {
64 let index = self.add_param(value);
65 let condition = format!("{} = ${}", field, index);
66 self.where_condition(condition.as_str());
67 self
68 }
69
70 fn where_ne<T: 'static + ToSql + Sync + Clone>(&mut self, field: &str, value: T) -> &mut Self {
86 let index = self.add_param(value);
87 let condition = format!("{} <> ${}", field, index);
88 self.where_condition(condition.as_str());
89 self
90 }
91}
92
93pub trait QueryBuilderWithGroupBy {
94 fn group_by(&mut self, field: &str) -> &mut Self;
95}
96
97pub trait QueryBuilderWithLimit {
98 fn limit(&mut self, limit: i64) -> &mut Self;
99}
100
101pub trait QueryBuilderWithOffset {
102 fn offset(&mut self, offset: i64) -> &mut Self;
103}
104
105pub trait QueryBuilderWithJoin {
106 fn inner_join(&mut self, table_name: &str, relation: &str) -> &mut Self;
107 fn left_join(&mut self, table_name: &str, relation: &str) -> &mut Self;
108 fn left_outer_join(&mut self, table_name: &str, relation: &str) -> &mut Self;
109}
110
111pub trait QueryBuilderWithSet {
112 fn set<T: 'static + ToSql + Sync + Clone>(&mut self, field: &str, value: T) -> &mut Self;
113 fn set_computed(&mut self, field: &str, value: &str) -> &mut Self;
114}
115
116pub enum Order {
117 Asc(String),
118 Desc(String),
119}
120
121impl Order {
122 pub fn to_string(&self) -> String {
123 match self {
124 Order::Asc(column) => format!("{} ASC", column),
125 Order::Desc(column) => format!("{} DESC", column),
126 }
127 }
128}
129
130pub trait QueryBuilderWithOrder {
131 fn order_by(&mut self, field: Order);
132}
133
134pub trait QueryBuilderWithQueries {
135 fn with_query(&mut self, name: &str, query: &str) -> &mut Self;
136}