package repository import ( "context" "database/sql" "errors" "github.com/jackc/pgerrcode" "github.com/jackc/pgx/v5/pgconn" ) var ( ErrAlreadyExists = errors.New("entry already exists") ErrNotFound = errors.New("entry not found") ) type AccountData struct { UUID string Email string PasswordHash string } // CreateAccount adds a new account to a database func CreateAccount(ctx context.Context, db *sql.DB, account *AccountData) error { query := "INSERT INTO accounts (uuid, email, password_hash) VALUES ($1, $2, $3)" if _, err := db.ExecContext(ctx, query, account.UUID, account.Email, account.PasswordHash); err != nil { var pgErr *pgconn.PgError if errors.As(err, &pgErr) { if pgErr.Code == pgerrcode.UniqueViolation { return ErrAlreadyExists } return err } return err } return nil } // GetPasswordHashForEmail returns the password hash for a user func GetPasswordHashForEmail(ctx context.Context, db *sql.DB, email string) (hash string, err error) { query := "SELECT password_hash FROM accounts WHERE email = $1;" if err = db.QueryRowContext(ctx, query, email).Scan(&hash); err != nil { if errors.Is(err, sql.ErrNoRows) { return "", ErrNotFound } return } return } // GetUUIDForEmail returns a uuid of a user func GetUUIDForEmail(ctx context.Context, db *sql.DB, email string) (uuid string, err error) { query := "SELECT uuid FROM accounts WHERE email = $1;" if err = db.QueryRow(query, email).Scan(&uuid); err != nil { if errors.Is(err, sql.ErrNoRows) { return "", ErrNotFound } return } return }