-
Notifications
You must be signed in to change notification settings - Fork 0
/
database_persistence.rb.OLD
111 lines (93 loc) · 2.68 KB
/
database_persistence.rb.OLD
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
require 'pg'
class DatabasePersistence
def initialize(logger)
@db = if Sinatra::Base.production?
PG.connect(ENV['DATABASE_URL'])
else
PG.connect(dbname: "todos")
end
@logger = logger
end
def query(statement, *params)
@logger.info("#{statement}: #{params}")
@db.exec_params(statement, params)
end
def find_list(id)
sql = <<~SQL
SELECT lists.*,
COUNT(todos.id) AS todos_count,
COUNT(NULLIF(todos.completed, true)) AS todos_remaining_count
FROM lists
INNER JOIN todos ON todos.list_id = lists.id
WHERE lists.id = $1
GROUP BY lists.id
ORDER BY lists.name;
SQL
result = query(sql, id)
tuple_to_list_hash(result.first)
end
def all_lists
sql = <<~SQL
SELECT lists.*,
COUNT(todos.id) AS todos_count,
COUNT(NULLIF(todos.completed, true)) AS todos_remaining_count
FROM lists
INNER JOIN todos ON todos.list_id = lists.id
GROUP BY lists.id
ORDER BY lists.name;
SQL
result = query(sql)
result.map do |tuple|
tuple_to_list_hash(tuple)
end
end
def create_new_list(list_name)
sql = 'INSERT INTO lists (name) VALUES ($1);'
query(sql, list_name)
end
def delete_list(id)
query('DELETE FROM todos WHERE list_id = $1', id)
query('DELETE FROM lists WHERE id = $1', id)
end
def update_list_name(id, new_name)
sql = 'UPDATE lists SET name = $1 WHERE id = $2;'
query(sql, new_name, id)
end
def create_new_todo(list_id, todo_name)
sql = 'INSERT INTO todos (name, list_id) VALUES ($1, $2);'
query(sql, todo_name, list_id)
end
def delete_todo_from_list(list_id, todo_id)
sql = 'DELETE FROM todos WHERE list_id = $1 AND id = $2;'
query(sql, list_id, todo_id)
end
def update_todo_status(list_id, todo_id, new_status)
sql = 'UPDATE todos SET completed = $1 WHERE list_id = $2 AND id = $3'
query(sql, new_status, list_id, todo_id)
end
def mark_all_todos_as_completed(list_id)
sql = 'UPDATE todos SET completed = true WHERE list_id = $1;'
query(sql, list_id)
end
def disconnect
@db.close
end
def find_todos_for_list(list_id)
todo_sql = 'SELECT * FROM todos WHERE list_id = $1'
todos_result = query(todo_sql, list_id)
todos_result.map do |todo_tuple|
{ id: todo_tuple['id'].to_i,
name: todo_tuple['name'],
completed: todo_tuple['completed'] == 't' }
end
end
private
def tuple_to_list_hash(tuple)
{
id: tuple['id'].to_i,
name: tuple['name'],
todos_count: tuple['todos_count'].to_i,
todos_remaining_count: tuple['todos_remaining_count'].to_i
}
end
end