use std::time::SystemTime; #[allow(dead_code)] #[derive(Debug)] pub struct Command { id: i64, name: String, nickname: Option, age: Option, create_time: Option, } impl<'a> Command { pub fn sql() -> BuilderSql<'a> { BuilderSql::default() } } #[derive(Debug)] pub struct BuilderSql<'a> { table_name: &'a str, id: &'a str, fields: Vec<(&'a str, &'a str, u16, &'a str)>, // 字段名,字段类型、字段长度、默认值 condition: Option<&'a str>, order: Option<&'a str>, limit: Option, offset: Option, } impl<'a> BuilderSql<'a>{ fn default() -> Self { let mut f = vec![]; f.push(("", "", 0,"")); Self { table_name: "", id: "", fields: f, condition: None, order: None, limit: None, offset: None, } } } impl<'a> BuilderSql<'a> { pub fn select(&mut self) -> String { let fields = self.fields.iter().map(|v| { v.clone().0 }).collect::>(); format!( "SELECT {} FROM {}{}", fields.join(","), self.table_name, match self.condition { Some(condition) => format!(" WHERE {}", condition), None => "".to_owned(), }, ) } pub fn condition(&mut self, condition: Option<&'a str>) -> &mut Self { self.condition = condition; self } } fn main() { let select = Command::sql().select(); println!("{}", select); }