An SQL statement passed to a query method is pieced together from strings at run time

tx0/go:sql-built-from-stringsrecommendedwarningsecurity, cwe-89

What it finds

db.Query("SELECT * FROM users WHERE name = '" + name + "'"): a value spliced into the text of a statement is parsed as SQL, so a quote in it ends the literal and the rest runs as part of the statement. Placeholders, as in db.Query("... WHERE name = ?", name), send the value apart from the statement.

The method must be Query, QueryRow, Exec, Prepare or their Context forms, in a file that imports database/sql, and the statement argument a concatenation with a part that is not constant, or a call of fmt.Sprintf with arguments, whose constant text starts with an SQL keyword such as SELECT, INSERT, UPDATE, DELETE or WITH. The statement may also be a local variable declared with such a value, as in q := fmt.Sprintf("SELECT ... %s", name) followed by db.Query(q). Names of tables or columns cannot be placeholders; when they come from a fixed set in the program, the finding can be suppressed.

From the rule's source, sql_built_from_strings.rs.

Example from the rule's tests
package p import (	"context"	"database/sql"	"fmt") func f(ctx context.Context, db *sql.DB, name, table string) error {	if _, err := db.Query("SELECT * FROM users WHERE name = '" + name + "'"); err != nil {tx0 reports: this SQL statement is built from strings at run time		return err	}	q := fmt.Sprintf("DELETE FROM %s WHERE id = 1", table)	if _, err := db.ExecContext(ctx, fmt.Sprintf("UPDATE users SET name = '%s'", name)); err != nil {tx0 reports: this SQL statement is built from strings at run time		return err	}	if _, err := db.Exec(q); err != nil {tx0 reports: this SQL statement is built from strings at run time		return err	}	_, err := db.Query("SELECT * FROM users WHERE name = ?", name)	return err}
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/go:sql-built-from-strings" = "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/go:sql-built-from-strings] reason="..."

tx0 explain tx0/go:sql-built-from-strings shows the same in the terminal. Found a false positive? Report it.