On Jan 22, 2012, at 7:50 PM, Jackson, Cameron wrote:

> I have a certain ORM model that is being referenced from several other 
> models. I don't want the user to be able to delete rows from that table that 
> are still being referenced elsewhere.
>  
> Ideally I would like something like:
>     refs = get_references(row)
>     if refs:
>         print "Can't delete row because of:"
>         for ref in refs:
>             print ref
>     else:
>         self.session.delete(row)
>  
> Or even just:
>     if is_being_referenced(row):
>         print "You can't delete that!"
>     else:
>         self.session.delete(row)
>  
> If there's no way to do either of those, then I would settle for:
>     try:
>         self.session.delete(row)
>     except sql.exc.DeletionError:
>         print "You can't delete that!"
>         #Again, a way to get a list of the offending references would be nice!
>  

So I'm assuming you'd like some kind of GUI-friendly indicator here.    If 
people are just writing code I'd argue the IntegrityError should be enough, as 
you know SQLA tries hard to not do redundant work versus what the database can 
do much better.   The error is much more complete, efficient, and accurate than 
the ORM could ever do.

Anyway, to do this reliably would definitely need the database to be accessed - 
any relationship that isn't loaded would need to be queried against, at least a 
"count" to see if rows exist.   Then, it gets more complicated if the operation 
is to cascade appropriately, such as if deleting A naturally deletes B, but 
then you get IntegrityError because row C depends on B - if you needed that 
then the functionality would have to cascade throughout everything, loading all 
the relationships in its path to get at the related records.

The implementation can also be very complicated if you expect it to work 
without your target object having relationships out to these other objects.   
Not only would you need to have some kind of registry that allows you to track 
all the other classes that might depend on this one, you'd also need to scan 
through all of them and query the database for every possible relationship 
pointing at your object.

So assuming you want just a really simple thing here, and also you can have all 
the relationships coming off the target class, an event-based approach would 
look through Session.deleted and look at all the relationship-bound references 
associated with the object:

from sqlalchemy.orm.interfaces import ONETOMANY, MANYTOMANY
from sqlalchemy.orm.properties import RelationshipProperty

@event.listens_for(Session, "before_flush")
def check_illegal_deletes(session, flush_context, instances):
    for obj in session.deleted:
        mapper = object_mapper(obj)
        for prop in mapper.get_properties():
           if isinstance(prop, RelationshipProperty) and \
                  prop.direction in (ONETOMANY, MANYTOMANY):
                  if (
                          # check for those that are loaded
                          prop.key in obj.__dict__ and 
                          bool(obj.__dict__[key])
                     ) or \
                    # do a count if not loaded.   this is if you need unloaded 
                    # things to be included
                    session.query(prop.mapper).with_parent(obj, 
prop.key).count():
                      raise Exception("object %s has referred objects in 
relationship %s" % (obj, key))
                     
if you truly need this to happen at the instant session.delete() is called, 
note that this isn't as complete as the event since it won't account for the 
"delete" cascade, but you can also subclass Session and override 
Session.delete() to perform a similar check as above.

> I tried doing the above, catching IntegrityError, but the problem is that 
> SQLA doesn't 'notice' the error and tell me about it until another action 
> occurs that causes other queries to be run. Is there some way I can make SQLA 
> check the integrity of the database immediately after the deletion? 
> Preferably without running unnecessary queries if that’s going to cause a 
> performance hit.

Session.delete() doesn't hit the database, it only marks the item for deletion 
on the next flush.  So you'd never get the IntegrityError until the flush.   
Also once you get the IntegrityError, that's the end of the line - unless 
you're catching the exception and then doing more queries yourself, there's no 
other queries being run.



>  
> Cheers,
> Cam
> Cameron Jackson
> Engineering Intern
> Air Operations
> Thales Australia
> Thales Australia Centre, WTC Northbank Wharf, Concourse Level,
> Siddeley Street, Melbourne, VIC 3005, Australia
> Tel: +61 3 8630 4591
> cameron.jack...@thalesgroup.com.au | www.thalesgroup.com.au
> ------------------------------------------------------------------------- 
> DISCLAIMER: This e-mail transmission and any documents, files and previous 
> e-mail messages attached to it are private and confidential. They may contain 
> proprietary or copyright material or information that is subject to legal 
> professional privilege. They are for the use of the intended recipient only. 
> Any unauthorised viewing, use, disclosure, copying, alteration, storage or 
> distribution of, or reliance on, this message is strictly prohibited. No part 
> may be reproduced, adapted or transmitted without the written permission of 
> the owner. If you have received this transmission in error, or are not an 
> authorised recipient, please immediately notify the sender by return email, 
> delete this message and all copies from your e-mail system, and destroy any 
> printed copies. Receipt by anyone other than the intended recipient should 
> not be deemed a waiver of any privilege or protection. Thales Australia does 
> not warrant or represent that this e-mail or any documents, files and 
> previous e-mail messages attached are error or virus free. 
> -------------------------------------------------------------------------
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
> To post to this group, send email to sqlalchemy@googlegroups.com.
> To unsubscribe from this group, send email to 
> sqlalchemy+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/sqlalchemy?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to