feat: added db transactions abstraction; cleaned up user registration; repos adapted new abstraction: all repos now support transactions, if present in ctx

This commit is contained in:
2026-09-01 14:55:20 +02:00
parent f87b0a0707
commit 2e3e82e776
14 changed files with 219 additions and 145 deletions
+5 -20
View File
@@ -2,30 +2,19 @@ package repository
import (
"context"
"database/sql"
"fmt"
"github.com/robindittmar/dttmr-api/internal/domain"
)
type UserRepo struct {
db *sql.DB
}
func NewUserRepo(db *sql.DB) *UserRepo {
return &UserRepo{db: db}
Repo
}
func (r *UserRepo) CreateUser(ctx context.Context, email string, name string, passwordHash string) (*domain.User, error) {
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("begin transaction: %w", err)
}
defer tx.Rollback()
user := &domain.User{Email: email, Name: name}
err = tx.QueryRowContext(ctx,
err := r.conn(ctx).QueryRowContext(ctx,
"INSERT INTO users (email, name, password_hash) VALUES ($1, $2, $3) RETURNING id, created_at",
email, name, passwordHash,
).Scan(&user.ID, &user.CreatedAt)
@@ -33,15 +22,11 @@ func (r *UserRepo) CreateUser(ctx context.Context, email string, name string, pa
return nil, fmt.Errorf("failed to insert user: %w", err)
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit transaction: %w", err)
}
return user, nil
}
func (r *UserRepo) DeleteUser(ctx context.Context, userID string) error {
_, err := r.db.ExecContext(ctx,
_, err := r.conn(ctx).ExecContext(ctx,
"DELETE FROM users WHERE id = $1",
userID,
)
@@ -53,7 +38,7 @@ func (r *UserRepo) DeleteUser(ctx context.Context, userID string) error {
}
func (r *UserRepo) ChangePassword(ctx context.Context, userID string, passwordHash string) error {
_, err := r.db.ExecContext(ctx,
_, err := r.conn(ctx).ExecContext(ctx,
"UPDATE users SET password_hash = $1 WHERE id = $2",
passwordHash, userID,
)
@@ -67,7 +52,7 @@ func (r *UserRepo) ChangePassword(ctx context.Context, userID string, passwordHa
func (r *UserRepo) GetUserByEmail(ctx context.Context, email string) (*domain.User, error) {
user := &domain.User{}
err := r.db.QueryRowContext(ctx,
err := r.conn(ctx).QueryRowContext(ctx,
"SELECT id, email, name FROM users WHERE email = $1",
email,
).Scan(&user.ID, &user.Email, &user.Name)