typed_sql/
lib.rs

1//! # Complex queries
2//! See [`Query`] for available methods.
3//!
4//! ```
5//! use typed_sql::{Query, Table, ToSql};
6//!
7//! #[derive(Table)]
8//! struct User {
9//!     id: i64,
10//!     name: String
11//! }
12//!
13//! let stmt = User::table()
14//!     .select()
15//!     .filter(|user| user.id.neq(6).and(user.id.gt(3)))
16//!     .group_by(|user| user.name)
17//!     .order_by(|user| user.name.then(user.id.ascending()))
18//!     .limit(5);
19//!
20//! assert_eq!(
21//!     stmt.to_sql(),
22//!     "SELECT * FROM users \
23//!     WHERE users.id != 6 AND users.id > 3 \
24//!     GROUP BY users.name \
25//!     ORDER BY users.name,users.id ASC \
26//!     LIMIT 5;"
27//! );
28//! ```
29//! ## Injections
30//! Queries with user input strings are vulnerable to SQL injections
31//! and therefore must be serialized with [`ToSql::to_sql_unchecked`].
32//!
33//! ```
34//! use typed_sql::{Insertable, Query, Table, ToSql};
35//!
36//! #[derive(Table, Insertable)]
37//! struct User {
38//!     name: String
39//! }
40//!
41//! let stmt = User::table().insert(User { name: String::from("untrusted") });
42//!
43//! assert_eq!(
44//!     stmt.to_sql_unchecked(),
45//!     "INSERT INTO users(name) VALUES ('untrusted');"
46//! );
47//! ```
48//!
49//! To avoid this use prepared statements with [`Binding`].
50//! ```
51//! use typed_sql::{Binding, Query, Table, ToSql};
52//!
53//! #[derive(Binding, Table)]
54//! struct User {
55//!     name: String
56//! }
57//!
58//! let id_plan = User::prepare("idplan", |binds| {
59//!     User::table().update(|user| user.name.eq(binds.name))
60//! });
61//!
62//! assert_eq!(
63//!     id_plan.to_sql(),
64//!     "PREPARE idplan AS UPDATE users SET users.name = $1;"
65//! );
66//!
67//! let stmt = id_plan.execute(User { name: String::from("foo") });
68//! assert_eq!(stmt.to_sql(), "EXECUTE idplan('foo');");
69//! ```
70
71#[cfg(feature = "sqlx")]
72pub mod fetch;
73#[cfg(feature = "sqlx")]
74pub use fetch::Fetch;
75
76pub mod query;
77pub use query::{Insertable, Join, Query, Queryable};
78
79mod sql;
80pub use sql::{CheckedSql, ToSql};
81
82pub mod table;
83pub use table::Table;
84
85pub mod types;
86pub use types::Binding;
87
88pub use typed_sql_derive::*;