Merge pull request #234 from vToMy/master

Added support for backref tuple to auto_delete_orphans
This commit is contained in:
Konsta Vesterinen
2016-10-20 09:59:56 +03:00
committed by GitHub
2 changed files with 10 additions and 6 deletions

View File

@@ -235,6 +235,8 @@ def auto_delete_orphans(attr):
'The relationship argument given for auto_delete_orphans needs to ' 'The relationship argument given for auto_delete_orphans needs to '
'have a backref relationship set.' 'have a backref relationship set.'
) )
if isinstance(backref, tuple):
backref = backref[0]
@sa.event.listens_for(sa.orm.Session, 'after_flush') @sa.event.listens_for(sa.orm.Session, 'after_flush')
def delete_orphan_listener(session, ctx): def delete_orphan_listener(session, ctx):
@@ -257,7 +259,7 @@ def auto_delete_orphans(attr):
( (
session.query(target_class) session.query(target_class)
.filter( .filter(
~getattr(target_class, attr.property.backref).any() ~getattr(target_class, backref).any()
) )
.delete(synchronize_session=False) .delete(synchronize_session=False)
) )

View File

@@ -1,5 +1,6 @@
import pytest import pytest
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy.orm import backref
from sqlalchemy_utils import auto_delete_orphans, ImproperlyConfigured from sqlalchemy_utils import auto_delete_orphans, ImproperlyConfigured
@@ -36,17 +37,18 @@ def Tag(Base):
return Tag return Tag
@pytest.fixture @pytest.fixture(params=['entries', backref('entries', lazy='select')],
def Entry(Base, Tag, tagging_tbl): ids=['backref_string', 'backref_with_keywords'])
def Entry(Base, Tag, tagging_tbl, request):
class Entry(Base): class Entry(Base):
__tablename__ = 'entry' __tablename__ = 'entry'
id = sa.Column(sa.Integer, primary_key=True) id = sa.Column(sa.Integer, primary_key=True)
tags = sa.orm.relationship( tags = sa.orm.relationship(
'Tag', Tag,
secondary=tagging_tbl, secondary=tagging_tbl,
backref='entries' backref=request.param
) )
auto_delete_orphans(Entry.tags) auto_delete_orphans(Entry.tags)
return Entry return Entry
@@ -60,7 +62,7 @@ def EntryWithoutTagsBackref(Base, Tag, tagging_tbl):
id = sa.Column(sa.Integer, primary_key=True) id = sa.Column(sa.Integer, primary_key=True)
tags = sa.orm.relationship( tags = sa.orm.relationship(
'Tag', Tag,
secondary=tagging_tbl secondary=tagging_tbl
) )
return EntryWithoutTagsBackref return EntryWithoutTagsBackref