Databases
Pools, placeholders, scanning, transactions, and N+1.
What is *sql.DB?
All questions with explanations (answers shown)
1. What is
*sql.DB?Answer: A connection pool, safe for concurrent use
Create one for the whole program, share it across goroutines, and never close it per request.
2. What is the default value of
SetMaxOpenConnsif you never call it?Answer: Unlimited
Unlimited, so a traffic spike keeps opening connections until Postgres hits
max_connectionsand refuses new ones. The pool limit is your backpressure. Always set it.3. Which is safe against SQL injection?
Answer:
db.QueryRowContext(ctx, "SELECT ... WHERE id = $1", id)Placeholders send the query and the data separately, so the data can never be parsed as SQL. There is no exception to this, not even for "internal" endpoints.
4. After looping with
rows.Next(), what must you not forget?Answer:
defer rows.Close()and checkingrows.Err()Without
Closeyou leak a pooled connection, and iteration errors surface only throughrows.Err(): the loop just ends early and looks successful.5. You call
repo.GetUseronce per row inside a loop over 200 notes. What is this called?Answer: The N+1 problem
201 round trips instead of one. Fix it with a JOIN, or one batched query using
WHERE id = ANY($1). It is one of the most common performance bugs in web code, in any language.6. Why use a named return value in a function that runs a transaction?
Answer: So the deferred rollback can see whether an error occurred
This is one of the few places where naming a return pays off:
defer func() { if err != nil { tx.Rollback() } }().7. Which of these should never happen inside a transaction?
Answer: An HTTP call to a third-party service
A transaction holds a pooled connection for its whole life. A slow third party then ties up a database connection, and enough of those use up the whole pool.
8. Why should you never write
SELECT *?Answer: Adding a column breaks every
Scanat once, with an unhelpful errorScanmatches columns positionally. List the columns and a new one changes nothing.9. Find the bug:
rows, err := db.QueryContext(ctx, q); if err != nil { return err }; for rows.Next() { if err := rows.Scan(&x); err != nil { return err } }; return rows.Err()Answer: There is no
defer rows.Close(), so an earlyreturninside the loop leaks a pooled connectionrowsholds a connection until it is closed. WhenNextreturns false the rows close themselves, but any early return skips that. Putdefer rows.Close()right after the error check.10. A list query sometimes returns fewer rows than expected, with no error. The loop is
for rows.Next() { ... }and thenreturn items, nil. What is the most likely cause?Answer:
rows.Err()is never checked, so an error part-way through (such as a dropped connection) looks like the end of the resultsNextreturns false both at the end and on an error. Onlyrows.Err()tells them apart. Return it after the loop.11. Which is the right fix for
db.QueryContext(ctx, fmt.Sprintf("SELECT id FROM users WHERE email = '%s'", email))?Answer: Pass the value as a parameter:
db.QueryContext(ctx, "SELECT id FROM users WHERE email = $1", email)Building SQL with
Sprintfis SQL injection. With a placeholder the value is sent separately from the SQL text, so it can never change the query. Escaping by hand always misses a case.12. A handler runs a slow report with
db.QueryContext(context.Background(), q). The user closes the tab. What happens, and what is the fix?Answer: The query keeps running and holding a connection; pass
r.Context()so it is cancelled when the client goes awaycontext.Background()is never cancelled.r.Context()is cancelled when the client disconnects, and the driver then cancels the query and frees the connection.