Deleting non existing record should raise an error in sqlalchemy

python, sqlalchemy

Solution

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

Problem

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.

Original source

Related problems