1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! 
//! Fuse features
//! 

use akita_core::Table;

use crate::segment::ISegment;
use crate::{AkitaError, AkitaMapper, IPage, Pool, Wrapper, database::DatabasePlatform};
use crate::{cfg_if, Params, TableName, DatabaseName, SchemaContent, TableDef, Rows, FromValue, Value, ToValue, GetFields};

pub struct Akita <'b> {
    db: Option<&'b mut DatabasePlatform>,
    akita_type: AkitaType,
    wrapper: Wrapper,
    table: String,
}

pub enum AkitaType {
    Query,
    Update,
}

impl <'b> Akita<'b> {
    
    pub fn new() -> Self {
        Akita { wrapper: Wrapper::new(), table: String::default(), akita_type: AkitaType::Query, db:None }
    }
    
    pub fn wrapper(mut self, wrapper: Wrapper) -> Self {
        self.wrapper = wrapper;
        self
    }

    pub fn conn(mut self, db: &'b mut DatabasePlatform) -> Self {
        self.db = db.into();
        self
    }

    pub fn table<S: Into<String>>(mut self, table: S) -> Self {
        self.table = table.into();
        self
    }

    pub fn affected_rows(&self) -> u64 {
        if let Some(db) = &self.db {
            db.affected_rows()
        } else {
            0
        }
    }

    pub fn last_insert_id(&self) -> u64 {
        if let Some(db) = &self.db {
            db.last_insert_id()
        } else {
            0
        }
    }

    pub fn list<T>(&mut self) -> Result<Vec<T>, AkitaError>
        where
        T: FromValue {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let wrapper = &mut self.wrapper;
        let select_fields = wrapper.get_select_sql();
        let where_condition = wrapper.get_sql_segment();
        
        let enumerated_columns = if select_fields.eq("*") || select_fields.is_empty() {
            "*".to_string()
        } else { 
            select_fields
        };
        
        let where_condition = if where_condition.trim().is_empty() { String::default() } else { format!("WHERE {}",where_condition) };
        let sql = format!("SELECT {} FROM {} {}", &enumerated_columns, &self.table, where_condition);
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        let rows = db.execute_result(&sql, Params::Nil)?;
        let mut entities = vec![];
        for data in rows.iter() {
            let entity = T::from_value(&data);
            entities.push(entity)
        }
        Ok(entities)
    }

    /// Get one the table of records
    pub fn one<T>(&mut self) -> Result<Option<T>, AkitaError>
    where
        T: FromValue
    {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let wrapper = &mut self.wrapper;
        let select_fields = wrapper.get_select_sql();
        let where_condition = wrapper.get_sql_segment();
        let enumerated_columns = if select_fields.eq("*") || select_fields.is_empty() {
            "*".to_string()
        } else { 
            select_fields
        };
        let where_condition = if where_condition.trim().is_empty() { String::default() } else { format!("WHERE {}",where_condition) };
        let sql = format!("SELECT {} FROM {} {}", &enumerated_columns, &self.table, where_condition);
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        let rows = db.execute_result(&sql, Params::Nil)?;
        Ok(rows.iter().next().map(|data| T::from_value(&data)))
    }

    /// Get table of records with page
    pub fn page<T>(&mut self, page: usize, size: usize) -> Result<IPage<T>, AkitaError>
    where
        T: FromValue
    {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let wrapper = &mut self.wrapper;
        let select_fields = wrapper.get_select_sql();
        let where_condition = wrapper.get_sql_segment();
        let enumerated_columns = if select_fields.eq("*") || select_fields.is_empty() {
            "*".to_string()
        } else { 
            select_fields
        };
        let where_condition = if where_condition.trim().is_empty() { String::default() } else { format!("WHERE {}",where_condition) };
        let count_sql = format!("select count(1) as count from {} {}", &self.table, where_condition);
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        let result = db.execute_result(&count_sql, Params::Nil)?;
        let count = result.iter().map(|d| i64::from_value(&d)).next().unwrap_or(0);
        let mut page = IPage::new(page, size ,count as usize, vec![]);
        if page.total > 0 {
            let sql = format!("SELECT {} FROM {} {} limit {}, {}", &enumerated_columns, &self.table, where_condition,page.offset(),  page.size);
            let rows = db.execute_result(&sql, Params::Nil)?;
            let mut entities = vec![];
            for dao in rows.iter() {
                let entity = T::from_value(&dao);
                entities.push(entity)
            }
            page.records = entities;
        }
        Ok(page)
    }

