br_db/types/
mod.rs

1use json::{JsonValue, object};
2
3#[cfg(feature = "db-sqlite")]
4pub mod sqlite;
5#[cfg(feature = "db-mysql")]
6pub mod mysql;
7#[cfg(feature = "db-mssql")]
8pub mod mssql;
9#[cfg(feature = "db-pgsql")]
10pub mod pgsql;
11
12pub trait DbMode {
13    /// 数据库是否存在
14    fn database_tables(&mut self) -> JsonValue;
15    /// 创建数据库
16    fn database_create(&mut self, name: &str) -> bool;
17    /// 备份
18    fn backups(&mut self, _filename: &str) -> bool {
19        false
20    }
21}
22
23#[derive(Debug)]
24pub struct TableOptions {
25    table_name: String,
26    table_title: String,
27    table_key: String,
28    table_fields: JsonValue,
29    table_unique: Vec<String>,
30    table_index: Vec<Vec<String>>,
31    table_partition: bool,
32    table_partition_columns: JsonValue,
33}
34impl TableOptions {
35    pub fn set_table_name(&mut self, name: &str) {
36        self.table_name = name.to_string()
37    }
38    pub fn set_table_title(&mut self, name: &str) {
39        self.table_title = name.to_string()
40    }
41    pub fn set_table_key(&mut self, name: &str) {
42        self.table_key = name.to_string()
43    }
44    pub fn set_table_fields(&mut self, fields: JsonValue) {
45        self.table_fields = fields;
46    }
47    pub fn set_table_unique(&mut self, unique: Vec<&str>) {
48        self.table_unique = unique.iter().map(|s| s.to_string()).collect();
49    }
50    pub fn set_table_index(&mut self, index: Vec<Vec<&str>>) {
51        self.table_index = index.iter().map(|s| s.iter().map(|s| s.to_string()).collect()).collect();
52    }
53    pub fn set_table_partition(&mut self, index: bool) {
54        self.table_partition = index;
55    }
56    pub fn set_table_partition_columns(&mut self, index: JsonValue) {
57        self.table_partition_columns = index;
58    }
59}
60impl Default for TableOptions {
61    fn default() -> Self {
62        Self {
63            table_name: "".to_string(),
64            table_title: "".to_string(),
65            table_key: "".to_string(),
66            table_fields: JsonValue::Null,
67            table_unique: vec![],
68            table_index: vec![],
69            table_partition: false,
70            table_partition_columns: JsonValue::Null,
71        }
72    }
73}
74pub trait Mode: DbMode {
75    fn table_create(&mut self, options: TableOptions) -> JsonValue;
76    fn table_update(&mut self, options: TableOptions) -> JsonValue;
77    /// 获取表信息
78    fn table_info(&mut self, table: &str) -> JsonValue;
79    /// 判断表是否存在
80    fn table_is_exist(&mut self, name: &str) -> bool;
81    /// 当前表
82    fn table(&mut self, name: &str) -> &mut Self;
83    /// 别名
84    fn change_table(&mut self, name: &str) -> &mut Self;
85
86    /// 主键自增
87    fn autoinc(&mut self) -> &mut Self;
88    /// 返回sql语句
89    fn fetch_sql(&mut self) -> &mut Self;
90    /// 排序
91    fn order(&mut self, field: &str, by: bool) -> &mut Self;
92    /// 分组
93    fn group(&mut self, field: &str) -> &mut Self;
94    /// 消除重复记录
95    fn distinct(&mut self) -> &mut Self;
96    /// JSON 字段
97    fn json(&mut self, field: &str) -> &mut Self;
98    /// 显示字段
99    fn field(&mut self, field: &str) -> &mut Self;
100    /// 隐藏字段
101    fn hidden(&mut self, name: &str) -> &mut Self;
102    /// 查询
103    fn where_and(&mut self, field: &str, compare: &str, value: JsonValue) -> &mut Self;
104    fn where_or(&mut self, field: &str, compare: &str, value: JsonValue) -> &mut Self;
105
106    /// 比较两个列
107    fn where_column(&mut self, field_a: &str, compare: &str, field_b: &str) -> &mut Self;
108    /// 分页
109    fn page(&mut self, page: i32, limit: i32) -> &mut Self;
110    /// 查询指定列并返回数组
111    fn column(&mut self, field: &str) -> JsonValue;
112    /// 总数量
113    fn count(&mut self) -> JsonValue;
114    /// 最大值
115    fn max(&mut self, field: &str) -> JsonValue;
116    /// 最小值
117    fn min(&mut self, field: &str) -> JsonValue;
118    /// 合计
119    fn sum(&mut self, field: &str) -> JsonValue;
120    /// 平均值
121    fn avg(&mut self, field: &str) -> JsonValue;
122    /// 获取集合
123    fn select(&mut self) -> JsonValue;
124    /// 获取单记录
125    fn find(&mut self) -> JsonValue;
126    /// 获取单一列值
127    fn value(&mut self, field: &str) -> JsonValue;
128    /// 添加
129    fn insert(&mut self, data: JsonValue) -> JsonValue;
130    /// 批量添加
131    fn insert_all(&mut self, data: JsonValue) -> JsonValue;
132
133    /// 更新
134    fn update(&mut self, data: JsonValue) -> JsonValue;
135    /// 批量更新
136    fn update_all(&mut self, data: JsonValue) -> JsonValue;
137    /// 删除
138    fn delete(&mut self) -> JsonValue;
139
140    /// 事务开始
141    fn transaction(&mut self) -> bool;
142    /// 事务提交
143    fn commit(&mut self) -> bool;
144    /// 事务回滚
145    fn rollback(&mut self) -> bool;
146    /// sql语句执行
147    fn sql(&mut self, sql: &str) -> Result<JsonValue, String>;
148    fn sql_execute(&mut self, sql: &str) -> Result<JsonValue, String>;
149    /// 自增
150    fn inc(&mut self, field: &str, num: f64) -> &mut Self;
151    /// 自减
152    fn dec(&mut self, field: &str, num: f64) -> &mut Self;
153
154    /// 构造子查询
155    fn buildsql(&mut self) -> String;
156    /// 连结
157    ///
158    /// * table 链表表名
159    /// * main_fields 主表id字段
160    /// * right_fields 关联字段名
161    fn join(&mut self, table: &str, main_fields: &str, right_fields: &str) -> &mut Self;
162
163    /// 内连接--用来取交集
164    ///
165    /// * table 链表表名
166    /// * main_fields 主表字段
167    /// * second_fields 附表关联字段
168    fn join_inner(&mut self, table: &str, main_fields: &str, second_fields: &str) -> &mut Self;
169}
170
171#[derive(Clone, Debug)]
172pub struct Params {
173    pub mode: String,
174    pub autoinc: bool,
175    pub table: String,
176    pub where_and: Vec<String>,
177    pub where_or: Vec<String>,
178    pub where_column: String,
179    pub inc_dec: JsonValue,
180    pub page: i32,
181    pub limit: i32,
182    pub fields: JsonValue,
183    pub top: String,
184    pub top2: String,
185    pub order: JsonValue,
186    pub group: JsonValue,
187    pub distinct: bool,
188    pub json: JsonValue,
189    pub sql: bool,
190    pub join: Vec<String>,
191    pub join_inner: Vec<String>,
192    pub join_table: String,
193}
194
195impl Params {
196    pub fn default(mode: &str) -> Self {
197        Self {
198            mode: mode.to_string(),
199            autoinc: false,
200            table: "".to_string(),
201            where_and: vec![],
202            where_or: vec![],
203            where_column: "".to_string(),
204            inc_dec: object! {},
205            page: -1,
206            limit: 10,
207            fields: object! {},
208            top: String::new(),
209            top2: String::new(),
210            order: object! {},
211            group: object! {},
212            distinct: false,
213            json: object! {},
214            sql: false,
215            join: Vec::new(),
216            join_inner: Vec::new(),
217            join_table: "".to_string(),
218        }
219    }
220    pub fn where_sql(&mut self) -> String {
221        let mut where_and_sql = vec![];
222        let mut where_or_sql = vec![];
223        let mut sql = vec![];
224
225        for item in self.where_or.iter() {
226            where_or_sql.push(item.clone());
227        }
228        if !where_or_sql.is_empty() {
229            sql.push(format!(" ( {} ) ", where_or_sql.join(" OR ")));
230        }
231
232        for item in self.where_and.iter() {
233            where_and_sql.push(item.clone());
234        }
235        if !where_and_sql.is_empty() {
236            sql.push(where_and_sql.join(" AND "));
237        }
238
239        if !self.where_column.is_empty() {
240            sql.push(self.where_column.clone());
241        }
242
243        if !sql.is_empty() {
244            return format!("WHERE {}", sql.join(" AND "));
245        }
246        "".to_string()
247    }
248    pub fn page_limit_sql(&mut self) -> String {
249        if self.page == -1 {
250            return "".to_string();
251        }
252        match self.mode.as_str() {
253            "mysql" => {
254                format!("LIMIT {},{}", self.page * self.limit - self.limit, self.limit)
255            }
256            "sqlite" => {
257                format!("LIMIT {} OFFSET {}", self.limit, self.page * self.limit - self.limit)
258            }
259            _ => "".to_string()
260        }
261    }
262    pub fn fields(&mut self) -> String {
263        let mut fields = vec![];
264        for (_, value) in self.fields.entries() {
265            match self.mode.as_str() {
266                "mssql" => {
267                    fields.push(format!("{}", value));
268                }
269                _ => {
270                    fields.push(format!("{}", value));
271                }
272            }
273        }
274        let fields = {
275            if fields.is_empty() {
276                "*".into()
277            } else {
278                fields.join(",")
279            }
280        };
281        match self.mode.as_str() {
282            "mysql" => {
283                fields.to_string()
284            }
285            "sqlite" => {
286                fields.to_string()
287            }
288            "mssql" => {
289                fields.to_string()
290            }
291            _ => fields.to_string()
292        }
293    }
294    pub fn top(&mut self) -> String {
295        match self.mode.as_str() {
296            "mssql" => {
297                let wheres = self.where_sql();
298                if !self.top2.is_empty() {
299                    let order = self.order();
300                    if order.is_empty() {
301                        self.top = format!("(select ROW_NUMBER() OVER(ORDER BY rand()) as ROW,* from {} {}) as ", self.table, wheres);
302                    } else {
303                        self.top = format!("(select ROW_NUMBER() OVER({}) as ROW,* from {} {}) as ", order, self.table, wheres);
304                    }
305                    return self.top.to_string();
306                }
307                self.top.to_string()
308            }
309            _ => {
310                "".to_string()
311            }
312        }
313    }
314    pub fn top2(&mut self) -> String {
315        match self.mode.as_str() {
316            "mssql" => {
317                if self.where_and.is_empty() && self.where_or.is_empty() && !self.top2.is_empty() {
318                    return format!("where {}", self.top2);
319                }
320                if (!self.where_and.is_empty() || !self.where_or.is_empty()) && !self.top2.is_empty() {
321                    return format!("AND {}", self.top2);
322                }
323                self.top2.to_string()
324            }
325            _ => {
326                "".to_string()
327            }
328        }
329    }
330    pub fn table(&mut self) -> String {
331        match self.mode.as_str() {
332            "mssql" => {
333                if !self.top2.is_empty() {
334                    return "t".to_string();
335                }
336                self.table.to_string()
337            }
338            _ => {
339                self.table.to_string()
340            }
341        }
342    }
343    pub fn join(&mut self) -> String {
344        match self.mode.as_str() {
345            "mssql" => {
346                let mut join = "".to_string();
347                for item in self.join.iter() {
348                    join = format!("{} {}", join, item);
349                }
350                join.to_string()
351            }
352            _ => {
353                let mut join = "".to_string();
354                for item in self.join.iter() {
355                    join = format!("{} {}", join, item);
356                }
357                join.to_string()
358            }
359        }
360    }
361
362    // 当前只匹配了MySQL
363    pub fn join_inner(&mut self) -> String {
364        match self.mode.as_str() {
365            "mysql" => {
366                let mut join_inner = "".to_string();
367                for item in self.join_inner.iter() {
368                    join_inner = format!("{} {}", join_inner, item);
369                }
370                join_inner.to_string()
371            }
372            _ => {
373                "".to_string()
374            }
375        }
376    }
377
378
379    pub fn order(&mut self) -> String {
380        let mut sql = vec![];
381        for (field, item) in self.order.entries() {
382            match self.mode.as_str() {
383                "mssql" => {
384                    sql.push(format!("{} {}", field, item));
385                }
386                "pgsql" => {
387                    sql.push(format!("{} {}", field, item));
388                }
389                _ => {
390                    sql.push(format!("`{}` {}", field, item));
391                }
392            }
393        }
394        if !sql.is_empty() {
395            return format!("ORDER BY {}", sql.join(","));
396        }
397        "".to_string()
398    }
399    pub fn group(&mut self) -> String {
400        let mut sql = vec![];
401        for (_, field) in self.group.entries() {
402            match self.mode.as_str() {
403                "mssql" => {
404                    sql.push(format!("{}.{}", self.join_table, field));
405                }
406                "pgsql" => {
407                    sql.push(format!("{}.{}", self.join_table, field));
408                }
409                _ => {
410                    sql.push(format!("{}.`{}`", self.join_table, field));
411                }
412            }
413        }
414        if !sql.is_empty() {
415            return format!("GROUP BY {}", sql.join(","));
416        }
417        "".to_string()
418    }
419    pub fn distinct(&self) -> String {
420        if self.distinct {
421            "DISTINCT".to_string()
422        } else {
423            "".to_string()
424        }
425    }
426    pub fn select_sql(&mut self) -> String {
427        format!("SELECT {} {} FROM {} {} {} {} {} {} {} {} {}", self.distinct(), self.fields(), self.top(), self.table(), self.join(), self.join_inner(), self.where_sql(), self.top2(), self.group(), self.order(), self.page_limit_sql())
428    }
429}