repository.*RoomPostgres.Create   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 9
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 2
rs 9.95
c 0
b 0
f 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