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
use std::io::{Error, ErrorKind};

use regex::Regex;
use sqlparser::ast::{Ident, ObjectName, SetExpr, Values};
use sqlparser::{ast::Statement, dialect::MySqlDialect, parser::Parser};
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;

pub fn format_insert_queries(sql: &str) -> Result<String, Box<dyn std::error::Error>> {
    let dialect = MySqlDialect {};
    let ast = Parser::parse_sql(&dialect, sql)?;

    if !is_insert_only(&ast) {
        return Err(Box::new(Error::new(
            ErrorKind::InvalidInput,
            "this sql contains queries other than insert.",
        )));
    }

    let comment_and_query_map = generate_comment_and_query_map(sql);

    let mut formatted_queries = ast
        .iter()
        .map(|query| {
            if let Statement::Insert {
                or: _,
                into: _,
                table_name,
                columns,
                overwrite: _,
                source,
                partitioned: _,
                after_columns: _,
                table: _,
                on: _,
                returning: _,
            } = query
            {
                if let SetExpr::Values(values) = &*source.body {
                    let max_char_length_vec = get_max_char_length_vec(columns, values);
                    let formatted_query =
                        generate_formatted_query(table_name, columns, values, &max_char_length_vec);
                    return formatted_query;
                }
            }
            return String::from("");
        })
        .collect::<Vec<String>>();

    let result = comment_and_query_map
        .into_iter()
        .map(|comment_or_query| {
            if comment_or_query.starts_with("INSERT INTO") {
                return formatted_queries.remove(0);
            } else {
                return comment_or_query;
            }
        })
        .collect::<Vec<String>>()
        .join("\n");

    return Ok(result);
}

#[wasm_bindgen]
pub fn format_insert_queries_wasm(sql: &str) -> Result<String, JsValue> {
    return match format_insert_queries(sql) {
        Ok(formatted_queries) => Ok(formatted_queries),
        Err(err) => Err(JsValue::from_str(&err.to_string())),
    };
}

fn is_insert_only(ast: &Vec<Statement>) -> bool {
    return ast.iter().fold(true, |a, query| match query {
        Statement::Insert {
            or: _,
            into: _,
            table_name: _,
            columns: _,
            overwrite: _,
            source: _,
            partitioned: _,
            after_columns: _,
            table: _,
            on: _,
            returning: _,
        } => return a && true,
        _ => return a && false,
    });
}

// this func returns a vec of comments and query prefixes.
// the prefixes are used to identify where each comment is written.
fn generate_comment_and_query_map(sql_with_comment: &str) -> Vec<String> {
    return Regex::new(r"(--.*)|(INSERT INTO)")
        .unwrap()
        .captures_iter(sql_with_comment)
        .map(|capture| return String::from(&capture[0]))
        .collect::<Vec<String>>();
}

fn get_max_char_length_vec(columns: &Vec<Ident>, values: &Values) -> Vec<usize> {
    return get_char_length_matrix(columns, values)
        .iter()
        .fold(
            vec![vec![0 as usize; 0]; columns.len()],
            |mut transposed_matrix, char_length_of_row| {
                char_length_of_row
                    .iter()
                    .enumerate()
                    .for_each(|(column_index, char_length)| {
                        transposed_matrix[column_index].push(*char_length)
                    });
                return transposed_matrix;
            },
        )
        .iter()
        .map(|char_length_of_column| {
            return char_length_of_column
                .into_iter()
                .max()
                .unwrap_or(&(0 as usize))
                .clone();
        })
        .collect::<Vec<usize>>();
}

fn get_char_length_matrix(columns: &Vec<Ident>, values: &Values) -> Vec<Vec<usize>> {
    return columns
        .iter()
        .map(|column| {
            return column.to_string().len();
        })
        .collect::<Vec<usize>>()
        .chunks(columns.len())
        .map(|chunk| chunk.to_vec())
        .chain(values.rows.iter().map(|row| {
            row.iter()
                .map(|value| {
                    return value.to_string().len();
                })
                .collect::<Vec<usize>>()
        }))
        .collect::<Vec<Vec<usize>>>();
}

// TODO: make it functional
// construct formatted query from scratch by using ast data
fn generate_formatted_query(
    table_name: &ObjectName,
    columns: &Vec<Ident>,
    values: &Values,
    max_char_length_vec: &Vec<usize>,
) -> String {
    let table_name_part: String = String::from("INSERT INTO ") + &table_name.to_string() + "\n";

    let mut column_name_part: String = String::from("(");
    for (index, column) in columns.iter().enumerate() {
        let adjustment =
            String::from(" ").repeat(max_char_length_vec[index] - column.to_string().len());
        column_name_part = column_name_part + &column.to_string() + &adjustment;
        if index != columns.len() - 1 {
            column_name_part += ","
        }
    }
    column_name_part += ")\n";

    let values_part: &str = "VALUES\n";

    let mut rows_part: String = String::from("");
    for (row_index, row) in values.rows.iter().enumerate() {
        rows_part += "(";
        for (column_index, value) in row.iter().enumerate() {
            let adjustment = String::from(" ")
                .repeat(max_char_length_vec[column_index] - value.to_string().len());
            rows_part = rows_part + &value.to_string() + &adjustment;
            if column_index != row.len() - 1 {
                rows_part += ","
            }
        }
        rows_part += ")";
        if row_index != values.rows.len() - 1 {
            rows_part += ","
        } else {
            rows_part += ";"
        }
        rows_part += "\n";
    }

    return String::from("") + &table_name_part + &column_name_part + &values_part + &rows_part;
}

// // The escape behavior of the sqlparser of v0.33.0 depends on if the value is quoted by backtick or else.
// // If the value is quoted by backtick, the sqlparser escapes the backslash.
// // But if the value is quoted by single quote or double quote, the sqlparser does NOT escape the backslash.
// // This module escape the value WHEN it is quoted by single quote or double quote.
// fn escape_stringified_value(str: &str) -> String {
//     let ch1 = str.chars().nth(0).unwrap();
//     match ch1 {
//         '\'' => {
//             return str
//                 .replace("\n", "\\n")
//                 .replace("\"", "\\\"")
//                 .replace("\t", "\\t")
//                 .replace("\r", "\\r")
//         }
//         '"' => {
//             return str
//                 .replace("\n", "\\n")
//                 .replace("'", "\\'")
//                 .replace("\t", "\\t")
//                 .replace("\r", "\\r")
//         }
//         _ => return str.to_string(),
//     }
// }

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn keep_backslashes_in_query_enclosed_with_backticks() {
        let query_with_backslash_with_backtick =
            r#"INSERT INTO `table` (`id`, `content`) VALUES (1, `\"e\nxample\"`);"#;
        let formatted = r#"INSERT INTO `table`
(`id`,`content`      )
VALUES
(1   ,`\"e\nxample\"`);
"#;
        assert_eq!(
            format_insert_queries(query_with_backslash_with_backtick).unwrap(),
            formatted
        );
    }

    #[test]
    fn keep_backslashes_in_query_enclosed_with_single_quotes() {
        let query_with_backslash_with_single_quote =
            r#"INSERT INTO `table` ('id', 'content') VALUES (1, '\"e\nxample\"');"#;
        let formatted = r#"INSERT INTO `table`
('id','content'      )
VALUES
(1   ,'\"e\nxample\"');
"#;
        assert_eq!(
            format_insert_queries(query_with_backslash_with_single_quote).unwrap(),
            formatted
        );
    }

    #[test]
    fn keep_backslashes_in_query_enclosed_with_double_quotes() {
        let query_with_backslash_with_double_quote =
            r#"INSERT INTO `table` ("id", "content") VALUES (1, "\'e\nxample\'");"#;
        let formatted = r#"INSERT INTO `table`
("id","content"      )
VALUES
(1   ,"\'e\nxample\'");
"#;
        assert_eq!(
            format_insert_queries(query_with_backslash_with_double_quote).unwrap(),
            formatted
        );
    }

    #[test]
    fn not_add_backslashes_to_query_enclosed_with_backticks() {
        let query_without_backslash_with_backticks =
            r#"INSERT INTO `table` (`id`, `content`) VALUES (1, `'"example"'`);"#;
        let formatted = r#"INSERT INTO `table`
(`id`,`content`    )
VALUES
(1   ,`'"example"'`);
"#;
        assert_eq!(
            format_insert_queries(query_without_backslash_with_backticks).unwrap(),
            formatted
        );
    }

    #[test]
    fn not_add_backslashes_to_query_enclosed_with_single_quotes() {
        let query_without_backslash_with_single_quotes =
            r#"INSERT INTO `table` ('id', 'content') VALUES (1, '"example"');"#;
        let formatted = r#"INSERT INTO `table`
('id','content'  )
VALUES
(1   ,'"example"');
"#;
        assert_eq!(
            format_insert_queries(query_without_backslash_with_single_quotes).unwrap(),
            formatted
        );
    }

    #[test]
    fn not_add_backslashes_to_query_enclosed_with_double_quotes() {
        let query_without_backslash_with_double_quotes =
            r#"INSERT INTO `table` ("id", "content") VALUES (1, "'example'");"#;
        let formatted = r#"INSERT INTO `table`
("id","content"  )
VALUES
(1   ,"'example'");
"#;
        assert_eq!(
            format_insert_queries(query_without_backslash_with_double_quotes).unwrap(),
            formatted
        );
    }

    #[test]
    fn work_with_function() {
        let query_with_function = "INSERT INTO `table` (`id`, `created_at`) VALUES (1, now());";
        let formatted = "INSERT INTO `table`\n(`id`,`created_at`)\nVALUES\n(1   ,now()       );\n";
        assert_eq!(
            format_insert_queries(query_with_function).unwrap(),
            formatted
        );
    }
}