Web application security · 6 MIN READ
SQL injection: the query text and the user's values must reach the driver separately
Send untrusted values as database/sql arguments, pick identifiers from allow-lists in code and escape LIKE wildcards with an explicit ESCAPE clause.
SQL injection happens when a value supplied by a user becomes part of the statement the database parses. database/sql gives you a second channel: the query text reaches the driver as one string and every argument travels beside it as a typed value. The SQL rows lesson stated that placeholders bind values, not grammar; this lesson makes that separation visible with a recording driver and covers the places where binding alone is not enough: identifiers, sort direction and LIKE patterns.
security · A MAP OF THE IDEA
- Keep statement constant
- Bind values as args
- Allow-list identifiers
- Escape LIKE wildcards
Useful when
- The database never parses user input as SQL syntax.
- Constant statements are easy to review, grep and prepare once.
Watch out
- Raw-SQL methods in ORMs and query builders reintroduce concatenation.
- A bound LIKE, regex or full-text value is still interpreted by its operator.
Implementation & operation cost: Almost nothing at run time; the cost is review discipline and a small allow-list map for every dynamic identifier.
Concatenation hands the parser your user's syntax
Build a statement with + or fmt.Sprintf and the database receives one string. It cannot know which characters came from your code and which came from a form field, so a name such as x' OR '1'='1 closes the string literal and appends a condition that is always true. Escaping quotes by hand looks like a fix until a different character set, a backslash rule or a numeric position that needs no quotes at all defeats it. The durable fix is structural: keep the statement constant and pass values through the driver's parameter mechanism, so a value never passes through the SQL parser as syntax. Placeholder syntax belongs to the driver, not to database/sql: PostgreSQL drivers use $1, $2 and so on, while MySQL and SQLite drivers use ?.
Record what database/sql actually hands the driver
A database driver implements a few interfaces from database/sql/driver. This program registers a tiny fake whose connection implements QueryerContext: database/sql calls it with the query string and a slice of driver.NamedValue, and the fake prints both instead of contacting a server. Four calls show a concatenated statement, a parameterized one, an allow-listed ORDER BY and a LIKE search for text that itself contains wildcard characters.
package main
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
"strings"
)
// recordingDriver is a test double: it prints what database/sql hands to a
// driver and returns no rows. A real driver sends the same two parts to the
// database server.
type recordingDriver struct{}
func (recordingDriver) Open(string) (driver.Conn, error) { return conn{}, nil }
type conn struct{}
func (conn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare not supported") }
func (conn) Close() error { return nil }
func (conn) Begin() (driver.Tx, error) { return nil, errors.New("transactions not supported") }
// QueryContext receives the SQL text and the arguments as separate values.
func (conn) QueryContext(_ context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
vals := make([]string, len(args))
for i, a := range args {
vals[i] = fmt.Sprintf("$%d=%T(%#v)", a.Ordinal, a.Value, a.Value)
}
fmt.Printf(" sql: %s\n args: [%s]\n", query, strings.Join(vals, " "))
return emptyRows{}, nil
}
type emptyRows struct{}
func (emptyRows) Columns() []string { return []string{"id"} }
func (emptyRows) Close() error { return nil }
func (emptyRows) Next([]driver.Value) error { return io.EOF }
// sortColumns maps a public sort key to a fixed SQL fragment.
var sortColumns = map[string]string{
"name": "name ASC",
"newest": "created_at DESC",
}
// likeEscaper makes %, _ and the escape character itself literal.
var likeEscaper = strings.NewReplacer("!", "!!", "%", "!%", "_", "!_")
func run(ctx context.Context, db *sql.DB, query string, args ...any) {
rows, err := db.QueryContext(ctx, query, args...)
if err != nil {
fmt.Println(" error:", err)
return
}
defer rows.Close()
for rows.Next() {
}
if err := rows.Err(); err != nil {
fmt.Println(" error:", err)
}
}
func main() {
sql.Register("recorder", recordingDriver{})
db, err := sql.Open("recorder", "")
if err != nil {
panic(err)
}
defer db.Close()
ctx := context.Background()
name := "x' OR '1'='1"
fmt.Println("concatenated (vulnerable):")
run(ctx, db, "SELECT id FROM users WHERE name = '"+name+"'")
fmt.Println("parameterized:")
run(ctx, db, "SELECT id FROM users WHERE name = $1", name)
fmt.Println("allow-listed ORDER BY:")
for _, key := range []string{"newest", "name; DROP TABLE users"} {
order, ok := sortColumns[key]
if !ok {
fmt.Printf(" rejected sort key %q\n", key)
continue
}
run(ctx, db, "SELECT id FROM users ORDER BY "+order+" LIMIT $1", 20)
}
fmt.Println("LIKE with escaped wildcards:")
pattern := "%" + likeEscaper.Replace("50%_off!") + "%"
run(ctx, db, "SELECT id FROM products WHERE title LIKE $1 ESCAPE '!'", pattern)
}In the first call the attacker's quote marks are inside the sql line and args is empty: the OR clause is now part of the statement. In the second call the statement is constant and the same characters arrive as a string argument bound to $1, so the database compares name with that exact string. database/sql converts each argument to a driver.Value before the driver sees it, which is why the untyped 20 arrives as int64. The sort key is looked up in a map of fixed SQL fragments, so the hostile key never reaches the driver at all. The LIKE pattern is still an argument, but its % and _ were escaped with ! first and the statement declares ESCAPE '!'. The fake parses nothing; it models the interface boundary, not database behavior.
Identifiers and keywords need an allow-list, not a placeholder
A placeholder can stand only where the grammar expects a value. Table names, column names, ASC and DESC are part of the statement's structure, so a database either rejects ORDER BY $1 or sorts every row by the same constant value, which silently does nothing. When a request legitimately chooses among columns, map public keys such as newest or name to SQL fragments written in your code, reject anything else with a 400 and keep the map next to the query so a reviewer sees the complete set. The same rule covers table names chosen for partitioning or tenancy: take them from configuration you own, never from the request. IN lists are the other common case: generate one placeholder per element from the count, and pass the elements as arguments.
// placeholders(3) == "$1, $2, $3"; the values themselves stay in args.
func placeholders(n int) string {
parts := make([]string, n)
for i := range parts {
parts[i] = "$" + strconv.Itoa(i+1)
}
return strings.Join(parts, ", ")
}
func postsByID(ctx context.Context, db *sql.DB, ids []int64) (*sql.Rows, error) {
if len(ids) == 0 || len(ids) > 500 {
return nil, errors.New("between 1 and 500 ids")
}
query := "SELECT id, title FROM posts WHERE id IN (" + placeholders(len(ids)) + ")"
args := make([]any, len(ids))
for i, id := range ids {
args[i] = id
}
return db.QueryContext(ctx, query, args...)
}This fragment runs in your own service against a real PostgreSQL driver. The SQL text is built only from a number your code controls, so this concatenation is safe; every id still travels as an argument. The empty-list check matters because IN () is a syntax error, and the upper bound matters because every database limits how many parameters one statement may carry. Drivers that encode slices can bind a whole array instead, as in id = ANY($1) with PostgreSQL.
A bound LIKE pattern is still a small language
Binding a search term stops injection into the statement, but LIKE interprets the bound value: % matches any run of characters and _ matches exactly one. A user searching for 100% or snake_case gets wrong results, and a pattern that begins with % cannot use an ordinary B-tree index, so a public search box needs length and rate limits anyway. Escape the wildcards and the escape character itself, then name that character in an ESCAPE clause instead of relying on a default: PostgreSQL and MySQL default to backslash, SQLite has none, and in MySQL a backslash inside a string literal is itself an escape, which is why the example uses !. Treat other embedded languages the same way: regular expressions, full-text query syntax and JSON path expressions accept operators inside a bound value, so validate their size and shape too.
Where injection survives in code that uses placeholders
Most real injections in Go services come through escape hatches. Query builders and ORMs offer raw-SQL methods for ORDER BY, WHERE fragments and JSON operators, and a fmt.Sprintf passed to one of them is exactly as dangerous as concatenating in db.QueryContext. Second-order injection is the delayed version: a value is stored safely through a parameter, then a reporting job or migration reads it back and splices it into dynamic SQL, trusting it because it came from your own database. Stored procedures that assemble EXECUTE strings move the problem into SQL instead of removing it. Some drivers can be configured to interpolate arguments on the client rather than using server-side parameters, which shifts escaping into the driver; keep the default unless you have measured a reason. Finally, limit the blast radius: the application's database role should not own the schema or read tables it never queries.
Review and test the boundary
In review, look at every QueryContext, ExecContext and QueryRowContext call and ask whether its query argument is a constant or is assembled only from fragments your code owns. Static analysis helps: gosec reports SQL built with string formatting or concatenation (rules G201 and G202). In tests, send hostile values such as quotes, semicolons, comment markers and wildcard characters through the real queries against a disposable database and assert on the rows returned, not merely on the absence of an error. A recording driver like the one above is useful in unit tests to assert that a function sends a constant statement and exactly the expected arguments.
TAKE THIS WITH YOU
Keep every statement constant and pass untrusted values as arguments; choose identifiers and sort order from an allow-list in code, and escape LIKE wildcards with an explicit ESCAPE clause.
Check your understanding
A list endpoint lets clients choose the sort column. Why does a placeholder not solve the injection risk?
Go to the source
Progress stays in this browser. No account needed.