SQL: from f-string to placeholder
builds on: Trust boundaries and untrusted input
The agent wrote the `-` lines. If someone sends `name` = `x' OR '1'='1`, the WHERE clause becomes always true and the query returns every user's email. In the `+` lines the value is handed to the driver separately from the SQL text, so the database never parses it as SQL. Each driver has its own placeholder syntax: `?` in sqlite3, `$1` in node-postgres, `%s` in psycopg. With psycopg the values still go in a separate tuple. The `%s` there is a marker for the driver, not Python's `%` operator.
// Python
--- a/app/users.py
+++ b/app/users.py
def find_users(db, name):
- q = (f"SELECT id, email FROM users "
- f"WHERE name = '{name}'")
- return db.execute(q).fetchall()
+ return db.execute(
+ "SELECT id, email FROM users "
+ "WHERE name = ?",
+ (name,),
+ ).fetchall()