-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
82 lines (66 loc) · 1.68 KB
/
db.go
File metadata and controls
82 lines (66 loc) · 1.68 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
)
type Storage struct {
db *pgxpool.Pool
}
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
func NewStorage(pool *pgxpool.Pool) *Storage {
return &Storage{db: pool}
}
func (s *Storage) CreateTask(ctx context.Context, title string) (Task, error) {
var task Task
err := s.db.QueryRow(ctx,
"INSERT INTO tasks (title) VALUES ($1) RETURNING id, title, done",
title,
).Scan(&task.ID, &task.Title, &task.Done)
return task, err
}
func (s *Storage) PrintTask(ctx context.Context, id int) (Task, error) {
var task Task
err := s.db.QueryRow(ctx,
"SELECT id, title, done FROM tasks WHERE id = $1",
id,
).Scan(&task.ID, &task.Title, &task.Done)
return task, err
}
func (s *Storage) UpdateTask(ctx context.Context, id int, title string, done bool) (Task, error) {
var task Task
err := s.db.QueryRow(ctx,
"UPDATE tasks SET title = $1, done = $2 WHERE id = $3 RETURNING id, title, done",
title, done, id,
).Scan(&task.ID, &task.Title, &task.Done)
return task, err
}
func (s *Storage) PrintAllTasks(ctx context.Context) ([]Task, error) {
rows, err := s.db.Query(ctx, "SELECT id, title, done FROM tasks")
if err != nil {
return nil, err
}
defer rows.Close()
var tasks []Task
for rows.Next() {
var task Task
if err := rows.Scan(&task.ID, &task.Title, &task.Done); err != nil {
return nil, err
}
tasks = append(tasks, task)
}
if err := rows.Err(); err != nil {
return nil, err
}
return tasks, nil
}
func (s *Storage) DeleteTask(ctx context.Context, id int) error {
_, err := s.db.Exec(ctx,
"DELETE FROM tasks WHERE id = $1",
id,
)
return err
}