-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathuser_repository.go
60 lines (46 loc) · 1.37 KB
/
user_repository.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (c) 2023-2024 Vasiliy Vasilyuk. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package testing_go_code_with_postgres
import (
"context"
"database/sql"
"fmt"
"github.com/google/uuid"
)
type DB interface {
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
func NewUserRepository(db DB) *UserRepository {
return &UserRepository{db: db}
}
type UserRepository struct {
db DB
}
func (r *UserRepository) ReadUser(ctx context.Context, userID uuid.UUID) (User, error) {
const sql = `SELECT user_id, username, created_at FROM users WHERE user_id = $1;`
user := User{}
row := r.db.QueryRowContext(ctx, sql, userID)
err := row.Scan(&user.ID, &user.Username, &user.CreatedAt)
if err != nil {
const format = "failed selection of User from database: %w"
return User{}, fmt.Errorf(format, err)
}
return user, nil
}
func (r *UserRepository) CreateUser(ctx context.Context, user User) error {
const sql = `INSERT INTO users (user_id, username, created_at) VALUES ($1,$2,$3);`
_, err := r.db.ExecContext(
ctx,
sql,
user.ID,
user.Username,
user.CreatedAt,
)
if err != nil {
const format = "failed insertion of User to database: %v"
return fmt.Errorf(format, err)
}
return nil
}