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!("{thread_id} 获取数据库锁失败: {e}\r\nSQL: {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!("{thread_id} 获取数据库锁失败: {e}\r\nSQL: {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!("{thread_id} 查询非事务: Err: {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!("{thread_id} 获取数据库锁失败: {e}\r\nSQL: {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!("{thread_id} 获取数据库锁失败: {e}\r\nSQL: {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!("{sql} {row},\r\n");
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!("{sql} {row},\r\n");
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='{name}'"
682        );
683        let (state, data) = self.query(sql);
684        if state {
685            if data[0]["count"].as_i64().unwrap() > 0 {
686                return true;
687            }
688            false
689        } else {
690            false
691        }
692    }
693
694    fn table(&mut self, name: &str) -> &mut Sqlite {
695        self.params = Params::default(self.connection.mode.str().as_str());
696        self.params.table = format!("{}{}", self.connection.prefix, name);
697        self.params.join_table = self.params.table.clone();
698        self
699    }
700    fn change_table(&mut self, name: &str) -> &mut Self {
701        self.params.join_table = name.to_string();
702        self
703    }
704    fn autoinc(&mut self) -> &mut Self {
705        self.params.autoinc = true;
706        self
707    }
708
709    fn fetch_sql(&mut self) -> &mut Self {
710        self.params.sql = true;
711        self
712    }
713
714    fn order(&mut self, field: &str, by: bool) -> &mut Self {
715        self.params.order[field] = {
716            if by {
717                "DESC"
718            } else {
719                "ASC"
720            }
721        }.into();
722        self
723    }
724
725    fn group(&mut self, field: &str) -> &mut Self {
726        let fields: Vec<&str> = field.split(",").collect();
727        for field in fields.iter() {
728            let fields = field.to_string();
729            self.params.group[fields.as_str()] = fields.clone().into();
730            self.params.fields[fields.as_str()] = fields.clone().into();
731        }
732        self
733    }
734
735    fn distinct(&mut self) -> &mut Self {
736        self.params.distinct = true;
737        self
738    }
739    fn json(&mut self, field: &str) -> &mut Self {
740        let list: Vec<&str> = field.split(",").collect();
741        for item in list.iter() {
742            self.params.json[item.to_string().as_str()] = item.to_string().into();
743        }
744        self
745    }
746
747    fn location(&mut self, field: &str) -> &mut Self {
748        let list: Vec<&str> = field.split(",").collect();
749        for item in list.iter() {
750            self.params.location[item.to_string().as_str()] = item.to_string().into();
751        }
752        self
753    }
754
755    fn field(&mut self, field: &str) -> &mut Self {
756        let list: Vec<&str> = field.split(",").collect();
757        let join_table = if self.params.join_table.is_empty() {
758            self.params.table.clone()
759        } else {
760            self.params.join_table.clone()
761        };
762        for item in list.iter() {
763            let item = item.to_string();
764            if item.contains(" as ") {
765                let text = item.split(" as ").collect::<Vec<&str>>().clone();
766                self.params.fields[item] = format!("{}.`{}` as `{}`", join_table, text[0], text[1]).into();
767            } else {
768                self.params.fields[item] = format!("{join_table}.`{item}`").into();
769            }
770        }
771        self
772    }
773    fn hidden(&mut self, name: &str) -> &mut Self {
774        let hidden: Vec<&str> = name.split(",").collect();
775        let sql = format!("PRAGMA table_info({})", self.params.table);
776        let (_, data) = self.query(sql);
777        for item in data.members() {
778            let name = item["name"].as_str().unwrap();
779            if !hidden.contains(&name) {
780                self.params.fields[name] = name.into();
781            }
782        }
783        self
784    }
785
786    fn where_and(&mut self, field: &str, compare: &str, mut value: JsonValue) -> &mut Self {
787        let join_table = if self.params.join_table.is_empty() {
788            self.params.table.clone()
789        } else {
790            self.params.join_table.clone()
791        };
792
793        if value.is_boolean() {
794            if value.as_bool().unwrap() {
795                value = 1.into();
796            } else {
797                value = 0.into();
798            }
799        }
800
801        match compare {
802            "between" => {
803                self.params.where_and.push(format!(
804                    "{}.`{}` between '{}' AND '{}'",
805                    join_table, field, value[0], value[1]
806                ));
807            }
808            "set" => {
809                let list: Vec<&str> = value.as_str().unwrap().split(",").collect();
810                let mut wheredata = vec![];
811                for item in list.iter() {
812                    wheredata.push(format!("{join_table}.`{field}` like '%{item}%'"));
813                }
814                self.params.where_and.push(format!("({})", wheredata.join(" or ")));
815            }
816            "notin" => {
817                let mut text = String::new();
818                for item in value.members() {
819                    text = format!("{text},'{item}'");
820                }
821                text = text.trim_start_matches(",").into();
822                self.params.where_and.push(format!("{join_table}.`{field}` not in ({text})"));
823            }
824            "in" => {
825                let mut text = String::new();
826                if value.is_array() {
827                    for item in value.members() {
828                        text = format!("{text},'{item}'");
829                    }
830                } else {
831                    let value = value.to_string();
832                    let value: Vec<&str> = value.split(",").collect();
833                    for item in value.iter() {
834                        text = format!("{text},'{item}'");
835                    }
836                }
837                text = text.trim_start_matches(",").into();
838
839                self.params.where_and.push(format!("{join_table}.`{field}` {compare} ({text})"));
840            }
841            "=" => {
842                if value.is_null() {
843                    self.params.where_and.push(format!("{}.`{}` {} {}", join_table, field, "IS", value));
844                } else {
845                    self.params.where_and.push(format!(
846                        "{join_table}.`{field}` {compare} '{value}'"
847                    ));
848                }
849            }
850            _ => {
851                if value.is_null() {
852                    self.params.where_and.push(format!("{join_table}.`{field}` {compare} {value}"));
853                } else {
854                    self.params.where_and.push(format!(
855                        "{join_table}.`{field}` {compare} '{value}'"
856                    ));
857                }
858            }
859        }
860        self
861    }
862    fn where_or(&mut self, field: &str, compare: &str, mut value: JsonValue) -> &mut Self {
863        let join_table = if self.params.join_table.is_empty() {
864            self.params.table.clone()
865        } else {
866            self.params.join_table.clone()
867        };
868
869        if value.is_boolean() {
870            if value.as_bool().unwrap() {
871                value = 1.into();
872            } else {
873                value = 0.into();
874            }
875        }
876        match compare {
877            "between" => {
878                self.params.where_or.push(format!(
879                    "{}.`{}` between '{}' AND '{}'",
880                    join_table, field, value[0], value[1]
881                ));
882            }
883            "set" => {
884                let tt = value.to_string().replace(",", "%");
885                self.params.where_or.push(format!("{join_table}.`{field}` like '%{tt}%'"));
886            }
887            "notin" => {
888                let mut text = String::new();
889                for item in value.members() {
890                    text = format!("{text},'{item}'");
891                }
892                text = text.trim_start_matches(",").into();
893                self.params.where_or.push(format!("{join_table}.`{field}` not in ({text})"));
894            }
895            "in" => {
896                let mut text = String::new();
897                if value.is_array() {
898                    for item in value.members() {
899                        text = format!("{text},'{item}'");
900                    }
901                } else {
902                    let value = value.as_str().unwrap();
903                    let value: Vec<&str> = value.split(",").collect();
904                    for item in value.iter() {
905                        text = format!("{text},'{item}'");
906                    }
907                }
908                text = text.trim_start_matches(",").into();
909                self.params.where_or.push(format!("{join_table}.`{field}` {compare} ({text})"));
910            }
911            _ => {
912                self.params.where_or.push(format!(
913                    "{join_table}.`{field}` {compare} '{value}'"
914                ));
915            }
916        }
917        self
918    }
919    fn where_column(&mut self, field_a: &str, compare: &str, field_b: &str) -> &mut Self {
920        self.params.where_column = format!(
921            "{}.`{}` {} {}.`{}`",
922            self.params.table, field_a, compare, self.params.table, field_b
923        );
924        self
925    }
926
927    fn update_column(&mut self, field_a: &str, compare: &str) -> &mut Self {
928        self.params.update_column.push(format!("{field_a} = {compare}"));
929        self
930    }
931
932    fn page(&mut self, page: i32, limit: i32) -> &mut Self {
933        self.params.page = page;
934        self.params.limit = limit;
935        self
936    }
937
938    fn column(&mut self, field: &str) -> JsonValue {
939        self.field(field);
940        self.group(field);
941        let sql = self.params.select_sql();
942        if self.params.sql {
943            return JsonValue::from(sql.clone());
944        }
945        self.table_info(self.params.table.clone().as_str());
946        let (state, data) = self.query(sql);
947        if state {
948            let mut list = array![];
949            for item in data.members() {
950                if self.params.json[field].is_empty() {
951                    list.push(item[field].clone()).unwrap();
952                } else {
953                    let data = json::parse(item[field].as_str().unwrap()).unwrap_or(array![]);
954                    list.push(data).unwrap();
955                }
956            }
957            list
958        } else {
959            array![]
960        }
961    }
962
963    fn count(&mut self) -> JsonValue {
964        self.params.fields["count"] = "count(*) as count".to_string().into();
965        let sql = self.params.select_sql();
966        if self.params.sql {
967            return JsonValue::from(sql.clone());
968        }
969        let (state, data) = self.query(sql);
970        match state {
971            true => data[0]["count"].clone(),
972            false => JsonValue::from(0),
973        }
974    }
975
976    fn max(&mut self, field: &str) -> JsonValue {
977        self.params.fields[field] = format!("max({field}) as {field}").into();
978        let sql = self.params.select_sql();
979        if self.params.sql {
980            return JsonValue::from(sql.clone());
981        }
982        let (state, data) = self.query(sql);
983        if state {
984            if data.len() > 1 {
985                return data;
986            }
987            data[0][field].clone()
988        } else {
989            JsonValue::from(0.0)
990        }
991    }
992
993    fn min(&mut self, field: &str) -> JsonValue {
994        self.params.fields[field] = format!("min({field}) as {field}").into();
995        let sql = self.params.select_sql();
996        let (state, data) = self.query(sql);
997        if state {
998            if data.len() > 1 {
999                return data;
1000            }
1001            data[0][field].clone()
1002        } else {
1003            JsonValue::from(0.0)
1004        }
1005    }
1006
1007    fn sum(&mut self, field: &str) -> JsonValue {
1008        self.params.fields[field] = format!("sum({field}) as {field}").into();
1009        let sql = self.params.select_sql();
1010        if self.params.sql {
1011            return JsonValue::from(sql.clone());
1012        }
1013        let (state, data) = self.query(sql);
1014        match state {
1015            true => {
1016                if data.len() > 1 {
1017                    return data;
1018                }
1019                if self.params.fields.len() > 1 {
1020                    return data[0].clone();
1021                }
1022                data[0][field].clone()
1023            }
1024            false => JsonValue::from(0),
1025        }
1026    }
1027    fn avg(&mut self, field: &str) -> JsonValue {
1028        self.params.fields[field] = format!("avg({field}) as {field}").into();
1029        let sql = self.params.select_sql();
1030        if self.params.sql {
1031            return JsonValue::from(sql.clone());
1032        }
1033        let (state, data) = self.query(sql);
1034        if state {
1035            if data.len() > 1 {
1036                return data;
1037            }
1038            data[0][field].clone()
1039        } else {
1040            JsonValue::from(0)
1041        }
1042    }
1043    fn select(&mut self) -> JsonValue {
1044        let sql = self.params.select_sql();
1045        if self.params.sql {
1046            return JsonValue::from(sql.clone());
1047        }
1048        self.table_info(self.params.table.clone().as_str());
1049        let (state, mut data) = self.query(sql.clone());
1050        match state {
1051            true => {
1052                for (field, _) in self.params.json.entries() {
1053                    for item in data.members_mut() {
1054                        if !item[field].is_empty() {
1055                            let json = item[field].to_string();
1056                            item[field] = match json::parse(&json) {
1057                                Ok(e) => e,
1058                                Err(_) => JsonValue::from(json),
1059                            };
1060                        }
1061                    }
1062                }
1063                data.clone()
1064            }
1065            false => {
1066                error!("{data:?}");
1067                array![]
1068            }
1069        }
1070    }
1071    fn find(&mut self) -> JsonValue {
1072        self.params.page = 1;
1073        self.params.limit = 1;
1074        let sql = self.params.select_sql();
1075        if self.params.sql {
1076            return JsonValue::from(sql.clone());
1077        }
1078
1079        self.table_info(self.params.table.clone().as_str());
1080        let (state, mut data) = self.query(sql.clone());
1081        match state {
1082            true => {
1083                if data.is_empty() {
1084                    return object! {};
1085                }
1086                for (field, _) in self.params.json.entries() {
1087                    if !data[0][field].is_empty() {
1088                        let json = data[0][field].to_string();
1089                        let json = json::parse(&json).unwrap_or(array![]);
1090                        data[0][field] = json;
1091                    } else {
1092                        data[0][field] = array![];
1093                    }
1094                }
1095                data[0].clone()
1096            }
1097            false => {
1098                error!("{data:?}");
1099                object! {}
1100            }
1101        }
1102    }
1103
1104    fn value(&mut self, field: &str) -> JsonValue {
1105        self.params.fields = object! {};
1106        self.params.fields[field] = format!("{}.`{}`", self.params.table, field).into();
1107        self.params.page = 1;
1108        self.params.limit = 1;
1109        let sql = self.params.select_sql();
1110        if self.params.sql {
1111            return JsonValue::from(sql.clone());
1112        }
1113        self.table_info(self.params.table.clone().as_str());
1114        let (state, mut data) = self.query(sql.clone());
1115        match state {
1116            true => {
1117                for (field, _) in self.params.json.entries() {
1118                    if !data[0][field].is_empty() {
1119                        let json = data[0][field].to_string();
1120                        let json = json::parse(&json).unwrap_or(array![]);
1121                        data[0][field] = json;
1122                    } else {
1123                        data[0][field] = array![];
1124                    }
1125                }
1126                data[0][field].clone()
1127            }
1128            false => {
1129                if self.connection.debug {
1130                    info!("{data:?}");
1131                }
1132                JsonValue::Null
1133            }
1134        }
1135    }
1136
1137    fn insert(&mut self, mut data: JsonValue) -> JsonValue {
1138        let mut fields = vec![];
1139        let mut values = vec![];
1140
1141        if !self.params.autoinc && data["id"].is_empty() {
1142            data["id"] = format!("{:X}", Local::now().timestamp_nanos_opt().unwrap()).into();
1143        }
1144        for (field, value) in data.entries() {
1145            fields.push(format!("`{field}`"));
1146
1147            if value.is_string() {
1148                if value.to_string().contains("'") {
1149                    values.push(format!("\"{}\"", value.to_string().replace("'", "''")));
1150                    continue;
1151                } else if value.to_string().contains('"') {
1152                    values.push(format!("'{value}'"));
1153                    continue;
1154                } else {
1155                    values.push(format!("\"{value}\""));
1156                    continue;
1157                }
1158            } else if value.is_array() || value.is_object() {
1159                if self.params.json[field].is_empty() {
1160                    values.push(format!("'{value}'"));
1161                } else {
1162                    let json = value.to_string();
1163                    let json = json.replace("'", "''");
1164                    values.push(format!("'{json}'"));
1165                }
1166                continue;
1167            } else if value.is_number() || value.is_boolean() || value.is_null() {
1168                values.push(format!("{value}"));
1169                continue;
1170            } else {
1171                values.push(format!("'{value}'"));
1172                continue;
1173            }
1174        }
1175        let fields = fields.join(",");
1176        let values = values.join(",");
1177
1178        let sql = format!(
1179            "INSERT INTO `{}` ({}) VALUES ({});",
1180            self.params.table, fields, values
1181        );
1182        if self.params.sql {
1183            return JsonValue::from(sql.clone());
1184        }
1185        let (state, ids) = self.execute(sql);
1186        match state {
1187            true => {
1188                if self.params.autoinc {
1189                    let (state, ids) = self.query(format!("select max(id) as id from {}", self.params.table));
1190                    return match state {
1191                        true => ids[0]["id"].clone(),
1192                        false => {
1193                            error!("{ids}");
1194                            JsonValue::from("")
1195                        }
1196                    };
1197                }
1198                data["id"].clone()
1199            }
1200            false => {
1201                error!("{ids}");
1202                JsonValue::from("")
1203            }
1204        }
1205    }
1206    fn insert_all(&mut self, mut data: JsonValue) -> JsonValue {
1207        let mut fields = String::new();
1208
1209        if !self.params.autoinc && data[0]["id"].is_empty() {
1210            data[0]["id"] = "".into();
1211        }
1212        for (field, _) in data[0].entries() {
1213            fields = format!("{fields},`{field}`");
1214        }
1215        fields = fields.trim_start_matches(",").parse().unwrap();
1216
1217        let core_count = num_cpus::get();
1218        let mut p = pools::Pool::new(core_count * 4);
1219        let autoinc = self.params.autoinc;
1220        for list in data.members() {
1221            let mut item = list.clone();
1222            p.execute(move |pcindex| {
1223                if !autoinc && item["id"].is_empty() {
1224                    let id = format!(
1225                        "{:X}{:X}",
1226                        Local::now().timestamp_nanos_opt().unwrap(),
1227                        pcindex
1228                    );
1229                    item["id"] = id.into();
1230                }
1231                let mut values = "".to_string();
1232                for (_, value) in item.entries() {
1233                    if value.is_string() {
1234                        values = format!("{},'{}'", values, value.to_string().replace("'", "''"));
1235                    } else if value.is_number() || value.is_boolean() {
1236                        values = format!("{values},{value}");
1237                    } else {
1238                        values = format!("{},'{}'", values, value.to_string().replace("'", "''"));
1239                    }
1240                }
1241                values = format!("({})", values.trim_start_matches(","));
1242                array![item["id"].clone(), values]
1243            });
1244        }
1245        let (ids_list, mut values) = p.insert_all();
1246
1247        values = values.trim_start_matches(",").parse().unwrap();
1248
1249        let sql = format!(
1250            "INSERT INTO {} ({}) VALUES {};",
1251            self.params.table, fields, values
1252        );
1253        if self.params.sql {
1254            return JsonValue::from(sql.clone());
1255        }
1256        let (state, data) = self.execute(sql.clone());
1257        match state {
1258            true => {
1259                if self.params.autoinc {
1260                    let (state, ids) = self.query(format!(
1261                        "SELECT id FROM {} GROUP BY id ORDER BY id DESC LIMIT {} OFFSET 0",
1262                        self.params.table,
1263                        ids_list.len()
1264                    ));
1265                    return match state {
1266                        true => {
1267                            let mut idlist = array![];
1268                            for item in ids.members() {
1269                                idlist.push(item["id"].clone()).unwrap();
1270                            }
1271                            idlist
1272                        }
1273                        false => {
1274                            error!("批量添加失败: {ids:?} {sql}");
1275                            array![]
1276                        }
1277                    };
1278                }
1279                JsonValue::from(ids_list)
1280            }
1281            false => {
1282                error!("批量添加失败: {data:?} {sql}");
1283                array![]
1284            }
1285        }
1286    }
1287
1288    fn update(&mut self, data: JsonValue) -> JsonValue {
1289        let mut values = vec![];
1290
1291        for (field, value) in data.entries() {
1292            if value.is_string() {
1293                values.push(format!(
1294                    "`{}` = '{}'",
1295                    field,
1296                    value.to_string().replace("'", "''")
1297                ));
1298            } else if value.is_array() || value.is_object() {
1299                if self.params.json[field].is_empty() {
1300                    values.push(format!("`{field}` = '{value}'"));
1301                } else {
1302                    let json = value.to_string();
1303                    let json = json.replace("'", "''");
1304                    values.push(format!("`{field}` = '{json}'"));
1305                }
1306                continue;
1307            } else if value.is_number() || value.is_boolean() || value.is_null() {
1308                values.push(format!("`{field}` = {value} "));
1309            } else {
1310                values.push(format!("`{field}` = '{value}' "));
1311            }
1312        }
1313
1314        for (field, value) in self.params.inc_dec.entries() {
1315            values.push(format!("{} = {}", field, value.to_string().clone()));
1316        }
1317
1318        let values = values.join(",");
1319        let sql = format!(
1320            "UPDATE `{}` SET {} {} {};",
1321            self.params.table.clone(),
1322            values,
1323            self.params.where_sql(),
1324            self.params.page_limit_sql()
1325        );
1326        if self.params.sql {
1327            return JsonValue::from(sql.clone());
1328        }
1329        let (state, data) = self.execute(sql);
1330        if state {
1331            data
1332        } else {
1333            error!("{data}");
1334            JsonValue::from(0)
1335        }
1336    }
1337
1338    fn update_all(&mut self, data: JsonValue) -> JsonValue {
1339        let mut values = vec![];
1340        let mut ids = vec![];
1341        for (field, _) in data[0].entries() {
1342            if field == "id" {
1343                continue;
1344            }
1345            let mut fields = vec![];
1346            for row in data.members() {
1347                let value = row[field].clone();
1348                let id = row["id"].clone();
1349                ids.push(id.clone());
1350                if value.is_string() {
1351                    fields.push(format!(
1352                        "WHEN '{}' THEN '{}'",
1353                        id,
1354                        value.to_string().replace("'", "''")
1355                    ));
1356                } else if value.is_array() || value.is_object() {
1357                    if self.params.json[field].is_empty() {
1358                        fields.push(format!("WHEN '{id}' THEN '{value}'"));
1359                    } else {
1360                        let json = value.to_string();
1361                        let json = json.replace("'", "''");
1362                        fields.push(format!("WHEN '{id}' THEN '{json}'"));
1363                    }
1364                    continue;
1365                } else if value.is_number() || value.is_boolean() || value.is_null() {
1366                    fields.push(format!("WHEN '{id}' THEN {value}"));
1367                } else {
1368                    fields.push(format!("WHEN '{id}' THEN '{value}'"));
1369                }
1370            }
1371            values.push(format!("`{}` = CASE id {} END", field, fields.join(" ")))
1372        }
1373
1374        self.where_and("id", "in", ids.into());
1375        for (field, value) in self.params.inc_dec.entries() {
1376            values.push(format!("{} = {}", field, value.to_string().clone()));
1377        }
1378
1379        let values = values.join(",");
1380        let sql = format!(
1381            "UPDATE {} SET {} {} {};",
1382            self.params.table.clone(),
1383            values,
1384            self.params.where_sql(),
1385            self.params.page_limit_sql()
1386        );
1387        if self.params.sql {
1388            return JsonValue::from(sql.clone());
1389        }
1390        let (state, data) = self.execute(sql);
1391        if state {
1392            data
1393        } else {
1394            error!("{data:?}");
1395            JsonValue::from(0)
1396        }
1397    }
1398    fn delete(&mut self) -> JsonValue {
1399        let sql = format!(
1400            "delete FROM `{}` {};",
1401            self.params.table.clone(),
1402            self.params.where_sql()
1403        );
1404        if self.params.sql {
1405            return JsonValue::from(sql.clone());
1406        }
1407        let (state, data) = self.execute(sql);
1408        match state {
1409            true => data,
1410            false => {
1411                error!("delete 失败>>>{data:?}");
1412                JsonValue::from(0)
1413            }
1414        }
1415    }
1416
1417    fn transaction(&mut self) -> bool {
1418        let thread_id = format!("{:?}", thread::current().id());
1419        let mut transaction = *TR_COUNT.lock().unwrap().get(&*thread_id.clone()).unwrap_or(&0);
1420        if transaction > 0 {
1421            transaction += 1;
1422            TR_COUNT.lock().unwrap().insert(thread_id.clone(), transaction);
1423            return true;
1424        }
1425
1426        loop {
1427            let mut t = TR_COUNT.lock().unwrap();
1428            if t.is_empty() {
1429                t.insert(thread_id.clone(), 1);
1430                break;
1431            }
1432            drop(t);
1433            thread::yield_now();
1434        }
1435
1436        let flags = OpenFlags::new().with_read_write().with_no_mutex();
1437        let db = match Connect::open_thread_safe_with_flags(
1438            self.connection.clone().get_dsn().as_str(),
1439            flags,
1440        ) {
1441            Ok(e) => Arc::new(e),
1442            Err(_) => {
1443                return false;
1444            }
1445        };
1446        TR.lock().unwrap().insert(thread_id.clone(), db);
1447        let (state, data) = self.query("BEGIN".to_string());
1448        if state {
1449            true
1450        } else {
1451            error!("{thread_id} 启动事务失败: {data}");
1452            TR.lock().unwrap().remove(&thread_id.clone());
1453            TR_COUNT.lock().unwrap().remove(&thread_id.clone());
1454            false
1455        }
1456    }
1457
1458    fn commit(&mut self) -> bool {
1459        let thread_id = format!("{:?}", thread::current().id());
1460
1461        let mut transaction = *TR_COUNT.lock().unwrap().get(&*thread_id.clone()).unwrap_or(&0);
1462        if transaction > 1 {
1463            transaction -= 1;
1464            TR_COUNT.lock().unwrap().insert(thread_id.clone(), transaction);
1465            return true;
1466        }
1467        let sql = "COMMIT";
1468        let (state, _) = self.query(sql.to_string());
1469        TR_COUNT.lock().unwrap().remove(&*thread_id.clone());
1470        TR.lock().unwrap().remove(&*thread_id.clone());
1471
1472        if state {
1473            true
1474        } else {
1475            error!("{thread_id} 提交事务失败");
1476            false
1477        }
1478    }
1479
1480    fn rollback(&mut self) -> bool {
1481        let thread_id = format!("{:?}", thread::current().id());
1482        let sql = "ROLLBACK";
1483
1484        let mut t = *TR_COUNT.lock().unwrap().get(&thread_id).unwrap();
1485        if t > 1 {
1486            t -= 1;
1487            TR_COUNT.lock().unwrap().insert(thread_id.clone(), t);
1488            return true;
1489        }
1490        let (state, _) = self.query(sql.to_string());
1491        TR_COUNT.lock().unwrap().remove(&*thread_id.clone());
1492        TR.lock().unwrap().remove(&*thread_id.clone());
1493
1494        if state {
1495            true
1496        } else {
1497            error!("回滚失败: {thread_id}");
1498            false
1499        }
1500    }
1501
1502    fn sql(&mut self, sql: &str) -> Result<JsonValue, String> {
1503        let (state, data) = self.query(sql.to_string());
1504        match state {
1505            true => Ok(data),
1506            false => Err(data.to_string()),
1507        }
1508    }
1509
1510    fn sql_execute(&mut self, sql: &str) -> Result<JsonValue, String> {
1511        let (state, data) = self.execute(sql.to_string());
1512        match state {
1513            true => Ok(data),
1514            false => Err(data.to_string()),
1515        }
1516    }
1517
1518    fn inc(&mut self, field: &str, num: f64) -> &mut Self {
1519        self.params.inc_dec[field] = format!("`{field}` + {num}").into();
1520        self
1521    }
1522
1523    fn dec(&mut self, field: &str, num: f64) -> &mut Self {
1524        self.params.inc_dec[field] = format!("`{field}` - {num}").into();
1525        self
1526    }
1527
1528    fn buildsql(&mut self) -> String {
1529        self.fetch_sql();
1530        let sql = self.select().to_string();
1531        format!("( {} ) `{}`", sql, self.params.table)
1532    }
1533
1534    fn join_fields(&mut self, fields: Vec<&str>) -> &mut Self {
1535        for field in fields {
1536            self.params.fields[field] = format!("{field} as {}", field.replace(".", "_")).into();
1537        }
1538        self
1539    }
1540
1541    fn join(&mut self, main_table: &str, main_fields: &str, right_table: &str, right_fields: &str) -> &mut Self {
1542        let main_table = if main_table.is_empty() {
1543            self.params.table.clone()
1544        } else {
1545            main_table.to_string()
1546        };
1547        self.params.join_table = right_table.to_string();
1548        self.params.join.push(format!(" LEFT JOIN {right_table} ON {main_table}.{main_fields} = {right_table}.{right_fields} "));
1549        self
1550    }
1551
1552    fn join_inner(&mut self, table: &str, main_fields: &str, second_fields: &str) -> &mut Self {
1553        let main_fields = if main_fields.is_empty() {
1554            "id"
1555        } else {
1556            main_fields
1557        };
1558        let second_fields = if second_fields.is_empty() {
1559            self.params.table.clone()
1560        } else {
1561            second_fields.to_string().clone()
1562        };
1563        let sec_table_name = format!("{}{}", table, "_2");
1564        let second_table = format!("{} {}", table, sec_table_name.clone());
1565        self.params.join_table = sec_table_name.clone();
1566        self.params.join.push(format!(
1567            " INNER JOIN {} ON {}.{} = {}.{}",
1568            second_table, self.params.table, main_fields, sec_table_name, second_fields
1569        ));
1570        self
1571    }
1572}