br_db/types/
mod.rs

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