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
//! DML stands for Data Manipulation Language
//! and this module contains the AST for DML operations
//! such as Insert, Delete, Update table.
mod dml_parser;

use crate::{
    ast::{
        BinaryOperation, ColumnName, Expr, Operator, Select, TableDef,
        TableLookup, TableName, Value,
    },
    parser::{column, list_fail, table, value},
    ColumnDef, Error,
};
pub use dml_parser::{bulk_delete, bulk_update, delete, insert, update};
use pom::parser::tag;
use serde::{Deserialize, Serialize};
use sqlparser::ast as sql;

#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Insert {
    pub into: TableName,
    pub columns: Vec<ColumnName>,
    pub source: Source,
    pub returning: Option<Vec<ColumnName>>,
}

/// Insert can get data from a set of values
/// or from a select statement
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub enum Source {
    Select(Select),
    Values(Vec<Vec<Value>>),
    Parameterized(Vec<usize>),
}

/// DELETE /product?product_id=1
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Delete {
    pub from: TableName,
    pub condition: Option<Expr>,
}

/// DELETE /product{product_id}
/// 1
/// 2
/// 3
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct BulkDelete {
    pub from: TableName,
    pub columns: Vec<ColumnName>,
    pub values: Vec<Vec<Value>>,
}

/// PATCH /product{description="I'm the new description now"}?product_id=1
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Update {
    pub table: TableName,
    pub columns: Vec<ColumnName>,
    pub values: Vec<Value>, // one value for each column
    pub condition: Option<Expr>,
}

/// PATCH /product{*product_id,name}
/// 1,go pro,1,go pro hero4
/// 2,shovel,2,slightly used shovel
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct BulkUpdate {
    pub table: TableName,
    pub columns: Vec<ColumnName>,
    pub values: Vec<Vec<Value>>,
}

impl Insert {
    pub fn into_sql_statement(
        &self,
        table_lookup: Option<&TableLookup>,
    ) -> Result<sql::Statement, Error> {
        Ok(sql::Statement::Insert {
            or: None,
            into: true,
            table_name: Into::into(&self.into),
            table_alias: None,
            columns: self.columns.iter().map(|c| Into::into(c)).collect(),
            source: Some(Box::new(sql::Query {
                with: None,
                body: Box::new(self.source.into_sql_setexpr(table_lookup)?),
                order_by: vec![],
                limit: None,
                offset: None,
                fetch: None,
                locks: vec![],
                for_clause: None,
                limit_by: vec![],
            })),
            after_columns: vec![],
            table: false,
            on: None,
            returning: None,
            replace_into: false,
            priority: None,
            ignore: false,
            overwrite: false,
            partitioned: None,
        })
    }
}

impl Delete {
    pub fn into_sql_statement(&self) -> Result<sql::Statement, Error> {
        Ok(sql::Statement::Delete {
            tables: vec![],
            from: sql::FromTable::WithFromKeyword(vec![Into::into(&self.from)]),
            selection: self.condition.as_ref().map(|expr| Into::into(expr)),
            returning: None,
            order_by: vec![],
            limit: None,
            using: None,
        })
    }
}

impl Update {
    pub fn into_sql_statement(&self) -> Result<sql::Statement, Error> {
        Ok(sql::Statement::Update {
            table: Into::into(&self.table),
            assignments: self
                .columns
                .iter()
                .zip(self.values.iter())
                .map(|(column, value)| sql::Assignment {
                    id: vec![Into::into(column)],
                    value: Into::into(value),
                })
                .collect(),
            selection: self.condition.as_ref().map(|expr| Into::into(expr)),
            from: None,
            returning: None,
        })
    }
}

/// a common code for building filter from columns old value and primary columns
fn build_filter_from_columns(
    columns: &[ColumnName],
    old_values: &[&Value],
    primary_columns: &[&ColumnDef],
) -> Option<Expr> {
    let pk_values: Vec<&Value> = primary_columns
        .iter()
        .filter_map(|pk| {
            columns.iter().zip(old_values.iter()).find_map(
                |(col, old_value)| {
                    if col == &pk.column {
                        Some(*old_value)
                    } else {
                        None
                    }
                },
            )
        })
        .collect();

    let pk_column_values: Vec<(&ColumnDef, &Value)> = primary_columns
        .into_iter()
        .zip(pk_values.into_iter())
        .map(|(column_def, value)| (*column_def, value))
        .collect();

    if let Some((column0, value0)) = pk_column_values.first() {
        let mut filter0 = Expr::BinaryOperation(Box::new(BinaryOperation {
            left: Expr::Column(column0.column.clone()),
            operator: Operator::Eq,
            right: Expr::Value((*value0).clone()),
        }));
        for (column, value) in pk_column_values.iter().skip(1) {
            let next_filter =
                Expr::BinaryOperation(Box::new(BinaryOperation {
                    left: Expr::Column(column.column.clone()),
                    operator: Operator::Eq,
                    right: Expr::Value((*value).clone()),
                }));

            filter0 = Expr::BinaryOperation(Box::new(BinaryOperation {
                left: filter0,
                operator: Operator::And,
                right: next_filter,
            }));
        }
        Some(filter0)
    } else {
        None
    }
}

