br_db/types/
sqlite.rs

1use crate::types::{DbMode, Mode, Params, TableOptions};
2use crate::Connection;
3use crate::{pools};
4use json::{array, object, JsonValue};
5use lazy_static::lazy_static;
6use log::{error, info};
7use sqlite::{Connection as Connect, ConnectionThreadSafe, OpenFlags, State, Statement, Type};
8use std::collections::HashMap;
9use std::sync::{Arc, Mutex};
10use std::thread;
11use chrono::Local;
12
13lazy_static! {
14    static ref DBS: Mutex<HashMap<String, Arc<ConnectionThreadSafe>>> = Mutex::new(HashMap::new());
15    static ref TR: Mutex<HashMap<String, Arc<ConnectionThreadSafe>>> = Mutex::new(HashMap::new());
16    static ref TR_COUNT: Mutex<HashMap<String, u32>> = Mutex::new(HashMap::new());
17    static ref SQL_LIST: Mutex<Vec<String>> = Mutex::new(Vec::new());
18    static ref FIELDS: Mutex<HashMap<String,JsonValue>> = Mutex::new(HashMap::new());
19}
20
21#[derive(Clone, Debug)]
22pub struct Sqlite {
23    /// 当前连接配置
24    pub connection: Connection,
25    /// 当前选中配置
26    pub default: String,
27
28    pub params: Params,
29}
30
31impl Sqlite {
32    pub fn connect(connection: Connection, default: String) -> Result<Self, String> {
33        let flags = OpenFlags::new().with_create().with_read_write();
34        match Connect::open_thread_safe_with_flags(connection.clone().get_dsn().as_str(), flags) {
35            Ok(e) => {
36                DBS.lock().unwrap().insert(default.clone(), Arc::new(e));
37                Ok(Self {
38                    connection: connection.clone(),
39                    default: default.clone(),
40                    params: Params::default("sqlite"),
41                })
42            }
43            Err(e) => {
44                error!(
45                    "sqlite 启动失败: {} {}",
46                    e,
47                    connection.clone().get_dsn().as_str()
48                );
49                Err(e.to_string())
50            }
51        }
52    }
53    fn query_handle(&mut self, mut statement: Statement, sql: String) -> (bool, JsonValue) {
54        let thread_id = format!("{:?}", thread::current().id());
55
56        let mut data = array![];
57        while let State::Row = match statement.next() {
58            Ok(e) => e,
59            Err(e) => {
60                let transaction = *TR_COUNT.lock().unwrap().get(&*thread_id.clone()).unwrap_or(&0);
61                if transaction > 0 {
62                    error!("{} 查询事务: {} {}", thread_id, e, sql.clone());
63                } else {
64                    error!("{} 非事务查询: {} {}", thread_id, e, sql.clone());
65                }
66                return (false, data);
67            }
68        } {
69            let mut list = object! {};
70            let mut index = 0;
71            for field in statement.column_names().iter() {
72                if !list[field.as_str()].is_null() {
73                    index += 1;
74                    continue;
75                }
76                match statement.column_type(field.as_str()) {
77                    Ok(types) => match types {
78                        Type::String => {
79                            let data = statement.read::<String, _>(index).unwrap();
80                            match data.as_str() {
81                                "false" => {
82                                    list[field.as_str()] = JsonValue::from(false);
83                                }
84                                "true" => {
85                                    list[field.as_str()] = JsonValue::from(true);
86                                }
87                                _ => {
88                                    list[field.as_str()] = JsonValue::from(data.clone());
89                                }
90                            }
91                        }
92                        Type::Integer => {
93                            if FIELDS.lock().unwrap().get(&self.params.table).is_none() {
94                                let data = statement.read::<i64, _>(index).unwrap();
95                                list[field.as_str()] = JsonValue::from(data);
96                            } else {
97                                let fields = FIELDS.lock().unwrap().get(&self.params.table).unwrap().clone();
98                                if fields[field.clone()].is_empty() {
99                                    let data = statement.read::<i64, _>(index).unwrap();
100                                    list[field.as_str()] = data.into();
101                                    continue;
102                                }
103                                match fields[field.clone()]["type"].as_str().unwrap() {
104                                    "INTEGER" => {
105                                        let data = statement.read::<i64, _>(index).unwrap();
106                                        list[field.as_str()] = JsonValue::from(data == 1);
107                                    }
108                                    x if x.contains("int(") => {
109                                        let data = statement.read::<i64, _>(index).unwrap();
110                                        list[field.as_str()] = data.into();
111                                    }
112                                    x if x.contains("decimal(") && x.ends_with(",0)") => {
113                                        let data = statement.read::<f64, _>(index).unwrap();
114                                        list[field.as_str()] = data.into();
115                                    }
116                                    _ => {
117                                        let data = statement.read::<i64, _>(index).unwrap();
118                                        list[field.as_str()] = data.into();
119                                    }
120                                }
121                            }
122                        }
123                        Type::Float => {
124                            let data = statement.read::<f64, _>(index).unwrap();
125                            list[field.as_str()] = JsonValue::from(data);
126                        }
127                        Type::Binary => {
128                            let data = statement.read::<String, _>(index).unwrap();
129                            list[field.as_str()] = JsonValue::from(data.clone());
130                        }
131                        Type::Null => match statement.read::<String, _>(index) {
132                            Ok(data) => {
133                                list[field.as_str()] = JsonValue::from(data.clone());
134                            }
135                            Err(_) => match statement.read::<f64, _>(index) {
136                                Ok(data) => {
137                                    if data == 0.0 {
138                                        list[field.as_str()] = JsonValue::from("");
139                                    } else {
140                                        list[field.as_str()] = JsonValue::from(data);
141                                    }
142                                }
143                                Err(_) => match statement.read::<i64, _>(index) {
144                                    Ok(data) => {
145                                        if data == 0 {
146                                            list[field.as_str()] = JsonValue::from("");
147                                        } else {
148                                            list[field.as_str()] = JsonValue::from(data);
149                                        }
150                                    }
151                                    Err(e) => {
152                                        error!("Type:{} {:?}", field.as_str(), e);
153                                    }
154                                },
155                            },
156                        },
157                    },
158                    Err(e) => {
159                        error!("query Err: {:?}", e);
160                    }
161                }
162                index += 1;
163            }
164            data.push(list).unwrap();
165        }
166        (true, data)
167    }
168    pub fn query(&mut self, sql: String) -> (bool, JsonValue) {
169        let thread_id = format!("{:?}", thread::current().id());
170
171        let transaction = *TR_COUNT.lock().unwrap().get(&*thread_id.clone()).unwrap_or(&0);
172        if transaction > 0 {
173            if self.connection.debug {
174                info!("{} 查询事务: sql: {:?}", thread_id, sql.clone());
175            }
176
177            let dbs = match TR.lock() {
178                Ok(dbs) => dbs,
179                Err(e) => {
180                    error!("{} 获取数据库锁失败: {}\r\nSQL: {}", thread_id, e, sql);
181                    return (false, JsonValue::from("数据库锁定失败"));
182                }
183            };
184            let db = dbs.get(&*thread_id.clone()).unwrap().clone();
185            let x = match db.prepare(sql.clone()) {
186                Ok(statement) => self.query_handle(statement, sql.clone()),
187                Err(e) => {
188                    error!("{} 查询事务: Err: {} {}", thread_id, e, sql.clone());
189                    (false, e.to_string().into())
190                }
191            };
192            x
193        } else {
194            if self.connection.debug {
195                info!("{} 非事务查询: sql: {:?}", thread_id, sql.clone());
196            }
197            let dbs = match DBS.lock() {
198                Ok(dbs) => dbs,
199                Err(e) => {
200                    error!("{} 获取数据库锁失败: {}\r\nSQL: {}", thread_id, e, sql);
201                    return (false, JsonValue::from("数据库锁定失败"));
202                }
203            };
204            let db = dbs.get(&*self.default).unwrap().clone();
205            let x = match db.prepare(sql.clone()) {
206                Ok(statement) => self.query_handle(statement, sql.clone()),
207                Err(e) => {
208                    error!("{} 查询非事务: Err: {}", thread_id, e);
209                    (false, e.to_string().into())
210                }
211            };
212            x
213        }
214    }
215
216    pub fn execute(&mut self, sql: String) -> (bool, JsonValue) {
217        let thread_id = format!("{:?}", thread::current().id());
218
219        let transaction = *TR_COUNT.lock().unwrap().get(&*thread_id.clone()).unwrap_or(&0);
220        if transaction > 0 {
221            if self.connection.debug {
222                info!("{} 执行事务: sql: {}", thread_id, sql.clone());
223            }
224
225            let dbs = match TR.lock() {
226                Ok(dbs) => dbs,
227                Err(e) => {
228                    error!("{} 获取数据库锁失败: {}\r\nSQL: {}", thread_id, e, sql);
229                    return (false, JsonValue::from("数据库锁定失败"));
230                }
231            };
232            let db = match dbs.get(&*thread_id) {
233                Some(db) => db.clone(),
234                None => {
235                    error!(
236                        "{} 未找到默认数据库配置: {}\r\nSQL: {}",
237                        thread_id, self.default, sql
238                    );
239                    return (false, JsonValue::from("未找到默认数据库配置"));
240                }
241            };
242            match db.execute(sql.clone()) {
243                Ok(_) => {
244                    let count = db.change_count();
245                    if self.connection.debug {
246                        info!(
247                            "{} count:{} total_count:{}",
248                            thread_id,
249                            count,
250                            db.total_change_count()
251                        );
252                    }
253                    (true, JsonValue::from(count))
254                }
255                Err(e) => {
256                    error!("{} 执行事务: \r\nErr: {}\r\n{}", thread_id, e, sql.clone());
257                    (false, JsonValue::from(e.to_string()))
258                }
259            }
260        } else {
261            if self.connection.debug {
262                info!("{} 执行非事务: \r\nsql: {}", thread_id, sql.clone());
263            }
264            let dbs = match DBS.lock() {
265                Ok(dbs) => dbs,
266                Err(e) => {
267                    error!("{} 获取数据库锁失败: {}\r\nSQL: {}", thread_id, e, sql);
268                    return (false, JsonValue::from("数据库锁定失败"));
269                }
270            };
271
272            let db = match dbs.get(&*self.default) {
273                Some(db) => db.clone(),
274                None => {
275                    error!(
276                        "{} 未找到默认数据库配置: {}\r\nSQL: {}",
277                        thread_id, self.default, sql
278                    );
279                    return (false, JsonValue::from("未找到默认数据库配置"));
280                }
281            };
282            match db.execute(sql.clone()) {
283                Ok(_) => {
284                    let count = db.change_count();
285                    if self.connection.debug {
286                        info!(
287                            "{} count: {} total_count: {}",
288                            thread_id,
289                            count,
290                            db.total_change_count()
291                        );
292                    }
293                    (true, JsonValue::from(count))
294                }
295                Err(e) => {
296                    error!(
297                        "{} 执行非事务: Err: {}\r\nSQL: {}",
298                        thread_id,
299                        e,
300                        sql.clone()
301                    );
302                    (false, JsonValue::from(e.to_string()))
303                }
304            }
305        }
306    }
307}
308
309impl DbMode for Sqlite {
310    fn database_tables(&mut self) -> JsonValue {
311        let sql = "select name from sqlite_master where type='table' order by name;".to_string();
312        match self.sql(sql.as_str()) {
313            Ok(e) => {
314                let mut list = vec![];
315                for item in e.members() {
316                    list.push(item["name"].clone());
317                }
318                list.into()
319            }
320            Err(_) => {
321                array![]
322            }
323        }
324    }
325    fn database_create(&mut self, _name: &str) -> bool {
326        todo!()
327    }
328}
329
330impl Mode for Sqlite {
331    fn table_create(&mut self, options: TableOptions) -> JsonValue {
332        let mut sql = String::new();
333        // 唯一约束
334        let mut unique_fields = String::new();
335        let mut unique_name = String::new();
336        let mut unique = String::new();
337        for item in options.table_unique.iter() {
338            if unique_fields.is_empty() {
339                unique_fields = format!("`{}`", item);
340                unique_name = format!("unique_{}", item);
341            } else {
342                unique_fields = format!("{},`{}`", unique_fields, item);
343                unique_name = format!("{}_{}", unique_name, item);
344            }
345            unique = format!(
346                "CREATE UNIQUE INDEX  {} on {} ({});\r\n",
347                unique_name, options.table_name, unique_fields
348            );
349        }
350
351        // 唯一索引
352        let mut index = vec![];
353        for row in options.table_index.iter() {
354            let mut index_fields = String::new();
355            let mut index_name = String::new();
356            for item in row.iter() {
357                if index_fields.is_empty() {
358                    index_fields = format!("`{}`", item);
359                    index_name = format!("index_{}", item);
360                } else {
361                    index_fields = format!("{},`{}`", index_fields, item);
362                    index_name = format!("{}_{}", index_name, item);
363                }
364            }
365            index.push(format!(
366                "CREATE INDEX {} on {} ({});\r\n",
367                index_name, options.table_name, index_fields
368            ));
369        }
370
371        for (name, field) in options.table_fields.entries() {
372            let row = br_fields::field("sqlite", name, field.clone());
373            sql = format!("{} {},\r\n", sql, row);
374        }
375
376        sql = sql.trim_end_matches(",\r\n").to_string();
377
378        let sql = format!(
379            "CREATE TABLE IF NOT EXISTS `{}` (\r\n{}\r\n);\r\n",
380            options.table_name, sql
381        );
382        if self.params.sql {
383            let mut list = vec![sql];
384            if !unique.is_empty() {
385                list.push(unique)
386            }
387            if !index.is_empty() {
388                list.extend(index)
389            }
390
391            return JsonValue::from(list.join(""));
392        }
393
394        let thread_id = format!("{:?}", thread::current().id());
395
396        let (state, _) = self.execute(sql.clone());
397        if state {
398            if !unique.is_empty() {
399                let (state, _) = self.execute(unique.clone());
400                info!(
401                    "{} {} 唯一索引创建:{}",
402                    thread_id, options.table_name, state
403                );
404            }
405            for sql in index.iter() {
406                let (state, _) = self.execute(sql.clone());
407                info!("{} {} 索引创建:{}", thread_id, options.table_name, state);
408            }
409            JsonValue::from(true)
410        } else {
411            JsonValue::from(false)
412        }
413    }
414    fn table_update(&mut self, options: TableOptions) -> JsonValue {
415        let thread_id = format!("{:?}", thread::current().id());
416
417        let mut sql = String::new();
418        let mut add = vec![];
419        let mut del = vec![];
420        let mut put = vec![];
421
422        let (_, mut fields_list) = self.query(format!("pragma table_info ('{}')", options.table_name));
423        let mut field_old = object! {};
424        for item in fields_list.members_mut() {
425            item["dflt_value"] = item["dflt_value"].to_string().trim_start_matches("'").trim_end_matches("'").into();
426            let name = item["name"].as_str().unwrap();
427            field_old[name] = item.clone();
428            if options.table_fields[name].is_empty() {
429                del.push(name);
430            }
431        }
432
433        let mut fields_list = vec![];
434        let mut fields_list_new = vec![];
435
436        for (name, field) in options.table_fields.entries() {
437            if field_old[name].is_empty() {
438                add.push(name);
439            } else {
440                fields_list.push(name);
441                fields_list_new.push(name);
442                let old_value = match field["mode"].as_str().unwrap() {
443                    "select" => {
444                        if field_old[name]["dflt_value"].clone().is_empty() {
445                            "".to_string()
446                        } else {
447                            field_old[name]["dflt_value"].clone().to_string()
448                        }
449                    }
450                    "switch" => {
451                        (field_old[name]["dflt_value"].to_string().parse::<i32>().unwrap() == 1).to_string()
452                    }
453                    _ => {
454                        field_old[name]["dflt_value"].clone().to_string()
455                    }
456                };
457                let new_value = match field["mode"].as_str().unwrap() {
458                    "select" => {
459                        field["def"].members().map(|x| x.to_string()).collect::<Vec<String>>().join(",")
460                    }
461                    _ => field["def"].clone().to_string()
462                };
463                if old_value != new_value {
464                    info!("{} 差异化当前: {} old_value: {} new_value: {} {}",
465                        options.table_name,
466                        name,
467                        old_value,
468                        new_value,
469                        old_value != new_value
470                    );
471                    info!("差异化更新: {} {:#} {:#}", name, field_old[name], field);
472                    put.push(name);
473                } else if field_old[name]["pk"].as_i64().unwrap() == 1 && name != options.table_key
474                {
475                    info!("{} 主键替换: {}", options.table_name, name);
476                    put.push(name);
477                }
478            }
479        }
480
481        let mut unique_fields = String::new();
482        let mut unique_name = String::new();
483        let mut unique = String::new();
484
485        // 唯一索引
486        for item in options.table_unique.iter() {
487            if unique_fields.is_empty() {
488                unique_fields = format!("`{}`", item);
489                unique_name = format!("unique_{}", item);
490            } else {
491                unique_fields = format!("{},`{}`", unique_fields, item);
492                unique_name = format!("{}_{}", unique_name, item);
493            }
494            unique = format!(
495                "CREATE UNIQUE INDEX  {}_{} on {} ({});\r\n",
496                options.table_name, unique_name, options.table_name, unique_fields
497            )
498        }
499
500        // 索引
501        let mut index = vec![];
502        for row in options.table_index.iter() {
503            let mut index_fields = String::new();
504            let mut index_name = String::new();
505            for item in row.iter() {
506                if index_fields.is_empty() {
507                    index_fields = item.to_string();
508                    index_name = format!("index_{}", item);
509                } else {
510                    index_fields = format!("{},{}", index_fields, item);
511                    index_name = format!("{}_{}", index_name, item);
512                }
513            }
514            index.push(format!(
515                "create index {}_{} on {} ({});\r\n",
516                options.table_name, index_name, options.table_name, index_fields
517            ));
518        }
519        for (name, field) in options.table_fields.entries() {
520            let row = br_fields::field("sqlite", name, field.clone());
521            sql = format!("{} {},\r\n", sql, row);
522        }
523
524        if !unique.is_empty() || !index.is_empty() {
525            let unique_text = unique.clone();
526            let (_, unique_old) = self.query(format!("PRAGMA index_list({});\r\n", options.table_name));
527            let mut index_old_list = vec![];
528            let mut index_new_list = vec![];
529            for item in unique_old.members() {
530                let origin = item["origin"].as_str().unwrap();
531                let unique_1 = item["unique"].as_usize().unwrap();
532                let name = item["name"].as_str().unwrap();
533
534                if origin == "c" && unique_1 == 1 {
535                    if unique.contains(format!(" {} ", name).as_str()) {
536                        unique = "".to_string();
537                    }
538                    continue;
539                }
540                if origin == "c" && unique_1 == 0 {
541                    index_old_list.push(item);
542                    for item in index.iter() {
543                        if item.contains(format!(" {} ", name).as_str()) {
544                            index_new_list.push(item.clone());
545                        }
546                    }
547                    continue;
548                }
549            }
550            if unique.is_empty() {
551                if index_old_list.len() == index.len() && index_old_list.len() == index_new_list.len()
552                {
553                    index = vec![];
554                } else {
555                    unique = unique_text;
556                }
557            }
558        }
559
560        sql = sql.trim_end_matches(",\r\n").to_string();
561        sql = format!(
562            "CREATE TABLE {}_tmp (\r\n{}\r\n);\r\n",
563            options.table_name, sql
564        );
565
566        let sqls = format!(
567            "replace INTO {}_tmp (`{}`) select `{}` from {00};\r\n",
568            options.table_name,
569            fields_list_new.join("`,`"),
570            fields_list.join("`,`")
571        );
572        let drop_sql = format!("drop table {};\r\n", options.table_name);
573        let alter_sql = format!("alter table {}_tmp rename to {00};\r\n", options.table_name);
574        let drop_sql_temp = format!("drop table {}_tmp;\r\n", options.table_name);
575
576        if self.params.sql {
577            let mut list = vec![sql, sqls, drop_sql, alter_sql, drop_sql_temp];
578            if !unique.is_empty() {
579                list.push(unique)
580            }
581            if !index.is_empty() {
582                list.extend(index)
583            }
584            return JsonValue::from(list.join(""));
585        }
586
587        if add.is_empty() && del.is_empty() && unique.is_empty() && index.is_empty() && put.is_empty()
588        {
589            return JsonValue::from(-1);
590        }
591
592        let (state, _) = self.execute(sql.clone());
593        let data = match state {
594            true => {
595                let (state, _) = self.execute(sqls.clone());
596                match state {
597                    true => {
598                        let (state, _) = self.execute(drop_sql);
599                        match state {
600                            true => {
601                                let (state, _) = self.execute(alter_sql);
602                                match state {
603                                    true => {
604                                        if !unique.is_empty() {
605                                            let (state, _) = self.execute(unique.clone());
606                                            info!(
607                                                "{} {} 唯一索引创建:{}",
608                                                thread_id, options.table_name, state
609                                            );
610                                        }
611                                        for index_sql in index.iter() {
612                                            let (state, _) = self.execute(index_sql.clone());
613                                            match state {
614                                                true => {}
615                                                false => {
616                                                    error!(
617                                                        "{} 索引创建失败: {} {}",
618                                                        options.table_name, state, index_sql
619                                                    );
620                                                    return JsonValue::from(0);
621                                                }
622                                            };
623                                        }
624
625                                        return JsonValue::from(1);
626                                    }
627                                    false => {
628                                        error!("{} 修改表名失败", options.table_name);
629                                        return JsonValue::from(0);
630                                    }
631                                }
632                            }
633                            false => {
634                                error!("{} 删除本表失败", options.table_name);
635                                return JsonValue::from(0);
636                            }
637                        }
638                    }
639                    false => {
640                        error!(
641                            "{} 添加tmp表记录失败 {:#} {:#}",
642                            options.table_name, sql, sqls
643                        );
644                        let sql = format!("drop table {}_tmp", options.table_name);
645                        let (_, _) = self.execute(sql);
646                        0
647                    }
648                }
649            }
650            false => {
651                error!("{} 创建TMP表失败 {:#}", options.table_name, sql);
652                let (_, _) = self.execute(drop_sql_temp);
653                0
654            }
655        };
656        JsonValue::from(data)
657    }
658
659    fn table_info(&mut self, table: &str) -> JsonValue {
660        if FIELDS.lock().unwrap().get(table).is_some() {
661            return FIELDS.lock().unwrap().get(table).unwrap().clone();
662        }
663        let sql = format!("PRAGMA table_info({})", table);
664        let (state, data) = self.query(sql);
665
666        match state {
667            true => {
668                let mut fields = object! {};
669                for item in data.members() {
670                    fields[item["name"].as_str().unwrap()] = item.clone();
671                }
672                FIELDS.lock().unwrap().insert(table.to_string(), fields.clone());
673                data
674            }
675            false => object! {}
676        }
677    }
678
679    fn table_is_exist(&mut self, name: &str) -> bool {
680        let sql = format!(
681            "SELECT count(*) as count FROM sqlite_master WHERE type='table' AND name='{}'",
682            name
683        );
684        let (state, data) = self.query(sql);
685        if state {
686            if data[0]["count"].as_i64().unwrap() > 0 {
687                return true;
688            }
689            false
690        } else {
691            false
692        }
693    }
694
695    fn table(&mut self, name: &str) -> &mut Sqlite {
696        self.params = Params::default(self.connection.mode.str().as_str());
697        self.params.table = format!("{}{}", self.connection.prefix, name);
698        self.params.join_table = self.params.table.clone();
699        self
700    }
701    fn change_table(&mut self, name: &str) -> &mut Self {
702        self.params.join_table = name.to_string();
703        self
704    }
705    fn autoinc(&mut self) -> &mut Self {
706        self.params.autoinc = true;
707        self
708    }
709
710    fn fetch_sql(&mut self) -> &mut Self {
711        self.params.sql = true;
712        self
713    }
714
715    fn order(&mut self, field: &str, by: bool) -> &mut Self {
716        self.params.order[field] = {
717            if by {
718                "DESC"
719            } else {
720                "ASC"
721            }
722        }.into();
723        self
724    }
725
726    fn group(&mut self, field: &str) -> &mut Self {
727        let fields: Vec<&str> = field.split(",").collect();
728        for field in fields.iter() {
729            let fields = field.to_string();
730            self.params.group[fields.as_str()] = fields.clone().into();
731            self.params.fields[fields.as_str()] = fields.clone().into();
732        }
733        self
734    }
735
736    fn distinct(&mut self) -> &mut Self {
737        self.params.distinct = true;
738        self
739    }
740    fn json(&mut self, field: &str) -> &mut Self {
741        let list: Vec<&str> = field.split(",").collect();
742        for item in list.iter() {
743            self.params.json[item.to_string().as_str()] = item.to_string().into();
744        }
745        self
746    }
747
748    fn field(&mut self, field: &str) -> &mut Self {
749        let list: Vec<&str> = field.split(",").collect();
750        let join_table = if self.params.join_table.is_empty() {
751            self.params.table.clone()
752        } else {
753            self.params.join_table.clone()
754        };
755        for item in list.iter() {
756            let item = item.to_string();
757            if item.contains(" as ") {
758                let text = item.split(" as ").collect::<Vec<&str>>().clone();
759                self.params.fields[item] = format!("{}.`{}` as `{}`", join_table, text[0], text[1]).into();
760            } else {
761                self.params.fields[item] = format!("{}.`{}`", join_table, item).into();
762            }
763        }
764        self
765    }
766    fn hidden(&mut self, name: &str) -> &mut Self {
767        let hidden: Vec<&str> = name.split(",").collect();
768        let sql = format!("PRAGMA table_info({})", self.params.table);
769        let (_, data) = self.query(sql);
770        for item in data.members() {
771            let name = item["name"].as_str().unwrap();
772            if !hidden.contains(&name) {
773                self.params.fields[name] = name.into();
774            }
775        }
776        self
777    }
778
779    fn where_and(&mut self, field: &str, compare: &str, mut value: JsonValue) -> &mut Self {
780        let join_table = if self.params.join_table.is_empty() {
781            self.params.table.clone()
782        } else {
783            self.params.join_table.clone()
784        };
785
786        if value.is_boolean() {
787            if value.as_bool().unwrap() {
788                value = 1.into();
789            } else {
790                value = 0.into();
791            }
792        }
793
794        match compare {
795            "between" => {
796                self.params.where_and.push(format!(
797                    "{}.`{}` between '{}' AND '{}'",
798                    join_table, field, value[0], value[1]
799                ));
800            }
801            "set" => {
802                let list: Vec<&str> = value.as_str().unwrap().split(",").collect();
803                let mut wheredata = vec![];
804                for item in list.iter() {
805                    wheredata.push(format!("{}.`{}` like '%{}%'", join_table, field, item));
806                }
807                self.params.where_and.push(format!("({})", wheredata.join(" or ")));
808            }
809            "notin" => {
810                let mut text = String::new();
811                for item in value.members() {
812                    text = format!("{},'{}'", text, item);
813                }
814                text = text.trim_start_matches(",").into();
815                self.params.where_and.push(format!("{}.`{}` not in ({})", join_table, field, text));
816            }
817            "in" => {
818                let mut text = String::new();
819                if value.is_array() {
820                    for item in value.members() {
821                        text = format!("{},'{}'", text, item);
822                    }
823                } else {
824                    let value = value.to_string();
825                    let value: Vec<&str> = value.split(",").collect();
826                    for item in value.iter() {
827                        text = format!("{},'{}'", text, item);
828                    }
829                }
830                text = text.trim_start_matches(",").into();
831
832                self.params.where_and.push(format!("{}.`{}` {} ({})", join_table, field, compare, text));
833            }
834            "=" => {
835                if value.is_null() {
836                    self.params.where_and.push(format!("{}.`{}` {} {}", join_table, field, "IS", value));
837                } else {
838                    self.params.where_and.push(format!(
839                        "{}.`{}` {} '{}'",
840                        join_table, field, compare, value
841                    ));
842                }
843            }
844            _ => {
845                if value.is_null() {
846                    self.params.where_and.push(format!("{}.`{}` {} {}", join_table, field, compare, value));
847                } else {
848                    self.params.where_and.push(format!(
849                        "{}.`{}` {} '{}'",
850                        join_table, field, compare, value
851                    ));
852                }
853            }
854        }
855        self
856    }
857    fn where_or(&mut self, field: &str, compare: &str, mut value: JsonValue) -> &mut Self {
858        let join_table = if self.params.join_table.is_empty() {
859            self.params.table.clone()
860        } else {
861            self.params.join_table.clone()
862        };
863
864        if value.is_boolean() {
865            if value.as_bool().unwrap() {
866                value = 1.into();
867            } else {
868                value = 0.into();
869            }
870        }
871        match compare {
872            "between" => {
873                self.params.where_or.push(format!(
874                    "{}.`{}` between '{}' AND '{}'",
875                    join_table, field, value[0], value[1]
876                ));
877            }
878            "set" => {
879                let tt = value.to_string().replace(",", "%");
880                self.params.where_or.push(format!("{}.`{}` like '%{}%'", join_table, field, tt));
881            }
882            "notin" => {
883                let mut text = String::new();
884                for item in value.members() {
885                    text = format!("{},'{}'", text, item);
886                }
887                text = text.trim_start_matches(",").into();
888                self.params.where_or.push(format!("{}.`{}` not in ({})", join_table, field, text));
889            }
890            "in" => {
891                let mut text = String::new();
892                if value.is_array() {
893                    for item in value.members() {
894                        text = format!("{},'{}'", text, item);
895                    }
896                } else {
897                    let value = value.as_str().unwrap();
898                    let value: Vec<&str> = value.split(",").collect();
899                    for item in value.iter() {
900                        text = format!("{},'{}'", text, item);
901                    }
902                }
903                text = text.trim_start_matches(",").into();
904                self.params.where_or.push(format!("{}.`{}` {} ({})", join_table, field, compare, text));
905            }
906            _ => {
907                self.params.where_or.push(format!(
908                    "{}.`{}` {} '{}'",
909                    join_table, field, compare, value
910                ));
911            }
912        }
913        self
914    }
915    fn where_column(&mut self, field_a: &str, compare: &str, field_b: &str) -> &mut Self {
916        self.params.where_column = format!(
917            "{}.`{}` {} {}.`{}`",
918            self.params.table, field_a, compare, self.params.table, field_b
919        );
920        self
921    }
922
923    fn page(&mut self, page: i32, limit: i32) -> &mut Self {
924        self.params.page = page;
925        self.params.limit = limit;
926        self
927    }
928
929    fn column(&mut self, field: &str) -> JsonValue {
930        self.field(field);
931        self.group(field);
932        let sql = self.params.select_sql();
933        if self.params.sql {
934            return JsonValue::from(sql.clone());
935        }
936        self.table_info(self.params.table.clone().as_str());
937        let (state, data) = self.query(sql);
938        if state {
939            let mut list = array![];
940            for item in data.members() {
941                if self.params.json[field].is_empty() {
942                    list.push(item[field].clone()).unwrap();
943                } else {
944                    let data = json::parse(item[field].as_str().unwrap()).unwrap_or(array![]);
945                    list.push(data).unwrap();
946                }
947            }
948            list
949        } else {
950            array![]
951        }
952    }
953
954    fn count(&mut self) -> JsonValue {
955        self.params.fields["count"] = "count(*) as count".to_string().into();
956        let sql = self.params.select_sql();
957        if self.params.sql {
958            return JsonValue::from(sql.clone());
959        }
960        let (state, data) = self.query(sql);
961        match state {
962            true => data[0]["count"].clone(),
963            false => JsonValue::from(0),
964        }
965    }
966
967    fn max(&mut self, field: &str) -> JsonValue {
968        self.params.fields[field] = format!("max({00}) as {00}", field).into();
969        let sql = self.params.select_sql();
970        if self.params.sql {
971            return JsonValue::from(sql.clone());
972        }
973        let (state, data) = self.query(sql);
974        if state {
975            if data.len() > 1 {
976                return data;
977            }
978            data[0][field].clone()
979        } else {
980            JsonValue::from(0.0)
981        }
982    }
983
984    fn min(&mut self, field: &str) -> JsonValue {
985        self.params.fields[field] = format!("min({00}) as {00}", field).into();
986        let sql = self.params.select_sql();
987        let (state, data) = self.query(sql);
988        if state {
989            if data.len() > 1 {
990                return data;
991            }
992            data[0][field].clone()
993        } else {
994            JsonValue::from(0.0)
995        }
996    }
997
998    fn sum(&mut self, field: &str) -> JsonValue {
999        self.params.fields[field] = format!("sum({00}) as {00}", field).into();
1000        let sql = self.params.select_sql();
1001        if self.params.sql {
1002            return JsonValue::from(sql.clone());
1003        }
1004        let (state, data) = self.query(sql);
1005        match state {
1006            true => {
1007                if data.len() > 1 {
1008                    return data;
1009                }
1010                if self.params.fields.len() > 1 {
1011                    return data[0].clone();
1012                }
1013                data[0][field].clone()
1014            }
1015            false => JsonValue::from(0),
1016        }
1017    }
1018    fn avg(&mut self, field: &str) -> JsonValue {
1019        self.params.fields[field] = format!("avg({00}) as {00}", field).into();
1020        let sql = self.params.select_sql();
1021        if self.params.sql {
1022            return JsonValue::from(sql.clone());
1023        }
1024        let (state, data) = self.query(sql);
1025        if state {
1026            if data.len() > 1 {
1027                return data;
1028            }
1029            data[0][field].clone()
1030        } else {
1031            JsonValue::from(0)
1032        }
1033    }
1034    fn select(&mut self) -> JsonValue {
1035        let sql = self.params.select_sql();
1036        if self.params.sql {
1037            return JsonValue::from(sql.clone());
1038        }
1039        self.table_info(self.params.table.clone().as_str());
1040        let (state, mut data) = self.query(sql.clone());
1041        match state {
1042            true => {
1043                for (field, _) in self.params.json.entries() {
1044                    for item in data.members_mut() {
1045                        if !item[field].is_empty() {
1046                            let json = item[field].to_string();
1047                            item[field] = match json::parse(&json) {
1048                                Ok(e) => e,
1049                                Err(_) => JsonValue::from(json),
1050                            };
1051                        }
1052                    }
1053                }
1054                data.clone()
1055            }
1056            false => {
1057                error!("{:?}", data);
1058                array![]
1059            }
1060        }
1061    }
1062    fn find(&mut self) -> JsonValue {
1063        self.params.page = 1;
1064        self.params.limit = 1;
1065        let sql = self.params.select_sql();
1066        if self.params.sql {
1067            return JsonValue::from(sql.clone());
1068        }
1069
1070        self.table_info(self.params.table.clone().as_str());
1071        let (state, mut data) = self.query(sql.clone());
1072        match state {
1073            true => {
1074                if data.is_empty() {
1075                    return object! {};
1076                }
1077                for (field, _) in self.params.json.entries() {
1078                    if !data[0][field].is_empty() {
1079                        let json = data[0][field].to_string();
1080                        let json = json::parse(&json).unwrap_or(array![]);
1081                        data[0][field] = json;
1082                    } else {
1083                        data[0][field] = array![];
1084                    }
1085                }
1086                data[0].clone()
1087            }
1088            false => {
1089                error!("{:?}", data);
1090                object! {}
1091            }
1092        }
1093    }
1094
1095    fn value(&mut self, field: &str) -> JsonValue {
1096        self.params.fields = object! {};
1097        self.params.fields[field] = format!("{}.`{}`", self.params.table, field).into();
1098        self.params.page = 1;
1099        self.params.limit = 1;
1100        let sql = self.params.select_sql();
1101        if self.params.sql {
1102            return JsonValue::from(sql.clone());
1103        }
1104        self.table_info(self.params.table.clone().as_str());
1105        let (state, mut data) = self.query(sql.clone());
1106        match state {
1107            true => {
1108                for (field, _) in self.params.json.entries() {
1109                    if !data[0][field].is_empty() {
1110                        let json = data[0][field].to_string();
1111                        let json = json::parse(&json).unwrap_or(array![]);
1112                        data[0][field] = json;
1113                    } else {
1114                        data[0][field] = array![];
1115                    }
1116                }
1117                data[0][field].clone()
1118            }
1119            false => {
1120                if self.connection.debug {
1121                    info!("{:?}", data);
1122                }
1123                JsonValue::Null
1124            }
1125        }
1126    }
1127
1128    fn insert(&mut self, mut data: JsonValue) -> JsonValue {
1129        let mut fields = vec![];
1130        let mut values = vec![];
1131
1132        if !self.params.autoinc && data["id"].is_empty() {
1133            data["id"] = format!("{:X}", Local::now().timestamp_nanos_opt().unwrap()).into();
1134        }
1135        for (field, value) in data.entries() {
1136            fields.push(format!("`{}`", field));
1137
1138            if value.is_string() {
1139                if value.to_string().contains("'") {
1140                    values.push(format!("\"{}\"", value.to_string().replace("'", "''")));
1141                    continue;
1142                } else if value.to_string().contains('"') {
1143                    values.push(format!("'{}'", value));
1144                    continue;
1145                } else {
1146                    values.push(format!("\"{}\"", value));
1147                    continue;
1148                }
1149            } else if value.is_array() || value.is_object() {
1150                if self.params.json[field].is_empty() {
1151                    values.push(format!("'{}'", value));
1152                } else {
1153                    let json = value.to_string();
1154                    let json = json.replace("'", "''");
1155                    values.push(format!("'{}'", json));
1156                }
1157                continue;
1158            } else if value.is_number() || value.is_boolean() || value.is_null() {
1159                values.push(format!("{}", value));
1160                continue;
1161            } else {
1162                values.push(format!("'{}'", value));
1163                continue;
1164            }
1165        }
1166        let fields = fields.join(",");
1167        let values = values.join(",");
1168
1169        let sql = format!(
1170            "INSERT INTO `{}` ({}) VALUES ({});",
1171            self.params.table, fields, values
1172        );
1173        if self.params.sql {
1174            return JsonValue::from(sql.clone());
1175        }
1176        let (state, ids) = self.execute(sql);
1177        match state {
1178            true => {
1179                if self.params.autoinc {
1180                    let (state, ids) = self.query(format!("select max(id) as id from {}", self.params.table));
1181                    return match state {
1182                        true => ids[0]["id"].clone(),
1183                        false => {
1184                            error!("{}", ids);
1185                            JsonValue::from("")
1186                        }
1187                    };
1188                }
1189                data["id"].clone()
1190            }
1191            false => {
1192                error!("{}", ids);
1193                JsonValue::from("")
1194            }
1195        }
1196    }
1197    fn insert_all(&mut self, mut data: JsonValue) -> JsonValue {
1198        let mut fields = String::new();
1199
1200        if !self.params.autoinc && data[0]["id"].is_empty() {
1201            data[0]["id"] = "".into();
1202        }
1203        for (field, _) in data[0].entries() {
1204            fields = format!("{},`{}`", fields, field);
1205        }
1206        fields = fields.trim_start_matches(",").parse().unwrap();
1207
1208        let core_count = num_cpus::get();
1209        let mut p = pools::Pool::new(core_count * 4);
1210        let autoinc = self.params.autoinc;
1211        for list in data.members() {
1212            let mut item = list.clone();
1213            p.execute(move |pcindex| {
1214                if !autoinc && item["id"].is_empty() {
1215                    let id = format!(
1216                        "{:X}{:X}",
1217                        Local::now().timestamp_nanos_opt().unwrap(),
1218                        pcindex
1219                    );
1220                    item["id"] = id.into();
1221                }
1222                let mut values = "".to_string();
1223                for (_, value) in item.entries() {
1224                    if value.is_string() {
1225                        values = format!("{},'{}'", values, value.to_string().replace("'", "''"));
1226                    } else if value.is_number() || value.is_boolean() {
1227                        values = format!("{},{}", values, value);
1228                    } else {
1229                        values = format!("{},'{}'", values, value.to_string().replace("'", "''"));
1230                    }
1231                }
1232                values = format!("({})", values.trim_start_matches(","));
1233                array![item["id"].clone(), values]
1234            });
1235        }
1236        let (ids_list, mut values) = p.insert_all();
1237
1238        values = values.trim_start_matches(",").parse().unwrap();
1239
1240        let sql = format!(
1241            "INSERT INTO {} ({}) VALUES {};",
1242            self.params.table, fields, values
1243        );
1244        if self.params.sql {
1245            return JsonValue::from(sql.clone());
1246        }
1247        let (state, data) = self.execute(sql.clone());
1248        match state {
1249            true => {
1250                if self.params.autoinc {
1251                    let (state, ids) = self.query(format!(
1252                        "SELECT id FROM {} GROUP BY id ORDER BY id DESC LIMIT {} OFFSET 0",
1253                        self.params.table,
1254                        ids_list.len()
1255                    ));
1256                    return match state {
1257                        true => {
1258                            let mut idlist = array![];
1259                            for item in ids.members() {
1260                                idlist.push(item["id"].clone()).unwrap();
1261                            }
1262                            idlist
1263                        }
1264                        false => {
1265                            error!("批量添加失败: {:?} {}", ids, sql);
1266                            array![]
1267                        }
1268                    };
1269                }
1270                JsonValue::from(ids_list)
1271            }
1272            false => {
1273                error!("批量添加失败: {:?} {}", data, sql);
1274                array![]
1275            }
1276        }
1277    }
1278
1279    fn update(&mut self, data: JsonValue) -> JsonValue {
1280        let mut values = vec![];
1281
1282        for (field, value) in data.entries() {
1283            if value.is_string() {
1284                values.push(format!(
1285                    "`{}` = '{}'",
1286                    field,
1287                    value.to_string().replace("'", "''")
1288                ));
1289            } else if value.is_array() || value.is_object() {
1290                if self.params.json[field].is_empty() {
1291                    values.push(format!("`{}` = '{}'", field, value));
1292                } else {
1293                    let json = value.to_string();
1294                    let json = json.replace("'", "''");
1295                    values.push(format!("`{}` = '{}'", field, json));
1296                }
1297                continue;
1298            } else if value.is_number() || value.is_boolean() || value.is_null() {
1299                values.push(format!("`{}` = {} ", field, value));
1300            } else {
1301                values.push(format!("`{}` = '{}' ", field, value));
1302            }
1303        }
1304
1305        for (field, value) in self.params.inc_dec.entries() {
1306            values.push(format!("{} = {}", field, value.to_string().clone()));
1307        }
1308
1309        let values = values.join(",");
1310        let sql = format!(
1311            "UPDATE `{}` SET {} {} {};",
1312            self.params.table.clone(),
1313            values,
1314            self.params.where_sql(),
1315            self.params.page_limit_sql()
1316        );
1317        if self.params.sql {
1318            return JsonValue::from(sql.clone());
1319        }
1320        let (state, data) = self.execute(sql);
1321        if state {
1322            data
1323        } else {
1324            error!("{}", data);
1325            JsonValue::from(0)
1326        }
1327    }
1328
1329    fn update_all(&mut self, data: JsonValue) -> JsonValue {
1330        let mut values = vec![];
1331        let mut ids = vec![];
1332        for (field, _) in data[0].entries() {
1333            if field == "id" {
1334                continue;
1335            }
1336            let mut fields = vec![];
1337            for row in data.members() {
1338                let value = row[field].clone();
1339                let id = row["id"].clone();
1340                ids.push(id.clone());
1341                if value.is_string() {
1342                    fields.push(format!(
1343                        "WHEN '{}' THEN '{}'",
1344                        id,
1345                        value.to_string().replace("'", "''")
1346                    ));
1347                } else if value.is_array() || value.is_object() {
1348                    if self.params.json[field].is_empty() {
1349                        fields.push(format!("WHEN '{}' THEN '{}'", id, value));
1350                    } else {
1351                        let json = value.to_string();
1352                        let json = json.replace("'", "''");
1353                        fields.push(format!("WHEN '{}' THEN '{}'", id, json));
1354                    }
1355                    continue;
1356                } else if value.is_number() || value.is_boolean() || value.is_null() {
1357                    fields.push(format!("WHEN '{}' THEN {}", id, value));
1358                } else {
1359                    fields.push(format!("WHEN '{}' THEN '{}'", id, value));
1360                }
1361            }
1362            values.push(format!("`{}` = CASE id {} END", field, fields.join(" ")))
1363        }
1364
1365        self.where_and("id", "in", ids.into());
1366        for (field, value) in self.params.inc_dec.entries() {
1367            values.push(format!("{} = {}", field, value.to_string().clone()));
1368        }
1369
1370        let values = values.join(",");
1371        let sql = format!(
1372            "UPDATE {} SET {} {} {};",
1373            self.params.table.clone(),
1374            values,
1375            self.params.where_sql(),
1376            self.params.page_limit_sql()
1377        );
1378        if self.params.sql {
1379            return JsonValue::from(sql.clone());
1380        }
1381        let (state, data) = self.execute(sql);
1382        if state {
1383            data
1384        } else {
1385            error!("{:?}", data);
1386            JsonValue::from(0)
1387        }
1388    }
1389    fn delete(&mut self) -> JsonValue {
1390        let sql = format!(
1391            "delete FROM `{}` {};",
1392            self.params.table.clone(),
1393            self.params.where_sql()
1394        );
1395        if self.params.sql {
1396            return JsonValue::from(sql.clone());
1397        }
1398        let (state, data) = self.execute(sql);
1399        match state {
1400            true => data,
1401            false => {
1402                error!("delete 失败>>>{:?}", data);
1403                JsonValue::from(0)
1404            }
1405        }
1406    }
1407
1408    fn transaction(&mut self) -> bool {
1409        let thread_id = format!("{:?}", thread::current().id());
1410        let mut transaction = *TR_COUNT.lock().unwrap().get(&*thread_id.clone()).unwrap_or(&0);
1411        if transaction > 0 {
1412            transaction += 1;
1413            TR_COUNT.lock().unwrap().insert(thread_id.clone(), transaction);
1414            return true;
1415        }
1416
1417        loop {
1418            let mut t = TR_COUNT.lock().unwrap();
1419            if t.is_empty() {
1420                t.insert(thread_id.clone(), 1);
1421                break;
1422            }
1423            drop(t);
1424            thread::yield_now();
1425        }
1426
1427        let flags = OpenFlags::new().with_read_write().with_no_mutex();
1428        let db = match Connect::open_thread_safe_with_flags(
1429            self.connection.clone().get_dsn().as_str(),
1430            flags,
1431        ) {
1432            Ok(e) => Arc::new(e),
1433            Err(_) => {
1434                return false;
1435            }
1436        };
1437        TR.lock().unwrap().insert(thread_id.clone(), db);
1438        let (state, data) = self.query("BEGIN".to_string());
1439        if state {
1440            true
1441        } else {
1442            error!("{} 启动事务失败: {}", thread_id, data);
1443            TR.lock().unwrap().remove(&thread_id.clone());
1444            TR_COUNT.lock().unwrap().remove(&thread_id.clone());
1445            false
1446        }
1447    }
1448
1449    fn commit(&mut self) -> bool {
1450        let thread_id = format!("{:?}", thread::current().id());
1451
1452        let mut transaction = *TR_COUNT.lock().unwrap().get(&*thread_id.clone()).unwrap_or(&0);
1453        if transaction > 1 {
1454            transaction -= 1;
1455            TR_COUNT.lock().unwrap().insert(thread_id.clone(), transaction);
1456            return true;
1457        }
1458        let sql = "COMMIT";
1459        let (state, _) = self.query(sql.to_string());
1460        TR_COUNT.lock().unwrap().remove(&*thread_id.clone());
1461        TR.lock().unwrap().remove(&*thread_id.clone());
1462
1463        if state {
1464            true
1465        } else {
1466            error!("{} 提交事务失败", thread_id);
1467            false
1468        }
1469    }
1470
1471    fn rollback(&mut self) -> bool {
1472        let thread_id = format!("{:?}", thread::current().id());
1473        let sql = "ROLLBACK";
1474
1475        let mut t = *TR_COUNT.lock().unwrap().get(&thread_id).unwrap();
1476        if t > 1 {
1477            t -= 1;
1478            TR_COUNT.lock().unwrap().insert(thread_id.clone(), t);
1479            return true;
1480        }
1481        let (state, _) = self.query(sql.to_string());
1482        TR_COUNT.lock().unwrap().remove(&*thread_id.clone());
1483        TR.lock().unwrap().remove(&*thread_id.clone());
1484
1485        if state {
1486            true
1487        } else {
1488            error!("回滚失败: {}", thread_id);
1489            false
1490        }
1491    }
1492
1493    fn sql(&mut self, sql: &str) -> Result<JsonValue, String> {
1494        let (state, data) = self.query(sql.to_string());
1495        match state {
1496            true => Ok(data),
1497            false => Err(data.to_string()),
1498        }
1499    }
1500
1501    fn sql_execute(&mut self, sql: &str) -> Result<JsonValue, String> {
1502        let (state, data) = self.execute(sql.to_string());
1503        match state {
1504            true => Ok(data),
1505            false => Err(data.to_string()),
1506        }
1507    }
1508
1509    fn inc(&mut self, field: &str, num: f64) -> &mut Self {
1510        self.params.inc_dec[field] = format!("`{}` + {}", field, num).into();
1511        self
1512    }
1513
1514    fn dec(&mut self, field: &str, num: f64) -> &mut Self {
1515        self.params.inc_dec[field] = format!("`{}` - {}", field, num).into();
1516        self
1517    }
1518
1519    fn buildsql(&mut self) -> String {
1520        self.fetch_sql();
1521        let sql = self.select().to_string();
1522        format!("( {} ) `{}`", sql, self.params.table)
1523    }
1524
1525    fn join(&mut self, table: &str, main_fields: &str, right_fields: &str) -> &mut Self {
1526        let main_fields = if main_fields.is_empty() {
1527            "id"
1528        } else {
1529            main_fields
1530        };
1531        let right_fields = if right_fields.is_empty() {
1532            self.params.table.clone()
1533        } else {
1534            right_fields.to_string().clone()
1535        };
1536        self.params.join_table = table.to_string();
1537        self.params.join.push(format!(
1538            " LEFT JOIN {} ON {}.{} = {}.{}",
1539            table, self.params.table, main_fields, table, right_fields
1540        ));
1541        self
1542    }
1543
1544    fn join_inner(&mut self, table: &str, main_fields: &str, second_fields: &str) -> &mut Self {
1545        let main_fields = if main_fields.is_empty() {
1546            "id"
1547        } else {
1548            main_fields
1549        };
1550        let second_fields = if second_fields.is_empty() {
1551            self.params.table.clone()
1552        } else {
1553            second_fields.to_string().clone()
1554        };
1555        let sec_table_name = format!("{}{}", table, "_2");
1556        let second_table = format!("{} {}", table, sec_table_name.clone());
1557        self.params.join_table = sec_table_name.clone();
1558        self.params.join.push(format!(
1559            " INNER JOIN {} ON {}.{} = {}.{}",
1560            second_table, self.params.table, main_fields, sec_table_name, second_fields
1561        ));
1562        self
1563    }
1564}