lua_sql_builder/mysql/
select.rs1use super::{
2 join::{Join, JoinType},
3 where_::{Combiner, Where},
4};
5
6pub struct Select<'a> {
7 distinct: bool,
8 from: &'a str,
9 limit: u32,
10 offset: u32,
11 columns: &'a str,
12 where_: Where,
13 group: &'a str,
14 order: &'a str,
15
16 joins: Vec<Join>,
17}
18
19#[allow(dead_code)]
20impl<'a> Select<'a> {
21 pub fn new() -> Select<'a> {
22 Select {
23 distinct: false,
24 from: "",
25 limit: 0,
26 offset: 0,
27 columns: "",
28 where_: Where::new(Combiner::And),
29 group: "",
30 order: "",
31 joins: vec![],
32 }
33 }
34
35 pub fn distinct(&mut self) -> &mut Select<'a> {
36 self.distinct = true;
37 self
38 }
39
40 pub fn from(&mut self, from: &'a str) -> &mut Select<'a> {
41 self.from = from;
42 self
43 }
44
45 pub fn columns(&mut self, columns: &'a str) -> &mut Select<'a> {
46 self.columns = columns;
47 self
48 }
49
50 pub fn where_(&mut self, where_: Where) -> &mut Select<'a> {
51 self.where_ = where_;
52 self
53 }
54
55 pub fn join(&mut self, table: &str, on: &str, join_type: JoinType) -> &mut Select<'a> {
56 self.joins
57 .push(Join::new(table.to_string(), on.to_string(), join_type));
58 self
59 }
60
61 pub fn group(&mut self, group: &'a str) -> &mut Select<'a> {
62 self.group = group;
63 self
64 }
65
66 pub fn order(&mut self, order: &'a str) -> &mut Select<'a> {
67 self.order = order;
68 self
69 }
70
71 pub fn limit(&mut self, limit: u32) -> &mut Select<'a> {
72 self.limit = limit;
73 self
74 }
75
76 pub fn offset(&mut self, offset: u32) -> &mut Select<'a> {
77 self.offset = offset;
78 self
79 }
80
81 pub fn build(&self) -> String {
82 let mut statement = "SELECT ".to_string();
83
84 if self.distinct {
85 statement.push_str("DISTINCT ");
86 }
87
88 if self.columns.len() > 0 {
89 statement.push_str(&format!("{} ", self.columns.trim_end()));
90 } else {
91 statement.push_str("* ");
92 }
93
94 if self.from.len() > 0 {
95 statement.push_str(&format!("FROM {} ", self.from));
96 }
97
98 if self.joins.len() > 0 {
99 for join in &self.joins {
100 statement.push_str(&join.build());
101 }
102 }
103
104 statement.push_str(&self.where_.build());
105
106 if self.group.len() > 0 {
107 statement.push_str(" GROUP BY ");
108 statement.push_str(&format!("{}", self.group.trim_end()));
109 }
110
111 if self.order.len() > 0 {
112 statement.push_str(" ORDER BY ");
113 statement.push_str(&format!("{}", self.order.trim_end()));
114 }
115
116 if self.limit > 0 {
117 statement.push_str(&format!(" LIMIT {}", self.limit));
118 }
119
120 if self.offset > 0 && self.limit > 0 {
121 statement.push_str(&format!(" OFFSET {}", self.offset));
122 }
123
124 statement = statement.trim().to_string() + ";";
125 statement
126 }
127}