    /// Get the total count of records
    pub fn count(&mut self) -> Result<usize, AkitaError> {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let wrapper = &mut self.wrapper;
        let where_condition = wrapper.get_sql_segment();
        let where_condition = if where_condition.trim().is_empty() { String::default() } else { format!("WHERE {}",where_condition) };
        let sql = format!(
            "SELECT COUNT(1) AS count FROM {} {}",
            &self.table,
            where_condition
        );
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        let result = db.execute_result(&sql, Params::Nil)?;
        let count = result.iter().map(|d| i64::from_value(&d)).next().map(|c| c as usize).unwrap_or(0);
        Ok(count)
    }

    /// Remove the records by wrapper.
    pub fn remove(&mut self) -> Result<(), AkitaError> {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let wrapper = &mut self.wrapper;
        let where_condition = wrapper.get_sql_segment();
        let where_condition = if where_condition.trim().is_empty() { String::default() } else { format!("WHERE {}",where_condition) };
        let sql = format!("delete from {} {}", &self.table, where_condition);
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        let _ = db.execute_result(&sql, Params::Nil)?;
        Ok(())
    }

    /// Update the records by wrapper.
    pub fn update(&mut self) -> Result<(), AkitaError> {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let sql = self.build_update_clause()?;
        let update_fields = &self.wrapper.fields_set;
        if update_fields.is_empty() {
            return Err(AkitaError::MissingField("Update Error, Missing update fields !".to_string()))
        } else {
            if self.db.is_none() {
                return Err(AkitaError::DataError("Missing database connection".to_string()))
            }
            let db = self.db.as_mut().expect("Missing database connection");
            db.execute_result(&sql, Params::Nil)?;
        }
        Ok(())
    }

    /// called multiple times when using database platform that doesn;t support multiple value
    pub fn save<T, I>(&mut self, entity: &T) -> Result<Option<I>, AkitaError>
    where
        T: GetFields + ToValue,
        I: FromValue
    {
        let columns = T::fields();
        let sql = self.build_insert_clause(&[entity])?;
        let data = entity.to_value();
        let mut values: Vec<Value> = Vec::with_capacity(columns.len());
        for col in columns.iter() {
            let value = data.get_obj_value(&col.name);
            match value {
                Some(value) => values.push(value.clone()),
                None => values.push(Value::Nil),
            }
        }
        let bvalues: Vec<&Value> = values.iter().collect();
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        db.execute_result(&sql,values.into())?;
        let rows: Rows = match *db {
            #[cfg(feature = "akita-mysql")]
            DatabasePlatform::Mysql(_) => db.execute_result("SELECT LAST_INSERT_ID();", Params::Nil)?,
            #[cfg(feature = "akita-sqlite")]
            DatabasePlatform::Sqlite(_) => db.execute_result("SELECT LAST_INSERT_ROWID();", Params::Nil)?,
            _=> panic!("the database platform must setup!")
        };
        let last_insert_id = rows.iter().next().map(|data| I::from_value(&data));
        Ok(last_insert_id)
    }

    /// called multiple times when using database platform that doesn;t support multiple value
    pub fn save_map<T>(&mut self, entity: &T) -> Result<(), AkitaError>
    where
        T: ToValue,
    {
        let columns = entity.to_value();
        let columns = if let Some(columns) = columns.as_object() {
            columns.keys().collect::<Vec<&String>>()
        } else { Vec::new() };
        let sql = self.build_insert_clause_map(&[entity])?;
        let data = entity.to_value();
        let mut values: Vec<Value> = Vec::with_capacity(columns.len());
        for col in columns.iter() {
            let value = data.get_obj_value(col);
            match value {
                Some(value) => values.push(value.clone()),
                None => values.push(Value::Nil),
            }
        }
        let bvalues: Vec<&Value> = values.iter().collect();
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        db.execute_result(&sql,values.into())?;
        Ok(())
    }

