An SQL query is built by formatting values into its text

tx0/python:sql-formattingrecommendedwarningsecurity, cwe-89

What it finds

cursor.execute(f"SELECT * FROM users WHERE name = '{name}'"): a query built by formatting values into its text breaks on quotes in the values, and lets whoever controls them change the query (CWE-89). Database drivers take the values apart from the query, as in cursor.execute("... WHERE name = %s", (name,)).

Reported are calls of methods named execute, executemany, executescript, raw and extra whose first argument starts with an SQL keyword and is an f-string with replacement fields, a % format or a .format call with values, or a concatenation with something that is not a literal.

From the rule's source, sql_formatting.rs.

Example from the rule's tests
def query(cursor, name, table, ids):    cursor.execute(f"SELECT * FROM users WHERE name = '{name}'")tx0 reports: this query is built with an f-string    cursor.execute("DELETE FROM %s" % table)tx0 reports: this query is built with % formatting    cursor.execute("select id from t where id in ({})".format(ids))tx0 reports: this query is built with str.format    cursor.execute("UPDATE t SET a = 1 WHERE b = " + name)tx0 reports: this query is built with concatenation    cursor.execute("SELECT * FROM users WHERE name = %s", (name,))    cursor.execute("SELECT 1 " "FROM t")    cursor.execute(f"VACUUM {table}")    cursor.execute("SELECT * FROM t " + "WHERE a = 1")
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/python:sql-formatting" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

# tx0: ignore[tx0/python:sql-formatting] reason="..."

tx0 explain tx0/python:sql-formatting shows the same in the terminal. Found a false positive? Report it.