simplify: replace mutex + ON CONFLICT with a single DB transaction
Remove the sync.Mutex and CreateUserAtomic (INSERT ON CONFLICT) in favor of a single DB transaction in CreateFirstUser that atomically checks for existing users and inserts. SQLite serializes write transactions, so this is sufficient to prevent the race condition without application-level locking.
This commit is contained in:
@@ -135,28 +135,42 @@ func FindUserByUsername(
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// CreateUserAtomic inserts a user using INSERT ... ON CONFLICT(username) DO NOTHING.
|
||||
// It returns nil, nil if the insert was a no-op due to a conflict (user already exists).
|
||||
func CreateUserAtomic(
|
||||
// CreateFirstUser atomically checks that no users exist and inserts the admin user.
|
||||
// Returns nil, nil if a user already exists (setup already completed).
|
||||
func CreateFirstUser(
|
||||
ctx context.Context,
|
||||
db *database.Database,
|
||||
username, passwordHash string,
|
||||
) (*User, error) {
|
||||
query := "INSERT INTO users (username, password_hash) VALUES (?, ?) ON CONFLICT(username) DO NOTHING"
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("beginning transaction: %w", err)
|
||||
}
|
||||
|
||||
result, err := db.Exec(ctx, query, username, passwordHash)
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
// Check if any user exists within the transaction.
|
||||
var count int
|
||||
|
||||
err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM users").Scan(&count)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("checking user count: %w", err)
|
||||
}
|
||||
|
||||
if count > 0 {
|
||||
return nil, nil //nolint:nilnil // nil,nil signals setup already completed
|
||||
}
|
||||
|
||||
result, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO users (username, password_hash) VALUES (?, ?)",
|
||||
username, passwordHash,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inserting user: %w", err)
|
||||
}
|
||||
|
||||
rowsAffected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("checking rows affected: %w", err)
|
||||
}
|
||||
|
||||
if rowsAffected == 0 {
|
||||
// Conflict: user already exists
|
||||
return nil, nil //nolint:nilnil // nil,nil means conflict (no insert happened)
|
||||
if err = tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("committing transaction: %w", err)
|
||||
}
|
||||
|
||||
insertID, err := result.LastInsertId()
|
||||
|
||||
Reference in New Issue
Block a user