impl BulkUpdate {
    /// convert bulk update into sql statements
    pub fn into_sql_statements(
        &self,
        table_lookup: Option<&TableLookup>,
    ) -> Result<Vec<sql::Statement>, Error> {
        let table_def = table_lookup
            .expect("must have a table lookup")
            .get_table_def(&self.table.name)
            .expect("must have a table_def");
        let updates = self.into_updates(table_def)?;
        Ok(updates
            .into_iter()
            .map(|update| update.into_sql_statement().expect("must convert"))
            .collect())
    }

    /// convert BulkUpdate into multiple Update AST
    fn into_updates(&self, table_def: &TableDef) -> Result<Vec<Update>, Error> {
        let columns_len = self.columns.len();

        let updates = self
            .values
            .iter()
            .map(|row| {
                let old_values: Vec<&Value> =
                    row.iter().take(columns_len).collect();

                let new_values: Vec<&Value> =
                    row.iter().skip(columns_len).collect();

                assert_eq!(
                    old_values.len(),
                    new_values.len(),
                    "must the same number of records"
                );

                // column and values that are changed
                let column_new_values: Vec<(ColumnName, Value)> = self
                    .columns
                    .iter()
                    .zip(old_values.clone().iter().zip(new_values.iter()))
                    .filter_map(|(column, (old_value, new_value))| {
                        if old_value != new_value {
                            Some((column.clone(), (*new_value).clone()))
                        } else {
                            None
                        }
                    })
                    .collect();

                let (columns, new_values): (Vec<ColumnName>, Vec<Value>) =
                    column_new_values.into_iter().unzip();

                Update {
                    table: self.table.clone(),
                    columns,
                    values: new_values,
                    condition: build_filter_from_columns(
                        &self.columns,
                        &old_values,
                        &table_def.get_primary_columns(),
                    ),
                }
            })
            .collect();

        Ok(updates)
    }
}

impl BulkDelete {
    /// convert bulk delete into sql statements
    pub fn into_multiple_sql_statements(
        &self,
        table_lookup: Option<&TableLookup>,
    ) -> Result<Vec<sql::Statement>, Error> {
        let table_def = table_lookup
            .expect("must have a table lookup")
            .get_table_def(&self.from.name)
            .expect("must have a table_def");
        //TODO: create a separate branch for building delete with no Lookup table needed
        let deletes = self.into_multiple_deletes(table_def)?;
        Ok(deletes
            .into_iter()
            .map(|delete| delete.into_sql_statement().expect("must convert"))
            .collect())
    }

    /// convert BulkDelete into multiple Delete AST
    fn into_multiple_deletes(
        &self,
        table_def: &TableDef,
    ) -> Result<Vec<Delete>, Error> {
        let deletes = self
            .values
            .iter()
            .map(|row| {
                let old_values: Vec<&Value> = row.iter().collect();
                Delete {
                    from: self.from.clone(),
                    condition: build_filter_from_columns(
                        &self.columns,
                        &old_values,
                        &table_def.get_primary_columns(),
                    ),
                }
            })
            .collect();

        Ok(deletes)
    }

    /// when there is a primary of this table, use the in filter
    pub fn into_single_sql_statement(
        &self,
        table_lookup: Option<&TableLookup>,
    ) -> Result<sql::Statement, Error> {
        let table_def = table_lookup
            .expect("must have a table lookup")
            .get_table_def(&self.from.name)
            .expect("must have a table_def");

        let primary_columns = table_def.get_primary_columns();
        if primary_columns.len() == 1 {
            let pk_column = &primary_columns[0];
            let pk_values: Vec<Value> = self
                .values
                .iter()
                .flat_map(|row| {
                    self.columns.iter().zip(row.iter()).filter_map(
                        |(col, value)| {
                            if pk_column.column.name == col.name {
                                Some(value.clone())
                            } else {
                                None
                            }
                        },
                    )
                })
                .collect();

            assert!(!pk_values.is_empty());

            let delete = Delete {
                from: self.from.clone(),
                condition: Some(Expr::BinaryOperation(Box::new(
                    BinaryOperation {
                        left: Expr::Column(ColumnName {
                            name: pk_column.column.name.clone(),
                        }),
                        operator: Operator::In,
                        right: Expr::MultiValue(pk_values),
                    },
                ))),
            };
            delete.into_sql_statement()
        } else {
            //TODO: must return an Err where pirmary key is not found on this table
            panic!("This is only applicable for table with primary column and only 1 primary column");
        }
    }
}

