sqlalchemy.orm.synonym

Here are the examples of the python api sqlalchemy.orm.synonym taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

24 Examples 7

Example 1

Project: sqlalchemy
Source File: test_deferred.py
View license
    def test_synonym_group_bug(self):
        orders, Order = self.tables.orders, self.classes.Order

        mapper(Order, orders, properties={
            'isopen':synonym('_isopen', map_column=True),
            'description':deferred(orders.c.description, group='foo')
        })

        sess = create_session()
        o1 = sess.query(Order).get(1)
        eq_(o1.description, "order 1")

Example 2

Project: sqlalchemy
Source File: test_inspect.py
View license
    @classmethod
    def setup_mappers(cls):
        cls._setup_stock_mapping()
        inspect(cls.classes.User).add_property(
            "name_syn",synonym("name")
        )

Example 3

Project: sqlalchemy
Source File: test_update_delete.py
View license
    def test_evaluate_synonym_string(self):
        class Foo(object):
            pass
        mapper(Foo, self.tables.users, properties={
            'uname': synonym("name", )
        })

        s = Session()
        jill = s.query(Foo).get(3)
        s.query(Foo).update(
            {'uname': 'moonbeam'},
            synchronize_session='evaluate')
        eq_(jill.uname, 'moonbeam')

Example 4

Project: sqlalchemy
Source File: test_update_delete.py
View license
    def test_evaluate_synonym_attr(self):
        class Foo(object):
            pass
        mapper(Foo, self.tables.users, properties={
            'uname': synonym("name", )
        })

        s = Session()
        jill = s.query(Foo).get(3)
        s.query(Foo).update(
            {Foo.uname: 'moonbeam'},
            synchronize_session='evaluate')
        eq_(jill.uname, 'moonbeam')

Example 5

Project: sqlalchemy
Source File: test_update_delete.py
View license
    def test_evaluate_double_synonym_attr(self):
        class Foo(object):
            pass
        mapper(Foo, self.tables.users, properties={
            'uname': synonym("name"),
            'ufoo': synonym('uname')
        })

        s = Session()
        jill = s.query(Foo).get(3)
        s.query(Foo).update(
            {Foo.ufoo: 'moonbeam'},
            synchronize_session='evaluate')
        eq_(jill.ufoo, 'moonbeam')

Example 6

Project: sqlalchemy
Source File: test_utils.py
View license
    def test_proxy_descriptor_one(self):
        class Point(object):
            def __init__(self, x, y):
                self.x, self.y = x, y

        self._fixture(Point, properties={
            'x_syn': synonym("x")
        })
        alias = aliased(Point)

        eq_(str(Point.x_syn), "Point.x_syn")
        eq_(str(alias.x_syn), "AliasedClass_Point.x_syn")

        sess = Session()
        self.assert_compile(
            sess.query(alias.x_syn).filter(alias.x_syn > Point.x_syn),
            "SELECT point_1.x AS point_1_x FROM point AS point_1, point "
            "WHERE point_1.x > point.x"
        )

Example 7

Project: Flexget
Source File: database.py
View license
def pipe_list_synonym(name):
    """Converts pipe separated text into a list"""

    def getter(self):
        attr = getattr(self, name)
        if attr:
            return attr.strip('|').split('|')

    def setter(self, value):
        if isinstance(value, str):
            setattr(self, name, value)
        else:
            setattr(self, name, '|'.join(value))

    return synonym(name, descriptor=property(getter, setter))

Example 8

Project: Flexget
Source File: database.py
View license
def text_date_synonym(name):
    """Converts Y-M-D date strings into datetime objects"""

    def getter(self):
        return getattr(self, name)

    def setter(self, value):
        if isinstance(value, basestring):
            try:
                setattr(self, name, datetime.strptime(value, '%Y-%m-%d'))
            except ValueError:
                # Invalid date string given, set to None
                setattr(self, name, None)
        else:
            setattr(self, name, value)

    return synonym(name, descriptor=property(getter, setter))

Example 9

