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
use sqlparser::ast::{Assignment, Expr, TableWithJoins};

use crate::ts_generator::{
    errors::TsGeneratorError,
    types::{db_conn::DBConn, ts_query::TsQuery},
};

use super::expressions::{
    translate_expr::translate_assignment, translate_table_with_joins::translate_table_from_assignments,
    translate_where_stmt::translate_where_stmt,
};

fn translate_assignments(
    ts_query: &mut TsQuery,
    table_with_joins: &TableWithJoins,
    assignments: &Vec<Assignment>,
    db_conn: &DBConn,
) -> Result<(), TsGeneratorError> {
    for assignment in assignments {
        let table = translate_table_from_assignments(&vec![table_with_joins.to_owned()], assignment).expect(
            "Failed to find the table based on assignment {assignment} from table with joins {table_with_joins}",
        );
        translate_assignment(assignment, table.as_str(), ts_query, db_conn).unwrap();
    }
    Ok(())
}

pub fn translate_update(
    ts_query: &mut TsQuery,
    table_with_joins: &TableWithJoins,
    assignments: &Vec<Assignment>,
    _from: &Option<TableWithJoins>,
    selection: &Option<Expr>,
    db_conn: &DBConn,
) -> Result<(), TsGeneratorError> {
    translate_assignments(ts_query, table_with_joins, assignments, db_conn)?;
    if selection.is_some() {
        translate_where_stmt(
            ts_query,
            &selection.to_owned().unwrap(),
            &None,
            &Some(&vec![table_with_joins.to_owned()]),
            db_conn,
        )?;
    }
    Ok(())
}