Total Lines | 55 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | package repository |
||
2 | |||
3 | import ( |
||
4 | "fmt" |
||
5 | |||
6 | "github.com/architectv/estate-task/pkg/model" |
||
7 | "github.com/jmoiron/sqlx" |
||
8 | ) |
||
9 | |||
10 | type RoomPostgres struct { |
||
11 | db *sqlx.DB |
||
12 | } |
||
13 | |||
14 | func NewRoomPostgres(db *sqlx.DB) *RoomPostgres { |
||
15 | 1 | return &RoomPostgres{db: db} |
|
16 | } |
||
17 | |||
18 | func (r *RoomPostgres) Create(room *model.Room) (int, error) { |
||
19 | 1 | var id int |
|
20 | 1 | query := fmt.Sprintf( |
|
21 | `INSERT INTO %s (description, price) VALUES ($1, $2) RETURNING id`, |
||
22 | roomsTable) |
||
23 | 1 | row := r.db.QueryRow(query, room.Description, room.Price) |
|
24 | 1 | if err := row.Scan(&id); err != nil { |
|
25 | 1 | return 0, err |
|
26 | } |
||
27 | |||
28 | 1 | return id, nil |
|
29 | } |
||
30 | |||
31 | func (r *RoomPostgres) Delete(id int) error { |
||
32 | 1 | query := fmt.Sprintf("DELETE FROM %s WHERE id=$1", roomsTable) |
|
33 | 1 | _, err := r.db.Exec(query, id) |
|
34 | |||
35 | 1 | return err |
|
36 | } |
||
37 | |||
38 | func (r *RoomPostgres) GetAll(sortField string, desc bool) ([]*model.Room, error) { |
||
39 | 1 | var rooms []*model.Room |
|
40 | |||
41 | 1 | query := fmt.Sprintf("SELECT * FROM %s ORDER BY %s", roomsTable, sortField) |
|
42 | 1 | if desc { |
|
43 | 1 | query += " DESC" |
|
44 | } |
||
45 | 1 | err := r.db.Select(&rooms, query) |
|
46 | |||
47 | 1 | return rooms, err |
|
48 | } |
||
49 | |||
50 | func (r *RoomPostgres) GetById(id int) (*model.Room, error) { |
||
51 | 1 | room := &model.Room{} |
|
52 | 1 | query := fmt.Sprintf("SELECT * FROM %s WHERE id=$1", roomsTable) |
|
53 | 1 | err := r.db.Get(room, query, id) |
|
54 | |||
55 | 1 | return room, err |
|
56 | } |
||
57 |