Project: Flexget
Source File: database.py
View license
def json_synonym(name):
    """Use json to serialize python objects for db storage."""

    def getter(self):
        return json.loads(getattr(self, name), decode_datetime=True)

    def setter(self, entry):
        setattr(self, name, unicode(json.dumps(entry, encode_datetime=True)))

    return synonym(name, descriptor=property(getter, setter))

Example 10

Project: Camelot
Source File: fields.py
View license
    def create_properties(self):
        if self.property is not None:
            self.entity._descriptor.add_property( self.name, self.property )

        if self.synonym:
            self.entity._descriptor.add_property( self.synonym, orm.synonym( self.name ) )

Example 11

Project: Camelot
Source File: fields.py
View license
    def create_properties(self):
        if self.property is not None:
            self.entity._descriptor.add_property( self.name, self.property )

        if self.synonym:
            self.entity._descriptor.add_property( self.synonym, orm.synonym( self.name ) )

Example 12

Project: COSMOS2
Source File: Stage.py
View license
    @declared_attr
    def status(cls):
        def get_status(self):
            return self._status

        def set_status(self, value):
            if self._status != value:
                self._status = value
                signal_stage_status_change.send(self)

        return synonym('_status', descriptor=property(get_status, set_status))

Example 13

Project: COSMOS2
Source File: Stage.py
View license
    @declared_attr
    def status(cls):
        def get_status(self):
            return self._status

        def set_status(self, value):
            if self._status != value:
                self._status = value
                signal_stage_status_change.send(self)

        return synonym('_status', descriptor=property(get_status, set_status))

Example 14

Project: COSMOS2
Source File: Task.py
View license
    @declared_attr
    def status(cls):
        def get_status(self):
            return self._status

        def set_status(self, value):
            if self._status != value:
                self._status = value
                signal_task_status_change.send(self)

        return synonym('_status', descriptor=property(get_status, set_status))

Example 15

Project: COSMOS2
Source File: Task.py
View license
    @declared_attr
    def status(cls):
        def get_status(self):
            return self._status

        def set_status(self, value):
            if self._status != value:
                self._status = value
                signal_task_status_change.send(self)

        return synonym('_status', descriptor=property(get_status, set_status))

Example 16

Project: COSMOS2
Source File: Workflow.py
View license
    @declared_attr
    def status(cls):
        def get_status(self):
            return self._status

        def set_status(self, value):
            if self._status != value:
                self._status = value
                signal_workflow_status_change.send(self)

        return synonym('_status', descriptor=property(get_status, set_status))

Example 17

Project: COSMOS2
Source File: Workflow.py
View license
    @declared_attr
    def status(cls):
        def get_status(self):
            return self._status

        def set_status(self, value):
            if self._status != value:
                self._status = value
                signal_workflow_status_change.send(self)

        return synonym('_status', descriptor=property(get_status, set_status))

Example 18

