belchior / sql_query_builder

Write SQL queries in a simple and composable way
https://crates.io/crates/sql_query_builder
MIT License
54 stars 5 forks source link

A way to get query + parameters separately instead of as a string? #1

Closed brandonros closed 1 year ago

brandonros commented 1 year ago

By only having as_string() isn't this library vulnerable to SQL injection?

belchior commented 1 year ago

The SQL injection is beyond the scope of the library but you can mitigate this vulnerability using placeholders like login = $1. The example above uses tokio_postgres to prevent agaisnt SQL injection.

use tokio_postgres::{Client, Error, types::ToSql, Row};
use sql_query_builder as sql;

type QueryParam<'a> = &'a (dyn ToSql + Sync);

pub async fn get_user(client: &Client, user_login: &str) -> Result<Vec<Row>, Error> {
  let params: Vec<QueryParam> = vec![user_login];

  let query = sql::Select::new()
    .select("id, login")
    .from("users")
    .where_clause("login = $1")
    .to_string();

  let rows = client.query(query.as_str(), &params[..]).await?;

  Ok(rows)
}