Reputation: 75
Why deleting non-existing record does not raise an error in sqlalchemy. no feedback on whether the record was deleted or not.
session.query(Element).filter(Element.id==ElementId).delete()
Thank you for your clarification.
Upvotes: 7
Views: 9931
Reputation: 1565
Adding an answer to @madogan, the edit queue was full and hence writing a new answer.
I've expanded his answer more in detail in a working solution:
class NoEntryFoundException(Exception):
pass
def delete_row_entry(element_id: int):
effected_rows = session.query(Element).filter(Element.id == element_id).delete()
if effected_rows == 0:
raise NoEntryFoundException(f'No row entry found with id: {element_id}')
else:
session.commit()
Upvotes: 0
Reputation: 665
Actually, sqlalchemy delete operation returns number of affected rows. So you can check and if affected rows is 0 then you can raise error.
effected_rows = session.query(Element).filter(Element.id==ElementId).delete()
if effected_rows == 0:
# raise exception
else:
# delete element
This works for me.
Upvotes: 4
Reputation: 55972
I don't think it is an error. For example it is perfectly legal to issue a query to delete records in sql that "don't exist"
If i have a table 'posts' with a column 'id'. with no records
DELETE FROM posts WHERE ID > 0;
It is perfectly valid sql, there is no error, even though there are no rows
I am not too familiar with sqlalchmey but could you check to see if value exists first?
element = session.query(Element).filter(Element.id==ElementId).first()
if element:
# delete element
else:
# raise exception
The above will issue an additional query though...
Also, if you want a delete
method that raises error you can create your own session class
Change SQLAlchemy's Session.delete() behaviour
and override delete
As zzzeek points out delete
with a criteria
Returns the number of rows deleted, excluding any cascades.
Which is another option for seeing if any rows are deleted
Upvotes: 8