df-helper 0.2.26

df helper tools db cache
Documentation
use std::process::exit;
use json::{JsonValue, object};
use sqlx::{Connection, MssqlConnection, Row};


pub struct Mssql {
    conn: MssqlConnection,
    table: String,
    database: String,
    pub fields: JsonValue,
    transaction: u32,
}

impl Mssql {
    /// 链接
    #[actix_rt::main]
    pub async fn connect(dsn: String, database: String) -> Self {
        let pool = MssqlConnection::connect(&dsn).await;
        match pool {
            Ok(e) => {
                Self {
                    conn: e,
                    fields: object! {},
                    table: String::new(),
                    database,
                    transaction: 0,
                }
            }
            Err(_e) => {
                println!("数据库连接错误:{:?}", _e);
                exit(500)
            }
        }
    }

    /// 获取指定表的字段内容
    pub fn fieldsinfo(&mut self, table: String) -> &mut Self {
        self.table = table.clone();
        let sql = format!("select * from information_schema.COLUMNS where TABLE_SCHEMA='{}' and table_name = '{}'", self.database, table);
        let data = object! {};

        // sqlx::query(sql.as_str()).try_map(|row: MssqlRow| {
        //     row.try_get::<i32, _>(0)
        // }).fetch_one(&mut self.conn);

        // self.conn.query_iter(sql).unwrap().for_each(|row| {
        //     let r = row.unwrap();
        //     let mut rows = object! {};
        //     let name: String = r.get("COLUMN_NAME").unwrap();
        //     let name = name.as_str().clone();
        //     let comment: String = r.get("COLUMN_COMMENT").unwrap();
        //     let sttr = tools::string::split(comment.clone(), "|");
        //     let title = sttr[0].as_str().unwrap();
        //     let mode = sttr[1].as_str().unwrap_or("string");
        //     let length: Option<i32> = r.get("CHARACTER_MAXIMUM_LENGTH").unwrap();
        //     let require = sttr[2].as_str().unwrap_or("").parse::<bool>().unwrap_or(false);
        //     match mode {
        //         "key" => {
        //             let auto = sttr[2].as_bool().unwrap_or(true);
        //             rows = fields::field::Key::field(name.clone(), title.clone(), length.unwrap(), auto.clone()).info();
        //         }
        //         "pass" => {
        //             let def: String = r.get("COLUMN_DEFAULT").unwrap_or("".to_string());
        //             let def = def.as_str().clone();
        //             rows = fields::field::Str::pass(require.clone(), name.clone(), title.clone(), length.unwrap(), def.clone()).info();
        //         }
        //         "string" => {
        //             let def: String = r.get("COLUMN_DEFAULT").unwrap_or("".to_string());
        //             let def = def.as_str().clone();
        //             rows = fields::field::Str::string(require.clone(), name.clone(), title.clone(), length.unwrap_or(20), def.clone()).info();
        //         }
        //         "datetime" => {
        //             let def = sttr[3].as_str().unwrap_or("");
        //             rows = fields::field::Date::datetime(require.clone(), name.clone(), title.clone(), def.clone()).info();
        //         }
        //         "timestamp" => {
        //             let dec = sttr[3].as_str().unwrap_or("").parse::<i32>().unwrap_or(0);
        //             let def = sttr[4].as_str().unwrap_or("").parse::<f64>().unwrap_or(0.0);
        //             rows = fields::field::Timestamp::timestamp(require.clone(), name.clone(), title.clone(), dec.clone(), def.clone()).info();
        //         }
        //         "number" => {
        //             let length = sttr[3].as_str().unwrap_or("").parse::<i32>().unwrap_or(0);
        //             let dec = sttr[4].as_str().unwrap_or("").parse::<i32>().unwrap_or(0);
        //             let def = sttr[5].as_str().unwrap_or("").parse::<f32>().unwrap_or(0.0);
        //
        //             rows = fields::field::Number::field(
        //                 require.clone(),
        //                 name.clone(),
        //                 title.clone(), length.clone(),
        //                 dec.clone(), def.clone()).info();
        //         }
        //         "file" => {
        //             let length = sttr[3].as_str().unwrap_or("").parse::<i32>().unwrap_or(1);
        //             let def = sttr[4].as_str().unwrap_or("");
        //             rows = fields::field::File::field(
        //                 require.clone(),
        //                 name.clone(),
        //                 title.clone(),
        //                 length.clone(),
        //                 def.clone(),
        //             ).info();
        //         }
        //         "table" => {
        //             let table = sttr[3].as_str().unwrap();
        //             let fields = sttr[4].as_str().unwrap();
        //             let api = sttr[5].as_str().unwrap_or("");
        //             let def = sttr[6].as_str().unwrap_or("");
        //             rows = fields::field::Table::field(
        //                 require.clone(),
        //                 name.clone(),
        //                 title.clone(),
        //                 table.clone(),
        //                 fields.clone(),
        //                 def.clone(),
        //                 api.clone()).info();
        //         }
        //         "text" => {
        //             let def = sttr[2].as_str().unwrap_or("");
        //             rows = fields::field::Text::field(
        //                 require.clone(),
        //                 name.clone(),
        //                 title.clone(),
        //                 def.clone(),
        //             ).info();
        //         }
        //         "select" => {
        //             let option: Option<String> = r.get("COLUMN_TYPE").unwrap();
        //             let option = option.unwrap();
        //             let mut options = array![];
        //             let multiple = sttr[3].as_str().unwrap_or("").parse::<bool>().unwrap_or(false);
        //             let option = {
        //                 if tools::string::search(option.as_str(), "enum(") {
        //                     let option = option.trim_start_matches("enum('").trim_end_matches("')");
        //                     let option = tools::string::split(option.to_string(), "','");
        //                     option
        //                 } else {
        //                     let option = option.trim_start_matches("set('").trim_end_matches("')");
        //                     let option = tools::string::split(option.to_string(), "','");
        //                     option
        //                 }
        //             };
        //             for item in option.members() {
        //                 if item != "" {
        //                     options.push(item.clone()).unwrap();
        //                 }
        //             }
        //             let def = sttr[4].as_str().unwrap_or("");
        //             rows = fields::field::Select::field(
        //                 require.clone(),
        //                 name.clone(),
        //                 title.clone(),
        //                 options.clone(),
        //                 multiple.clone(),
        //                 def.into(),
        //             ).info();
        //         }
        //         "switch" => {
        //             let def = sttr[3].as_str().unwrap_or("").parse::<bool>().unwrap_or(false);
        //             rows = fields::field::Switch::field(
        //                 require.clone(),
        //                 name.clone(),
        //                 title.clone(),
        //                 def.into(),
        //             ).info();
        //         }
        //         "year" => {
        //             let def = {
        //                 let def: Option<String> = r.get("COLUMN_DEFAULT").unwrap();
        //                 if def == None {
        //                     "0000".to_string()
        //                 } else {
        //                     def.unwrap()
        //                 }
        //             };
        //             let def = def.as_str().clone();
        //             rows = fields::field::Date::year(
        //                 require.clone(),
        //                 name.clone(),
        //                 title.clone(),
        //                 def.into(),
        //             ).info();
        //         }
        //         "date" => {
        //             let def = {
        //                 let def: Option<String> = r.get("COLUMN_DEFAULT").unwrap();
        //                 if def == None {
        //                     "0000-01-01".to_string()
        //                 } else {
        //                     def.unwrap()
        //                 }
        //             };
        //             let def = def.as_str();
        //             rows = fields::field::Date::date(
        //                 require.clone(),
        //                 name.clone(),
        //                 title.clone(),
        //                 def.into(),
        //             ).info();
        //         }
        //         "time" => {
        //             let def: String = r.get("COLUMN_DEFAULT").unwrap_or("00:00:00".to_string());
        //             let def = def.as_str();
        //             rows = fields::field::Date::time(
        //                 require.clone(),
        //                 name.clone(),
        //                 title.clone(),
        //                 def.into(),
        //             ).info();
        //         }
        //         _ => {
        //             println!("未知数据类型: {}", mode);
        //         }
        //     }
        //     data[name.clone()] = rows.into();
        // });
        //
        //
        //


        self.fields[self.table.clone()] = data.into();
        self
    }
    /// 查询
    pub fn select(&mut self, _sql: String, _field_list: Vec<String>) -> JsonValue {
        return object! {};
    }

