From a30b42421da68ba599291cac0b83b798b0a85c93 Mon Sep 17 00:00:00 2001 From: Konsta Vesterinen Date: Fri, 12 Dec 2014 10:13:48 +0200 Subject: [PATCH] Add direction and uselist properties --- sqlalchemy_utils/path.py | 16 +++++++++++++++- tests/test_path.py | 14 +++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/sqlalchemy_utils/path.py b/sqlalchemy_utils/path.py index 96f274b..aaa812e 100644 --- a/sqlalchemy_utils/path.py +++ b/sqlalchemy_utils/path.py @@ -1,5 +1,6 @@ import sqlalchemy as sa from sqlalchemy.orm.attributes import InstrumentedAttribute +from sqlalchemy.util.langhelpers import symbol from .utils import str_coercible @@ -105,9 +106,22 @@ class AttrPath(object): if el is element: return index + @property + def direction(self): + symbols = [part.property.direction for part in self.parts] + if symbol('MANYTOMANY') in symbols: + return symbol('MANYTOMANY') + elif symbol('MANYTOONE') in symbols and symbol('ONETOMANY') in symbols: + return symbol('MANYTOMANY') + return symbols[0] + + @property + def uselist(self): + return any(part.property.uselist for part in self.parts) + def __getitem__(self, slice): result = self.parts[slice] - if isinstance(result, list): + if isinstance(result, list) and result: if result[0] is self.parts[0]: class_ = self.class_ else: diff --git a/tests/test_path.py b/tests/test_path.py index bc77e77..3246fa1 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -1,6 +1,7 @@ import six -from pytest import mark import sqlalchemy as sa +from pytest import mark +from sqlalchemy.util.langhelpers import symbol from sqlalchemy_utils.path import Path, AttrPath from tests import TestCase @@ -41,6 +42,17 @@ class TestAttrPath(TestCase): self.Section = Section self.SubSection = SubSection + @mark.parametrize( + ('class_', 'path', 'direction'), + ( + ('SubSection', 'section', symbol('MANYTOONE')), + ) + ) + def test_direction(self, class_, path, direction): + assert ( + AttrPath(getattr(self, class_), path).direction == direction + ) + def test_invert(self): path = ~ AttrPath(self.SubSection, 'section.document') assert path.parts == [