Python sqlalchemy.ext.declarative.declared_attr() Examples

The following are 6 code examples of sqlalchemy.ext.declarative.declared_attr(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.ext.declarative , or try the search function .
Example #1
Source File: relationship.py    From AnyBlok with Mozilla Public License 2.0 6 votes vote down vote up
def create_column(self, cname, remote_type, foreign_key, properties):

        def wrapper(cls):
            return SA_Column(
                cname.attribute_name,
                remote_type,
                nullable=self.nullable,
                unique=self.unique,
                index=self.index,
                primary_key=self.primary_key,
                info=dict(label=self.label, foreign_key=foreign_key))

        properties[(anyblok_column_prefix +
                    cname.attribute_name)] = declared_attr(wrapper)
        properties['loaded_columns'].append(cname.attribute_name)
        properties['hybrid_property_columns'].append(cname.attribute_name)
        properties[cname.attribute_name] = hybrid_property(
            self.wrap_getter_column(cname.attribute_name),
            super(Many2One, self).wrap_setter_column(cname.attribute_name),
            expr=self.wrap_expr_column(cname.attribute_name)) 
Example #2
Source File: test_reflection.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_mapper_args_deferred(self):
        """test that __mapper_args__ is not called until *after*
        table reflection"""

        class User(decl.DeferredReflection, fixtures.ComparableEntity, Base):
            __tablename__ = "users"

            @decl.declared_attr
            def __mapper_args__(cls):
                return {"primary_key": cls.__table__.c.id}

        decl.DeferredReflection.prepare(testing.db)
        sess = Session()
        sess.add_all(
            [User(name="G"), User(name="Q"), User(name="A"), User(name="C")]
        )
        sess.commit()
        eq_(
            sess.query(User).order_by(User.name).all(),
            [User(name="A"), User(name="C"), User(name="G"), User(name="Q")],
        ) 
Example #3
Source File: table_and_mapper.py    From AnyBlok with Mozilla Public License 2.0 5 votes vote down vote up
def insert_in_bases_table_args(self, new_base, transformation_properties):
        """Add table __table_args__ in new_base

        :param new_base: the base to be put on front of all bases
        :param transformation_properties: the properties of the model
        """
        if (
            transformation_properties['table_args'] and
            transformation_properties['table_kwargs']
        ):

            def __table_args__(cls_):
                res = cls_.define_table_args() + (cls_.define_table_kwargs(),)
                return res

            new_base.__table_args__ = declared_attr(__table_args__)
        elif transformation_properties['table_args']:

            def __table_args__(cls_):
                return cls_.define_table_args()

            new_base.__table_args__ = declared_attr(__table_args__)
        elif transformation_properties['table_kwargs']:

            def __table_args__(cls_):
                return cls_.define_table_kwargs()

            new_base.__table_args__ = declared_attr(__table_args__) 
Example #4
Source File: table_and_mapper.py    From AnyBlok with Mozilla Public License 2.0 5 votes vote down vote up
def insert_in_bases_mapper_args(self, new_base, transformation_properties):
        """Add table __mapper_args__ in new_base

        :param new_base: the base to be put on front of all bases
        :param transformation_properties: the properties of the model
        """
        if transformation_properties['mapper_args']:

            def __mapper_args__(cls_):
                return cls_.define_mapper_args()

            new_base.__mapper_args__ = declared_attr(__mapper_args__) 
Example #5
Source File: model.py    From planespotter with MIT License 5 votes vote down vote up
def should_set_tablename(cls):
    """Determine whether ``__tablename__`` should be automatically generated
    for a model.

    * If no class in the MRO sets a name, one should be generated.
    * If a declared attr is found, it should be used instead.
    * If a name is found, it should be used if the class is a mixin, otherwise
      one should be generated.
    * Abstract models should not have one generated.

    Later, :meth:`._BoundDeclarativeMeta.__table_cls__` will determine if the
    model looks like single or joined-table inheritance. If no primary key is
    found, the name will be unset.
    """
    if (
        cls.__dict__.get('__abstract__', False)
        or not any(isinstance(b, DeclarativeMeta) for b in cls.__mro__[1:])
    ):
        return False

    for base in cls.__mro__:
        if '__tablename__' not in base.__dict__:
            continue

        if isinstance(base.__dict__['__tablename__'], declared_attr):
            return False

        return not (
            base is cls
            or base.__dict__.get('__abstract__', False)
            or not isinstance(base, DeclarativeMeta)
        )

    return True 
Example #6
Source File: __init__.py    From AnyBlok with Mozilla Public License 2.0 4 votes vote down vote up
def declare_field(cls, registry, name, field, namespace, properties,
                      transformation_properties):
        """ Declare the field/column/relationship to put in the properties
        of the model

        :param registry: the current  registry
        :param name: name of the field / column or relationship
        :param field: the declaration field / column or relationship
        :param namespace: the namespace of the model
        :param properties: the properties of the model
        """
        if name in properties['loaded_columns']:
            return

        if field.must_be_copied_before_declaration():
            field = deepcopy(field)

        attr_name = name
        if field.use_hybrid_property:
            attr_name = anyblok_column_prefix + name

        if field.must_be_declared_as_attr():
            # All the declaration are seen as mixin for sqlalchemy
            # some of them need de be defered for the initialisation
            # cause of the mixin as relation ship and column with foreign key
            def wrapper(cls):
                return field.get_sqlalchemy_mapping(
                    registry, namespace, name, properties)

            properties[attr_name] = declared_attr(wrapper)
            properties[attr_name].anyblok_field = field
        else:
            properties[attr_name] = field.get_sqlalchemy_mapping(
                registry, namespace, name, properties)

        if field.use_hybrid_property:
            properties[name] = field.get_property(
                registry, namespace, name, properties)
            properties['hybrid_property_columns'].append(name)

        registry.call_plugins('declare_field', name, field, namespace,
                              properties, transformation_properties)

        properties['loaded_columns'].append(name)
        field.update_properties(registry, namespace, name, properties)