-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathuser_repository.py
More file actions
55 lines (46 loc) · 1.72 KB
/
Copy pathuser_repository.py
File metadata and controls
55 lines (46 loc) · 1.72 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
from psycopg.rows import dict_row
class UserRepository:
def __init__(self, conn):
self.conn = conn
def get_content(self):
with self.conn.cursor(row_factory=dict_row) as cur:
cur.execute("SELECT * FROM users")
return cur.fetchall()
def get_by_term(self, search_term=""):
with self.conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"SELECT * FROM users WHERE name ILIKE %s",
(f"%{search_term}%",),
)
return cur.fetchall()
def find(self, id):
with self.conn.cursor(row_factory=dict_row) as cur:
cur.execute("SELECT * FROM users WHERE id = %s", (id,))
return cur.fetchone()
def save(self, user_data):
if "id" not in user_data:
id = self._create(user_data)
else:
id = self._update(user_data)
return id
def _update(self, user_data):
with self.conn.cursor() as cur:
cur.execute(
"UPDATE users SET name = %s, email = %s WHERE id = %s",
(user_data["name"], user_data["email"], user_data["id"]),
)
self.conn.commit()
return user_data["id"]
def _create(self, user_data):
with self.conn.cursor() as cur:
cur.execute(
"INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id",
(user_data["name"], user_data["email"]),
)
user_data["id"] = cur.fetchone()[0]
self.conn.commit()
return user_data["id"]
def destroy(self, id):
with self.conn.cursor() as cur:
cur.execute("DELETE FROM users WHERE id = %s", (id,))
self.conn.commit()