Project: pokedex
Source File: multilang.py
View license
def create_translation_table(_table_name, foreign_class, relation_name,
    language_class, relation_lazy='select', **kwargs):
    """Creates a table that represents some kind of data attached to the given
    foreign class, but translated across several languages.  Returns the new
    table's mapped class.  It won't be declarative, but it will have a
    `__table__` attribute so you can retrieve the Table object.

    `foreign_class` must have a `__singlename__`, currently only used to create
    the name of the foreign key column.

    Also supports the notion of a default language, which is attached to the
    session.  This is English by default, for historical and practical reasons.

    Usage looks like this:

        class Foo(Base): ...

        create_translation_table('foo_bars', Foo, 'bars',
            name = Column(...),
        )

        # Now you can do the following:
        foo.name
        foo.name_map['en']
        foo.foo_bars['en']

        foo.name_map['en'] = "new name"
        del foo.name_map['en']

        q.options(joinedload(Foo.bars_local))
        q.options(joinedload(Foo.bars))

    The following properties are added to the passed class:

    - `(relation_name)`, a relation to the new table.  It uses a dict-based
      collection class, where the keys are language identifiers and the values
      are rows in the created tables.
    - `(relation_name)_local`, a relation to the row in the new table that
      matches the current default language.
    - `(relation_name)_table`, the class created by this function.

    Note that these are distinct relations.  Even though the former necessarily
    includes the latter, SQLAlchemy doesn't treat them as linked; loading one
    will not load the other.  Modifying both within the same transaction has
    undefined behavior.

    For each column provided, the following additional attributes are added to
    Foo:

    - `(column)_map`, an association proxy onto `foo_bars`.
    - `(column)`, an association proxy onto `foo_bars_local`.

    Pardon the naming disparity, but the grammar suffers otherwise.

    Modifying these directly is not likely to be a good idea.

    For Markdown-formatted columns, `(column)_map` and `(column)` will give
    Markdown objects.
    """
    # n.b.: language_class only exists for the sake of tests, which sometimes
    # want to create tables entirely separate from the pokedex metadata

    foreign_key_name = foreign_class.__singlename__ + '_id'

    Translations = type(_table_name, (object,), {
        '_language_identifier': association_proxy('local_language', 'identifier'),
        'relation_name': relation_name,
        '__tablename__': _table_name,
    })

    # Create the table object
    table = Table(_table_name, foreign_class.__table__.metadata,
        Column(foreign_key_name, Integer, ForeignKey(foreign_class.id),
            primary_key=True, nullable=False,
            doc=u"ID of the %s these texts relate to" % foreign_class.__singlename__),
        Column('local_language_id', Integer, ForeignKey(language_class.id),
            primary_key=True, nullable=False,
            doc=u"Language these texts are in"),
    )
    Translations.__table__ = table

    # Add ye columns
    # Column objects have a _creation_order attribute in ascending order; use
    # this to get the (unordered) kwargs sorted correctly
    kwitems = list(kwargs.items())
    kwitems.sort(key=lambda kv: kv[1]._creation_order)
    for name, column in kwitems:
        column.name = name
        table.append_column(column)

    # Construct ye mapper
    mapper(Translations, table, properties={
        'foreign_id': synonym(foreign_key_name),
        'local_language': relationship(language_class,
            primaryjoin=table.c.local_language_id == language_class.id,
            innerjoin=True),
    })

    # Add full-table relations to the original class
    # Foo.bars_table
    setattr(foreign_class, relation_name + '_table', Translations)
    # Foo.bars
    setattr(foreign_class, relation_name, relationship(Translations,
        primaryjoin=foreign_class.id == Translations.foreign_id,
        collection_class=attribute_mapped_collection('local_language'),
    ))
    # Foo.bars_local
    # This is a bit clever; it uses bindparam() to make the join clause
    # modifiable on the fly.  db sessions know the current language and
    # populate the bindparam.
    # The 'dummy' value is to trick SQLA; without it, SQLA thinks this
    # bindparam is just its own auto-generated clause and everything gets
    # fucked up.
    local_relation_name = relation_name + '_local'
    setattr(foreign_class, local_relation_name, relationship(Translations,
        primaryjoin=and_(
            Translations.foreign_id == foreign_class.id,
            Translations.local_language_id == bindparam('_default_language_id',
                value='dummy', type_=Integer, required=True),
        ),
        foreign_keys=[Translations.foreign_id, Translations.local_language_id],
        uselist=False,
        lazy=relation_lazy,
    ))

    # Add per-column proxies to the original class
    for name, column in kwitems:
        getset_factory = None
        string_getter = column.info.get('string_getter')
        if string_getter:
            getset_factory = _getset_factory_factory(
                column.name, string_getter)

        # Class.(column) -- accessor for the default language's value
        setattr(foreign_class, name,
            LocalAssociationProxy(local_relation_name, name,
                    getset_factory=getset_factory))

        # Class.(column)_map -- accessor for the language dict
        # Need a custom creator since Translations doesn't have an init, and
        # these are passed as *args anyway
        def creator(language, value):
            row = Translations()
            row.local_language = language
            setattr(row, name, value)
            return row
        setattr(foreign_class, name + '_map',
            association_proxy(relation_name, name, creator=creator,
                    getset_factory=getset_factory))

    # Add to the list of translation classes
    foreign_class.translation_classes.append(Translations)

    # Done
    return Translations

