I need to verify existence of entities in the database.
If db_is_team_exist(team_id):
If db_is_user_exist_by_id(user_id):
ok
else:
raise ObjectDoesNotExist("user", user_id)
else:
raise ObjectDoesNotExist("team", team_id)
Query functions in the database:
def db_is_team_exist(team_id: str) -> bool:
cursor.execute(f "SELECT COUNT(1) FROM teams WHERE id='{team_id}';")
return bool(cursor.fetchone()[0])
def db_is_user_exist_by_id(user_id: str) -> bool:
cursor.execute(f "SELECT COUNT(1) FROM users WHERE id='{user_id}';")
return bool(cursor.fetchone()[0])
Sometimes there are too many of these checks for me to afford such a load on the database. Is there any way to check existence of two entities which are in different tables with one query? Or reduce the number of queries in the database in another way?
CodePudding user response:
You can technically use a single query like:
SELECT 1 WHERE
EXISTS (SELECT 'x' FROM teams WHERE id='{team_id}')
AND
EXISTS (SELECT 'x' FROM users WHERE id='{user_id}')
Please use proper parameterized queries though.
