Last active
December 5, 2023 16:39
-
-
Save langyo/0ffe992e5ccd70880d786fbe1c2e1d05 to your computer and use it in GitHub Desktop.
Rust demo - SQL rewriter powered by the crate sqlparser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "rust-sqlparser-demo" | |
version = "0.1.0" | |
edition = "2021" | |
[dependencies] | |
sqlparser = "0.40" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use sqlparser::ast::{Expr, Value}; | |
use sqlparser::dialect::GenericDialect; | |
use sqlparser::parser::Parser; | |
fn main() { | |
let sql = r#"INSERT INTO "test" (`id`, "sort", name, 'ass') VALUES (?, ?, ?, ?)"#; | |
let dialect = GenericDialect {}; | |
let mut ast = Parser::parse_sql(&dialect, sql).unwrap(); | |
match &mut ast[0] { | |
sqlparser::ast::Statement::Insert { | |
columns, source, .. | |
} => { | |
for item in columns.iter_mut() { | |
item.quote_style = Some('"'); | |
} | |
if let Some(obj) = source { | |
match &mut *obj.body { | |
sqlparser::ast::SetExpr::Values(obj) => { | |
for mut item in obj.rows[0].iter_mut() { | |
match &mut item { | |
Expr::Value(value) => { | |
*value = Value::SingleQuotedString("233".to_string()); | |
} | |
_ => todo!(), | |
} | |
} | |
} | |
_ => todo!(), | |
} | |
} | |
} | |
_ => todo!(), | |
} | |
let statement = &ast[0]; | |
let sql = statement.to_string(); | |
println!("SQL: {}", sql); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment