SQL Injection Prevention Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓SQL Injection Prevention runs in O(n) time and O(n) space, in Rust as in every other language.
- ✓std has no SQL at all. sqlx is the default for async work: the query! and query_as! macros type-check your SQL against a live database at compile time, and the runtime form is sqlx::query("...
- ✓format! never goes near SQL, and since the compiler cannot say so, reviewers do. The query!
- ✓The Rust trap: Rust's hole is at protocol level rather than in syntax. tokio-postgres offers simple_query and batch_execute, which use Postgres's simple query protocol: they accept no parameters at all and will happily run several semicolon-separated statements in one message.
- ✓tokio-postgres has no statement cache: Client::query with a &str prepares internally on every call, minting a fresh statement name (s0, s1, ...), paying Parse and Describe every time and a Close on drop.
What SQL Injection Prevention actually is
SQL Injection Prevention in Rust: what you actually reach for
Rust implementation
use tokio_postgres::Client;
#[derive(Clone, Copy)]
pub enum Sort { Created, Name }
impl Sort {
// Returns &'static str, so the ORDER BY fragment is a literal compiled
// into the binary. Nothing attacker-shaped can become syntax.
fn column(self) -> &'static str {
match self {
Sort::Created => "created_at",
Sort::Name => "display_name",
}
}
}
pub async fn search(
client: &Client,
term: &str,
sort: Sort,
limit: i64,
) -> Result<Vec<(i32, String)>, tokio_postgres::Error> {
// Extended protocol, one statement, values bound out of band. Never
// simple_query or batch_execute here: they take no parameters and
// allow several statements per message.
let sql = format!(
"SELECT id, display_name FROM customer \
WHERE display_name ILIKE $1 ORDER BY {} DESC LIMIT $2",
sort.column()
);
let pattern = format!("%{term}%");
// ToStatement is sealed and implemented for str and Statement, not
// String, so pass a &str. Note this re-prepares on every call; hoist
// client.prepare(&sql).await? into a reused Statement if it is hot.
let rows = client.query(sql.as_str(), &[&pattern, &limit]).await?;
Ok(rows.iter().map(|r| (r.get(0), r.get(1))).collect())
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for SQL Injection Prevention?
std has no SQL at all. sqlx is the default for async work: the query! and query_as! macros type-check your SQL against a live database at compile time, and the runtime form is sqlx::query("... where id = $1").bind(id).fetch_all(&pool). tokio-postgres is the layer below, with client.query("... $1", &[&id]) taking a &[&(dyn ToSql + Sync)]. rusqlite covers SQLite through params![] and named_params!. For SQL that must be assembled, sqlx::QueryBuilder is the sanctioned tool, and diesel offers a fully typed DSL plus sql_query with .bind::<Text, _>() for the raw path.
What is the most common Rust mistake when implementing SQL Injection Prevention?
Rust's hole is at protocol level rather than in syntax. tokio-postgres offers simple_query and batch_execute, which use Postgres's simple query protocol: they accept no parameters at all and will happily run several semicolon-separated statements in one message. They exist for migrations, and reaching for one because &[&(dyn ToSql + Sync)] is fiddly to satisfy converts a bound query into a textbook stacked-statement injection. A quieter one: ToSql maps Option::None to NULL, so WHERE col = $1 with None matches nothing rather than matching NULLs, a silent logic bug that survives any test which only ever passes Some.
How does SQL Injection Prevention actually perform in Rust?
tokio-postgres has no statement cache: Client::query with a &str prepares internally on every call, minting a fresh statement name (s0, s1, ...), paying Parse and Describe every time and a Close on drop. The interpolated and the parameterised form therefore cost the same on the wire; format! is a safety defect, not a latency one. The latency fix is to prepare once and reuse the Statement, or to use a pool wrapper such as deadpool-postgres, whose prepare_cached keys on the SQL text. Binding is dynamic dispatch through ToSql into the binary protocol, no allocation for integers and a borrow for &str, and no GC smooths anything over, so lifetimes must outlive the future. sqlx macros do their work at compile time and add nothing at runtime; the pool checkout, not the bind, is what to measure. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.