33from fastapi import HTTPException
44from fastapi .datastructures import QueryParams
55
6- from src .infra .database .database import PgDatabase
6+ from src .infra .database .database import Database
77from src .services import paginate , fields_to_update
88from src .infra .security .hashing import bcrypt_context
99from src .infra .database import retrieve_table_columns
1212
1313
1414class UserService :
15- def __init__ (self ) -> None :
15+ def __init__ (self , database : Database ) -> None :
16+ self .database = database
1617 self .table = "usuario"
1718 self .columns = retrieve_table_columns (self .table )
1819 try :
@@ -70,7 +71,7 @@ def view(self, user_id: int) -> dict[str, Any] | None:
7071 user = None
7172
7273 try :
73- with PgDatabase () as db :
74+ with self . database as db :
7475 db .cursor .execute (
7576 f"SELECT { self .all_columns } FROM { self .table } WHERE id = %s" ,
7677 (user_id ,),
@@ -90,7 +91,7 @@ def view_by_email(self, email: str) -> dict[str, Any] | None:
9091 user = None
9192
9293 try :
93- with PgDatabase () as db :
94+ with self . database as db :
9495 db .cursor .execute (
9596 f"SELECT { self .all_columns } FROM { self .table } WHERE email = %s" ,
9697 (email ,),
@@ -110,7 +111,7 @@ def add(self, user: UserAddSchema) -> int:
110111 senha = bcrypt_context .hash (user .senha )
111112
112113 try :
113- with PgDatabase () as db :
114+ with self . database as db :
114115 db .cursor .execute (
115116 f"INSERT INTO { self .table } (email, senha, tipo_usuario_id) VALUES (%s, %s, %s) RETURNING id" ,
116117 (user .email .lower (), senha , user .tipo_usuario_id ),
@@ -150,7 +151,7 @@ def edit(self, user_id: int, user: UserEditSchema) -> None:
150151
151152 set_fields , set_values = fields_to_update (user_dict )
152153 try :
153- with PgDatabase () as db :
154+ with self . database as db :
154155 db .cursor .execute (
155156 f"UPDATE { self .table } SET { set_fields } WHERE id = %s" ,
156157 set_values + (user_id ,),
@@ -163,7 +164,7 @@ def edit(self, user_id: int, user: UserEditSchema) -> None:
163164
164165 def delete (self , user_id : int ) -> None :
165166 try :
166- with PgDatabase () as db :
167+ with self . database as db :
167168 db .cursor .execute (f"DELETE FROM { self .table } WHERE id = %s" , (user_id ,))
168169 db .connection .commit ()
169170 except Exception :
0 commit comments