Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting non existing record should raise an error in sqlalchemy

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.

like image 787
zorro Avatar asked Feb 20 '13 16:02

zorro


People also ask

How do I delete a record in SQLAlchemy?

Delete multiple rows in SQLAlchemyPass the delete query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results. The SQLAlchemy query shown in the below code deletes the “non-fiction” genre this will effectively delete multiple rows at one go.

What function from the session object is used to delete items in SQLAlchemy?

Session. delete() marks an object for deletion, which will result in a DELETE statement emitted for each primary key affected.

How do I delete a record in flask?

How do I delete a record in SQLAlchemy? Python Flask and SQLAlchemy ORM It is easy to perform delete operation on a single table. All you have to do is to delete an object of the mapped class from a session and commit the action.

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance. While not directly relevant to this section, if we want to get at it, we should use the inspect() function to access it).


2 Answers

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

like image 164
dm03514 Avatar answered Sep 30 '22 15:09

dm03514


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.

like image 40
madogan Avatar answered Sep 30 '22 15:09

madogan