1use json::{JsonValue, object};
2static DISABLE_FIELD: &[&str] = &["default", "select", "delete", "insert", "update", "order", "group", "user", "password", "desc", "index", "from", "host", "user", "read", "partition"];
3
4#[cfg(feature = "db-sqlite")]
5pub mod sqlite;
6#[cfg(feature = "db-mysql")]
7pub mod mysql;
8#[cfg(feature = "db-mssql")]
9pub mod mssql;
10#[cfg(feature = "db-pgsql")]
11pub mod pgsql;
12
13pub trait DbMode {
14 fn database_tables(&mut self) -> JsonValue;
16 fn database_create(&mut self, name: &str) -> bool;
18 fn backups(&mut self, _filename: &str) -> bool {
20 false
21 }
22}
23
24#[derive(Debug, Clone)]
25pub struct TableOptions {
26 table_name: String,
27 table_title: String,
28 table_key: String,
29 table_fields: JsonValue,
30 table_unique: Vec<String>,
31 table_index: Vec<Vec<String>>,
32 table_partition: bool,
33 table_partition_columns: JsonValue,
34}
35impl TableOptions {
36 pub fn set_table_name(&mut self, name: &str) {
37 self.table_name = name.to_string()
38 }
39 pub fn set_table_title(&mut self, name: &str) {
40 self.table_title = name.to_string()
41 }
42 pub fn set_table_key(&mut self, name: &str) {
43 self.table_key = name.to_string()
44 }
45 pub fn set_table_fields(&mut self, fields: JsonValue) {
46 self.table_fields = fields;
47 }
48 pub fn set_table_unique(&mut self, unique: Vec<&str>) {
49 self.table_unique = unique.iter().map(|s| s.to_string()).collect();
50 }
51 pub fn set_table_index(&mut self, index: Vec<Vec<&str>>) {
52 self.table_index = index.iter().map(|s| s.iter().map(|s| s.to_string()).collect()).collect();
53 }
54 pub fn set_table_partition(&mut self, index: bool) {
55 self.table_partition = index;
56 }
57 pub fn set_table_partition_columns(&mut self, index: JsonValue) {
58 self.table_partition_columns = index;
59 }
60}
61impl Default for TableOptions {
62 fn default() -> Self {
63 Self {
64 table_name: "".to_string(),
65 table_title: "".to_string(),
66 table_key: "".to_string(),
67 table_fields: JsonValue::Null,
68 table_unique: vec![],
69 table_index: vec![],
70 table_partition: false,
71 table_partition_columns: JsonValue::Null,
72 }
73 }
74}
75pub trait Mode: DbMode {
76 fn table_create(&mut self, options: TableOptions) -> JsonValue;
77 fn table_update(&mut self, options: TableOptions) -> JsonValue;
78 fn table_info(&mut self, table: &str) -> JsonValue;
80 fn table_is_exist(&mut self, name: &str) -> bool;
82 fn table(&mut self, name: &str) -> &mut Self;
84 fn change_table(&mut self, name: &str) -> &mut Self;
86
87 fn autoinc(&mut self) -> &mut Self;
89 fn fetch_sql(&mut self) -> &mut Self;
91 fn order(&mut self, field: &str, by: bool) -> &mut Self;
93 fn group(&mut self, field: &str) -> &mut Self;
95 fn distinct(&mut self) -> &mut Self;
97 fn json(&mut self, field: &str) -> &mut Self;
99 fn location(&mut self, field: &str) -> &mut Self;
101 fn field(&mut self, field: &str) -> &mut Self;
103 fn hidden(&mut self, name: &str) -> &mut Self;
105 fn where_and(&mut self, field: &str, compare: &str, value: JsonValue) -> &mut Self;
107 fn where_or(&mut self, field: &str, compare: &str, value: JsonValue) -> &mut Self;
108
109 fn where_column(&mut self, field_a: &str, compare: &str, field_b: &str) -> &mut Self;
111 fn update_column(&mut self, field_a: &str, compare: &str) -> &mut Self;
113 fn page(&mut self, page: i32, limit: i32) -> &mut Self;
115 fn column(&mut self, field: &str) -> JsonValue;
117 fn count(&mut self) -> JsonValue;
119 fn max(&mut self, field: &str) -> JsonValue;
121 fn min(&mut self, field: &str) -> JsonValue;
123 fn sum(&mut self, field: &str) -> JsonValue;
125 fn avg(&mut self, field: &str) -> JsonValue;
127 fn select(&mut self) -> JsonValue;
129 fn find(&mut self) -> JsonValue;
131 fn value(&mut self, field: &str) -> JsonValue;
133 fn insert(&mut self, data: JsonValue) -> JsonValue;
135 fn insert_all(&mut self, data: JsonValue) -> JsonValue;
137
138 fn update(&mut self, data: JsonValue) -> JsonValue;
140 fn update_all(&mut self, data: JsonValue) -> JsonValue;
142 fn delete(&mut self) -> JsonValue;
144
145 fn transaction(&mut self) -> bool;
147 fn commit(&mut self) -> bool;
149 fn rollback(&mut self) -> bool;
151 fn sql(&mut self, sql: &str) -> Result<JsonValue, String>;
153 fn sql_execute(&mut self, sql: &str) -> Result<JsonValue, String>;
154 fn inc(&mut self, field: &str, num: f64) -> &mut Self;
156 fn dec(&mut self, field: &str, num: f64) -> &mut Self;
158
159 fn buildsql(&mut self) -> String;
161
162 fn join_fields(&mut self, fields: Vec<&str>) -> &mut Self;
163 fn join(&mut self, main_table: &str, main_fields: &str, right_table: &str, right_fields: &str) -> &mut Self;
169
170 fn join_inner(&mut self, table: &str, main_fields: &str, second_fields: &str) -> &mut Self;
176}
177
178#[derive(Clone, Debug)]
179pub struct Params {
180 pub mode: String,
181 pub autoinc: bool,
182 pub table: String,
183 pub where_and: Vec<String>,
184 pub where_or: Vec<String>,
185 pub where_column: String,
186 pub update_column: Vec<String>,
187 pub inc_dec: JsonValue,
188 pub page: i32,
189 pub limit: i32,
190 pub fields: JsonValue,
191 pub top: String,
192 pub top2: String,
193 pub order: JsonValue,
194 pub group: JsonValue,
195 pub distinct: bool,
196 pub json: JsonValue,
197 pub location: JsonValue,
198 pub sql: bool,
199 pub join: Vec<String>,
200 pub join_inner: Vec<String>,
201 pub join_table: String,
202}
203
204impl Params {
205 pub fn default(mode: &str) -> Self {
206 Self {
207 mode: mode.to_string(),
208 autoinc: false,
209 table: "".to_string(),
210 where_and: vec![],
211 where_or: vec![],
212 where_column: "".to_string(),
213 update_column: vec![],
214 inc_dec: object! {},
215 page: -1,
216 limit: 10,
217 fields: object! {},
218 top: String::new(),
219 top2: String::new(),
220 order: object! {},
221 group: object! {},
222 distinct: false,
223 json: object! {},
224 location: object! {},
225 sql: false,
226 join: Vec::new(),
227 join_inner: Vec::new(),
228 join_table: "".to_string(),
229 }
230 }
231 pub fn where_sql(&mut self) -> String {
232 let mut where_and_sql = vec![];
233 let mut where_or_sql = vec![];
234 let mut sql = vec![];
235
236 for item in self.where_or.iter() {
237 where_or_sql.push(item.clone());
238 }
239 if !where_or_sql.is_empty() {
240 sql.push(format!(" ( {} ) ", where_or_sql.join(" OR ")));
241 }
242
243 for item in self.where_and.iter() {
244 where_and_sql.push(item.clone());
245 }
246 if !where_and_sql.is_empty() {
247 sql.push(where_and_sql.join(" AND "));
248 }
249
250 if !self.where_column.is_empty() {
251 sql.push(self.where_column.clone());
252 }
253
254 if !sql.is_empty() {
255 return format!("WHERE {}", sql.join(" AND "));
256 }
257 "".to_string()
258 }
259 pub fn page_limit_sql(&mut self) -> String {
260 if self.page == -1 {
261 return "".to_string();
262 }
263 match self.mode.as_str() {
264 "mysql" => {
265 format!("LIMIT {},{}", self.page * self.limit - self.limit, self.limit)
266 }
267 "sqlite" => {
268 format!("LIMIT {} OFFSET {}", self.limit, self.page * self.limit - self.limit)
269 }
270 _ => "".to_string()
271 }
272 }
273 pub fn fields(&mut self) -> String {
274 let mut fields = vec![];
275 for (_, value) in self.fields.entries() {
276 match self.mode.as_str() {
277 "mssql" => {
278 fields.push(format!("{value}"));
279 }
280 "mysql" => {
281 if DISABLE_FIELD.contains(&value.as_str().unwrap()) {
282 fields.push(format!("`{value}`"));
283 } else {
284 fields.push(format!("{value}"));
285 }
286 }
287 _ => {
288 fields.push(format!("{value}"));
289 }
290 }
291 }
292 let fields = {
293 if fields.is_empty() {
294 "*".into()
295 } else {
296 fields.join(",")
297 }
298 };
299 match self.mode.as_str() {
300 "mysql" => {
301 fields.to_string()
302 }
303 "sqlite" => {
304 fields.to_string()
305 }
306 "mssql" => {
307 fields.to_string()
308 }
309 _ => fields.to_string()
310 }
311 }
312 pub fn top(&mut self) -> String {
313 match self.mode.as_str() {
314 "mssql" => {
315 let wheres = self.where_sql();
316 if !self.top2.is_empty() {
317 let order = self.order();
318 if order.is_empty() {
319 self.top = format!("(select ROW_NUMBER() OVER(ORDER BY rand()) as ROW,* from {} {}) as ", self.table, wheres);
320 } else {
321 self.top = format!("(select ROW_NUMBER() OVER({}) as ROW,* from {} {}) as ", order, self.table, wheres);
322 }
323 return self.top.to_string();
324 }
325 self.top.to_string()
326 }
327 _ => {
328 "".to_string()
329 }
330 }
331 }
332 pub fn top2(&mut self) -> String {
333 match self.mode.as_str() {
334 "mssql" => {
335 if self.where_and.is_empty() && self.where_or.is_empty() && !self.top2.is_empty() {
336 return format!("where {}", self.top2);
337 }
338 if (!self.where_and.is_empty() || !self.where_or.is_empty()) && !self.top2.is_empty() {
339 return format!("AND {}", self.top2);
340 }
341 self.top2.to_string()
342 }
343 _ => {
344 "".to_string()
345 }
346 }
347 }
348 pub fn table(&mut self) -> String {
349 match self.mode.as_str() {
350 "mssql" => {
351 if !self.top2.is_empty() {
352 return "t".to_string();
353 }
354 self.table.to_string()
355 }
356 _ => {
357 self.table.to_string()
358 }
359 }
360 }
361 pub fn join(&mut self) -> String {
362 match self.mode.as_str() {
363 "mssql" => {
364 self.join.join(" ")
365 }
366 _ => {
367 self.join.join(" ")
368 }
369 }
370 }
371
372 pub fn join_inner(&mut self) -> String {
374 match self.mode.as_str() {
375 "mysql" => {
376 let mut join_inner = "".to_string();
377 for item in self.join_inner.iter() {
378 join_inner = format!("{join_inner} {item}");
379 }
380 join_inner.to_string()
381 }
382 _ => {
383 "".to_string()
384 }
385 }
386 }
387
388
389 pub fn order(&mut self) -> String {
390 let mut sql = vec![];
391 for (field, item) in self.order.entries() {
392 match self.mode.as_str() {
393 "mssql" => {
394 sql.push(format!("{field} {item}"));
395 }
396 "pgsql" => {
397 sql.push(format!("{field} {item}"));
398 }
399 _ => {
400 sql.push(format!("{field} {item}"));
401 }
402 }
403 }
404 if !sql.is_empty() {
405 return format!("ORDER BY {}", sql.join(","));
406 }
407 "".to_string()
408 }
409 pub fn group(&mut self) -> String {
410 let mut sql = vec![];
411 for (_, field) in self.group.entries() {
412 if DISABLE_FIELD.contains(&&*field.clone().to_string()) {
413 sql.push(format!("`{field}`"));
414 } else if field.to_string().contains(".") {
415 sql.push(format!("{}", field));
416 } else {
417 sql.push(format!("{}.{}", self.table, field));
418 }
419 }
420 if !sql.is_empty() {
421 return format!("GROUP BY {}", sql.join(","));
422 }
423 "".to_string()
424 }
425 pub fn distinct(&self) -> String {
426 if self.distinct {
427 "DISTINCT".to_string()
428 } else {
429 "".to_string()
430 }
431 }
432 pub fn select_sql(&mut self) -> String {
433 format!("SELECT {} {} FROM {} {} {} {} {} {} {} {} {}", self.distinct(), self.fields(), self.top(), self.table(), self.join(), self.join_inner(), self.where_sql(), self.top2(), self.group(), self.order(), self.page_limit_sql())
434 }
435}