Added naturally_equivalent utility function
This commit is contained in:
@@ -210,6 +210,26 @@ def identity(obj):
|
||||
return tuple(id_)
|
||||
|
||||
|
||||
def naturally_equivalent(obj, obj2):
|
||||
"""
|
||||
Returns whether or not two given SQLAlchemy declarative instances are
|
||||
naturally equivalent (all their non primary key properties are equivalent).
|
||||
|
||||
:param obj: SQLAlchemy declarative model object
|
||||
:param obj2: SQLAlchemy declarative model object to compare with `obj`
|
||||
"""
|
||||
for prop in sa.inspect(obj.__class__).iterate_properties:
|
||||
if not isinstance(prop, sa.orm.ColumnProperty):
|
||||
continue
|
||||
|
||||
if prop.columns[0].primary_key:
|
||||
continue
|
||||
|
||||
if not (getattr(obj, prop.key) == getattr(obj2, prop.key)):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def render_statement(statement, bind=None):
|
||||
"""
|
||||
Generate an SQL expression string with bound parameters rendered inline
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy_utils import escape_like, defer_except
|
||||
from sqlalchemy_utils import escape_like
|
||||
from sqlalchemy_utils.functions import naturally_equivalent
|
||||
from tests import TestCase
|
||||
from sqlalchemy_utils.functions import (
|
||||
non_indexed_foreign_keys,
|
||||
@@ -12,6 +13,18 @@ class TestEscapeLike(TestCase):
|
||||
assert escape_like('_*%') == '*_***%'
|
||||
|
||||
|
||||
class TestNaturallyEquivalent(TestCase):
|
||||
def test_returns_true_when_properties_match(self):
|
||||
assert naturally_equivalent(
|
||||
self.User(name=u'someone'), self.User(name=u'someone')
|
||||
)
|
||||
|
||||
def test_skips_primary_keys(self):
|
||||
assert naturally_equivalent(
|
||||
self.User(id=1, name=u'someone'), self.User(id=2, name=u'someone')
|
||||
)
|
||||
|
||||
|
||||
class TestFindNonIndexedForeignKeys(TestCase):
|
||||
# dns = 'postgres://postgres@localhost/sqlalchemy_utils_test'
|
||||
|
||||
|
Reference in New Issue
Block a user