Example 19

Project: sqlalchemy
Source File: test_utils.py
View license
    def test_parententity_vs_parentmapper(self):
        class Point(object):
            pass

        self._fixture(Point, properties={
            'x_syn': synonym("x")
        })
        pa = aliased(Point)

        is_(Point.x_syn._parententity, inspect(Point))
        is_(Point.x._parententity, inspect(Point))
        is_(Point.x_syn._parentmapper, inspect(Point))
        is_(Point.x._parentmapper, inspect(Point))

        is_(
            Point.x_syn.__clause_element__()._annotations['parententity'],
            inspect(Point))
        is_(
            Point.x.__clause_element__()._annotations['parententity'],
            inspect(Point))
        is_(
            Point.x_syn.__clause_element__()._annotations['parentmapper'],
            inspect(Point))
        is_(
            Point.x.__clause_element__()._annotations['parentmapper'],
            inspect(Point))

        pa = aliased(Point)

        is_(pa.x_syn._parententity, inspect(pa))
        is_(pa.x._parententity, inspect(pa))
        is_(pa.x_syn._parentmapper, inspect(Point))
        is_(pa.x._parentmapper, inspect(Point))

        is_(
            pa.x_syn.__clause_element__()._annotations['parententity'],
            inspect(pa)
        )
        is_(
            pa.x.__clause_element__()._annotations['parententity'],
            inspect(pa)
        )
        is_(
            pa.x_syn.__clause_element__()._annotations['parentmapper'],
            inspect(Point))
        is_(
            pa.x.__clause_element__()._annotations['parentmapper'],
            inspect(Point))

Example 20

Project: Flexget
Source File: database.py
View license
def entry_synonym(name):
    """Use json to serialize python objects for db storage."""

    def only_builtins(item):
        supported_types = (str, unicode, int, float, long, bool, datetime)
        # dict, list, tuple and set are also supported, but handled separately

        if isinstance(item, supported_types):
            return item
        elif isinstance(item, Mapping):
            result = {}
            for key, value in item.items():
                try:
                    result[key] = only_builtins(value)
                except TypeError:
                    continue
            return result
        elif isinstance(item, (list, tuple, set)):
            result = []
            for value in item:
                try:
                    result.append(only_builtins(value))
                except ValueError:
                    continue
            if isinstance(item, list):
                return result
            elif isinstance(item, tuple):
                return tuple(result)
            else:
                return set(result)
        else:
            for s_type in supported_types:
                if isinstance(item, s_type):
                    return s_type(item)

        # If item isn't a subclass of a builtin python type, raise ValueError.
        raise TypeError('%r is not of type Entry.' % type(item))

    def getter(self):
        return Entry(json.loads(getattr(self, name), decode_datetime=True))

    def setter(self, entry):
        if isinstance(entry, Entry) or isinstance(entry, dict):
            setattr(self, name, unicode(json.dumps(only_builtins(dict(entry)), encode_datetime=True)))
        else:
            raise TypeError('%r is not of type Entry or dict.' % type(entry))

    return synonym(name, descriptor=property(getter, setter))

Example 21

Project: flask-lastuser
Source File: sqlalchemy.py
View license
    @declared_attr
    def userid(cls):
        """Synonym for buid if the model has no existing userid column."""
        return synonym('buid')

Example 22

Project: flask-lastuser
Source File: sqlalchemy.py
View license
    @declared_attr
    def buid(cls):
        """Synonym for userid."""
        return synonym('userid')

Example 23

Project: amivapi
Source File: utils.py
View license
    @declared_attr
    def _id(cls):
        return synonym("id")

Example 24

Project: neutron-lib
Source File: model_base.py
View license
    @declarative.declared_attr
    def tenant_id(cls):
        return orm.synonym(
            'project_id',
            descriptor=property(cls.get_tenant_id, cls.set_tenant_id))