impl Source {
    fn into_sql_setexpr(
        &self,
        table_lookup: Option<&TableLookup>,
    ) -> Result<sql::SetExpr, Error> {
        let ret = match self {
            Source::Select(select) => sql::SetExpr::Select(Box::new(
                select.into_sql_select(table_lookup)?,
            )),
            Source::Values(rows) => sql::SetExpr::Values(sql::Values {
                explicit_row: false,
                rows: rows
                    .iter()
                    .map(|record| {
                        record.iter().map(|v| Into::into(v)).collect()
                    })
                    .collect(),
            }),
            Source::Parameterized(_params) => {
                todo!("maybe remove parameterized source");
                //println!("parameterized params: {:?}", params);
                //sql::SetExpr::ParameterizedValue(params.to_owned())
            }
        };
        Ok(ret)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{
        expr::BinaryOperation, parser::utils::to_chars, Operator,
    };

    #[test]
    fn test_insert() {
        let input = to_chars(
            "product{product_id,created_by,created,is_active}?returning=product_id,name\n\
            1,1,2019-10-10T10:10:10.122,true
            ",
        );
        let ret = insert().parse(&input).expect("must be parsed");
        println!("{:#?}", ret);
        let statement: sql::Statement =
            ret.into_sql_statement(None).expect("must not fail");
        assert_eq!(
            statement.to_string(),
            "INSERT INTO product (product_id, created_by, created, is_active) VALUES "
        );
        assert_eq!(
            ret,
            Insert {
                into: TableName {
                    name: "product".into()
                },
                columns: vec![
                    ColumnName {
                        name: "product_id".into()
                    },
                    ColumnName {
                        name: "created_by".into()
                    },
                    ColumnName {
                        name: "created".into()
                    },
                    ColumnName {
                        name: "is_active".into()
                    },
                ],
                source: Source::Values(vec![]),
                returning: Some(vec![
                    ColumnName {
                        name: "product_id".into()
                    },
                    ColumnName {
                        name: "name".into()
                    },
                ])
            }
        );
    }

    #[test]
    fn test_update() {
        let input = to_chars(
            r#"product{description="I'm the new description now",is_active=false}?product_id=1"#,
        );
        let ret = update().parse(&input).expect("must be parsed");
        println!("{:#?}", ret);
        let statement: sql::Statement = ret.into_sql_statement().unwrap();
        assert_eq!(
            statement.to_string(),
            r#"UPDATE product SET description = 'I''m the new description now', is_active = false WHERE product_id = 1"#
        );
        assert_eq!(
            ret,
            Update {
                table: TableName {
                    name: "product".into()
                },
                columns: vec![
                    ColumnName {
                        name: "description".into(),
                    },
                    ColumnName {
                        name: "is_active".into()
                    },
                ],
                values: vec![
                    Value::String("I'm the new description now".into(),),
                    Value::Bool(false,),
                ],
                condition: Some(Expr::BinaryOperation(Box::new(
                    BinaryOperation {
                        left: Expr::Column(ColumnName {
                            name: "product_id".into()
                        },),
                        operator: Operator::Eq,
                        right: Expr::Value(Value::Number(1.0))
                    }
                )))
            }
        )
    }
    #[test]
    fn test_delete() {
        let input = to_chars(r#"product?product_id=1"#);
        let ret = delete().parse(&input).expect("must be parsed");
        println!("{:#?}", ret);
        let statement: sql::Statement = ret.into_sql_statement().unwrap();
        assert_eq!(
            statement.to_string(),
            "DELETE FROM product WHERE product_id = 1"
        );
        assert_eq!(
            ret,
            Delete {
                from: TableName {
                    name: "product".into()
                },
                condition: Some(Expr::BinaryOperation(Box::new(
                    BinaryOperation {
                        left: Expr::Column(ColumnName {
                            name: "product_id".into()
                        },),
                        operator: Operator::Eq,
                        right: Expr::Value(Value::Number(1.0))
                    }
                )))
            }
        );
    }

    #[test]
    fn test_bulk_delete() {
        let input = to_chars("product{name,is_active}");
        let ret = bulk_delete().parse(&input).expect("must be parsed");
        println!("{:#?}", ret);
        assert_eq!(
            ret,
            BulkDelete {
                from: TableName {
                    name: "product".into()
                },
                columns: vec![
                    ColumnName {
                        name: "name".into()
                    },
                    ColumnName {
                        name: "is_active".into()
                    }
                ],
                values: vec![]
            }
        );
    }

    #[test]
    fn test_bulk_update() {
        let input = to_chars("product{name,is_active}");
        let ret = bulk_update().parse(&input).expect("must be parsed");
        println!("{:#?}", ret);
        assert_eq!(
            ret,
            BulkUpdate {
                table: TableName {
                    name: "product".into()
                },
                columns: vec![
                    ColumnName {
                        name: "name".into()
                    },
                    ColumnName {
                        name: "is_active".into()
                    }
                ],
                values: vec![]
            }
        );
    }
}