SQL Injection Prevention Implementation in Swift
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 Swift as in every other language.
- ✓Foundation has no database layer. The SQLite C API is reachable with import SQLite3 (sqlite3_prepare_v2, sqlite3_bind_text, sqlite3_step, sqlite3_finalize), but almost nobody writes that by hand.
- ✓The reviewable signal in Swift is the static type of the SQL, not its spelling. A GRDB SQL or a PostgresQuery built by interpolation is safe by construction; a String assembled with + or interpolation and then handed to an API that takes a String is the reject, because the safe interpolation machinery never ran on it.
- ✓The Swift trap: Two things bite here that bite nowhere else. First, safety lives in the type rather than the syntax, so the identical \(term) is a bound parameter inside a PostgresQuery and a concatenation inside a String, and type inference from the surrounding call can silently pick the unsafe meaning of source that looks the same.
- ✓Argument arrays are value types with copy-on-write, so passing them around is a retain rather than a copy until something mutates.
What SQL Injection Prevention actually is
SQL Injection Prevention in Swift: what you actually reach for
Swift implementation
import GRDB
struct UnsortableColumn: Error {}
enum Sort: String {
case created, name
// ORDER BY is parsed before any value is bound, so it must be constant.
var column: String {
switch self {
case .created: return "created_at"
case .name: return "display_name"
}
}
}
func search(_ db: Database, term: String, sort raw: String, limit: Int) throws -> [String] {
guard let sort = Sort(rawValue: raw) else { throw UnsortableColumn() }
// Annotating SQL rather than String is what makes this safe: every
// \(value) below becomes a bound parameter, and \(identifier:) is
// quoted as a name instead of pasted in as syntax.
let query: SQL = """
SELECT display_name FROM customer
WHERE display_name LIKE \("%" + term + "%")
ORDER BY \(identifier: sort.column) DESC
LIMIT \(limit)
"""
return try String.fetchAll(db, literal: query)
}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 Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for SQL Injection Prevention?
Foundation has no database layer. The SQLite C API is reachable with import SQLite3 (sqlite3_prepare_v2, sqlite3_bind_text, sqlite3_step, sqlite3_finalize), but almost nobody writes that by hand. GRDB.swift is the ecosystem standard, with try Row.fetchAll(db, sql: "... where id = ?", arguments: [id]) and a StatementArguments type; its SQL type is ExpressibleByStringInterpolation, so \(value) becomes a bound parameter while \(identifier:), \(literal:) and \(sql:) are the explicit opt-outs. Server-side, PostgresNIO's PostgresQuery does the same thing, binding every \(value) and reserving \(unescaped:) for raw text.
What is the most common Swift mistake when implementing SQL Injection Prevention?
Two things bite here that bite nowhere else. First, safety lives in the type rather than the syntax, so the identical \(term) is a bound parameter inside a PostgresQuery and a concatenation inside a String, and type inference from the surrounding call can silently pick the unsafe meaning of source that looks the same. Annotate the literal's type explicitly. Second, if you drop to the C API, sqlite3_bind_text defaults to SQLITE_STATIC, meaning SQLite keeps your pointer: a Swift String bridged to UTF-8 only for the duration of a withCString call is freed before sqlite3_step, so you bind released memory. Pass SQLITE_TRANSIENT, obtained via unsafeBitCast(-1, to: sqlite3_destructor_type.self).
How does SQL Injection Prevention actually perform in Swift?
Argument arrays are value types with copy-on-write, so passing them around is a retain rather than a copy until something mutates. Each bound String pays ARC traffic and, unless it is already contiguous UTF-8, a bridging allocation to hand C a buffer. GRDB caches compiled statements per database connection keyed by the SQL text, so an interpolated literal defeats the statement cache exactly as it defeats the safety, while the same text with different arguments reuses the compiled statement. Actor-isolated or serialised database access usually dominates all of this. 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 trialStudying for this? Replit free tiers and academic plans are laid out 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.