Is there any sql escape crate you know of?

I am using sqlite and some parts I need to execute input received from user are there any sql escape crates you know?
I checked crates.io with no luck

If you’re using sqlite then it should already have sql escaping built in whenever you use things like prepared statements.

How are you interacting with sqlite at the moment? Does the library you are using let you pass in some sort of sql: &str and a set of parameters (e.g. like Connection::execute() from rusqlite)?

3 Likes

Just to clarify: if you mean something like phps mysql(real)escapestring; that is not the recommended way to execute queries. What you would instead do (as a previous answer already stated) is create a prepared statement, which tells the sql server “here is a query with some holes for values in it, and I will give you those values later”, and execute the statement with those values. This way, the sql server knows exactly what is part of the query and what is part of the code, and there is much less chance of any injection attempts getting through.

Apologies if this is super on-the-nose/you knew that already, I just think it bears repeating :innocent:

1 Like

im using sqlite library. I saw the rusqlite project but I have written a lot of stuff using sqlite already and I running against a deadline o its not exactly the best Tim for me to change all the code I wrote specific to the sqlite library

Which from a very short look at it, just expects a string which is a raw SQL query. So just writing NULL literally should work.

If not perhaps don’t tell what you tried but give explicit examples.

After many of you suggested using prepared queries I have just written this piece of code I hope it helps someone else as well. Thanks for all the help and suggestions.

pub fn prepared_insert(
    sql: &str, params: &[sqlite::Value], con: &sqlite::Connection,
) -> sqlite::Result<Option<Vec<sqlite::Value>>>
{
    let mut cursor = con.prepare(sql)?.cursor();
    cursor.bind(params)?;
    let val = cursor.next()?;
    Ok(val
        .map(|v| Some(v.iter().cloned().collect()))
        .unwrap_or_default())
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.