    /// called multiple times when using database platform that doesn;t support multiple value
    pub fn save_map_batch<T>(&mut self, entities: &[&T]) -> Result<(), AkitaError>
        where
            T: ToValue,
    {
        if entities.len() == 0 {
            return Err(AkitaError::DataError("data cannot be empty".to_string()))
        }
        let columns = entities[0].to_value();
        let columns = if let Some(columns) = columns.as_object() {
            columns.keys().collect::<Vec<&String>>()
        } else { Vec::new() };
        let sql = self.build_insert_clause_map(entities)?;
        let mut values: Vec<Value> = Vec::with_capacity(columns.len());
        for entity in entities.iter() {
           for col in columns.iter() {
               let data = entity.to_value();
               let value = data.get_obj_value(col);
               match value {
                   Some(value) => values.push(value.clone()),
                   None => values.push(Value::Nil),
               }
           }
        }
        let bvalues: Vec<&Value> = values.iter().collect();
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        db.execute_result(&sql,values.into())?;
        Ok(())
    }

    /// Performs text query and maps each row of the first result set.

    #[allow(clippy::redundant_closure)]
    pub fn query_map<T, F, Q, U>(mut self, mut f: F) -> Result<Vec<U>, AkitaError>
    where
        T: FromValue,
        F: FnMut(T) -> U,
    {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let wrapper = &mut self.wrapper;
        let select_fields = wrapper.get_select_sql();
        let where_condition = wrapper.get_sql_segment();
        let enumerated_columns = if select_fields.eq("*") || select_fields.is_empty() {
            "*".to_string()
        } else { 
            select_fields
        };
        
        let where_condition = if where_condition.trim().is_empty() { String::default() } else { format!("WHERE {}",where_condition) };
        let sql = format!("SELECT {} FROM {} {}", &enumerated_columns, &self.table, where_condition);
        self.query_fold(sql, Vec::new(), |mut acc, row| {
            acc.push(f(row));
            acc
        })
    }

    /// Performs text query and maps each row of the first result set.

    #[allow(clippy::redundant_closure)]
    pub fn exec_map<T, F, Q, U>(mut self, query: Q, mut f: F) -> Result<Vec<U>, AkitaError>
    where
        Q: Into<String>,
        T: FromValue,
        F: FnMut(T) -> U,
    {
        self.query_fold(query, Vec::new(), |mut acc, row| {
            acc.push(f(row));
            acc
        })
    }

    /// Performs text query and folds the first result set to a single value.
    pub fn query_fold<T, F, Q, U>(mut self, query: Q, init: U, mut f: F) -> Result<U, AkitaError>
    where
        Q: Into<String>,
        T: FromValue,
        F: FnMut(U, T) -> U,
    {
        self.exec_iter::<_, _>(query, ()).map(|r| r.iter().map(|data| T::from_value(&data))
            .fold(init, |acc, row| f(acc, row)))
    }

    #[allow(clippy::redundant_closure)]
    pub fn query_iter<'a>(
        mut self,
    ) -> Result<Rows, AkitaError>
    {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let wrapper = &mut self.wrapper;
        let select_fields = wrapper.get_select_sql();
        let where_condition = wrapper.get_sql_segment();
        let enumerated_columns = if select_fields.eq("*") || select_fields.is_empty() {
            "*".to_string()
        } else { 
            select_fields
        };
        
        let where_condition = if where_condition.trim().is_empty() { String::default() } else { format!("WHERE {}",where_condition) };
        let sql = format!("SELECT {} FROM {} {}", &enumerated_columns, &self.table, where_condition);
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        let rows = db.execute_result(&sql, Params::Nil)?;
        Ok(rows)
    }

    #[allow(clippy::redundant_closure)]
    pub fn exec_iter<'a,S: Into<String>, P: Into<Params>>(
        mut self,
        sql: S,
        params: P,
    ) -> Result<Rows, AkitaError>
    {
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        let rows = db.execute_result(&sql.into(), params.into())?;
        Ok(rows)
    }

    #[allow(clippy::redundant_closure)]
    pub fn exec_raw<'a, R, S: Into<String>, P: Into<Params>>(
        mut self,
        sql: S,
        params: P,
    ) -> Result<Vec<R>, AkitaError>
    where
        R: FromValue,
    {
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        let rows = db.execute_result(&sql.into(), params.into())?;
        Ok(rows.iter().map(|data| R::from_value(&data)).collect::<Vec<R>>())
    }

    pub fn query_first<'a, R>(
        mut self
    ) -> Result<R, AkitaError>
    where
        R: FromValue,
    {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let wrapper = &mut self.wrapper;
        let select_fields = wrapper.get_select_sql();
        let where_condition = wrapper.get_sql_segment();
        let enumerated_columns = if select_fields.eq("*") || select_fields.is_empty() {
            "*".to_string()
        } else { 
            select_fields
        };
        
        let where_condition = if where_condition.trim().is_empty() { String::default() } else { format!("WHERE {}",where_condition) };
        let sql = format!("SELECT {} FROM {} {}", &enumerated_columns, &self.table, where_condition);
        let result: Result<Vec<R>, AkitaError> = self.exec_raw(&sql, ());
        match result {
            Ok(mut result) => match result.len() {
                0 => Err(AkitaError::DataError("Zero record returned".to_string())),
                1 => Ok(result.remove(0)),
                _ => Err(AkitaError::DataError("More than one record returned".to_string())),
            },
            Err(e) => Err(e),
        }
    }

    pub fn exec_first<'a, R, S: Into<String>, P: Into<Params>>(
        mut self,
        sql: S,
        params: P,
    ) -> Result<R, AkitaError>
    where
        R: FromValue,
    {
        let sql: String = sql.into();
        let result: Result<Vec<R>, AkitaError> = self.exec_raw(&sql, params);
        match result {
            Ok(mut result) => match result.len() {
                0 => Err(AkitaError::DataError("Zero record returned".to_string())),
                1 => Ok(result.remove(0)),
                _ => Err(AkitaError::DataError("More than one record returned".to_string())),
            },
            Err(e) => Err(e),
        }
    }

    pub fn exec_drop<'a, S: Into<String>, P: Into<Params>>(
        mut self,
        sql: S,
        params: P,
    ) -> Result<(), AkitaError>
    {
        let sql: String = sql.into();
        let _result: Result<Vec<()>, AkitaError> = self.exec_raw(&sql, params);
        Ok(())
    }

    pub fn query_first_opt<'a, R>(
        mut self,
    ) -> Result<Option<R>, AkitaError>
    where
        R: FromValue,
    {
        if self.table.is_empty() {
            return Err(AkitaError::MissingTable("Find Error, Missing Table Name !".to_string()))
        }
        let wrapper = &mut self.wrapper;
        let select_fields = wrapper.get_select_sql();
        let where_condition = wrapper.get_sql_segment();
        let enumerated_columns = if select_fields.eq("*") || select_fields.is_empty() {
            "*".to_string()
        } else { 
            select_fields
        };
        
        let where_condition = if where_condition.trim().is_empty() { String::default() } else { format!("WHERE {}",where_condition) };
        let sql = format!("SELECT {} FROM {} {}", &enumerated_columns, &self.table, where_condition);
        let result: Result<Vec<R>, AkitaError> = self.exec_raw(&sql, ());
        match result {
            Ok(mut result) => match result.len() {
                0 => Ok(None),
                1 => Ok(Some(result.remove(0))),
                _ => Err(AkitaError::DataError("More than one record returned".to_string())),
            },
            Err(e) => Err(e),
        }
    }

    pub fn exec_first_opt<'a, R, S: Into<String>, P: Into<Params>>(
        mut self,
        sql: S,
        params: P,
    ) -> Result<Option<R>, AkitaError>
    where
        R: FromValue,
    {
        let sql: String = sql.into();
        let result: Result<Vec<R>, AkitaError> = self.exec_raw(&sql, params);
        match result {
            Ok(mut result) => match result.len() {
                0 => Ok(None),
                1 => Ok(Some(result.remove(0))),
                _ => Err(AkitaError::DataError("More than one record returned".to_string())),
            },
            Err(e) => Err(e),
        }
    }

    /// build an update clause
    pub fn build_update_clause(&mut self) -> Result<String, AkitaError> {
        let set_fields = &mut self.wrapper.fields_set;
        let mut sql = String::new();
        sql += &format!("update {} ", &self.table);
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        let fields = set_fields.iter().map(|f| f.0.to_owned()).collect::<Vec<String>>();
            // columns.iter().filter(|col| !set_fields.is_empty() && fields.contains(&col.name) && col.exist).collect::<Vec<_>>()
            sql += &format!(
                "set {}",
                set_fields
                    .iter_mut()
                    .enumerate()
                    .map(|(x, (col, value))| {
                        #[allow(unreachable_patterns)]
                        match db {
                            #[cfg(feature = "akita-mysql")]
                            DatabasePlatform::Mysql(_) => format!("`{}` = {}", col, value.get_sql_segment()),
                            #[cfg(feature = "akita-sqlite")]
                            DatabasePlatform::Sqlite(_) => format!("`{}` = ${}", col, x + 1),
                            _ => format!("`{}` = ${}", col, x + 1),
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", ")
            );
        let where_condition = self.wrapper.get_sql_segment();
        if !where_condition.is_empty() {
            sql += &format!(" where {} ", where_condition);
        }
        Ok(sql)
    }

    /// build an insert clause
    pub fn build_insert_clause_map<T>(&mut self, entities: &[T]) -> Result<String, AkitaError>
    where
        T: ToValue,
    {
        let table = &self.table;
        if entities.len() == 0 {
            return Err(AkitaError::DataError("data cannot be empty".to_string()))
        }
        let columns = entities[0].to_value();
        let columns = if let Some(columns) = columns.as_object() {
            columns.keys().collect::<Vec<&String>>()
        } else { Vec::new() };
        let columns_len = columns.len();
        let mut sql = String::new();
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        sql += &format!("INSERT INTO {} ", table);
        sql += &format!(
            "({})\n",
            columns
                .iter()
                .map(|c| format!("`{}`", c))
                .collect::<Vec<_>>()
                .join(", ")
        );
        sql += "VALUES ";
        sql += &entities
            .iter()
            .enumerate()
            .map(|(y, _)| {
                format!(
                    "\n\t({})",
                    columns
                        .iter()
                        .enumerate()
                        .map(|(x, _)| {
                            #[allow(unreachable_patterns)]
                            match db {
                                #[cfg(feature = "with-sqlite")]
                                DatabasePlatform::Sqlite(_) => format!("${}", y * columns_len + x + 1),
                                #[cfg(feature = "akita-mysql")]
                                DatabasePlatform::Mysql(_) => "?".to_string(),
                                _ => format!("${}", y * columns_len + x + 1),
                            }
                        })
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
            .collect::<Vec<_>>()
            .join(", ");
        Ok(sql)
    }

    /// build an insert clause
    pub fn build_insert_clause<T>(&mut self, entities: &[&T]) -> Result<String, AkitaError>
    where
        T: GetFields + ToValue,
    {
        let table = &self.table;
        let columns = T::fields();
        let columns_len = columns.len();
        let mut sql = String::new();
        if self.db.is_none() {
            return Err(AkitaError::DataError("Missing database connection".to_string()))
        }
        let db = self.db.as_mut().expect("Missing database connection");
        sql += &format!("INSERT INTO {} ", table);
        sql += &format!(
            "({})\n",
            columns
                .iter().filter(|f| f.exist)
                .map(|c| format!("`{}`", c.name))
                .collect::<Vec<_>>()
                .join(", ")
        );
        sql += "VALUES ";
        sql += &entities
            .iter()
            .enumerate()
            .map(|(y, _)| {
                format!(
                    "\n\t({})",
                    columns
                        .iter().filter(|f| f.exist)
                        .enumerate()
                        .map(|(x, _)| {
                            #[allow(unreachable_patterns)]
                            match db {
                                #[cfg(feature = "with-sqlite")]
                                DatabasePlatform::Sqlite(_) => format!("${}", y * columns_len + x + 1),
                                #[cfg(feature = "akita-mysql")]
                                DatabasePlatform::Mysql(_) => "?".to_string(),
                                _ => format!("${}", y * columns_len + x + 1),
                            }
                        })
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
            .collect::<Vec<_>>()
            .join(", ");
        Ok(sql)
    }

}