Crate concatsql

source ·
Expand description

ConcatSQL

concatsql is a secure library for PostgreSQL, MySQL and SQLite.
Unlike other libraries, you can use string concatenation to prevent SQL injection.

use concatsql::prelude::*;

fn main() {
    let conn = concatsql::sqlite::open(":memory:").unwrap();
    conn.execute(r#"
            CREATE TABLE users (name TEXT, age INTEGER);
            INSERT INTO users (name, age) VALUES ('Alice', 42);
            INSERT INTO users (name, age) VALUES ('Bob',   69);
    "#).unwrap();

    let age = String::from("42");  // user input
    let sql = query!("SELECT name FROM users WHERE age = {age}");
    // At runtime it will be transformed into a query like
    assert_eq!(sql.simulate(), "SELECT name FROM users WHERE age = '42'");
    for row in conn.rows(&sql).unwrap() {
        assert_eq!(row.get(0).unwrap(),      "Alice");
        assert_eq!(row.get("name").unwrap(), "Alice");
    }

    let age = String::from("42 OR 1=1; --");  // user input
    let sql = query!("SELECT name FROM users WHERE age = {age}");
    // At runtime it will be transformed into a query like
    assert_eq!(sql.simulate(), "SELECT name FROM users WHERE age = '42 OR 1=1; --'");
    conn.iterate(&sql, |_| { unreachable!() }).unwrap();
}

Modules

mysqlmysql
Interface to MySQL of ConcatSQL.
postgrespostgres
Interface to PostgreSQL of ConcatSQL.
Re-exports important traits and types.
sqlitesqlite
Interface to SQLite of ConcatSQL.

Macros

A macro making it more convenient to pass heterogeneous lists of parameters as a &[&dyn ToValue].
prepDeprecated
Prepare a SQL statement for execution.
Prepare a SQL statement for execution.
Sanitizes a string so that it is safe to use within an SQL LIKE statement.

Structs

A database connection.
A single result row of a query.
Wraps a String type.

Enums

Enum listing possible errors from concatsql.
Change the output error message.
Values that can be bound as static placeholders.

Traits

Parse a value from a sql string.
A trait implemented by types that can index into columns of a row.
A trait for converting that can be converted to WrapString.
A trait for types that can be converted into Database values.

Functions

Convert special characters to HTML entities.
prepDeprecated
Prepare a SQL statement for execution.
Does not escape.

Type Definitions

A typedef of the result returned by many methods.