Dev Skills
Go tests·12 questions

Databases

Pools, placeholders, scanning, transactions, and N+1.

1 / 12

What is *sql.DB?

All questions with explanations (answers shown)
  1. 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. 2. What is the default value of SetMaxOpenConns if you never call it?

    Answer: Unlimited

    Unlimited, so a traffic spike keeps opening connections until Postgres hits max_connections and refuses new ones. The pool limit is your backpressure. Always set it.

  3. 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. 4. After looping with rows.Next(), what must you not forget?

    Answer: defer rows.Close() and checking rows.Err()

    Without Close you leak a pooled connection, and iteration errors surface only through rows.Err(): the loop just ends early and looks successful.

  5. 5. You call repo.GetUser once 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. 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. 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. 8. Why should you never write SELECT *?

    Answer: Adding a column breaks every Scan at once, with an unhelpful error

    Scan matches columns positionally. List the columns and a new one changes nothing.

  9. 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 early return inside the loop leaks a pooled connection

    rows holds a connection until it is closed. When Next returns false the rows close themselves, but any early return skips that. Put defer rows.Close() right after the error check.

  10. 10. A list query sometimes returns fewer rows than expected, with no error. The loop is for rows.Next() { ... } and then return 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 results

    Next returns false both at the end and on an error. Only rows.Err() tells them apart. Return it after the loop.

  11. 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 Sprintf is 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. 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 away

    context.Background() is never cancelled. r.Context() is cancelled when the client disconnects, and the driver then cancels the query and frees the connection.