Expand description
Construct a full SQL query using raw SQL.
This function exists for cases where a query needs to be written that is not
supported by the query builder. Unlike most queries in Diesel, sql_query
will deserialize its data by name, not by index. That means that you cannot
deserialize into a tuple, and structs which you deserialize from this
function will need to have #[derive(QueryableByName)]
.
This function is intended for use when you want to write the entire query
using raw SQL. If you only need a small bit of raw SQL in your query, use
sql
instead.
Query parameters can be bound into the raw query using SqlQuery::bind()
.
Safety
The implementation of QueryableByName
will assume that columns with a
given name will have a certain type. The compiler will be unable to verify
that the given type is correct. If your query returns a column of an
unexpected type, the result may have the wrong value, or return an error.
Examples
let users = sql_query("SELECT * FROM users ORDER BY id")
.load(connection);
let expected_users = vec![
User { id: 1, name: "Sean".into() },
User { id: 2, name: "Tess".into() },
];
assert_eq!(Ok(expected_users), users);
// Checkout the documentation of your database for the correct
// bind placeholder
let users = sql_query("SELECT * FROM users WHERE id > ? AND name <> ?");
let users = users
.bind::<Integer, _>(1)
.bind::<Text, _>("Tess")
.get_results(connection);
let expected_users = vec![
User { id: 3, name: "Jim".into() },
];
assert_eq!(Ok(expected_users), users);