-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase_persistence.rb
90 lines (73 loc) · 2.18 KB
/
database_persistence.rb
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
require 'pg'
class DatabasePersistence
def initialize(logger)
@db = if Sinatra::Base.production?
PG.connect(dbname: "todos", user: "postgres")
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 = 'SELECT * FROM lists WHERE id = $1;'
result = query(sql, id)
tuple = result.first
list_id = tuple['id'].to_i
todos = find_todos_for_list(list_id)
{ id: list_id, name: tuple['name'], todos: todos }
end
def all_lists
sql = 'SELECT * FROM lists;'
result = query(sql)
result.map do |tuple|
list_id = tuple['id'].to_i
todos = find_todos_for_list(list_id)
{ id: list_id, name: tuple['name'], todos: todos }
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
private
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
end