senkenn / sqlsurge

Visual Studio Code extension for SQL language server
https://marketplace.visualstudio.com/items?itemName=senken.sqlsurge
MIT License
18 stars 0 forks source link

Extract raw sql on sqlx with Rust AST #15

Closed senkenn closed 7 months ago

senkenn commented 7 months ago

https://github.com/mtshiba/ruast There is a implementation by shiba.

senkenn commented 7 months ago

ast expoler https://astexplorer.net/

senkenn commented 7 months ago

https://docs.rs/syn/latest/syn/fn.parse_file.html it can parse file content to last.

sample code

pub fn extract_sql_list(source_txt: String) -> Vec<String> {
    let mut sql_nodes = Vec::new();

    let ast = syn::parse_file(&source_txt).unwrap();
    if let Some(shebang) = ast.shebang {
        println!("{}", shebang);
    }
    println!("{} items", ast.items.len());

    sql_nodes
}

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

    #[test]
    fn it_works() {
        let result = extract_sql_list(
            r##"
                async fn add_todo(pool: &PgPool, description: String) -> anyhow::Result<i64> {
                    let rec = sqlx::query!(
                        r#"
                INSERT INTO todos ( description )
                VALUES ( $1 )
                RETURNING id
                        "#,
                        description
                    )
                    .fetch_one(pool)
                    .await?;

                    Ok(rec.id)
                } 
            "##
            .to_string(),
        );
    }
}
senkenn commented 7 months ago

https://docs.rs/syn/latest/syn/visit/index.html

there is visit function similar to ts compiler api

senkenn commented 7 months ago

syn cannot get the parent node...

senkenn commented 7 months ago

close with https://github.com/senkenn/sqlsurge/pull/20