sqlrite/sql/parser/
insert.rs1use sqlparser::ast::{Expr, Insert, SetExpr, Statement, Value, Values};
2
3use crate::error::{Result, SQLRiteError};
4
5#[derive(Debug)]
9pub struct InsertQuery {
10 pub table_name: String,
11 pub columns: Vec<String>,
12 pub rows: Vec<Vec<String>>,
13}
14
15impl InsertQuery {
16 pub fn new(statement: &Statement) -> Result<InsertQuery> {
17 let tname: Option<String>;
18 let mut columns: Vec<String> = vec![];
19 let mut all_values: Vec<Vec<String>> = vec![];
20
21 match statement {
22 Statement::Insert(Insert {
23 table,
24 columns: cols,
25 source,
26 ..
27 }) => {
28 tname = Some(table.to_string());
29 for col in cols {
30 columns.push(col.to_string());
31 }
32
33 let source = source.as_ref().ok_or_else(|| {
34 SQLRiteError::Internal(
35 "INSERT statement is missing a source expression".to_string(),
36 )
37 })?;
38
39 if let SetExpr::Values(Values { rows, .. }) = source.body.as_ref() {
40 for row in rows {
41 let mut value_set: Vec<String> = vec![];
42 for e in row {
43 match e {
44 Expr::Value(v) => match &v.value {
45 Value::Number(n, _) => {
46 value_set.push(n.to_string());
47 }
48 Value::Boolean(b) => {
49 if *b {
50 value_set.push("true".to_string());
51 } else {
52 value_set.push("false".to_string());
53 }
54 }
55 Value::SingleQuotedString(sqs) => {
56 value_set.push(sqs.to_string());
57 }
58 Value::Null => {
59 value_set.push("Null".to_string());
60 }
61 _ => {}
62 },
63 Expr::Identifier(i) => {
64 value_set.push(i.to_string());
65 }
66 _ => {}
67 }
68 }
69 all_values.push(value_set);
70 }
71 }
72 }
73 _ => {
74 return Err(SQLRiteError::Internal(
75 "Error parsing insert query".to_string(),
76 ));
77 }
78 }
79
80 match tname {
81 Some(t) => Ok(InsertQuery {
82 table_name: t,
83 columns,
84 rows: all_values,
85 }),
86 None => Err(SQLRiteError::Internal(
87 "Error parsing insert query".to_string(),
88 )),
89 }
90 }
91}