Code RoomPhantom read allows duplicate email
HardPrep Room Coding #2271

Phantom read allows duplicate email

Code reviewDatabases & SQLSenior–Staff~28 min

Review this Go signup function that enforces one account per email.

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.

0:00 of about 28 min
Mark a line and say what kind of problem it is.0 findings
1func CreateUser(ctx context.Context, db *sql.DB, email, name string) error {
2 tx, _ := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
3 var n int
4 tx.QueryRowContext(ctx,
5 "SELECT COUNT(*) FROM users WHERE email = $1", email).Scan(&n)
6 if n > 0 {
7 tx.Rollback()
8 return ErrEmailTaken
9 }
10 _, err := tx.ExecContext(ctx,
11 "INSERT INTO users (email, name) VALUES ($1, $2)", email, name)
12 if err != nil {
13 tx.Rollback()
14 return err
15 }
16 return tx.Commit()
17}
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.