    /// 新增
    pub fn insert(&mut self, _sql: String) -> JsonValue {
        JsonValue::from(0)
    }

    /// 更新
    pub fn update(&mut self, _sql: String) -> JsonValue {
        JsonValue::from(0)
    }

    /// 删除
    pub fn delete(&mut self, _sql: String) -> JsonValue {
        JsonValue::from(0)
    }
    /// 分割字符串
    fn _split(&mut self, data: &str) -> String {
        let data = String::from(data);
        let list: Vec<&str> = data.split(" as ").collect();
        if list.len() == 1 {
            return list[0].to_string();
        }
        return list[1].to_string();
    }
    /// 聚合查询
    pub fn aggregate_query(&mut self, _mode: &str, _sql: String, mut fields: Vec<String>) -> JsonValue {
        for index in 0..fields.len() {
            fields[index] = self._split(fields[index].as_str().clone());
        }
        JsonValue::from(0)
    }

    /// 开启事务
    pub fn transaction(&mut self) -> bool {
        if self.transaction > 0 {
            self.transaction += 1;
            return true;
        }
        let _sql = "begin";
        false
    }
    /// 提交事务
    pub fn commit(&mut self) -> bool {
        if self.transaction > 1 {
            self.transaction -= 1;
            return true;
        }
        let _sql = "commit";
        false
    }
    /// 回滚事务
    pub fn rollback(&mut self) -> bool {
        let _sql = "rollback";
        false
    }
    /// 查询表是否存在
    pub fn query_table(&mut self, table: &str) -> bool {
        let _sql = format!("SHOW TABLES LIKE '{}'", table);
        false
    }
    /// 创建数据表
    pub fn create_table(&mut self, _sql: &str) -> bool {
        false
    }
    /// 删除数据表
    pub fn delete_table(&mut self, _sql: &str) -> bool {
        false
    }
    /// 更新数据表
    pub fn update_table(&mut self, _sql: &str) -> bool {
        false
    }
}