sqlalchemy.orm.declarative_base

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

72 Examples 7

3 Source : gcs_import_to_cloud_sql.py
with GNU General Public License v3.0
from Recidiviz

def build_temporary_sqlalchemy_table(table: Table) -> Table:
    # Create a throwaway Base to map the model to
    base = declarative_base()
    return table.to_metadata(
        base.metadata,
        # Replace our model's table name with the temporary table's name
        name=get_temporary_table_name(table),
    )


@attr.s

3 Source : gcs_import_to_cloud_sql_test.py
with GNU General Public License v3.0
from Recidiviz

    def build_table(self, name: str, *args: List[Any]) -> Table:
        base = declarative_base()

        return Table(name, base.metadata, *args)

    def test_rename(self) -> None:

3 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _wrong_expr_fixture(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            _value = Column("value", String)

            @hybrid.hybrid_property
            def value(self):
                return self._value is not None

            @value.expression
            def value(cls):
                return cls._value is not None

        return A

    def _relationship_fixture(self):

3 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _unnamed_expr_fixture(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            firstname = Column(String)
            lastname = Column(String)

            @hybrid.hybrid_property
            def name(self):
                return self.firstname + " " + self.lastname

        return A

    def test_labeling_for_unnamed(self, _unnamed_expr_fixture):

3 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _fixture(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            _value = Column("value", String)

            @hybrid.hybrid_property
            def value(self):
                "This is an instance-level docstring"
                return self._value

        return A

    @testing.fixture

3 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _function_fixture(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            value = Column(Integer)

            @hybrid.hybrid_property
            def foo_value(self):
                return func.foo(self.value)

        return A

    @testing.fixture

3 Source : test_indexable.py
with MIT License
from sqlalchemy

    def test_value_is_none_attributeerror(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column("id", Integer, primary_key=True)
            array = Column("_array", ARRAY(Integer))
            first = index_property("array", 1)

        a = A()
        assert_raises(AttributeError, getattr, a, "first")

        assert_raises(AttributeError, delattr, a, "first")

    def test_get_attribute_error(self):

3 Source : test_indexable.py
with MIT License
from sqlalchemy

    def test_get_attribute_error(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column("id", Integer, primary_key=True)
            array = Column("_array", ARRAY(Integer))
            first = index_property("array", 1)

        a = A(array=[])
        assert_raises(AttributeError, lambda: a.first)

    def test_set_immutable(self):

3 Source : test_indexable.py
with MIT License
from sqlalchemy

    def test_set_immutable(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            array = Column(ARRAY(Integer))
            first = index_property("array", 1, mutable=False)

        a = A()

        def set_():
            a.first = 10

        assert_raises(AttributeError, set_)

    def test_set_mutable_dict(self):

3 Source : test_mutable.py
with MIT License
from sqlalchemy

    def define_tables(cls, metadata):
        from sqlalchemy.sql.sqltypes import ARRAY

        MutableList = cls._type_fixture()

        Base = declarative_base(metadata=metadata)

        class Mixin:
            data = Column(MutableList.as_mutable(ARRAY(Integer)))

        class Foo(Mixin, Base):
            __tablename__ = "foo"
            id = Column(Integer, primary_key=True)


class MutableListWithScalarPickleTest(

3 Source : test_basic.py
with MIT License
from sqlalchemy

    def test_unbound_declarative_base(self):
        Base = declarative_base()

        class User(Base):
            __tablename__ = "user"
            id = Column(Integer, primary_key=True)

        s = Session()

        with testing.expect_raises(exc.UnboundExecutionError):
            s.get_bind(User)

    def test_unbound_cls_registry(self):

3 Source : test_basic.py
with MIT License
from sqlalchemy

    def test_shared_class_registry(self):
        reg = {}
        Base1 = declarative_base(class_registry=reg)
        Base2 = declarative_base(class_registry=reg)

        class A(Base1):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)

        class B(Base2):
            __tablename__ = "b"
            id = Column(Integer, primary_key=True)
            aid = Column(Integer, ForeignKey(A.id))
            as_ = relationship("A")

        assert B.as_.property.mapper.class_ is A

    def test_custom_base(self):

3 Source : test_basic.py
with MIT License
from sqlalchemy

    def test_custom_base(self):
        class MyBase:
            def foobar(self):
                return "foobar"

        Base = declarative_base(cls=MyBase)
        assert hasattr(Base, "metadata")
        assert Base().foobar() == "foobar"

    def test_as_declarative(self, metadata):

3 Source : test_basic.py
with MIT License
from sqlalchemy

    def test_custom_mapper_attribute(self):
        def mymapper(cls, tbl, **kwargs):
            m = sa.orm.Mapper(cls, tbl, **kwargs)
            m.CHECK = True
            return m

        base = declarative_base()

        class Foo(base):
            __tablename__ = "foo"
            __mapper_cls__ = mymapper
            id = Column(Integer, primary_key=True)

        eq_(Foo.__mapper__.CHECK, True)

    def test_custom_mapper_argument(self):

3 Source : test_basic.py
with MIT License
from sqlalchemy

    def test_custom_mapper_argument(self):
        def mymapper(cls, tbl, **kwargs):
            m = sa.orm.Mapper(cls, tbl, **kwargs)
            m.CHECK = True
            return m

        base = declarative_base(mapper=mymapper)

        class Foo(base):
            __tablename__ = "foo"
            id = Column(Integer, primary_key=True)

        eq_(Foo.__mapper__.CHECK, True)

    def test_no_change_to_all_descriptors(self):

3 Source : test_basic.py
with MIT License
from sqlalchemy

    def test_no_change_to_all_descriptors(self):
        base = declarative_base()

        class Foo(base):
            __tablename__ = "foo"
            id = Column(Integer, primary_key=True)

        eq_(Foo.__mapper__.all_orm_descriptors.keys(), ["id"])

    def test_cls_docstring(self):

3 Source : test_basic.py
with MIT License
from sqlalchemy

    def test_cls_docstring(self):
        class MyBase:
            """MyBase Docstring"""

        Base = declarative_base(cls=MyBase)

        eq_(Base.__doc__, MyBase.__doc__)

    def test_delattr_mapped_raises(self):

3 Source : test_basic.py
with MIT License
from sqlalchemy

    def test_delattr_mapped_raises(self):
        Base = declarative_base()

        class Foo(Base):
            __tablename__ = "foo"

            id = Column(Integer, primary_key=True)
            data = Column(String)

        def go():
            del Foo.data

        assert_raises_message(
            NotImplementedError,
            "Can't un-map individual mapped attributes on a mapped class.",
            go,
        )

    def test_delattr_hybrid_fine(self):

3 Source : test_typed_mapping.py
with MIT License
from sqlalchemy

    def test_legacy_declarative_base(self):
        typ = VARCHAR(50)
        Base = declarative_base(type_annotation_map={str: typ})

        class MyClass(Base):
            __tablename__ = "mytable"

            id: Mapped[int] = mapped_column(primary_key=True)
            data: Mapped[str]
            x: Mapped[int]

        is_(MyClass.__table__.c.data.type, typ)
        is_true(MyClass.__table__.c.id.primary_key)

    def test_required_no_arg(self, decl_base):

3 Source : test_descriptor.py
with MIT License
from sqlalchemy

    def _fixture(self):
        Base = declarative_base()

        class Foo(Base):
            __tablename__ = "foo"
            id = Column(Integer, primary_key=True)

        return Foo

    def test_fixture(self):

3 Source : test_inspect.py
with MIT License
from sqlalchemy

    def test_all_orm_descriptors_pep520_noinh(self):
        from sqlalchemy.orm import declarative_base

        Base = declarative_base()

        glbls = {}
        names, MyClass = self._ordered_name_fixture(
            glbls, "MyClass", Base, Base
        )

        eq_(MyClass.__mapper__.all_orm_descriptors.keys(), names)

    def test_all_orm_descriptors_pep520_onelevel_inh(self):

0 Source : test_search.py
with GNU Affero General Public License v3.0
from andrewcooke

    def test_sqlalchemy(self):

        engine = create_engine('sqlite:///:memory:')
        Base = declarative_base()
        Session = sessionmaker(engine)

        class Table(Base):
            __tablename__ = 'table'
            id = Column(Integer, primary_key=True)

        Base.metadata.create_all(engine)

        with Session() as s:
            q1 = select(Table).filter(Table.id == 1)
            q2 = select(Table).filter(Table.id == 2)
            q3 = union(q1, q2).subquery()

        with Session() as s:
            q1 = select(Table).filter(Table.id == 1)
            q2 = select(Table).filter(Table.id == 2)
            cte = union(q1, q2).cte()
            q3 = select(Table).filter(Table.id.in_(cte))
            q4 = select(Table).filter(Table.id.in_(cte))
            q5 = union(q3, q4).subquery()
            log.debug(q5)


0 Source : test_sqlalchemy.py
with GNU Affero General Public License v3.0
from andrewcooke

    def test_sqlalchemy(self):

        # using postgres with log_statement=all so that we can see the incorrect queries
        # (use a transient docker instance)

        dbname = ''.join(choice(ascii_letters) for _ in range(16)).lower()
        # https://stackoverflow.com/questions/6506578/how-to-create-a-new-database-using-sqlalchemy
        engine = create_engine('postgresql://postgres@localhost:5432/postgres')
        conn = engine.connect()
        conn.execute('commit')
        conn.execute(f'create database {dbname}')
        conn.close()

        engine = create_engine(f'postgresql://postgres@localhost:5432/{dbname}')
        Base = declarative_base()
        Session = sessionmaker(engine)

        class SourceType(IntEnum):
            SOURCE = 0
            ACTIVITY = 2
            ACTIVITY_TOPIC = 10

        class StatisticJournalType(IntEnum):
            STATISTIC = 0
            TIMESTAMP = 4

        class FileHash(Base):
            __tablename__ = 'file_hash'
            id = Column(Integer, primary_key=True)

        class Source(Base):
            __tablename__ = 'source'
            id = Column(Integer, primary_key=True)
            type = Column(Integer, nullable=False, index=True)
            __mapper_args__ = {
                'polymorphic_identity': SourceType.SOURCE,
                'polymorphic_on': type
            }

        class GroupedSource(Source):
            __abstract__ = True

        class ActivityJournal(GroupedSource):
            __tablename__ = 'activity_journal'
            id = Column(Integer, ForeignKey('source.id', ondelete='cascade'), primary_key=True)
            file_hash_id = Column(Integer, ForeignKey('file_hash.id'), nullable=False, index=True, unique=True)
            file_hash = relationship('FileHash', backref=backref('activity_journal', uselist=False))
            __mapper_args__ = {
                'polymorphic_identity': SourceType.ACTIVITY
            }

        class ActivityTopicJournal(GroupedSource):
            __tablename__ = 'activity_topic_journal'
            id = Column(Integer, ForeignKey('source.id', ondelete='cascade'), primary_key=True)
            file_hash_id = Column(Integer, ForeignKey('file_hash.id'),
                                  nullable=False, index=True, unique=True)
            file_hash = relationship('FileHash', backref=backref('activity_topic_journal', uselist=False))
            __mapper_args__ = {
                'polymorphic_identity': SourceType.ACTIVITY_TOPIC
            }

        class StatisticName(Base):
            __tablename__ = 'statistic_name'
            id = Column(Integer, primary_key=True)
            name = Column(Text, nullable=False)

        class StatisticJournal(Base):
            __tablename__ = 'statistic_journal'
            id = Column(Integer, primary_key=True)
            type = Column(Integer, nullable=False, index=True)
            statistic_name_id = Column(Integer, ForeignKey('statistic_name.id', ondelete='cascade'), nullable=False)
            statistic_name = relationship('StatisticName')
            source_id = Column(Integer, ForeignKey('source.id', ondelete='cascade'), nullable=False)
            source = relationship('Source')
            __mapper_args__ = {
                'polymorphic_identity': StatisticJournalType.STATISTIC,
                'polymorphic_on': 'type'
            }

        class StatisticJournalTimestamp(StatisticJournal):
            __tablename__ = 'statistic_journal_timestamp'
            id = Column(Integer, ForeignKey('statistic_journal.id', ondelete='cascade'), primary_key=True)
            value = Column(DateTime, nullable=False)
            __mapper_args__ = {
                'polymorphic_identity': StatisticJournalType.TIMESTAMP
            }

        Base.metadata.create_all(engine)

        def build_source_query(s, value):
            q = s.query(Source.id). \
                join(StatisticJournalTimestamp). \
                join(StatisticName). \
                filter(StatisticName.name.like('start')). \
                filter(StatisticJournalTimestamp.value > value)
            q_direct = s.query(ActivityJournal.id). \
                filter(ActivityJournal.id.in_(q.subquery().select()))
            q_via_topic = s.query(ActivityJournal.id). \
                join(FileHash). \
                join(ActivityTopicJournal). \
                filter(ActivityTopicJournal.id.in_(q.subquery().select()))
            constraints = union(q_direct, q_via_topic).subquery().select()
            return s.query(Source).filter(Source.id.in_(constraints))

        with Session() as s:
            build_source_query(s, dt.datetime(2020, 1, 1, 3, 0, tzinfo=pytz.UTC)).all()
            build_source_query(s, dt.datetime(2021, 1, 1, 3, 0, tzinfo=pytz.UTC)).all()

0 Source : test_memusage.py
with MIT License
from sqlalchemy

    def test_optimized_get(self):

        Base = declarative_base(metadata=self.metadata)

        class Employee(Base):
            __tablename__ = "employee"
            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )
            type = Column(String(10))
            __mapper_args__ = {"polymorphic_on": type}

        class Engineer(Employee):
            __tablename__ = " engineer"
            id = Column(ForeignKey("employee.id"), primary_key=True)

            engineer_name = Column(String(50))
            __mapper_args__ = {"polymorphic_identity": "engineer"}

        Base.metadata.create_all(testing.db)

        s = Session(testing.db)
        s.add(Engineer(engineer_name="wally"))
        s.commit()
        s.close()

        @assert_cycles()
        def go():
            e1 = s.query(Employee).first()
            e1.engineer_name

        go()

    def test_visit_binary_product(self):

0 Source : test_types.py
with MIT License
from sqlalchemy

    def test_hashable_flag(self, metadata, connection, type_, data):
        Base = declarative_base(metadata=metadata)

        class A(Base):
            __tablename__ = "a1"
            id = Column(Integer, primary_key=True)
            data = Column(type_)

        Base.metadata.create_all(connection)
        s = Session(connection)
        s.add_all([A(data=elem) for elem in data])
        s.commit()

        eq_(
            [
                (obj.A.id, obj.data)
                for obj in s.query(A, A.data).order_by(A.id)
            ],
            list(enumerate(data, 1)),
        )


class TimestampTest(fixtures.TestBase, AssertsExecutionResults):

0 Source : test_types.py
with MIT License
from sqlalchemy

    def test_eval_none_flag_orm(self, connection):
        Base = declarative_base()

        class Data(Base):
            __table__ = self.tables.data_table

        with Session(connection) as s:
            d1 = Data(name="d1", data=None, nulldata=None)
            s.add(d1)
            s.commit()

            s.bulk_insert_mappings(
                Data, [{"name": "d2", "data": None, "nulldata": None}]
            )
            eq_(
                s.query(
                    cast(self.tables.data_table.c.data, String),
                    cast(self.tables.data_table.c.nulldata, String),
                )
                .filter(self.tables.data_table.c.name == "d1")
                .first(),
                ("null", None),
            )
            eq_(
                s.query(
                    cast(self.tables.data_table.c.data, String),
                    cast(self.tables.data_table.c.nulldata, String),
                )
                .filter(self.tables.data_table.c.name == "d2")
                .first(),
                ("null", None),
            )

    def test_literal(self, connection):

0 Source : test_inheritance.py
with MIT License
from sqlalchemy

    def setup_test(self):
        global Base
        Base = declarative_base()

    def teardown_test(self):

0 Source : test_associationproxy.py
with MIT License
from sqlalchemy

    def test_resolve_aliased_class(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            value = Column(String)

        class B(Base):
            __tablename__ = "b"
            id = Column(Integer, primary_key=True)
            a_id = Column(Integer, ForeignKey(A.id))
            a = relationship(A)
            a_value = association_proxy("a", "value")

        spec = aliased(B).a_value

        is_(spec.owning_class, B)

        spec = B.a_value

        is_(spec.owning_class, B)

    def test_resolved_w_subclass(self):

0 Source : test_associationproxy.py
with MIT License
from sqlalchemy

    def test_resolved_w_subclass(self):
        # test for issue #4185, as well as several below

        Base = declarative_base()

        class Mixin:
            @declared_attr
            def children(cls):
                return association_proxy("_children", "value")

        # 1. build parent, Mixin.children gets invoked, we add
        # Parent.children
        class Parent(Mixin, Base):
            __tablename__ = "parent"
            id = Column(Integer, primary_key=True)

            _children = relationship("Child")

        class Child(Base):
            __tablename__ = "child"
            parent_id = Column(
                Integer, ForeignKey(Parent.id), primary_key=True
            )
            value = Column(String)

        # 2. declarative builds up SubParent, scans through all attributes
        # over all classes.  Hits Mixin, hits "children", accesses "children"
        # in terms of the class, e.g. SubParent.children.  SubParent isn't
        # mapped yet.  association proxy then sets up "owning_class"
        # as NoneType.
        class SubParent(Parent):
            __tablename__ = "subparent"
            id = Column(Integer, ForeignKey(Parent.id), primary_key=True)

        configure_mappers()

        # 3. which would break here.
        p1 = Parent()
        eq_(p1.children, [])

    def test_resolved_to_correct_class_one(self):

0 Source : test_associationproxy.py
with MIT License
from sqlalchemy

    def test_resolved_to_correct_class_one(self):
        Base = declarative_base()

        class Parent(Base):
            __tablename__ = "parent"
            id = Column(Integer, primary_key=True)
            _children = relationship("Child")
            children = association_proxy("_children", "value")

        class Child(Base):
            __tablename__ = "child"
            parent_id = Column(
                Integer, ForeignKey(Parent.id), primary_key=True
            )
            value = Column(String)

        class SubParent(Parent):
            __tablename__ = "subparent"
            id = Column(Integer, ForeignKey(Parent.id), primary_key=True)

        is_(SubParent.children.owning_class, SubParent)
        is_(Parent.children.owning_class, Parent)

    def test_resolved_to_correct_class_two(self):

0 Source : test_associationproxy.py
with MIT License
from sqlalchemy

    def test_resolved_to_correct_class_two(self):
        Base = declarative_base()

        class Parent(Base):
            __tablename__ = "parent"
            id = Column(Integer, primary_key=True)
            _children = relationship("Child")

        class Child(Base):
            __tablename__ = "child"
            parent_id = Column(
                Integer, ForeignKey(Parent.id), primary_key=True
            )
            value = Column(String)

        class SubParent(Parent):
            __tablename__ = "subparent"
            id = Column(Integer, ForeignKey(Parent.id), primary_key=True)
            children = association_proxy("_children", "value")

        is_(SubParent.children.owning_class, SubParent)

    def test_resolved_to_correct_class_three(self):

0 Source : test_associationproxy.py
with MIT License
from sqlalchemy

    def test_resolved_to_correct_class_three(self):
        Base = declarative_base()

        class Parent(Base):
            __tablename__ = "parent"
            id = Column(Integer, primary_key=True)
            _children = relationship("Child")

        class Child(Base):
            __tablename__ = "child"
            parent_id = Column(
                Integer, ForeignKey(Parent.id), primary_key=True
            )
            value = Column(String)

        class SubParent(Parent):
            __tablename__ = "subparent"
            id = Column(Integer, ForeignKey(Parent.id), primary_key=True)
            children = association_proxy("_children", "value")

        class SubSubParent(SubParent):
            __tablename__ = "subsubparent"
            id = Column(Integer, ForeignKey(SubParent.id), primary_key=True)

        is_(SubParent.children.owning_class, SubParent)
        is_(SubSubParent.children.owning_class, SubSubParent)

    def test_resolved_to_correct_class_four(self):

0 Source : test_associationproxy.py
with MIT License
from sqlalchemy

    def test_resolved_to_correct_class_four(self):
        Base = declarative_base()

        class Parent(Base):
            __tablename__ = "parent"
            id = Column(Integer, primary_key=True)
            _children = relationship("Child")
            children = association_proxy(
                "_children", "value", creator=lambda value: Child(value=value)
            )

        class Child(Base):
            __tablename__ = "child"
            parent_id = Column(
                Integer, ForeignKey(Parent.id), primary_key=True
            )
            value = Column(String)

        class SubParent(Parent):
            __tablename__ = "subparent"
            id = Column(Integer, ForeignKey(Parent.id), primary_key=True)

        sp = SubParent()
        sp.children = "c"
        is_(SubParent.children.owning_class, SubParent)
        is_(Parent.children.owning_class, Parent)

    def test_resolved_to_correct_class_five(self):

0 Source : test_associationproxy.py
with MIT License
from sqlalchemy

    def test_resolved_to_correct_class_five(self):
        Base = declarative_base()

        class Mixin:
            children = association_proxy("_children", "value")

        class Parent(Mixin, Base):
            __tablename__ = "parent"
            id = Column(Integer, primary_key=True)
            _children = relationship("Child")

        class Child(Base):
            __tablename__ = "child"
            parent_id = Column(
                Integer, ForeignKey(Parent.id), primary_key=True
            )
            value = Column(String)

        # this triggers the owning routine, doesn't fail
        Mixin.children

        p1 = Parent()

        c1 = Child(value="c1")
        p1._children.append(c1)
        is_(Parent.children.owning_class, Parent)
        eq_(p1.children, ["c1"])

    def _test_never_assign_nonetype(self):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _fixture(self):
        Base = declarative_base()

        class UCComparator(hybrid.Comparator):
            def __eq__(self, other):
                if other is None:
                    return self.expression is None
                else:
                    return func.upper(self.expression) == func.upper(other)

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)

            _value = Column("value", String)

            @hybrid.hybrid_property
            def value(self):
                "This is a docstring"
                return self._value - 5

            @value.comparator
            def value(cls):
                return UCComparator(cls._value)

            @value.setter
            def value(self, v):
                self._value = v + 5

        return A

    def test_set_get(self):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def test_no_name_one(self):
        """test :ticket:`6215`"""

        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            name = Column(String(50))

            @hybrid.hybrid_property
            def same_name(self):
                return self.id

            def name1(self):
                return self.id

            different_name = hybrid.hybrid_property(name1)

            no_name = hybrid.hybrid_property(lambda self: self.name)

        stmt = select(A.same_name, A.different_name, A.no_name)
        compiled = stmt.compile()

        eq_(
            [ent._label_name for ent in compiled.compile_state._entities],
            ["same_name", "id", "name"],
        )

    def test_no_name_two(self):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def test_no_name_two(self):
        """test :ticket:`6215`"""
        Base = declarative_base()

        class SomeMixin:
            @hybrid.hybrid_property
            def same_name(self):
                return self.id

            def name1(self):
                return self.id

            different_name = hybrid.hybrid_property(name1)

            no_name = hybrid.hybrid_property(lambda self: self.name)

        class A(SomeMixin, Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            name = Column(String(50))

        stmt = select(A.same_name, A.different_name, A.no_name)
        compiled = stmt.compile()

        eq_(
            [ent._label_name for ent in compiled.compile_state._entities],
            ["same_name", "id", "name"],
        )

    def test_custom_op(self, registry):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _fixture(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            _value = Column("value", String)

            @hybrid.hybrid_property
            def value(self):
                "This is an instance-level docstring"
                return int(self._value) - 5

            @value.expression
            def value(cls):
                "This is a class-level docstring"
                return func.foo(cls._value) + cls.bar_value

            @value.setter
            def value(self, v):
                self._value = v + 5

            @hybrid.hybrid_property
            def bar_value(cls):
                return func.bar(cls._value)

        return A

    def _wrong_expr_fixture(self):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _relationship_fixture(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            b_id = Column("bid", Integer, ForeignKey("b.id"))
            _value = Column("value", String)

            @hybrid.hybrid_property
            def value(self):
                return int(self._value) - 5

            @value.expression
            def value(cls):
                return func.foo(cls._value) + cls.bar_value

            @value.setter
            def value(self, v):
                self._value = v + 5

            @hybrid.hybrid_property
            def bar_value(cls):
                return func.bar(cls._value)

        class B(Base):
            __tablename__ = "b"
            id = Column(Integer, primary_key=True)

            as_ = relationship("A")

        return A, B

    @testing.fixture

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _related_polymorphic_attr_fixture(self):
        """test for #7425"""

        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)

            bs = relationship("B", back_populates="a", lazy="joined")

        class B(Base):
            __tablename__ = "poly"
            __mapper_args__ = {
                "polymorphic_on": "type",
                # if with_polymorphic is removed, issue does not occur
                "with_polymorphic": "*",
            }
            name = Column(String, primary_key=True)
            type = Column(String)
            a_id = Column(ForeignKey(A.id))

            a = relationship(A, back_populates="bs")

            @hybrid.hybrid_property
            def is_foo(self):
                return self.name == "foo"

        return A, B

    def test_cloning_in_polymorphic_any(

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _fixture(self, assignable):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            _value = Column("value", String)

            @hybrid.hybrid_property
            def value(self):
                return self._value - 5

            if assignable:

                @value.setter
                def value(self, v):
                    self._value = v + 5

        return A

    def test_nonassignable(self):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _fixture(self):
        Base = declarative_base()

        class Person(Base):
            __tablename__ = "person"
            id = Column(Integer, primary_key=True)
            _name = Column(String)

            @hybrid.hybrid_property
            def name(self):
                return self._name

            @name.setter
            def name(self, value):
                self._name = value.title()

        class OverrideSetter(Person):
            __tablename__ = "override_setter"
            id = Column(Integer, ForeignKey("person.id"), primary_key=True)
            other = Column(String)

            @Person.name.setter
            def name(self, value):
                self._name = value.upper()

        class OverrideGetter(Person):
            __tablename__ = "override_getter"
            id = Column(Integer, ForeignKey("person.id"), primary_key=True)
            other = Column(String)

            @Person.name.getter
            def name(self):
                return "Hello " + self._name

        class OverrideExpr(Person):
            __tablename__ = "override_expr"
            id = Column(Integer, ForeignKey("person.id"), primary_key=True)
            other = Column(String)

            @Person.name.overrides.expression
            def name(self):
                return func.concat("Hello", self._name)

        class FooComparator(hybrid.Comparator):
            def __clause_element__(self):
                return func.concat("Hello", self.expression._name)

        class OverrideComparator(Person):
            __tablename__ = "override_comp"
            id = Column(Integer, ForeignKey("person.id"), primary_key=True)
            other = Column(String)

            @Person.name.overrides.comparator
            def name(self):
                return FooComparator(self)

        return (
            Person,
            OverrideSetter,
            OverrideGetter,
            OverrideExpr,
            OverrideComparator,
        )

    def test_property(self):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _name_mismatch_fixture(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            addresses = relationship("B")

            @hybrid.hybrid_property
            def some_email(self):
                if self.addresses:
                    return self.addresses[0].email_address
                else:
                    return None

            @some_email.expression
            def some_email(cls):
                return B.email_address

        class B(Base):
            __tablename__ = "b"
            id = Column(Integer, primary_key=True)
            aid = Column(ForeignKey("a.id"))
            email_address = Column(String)

        return A, B

    def test_dont_assume_attr_key_is_present(self, _name_mismatch_fixture):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _fixture(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            _value = Column("value", String)

            @hybrid.hybrid_property
            def value(self):
                return self._value

            value_syn = synonym("value")

            @hybrid.hybrid_property
            def string_value(self):
                return "foo"

            string_value_syn = synonym("string_value")

            @hybrid.hybrid_property
            def string_expr_value(self):
                return "foo"

            @string_expr_value.expression
            def string_expr_value(cls):
                return literal_column("'foo'")

            string_expr_value_syn = synonym("string_expr_value")

        return A

    def test_hasattr(self):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def _fixture(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column(Integer, primary_key=True)
            _value = Column("value", String)

            @hybrid.hybrid_method
            def value(self, x):
                "This is an instance-level docstring"
                return int(self._value) + x

            @value.expression
            def value(cls, value):
                "This is a class-level docstring"
                return func.foo(cls._value, value) + value

            @hybrid.hybrid_method
            def other_value(self, x):
                "This is an instance-level docstring"
                return int(self._value) + x

            @other_value.expression
            def other_value(cls, value):
                return func.foo(cls._value, value) + value

        return A

    def test_call(self):

0 Source : test_hybrid.py
with MIT License
from sqlalchemy

    def setup_test_class(cls):
        from sqlalchemy import literal

        symbols = ("usd", "gbp", "cad", "eur", "aud")
        currency_lookup = dict(
            ((currency_from, currency_to), Decimal(str(rate)))
            for currency_to, values in zip(
                symbols,
                [
                    (1, 1.59009, 0.988611, 1.37979, 1.02962),
                    (0.628895, 1, 0.621732, 0.867748, 0.647525),
                    (1.01152, 1.6084, 1, 1.39569, 1.04148),
                    (0.724743, 1.1524, 0.716489, 1, 0.746213),
                    (0.971228, 1.54434, 0.960166, 1.34009, 1),
                ],
            )
            for currency_from, rate in zip(symbols, values)
        )

        class Amount:
            def __init__(self, amount, currency):
                self.currency = currency
                self.amount = amount

            def __add__(self, other):
                return Amount(
                    self.amount + other.as_currency(self.currency).amount,
                    self.currency,
                )

            def __sub__(self, other):
                return Amount(
                    self.amount - other.as_currency(self.currency).amount,
                    self.currency,
                )

            def __lt__(self, other):
                return self.amount   <   other.as_currency(self.currency).amount

            def __gt__(self, other):
                return self.amount > other.as_currency(self.currency).amount

            def __eq__(self, other):
                return self.amount == other.as_currency(self.currency).amount

            def as_currency(self, other_currency):
                return Amount(
                    currency_lookup[(self.currency, other_currency)]
                    * self.amount,
                    other_currency,
                )

            def __clause_element__(self):
                # helper method for SQLAlchemy to interpret
                # the Amount object as a SQL element
                if isinstance(self.amount, (float, int, Decimal)):
                    return literal(self.amount)
                else:
                    return self.amount

            def __str__(self):
                return "%2.4f %s" % (self.amount, self.currency)

            def __repr__(self):
                return "Amount(%r, %r)" % (self.amount, self.currency)

        Base = declarative_base()

        class BankAccount(Base):
            __tablename__ = "bank_account"
            id = Column(Integer, primary_key=True)

            _balance = Column("balance", Numeric)

            @hybrid.hybrid_property
            def balance(self):
                """Return an Amount view of the current balance."""
                return Amount(self._balance, "usd")

            @balance.setter
            def balance(self, value):
                self._balance = value.as_currency("usd").amount

        cls.Amount = Amount
        cls.BankAccount = BankAccount

    def test_instance_one(self):

0 Source : test_indexable.py
with MIT License
from sqlalchemy

    def test_array(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column("id", Integer, primary_key=True)
            array = Column("_array", ARRAY(Integer), default=[])
            first = index_property("array", 0)
            tenth = index_property("array", 9)

        a = A(array=[1, 2, 3])
        eq_(a.first, 1)
        assert_raises(AttributeError, lambda: a.tenth)
        a.first = 100
        eq_(a.first, 100)
        eq_(a.array, [100, 2, 3])
        del a.first
        eq_(a.first, 2)

        a2 = A(first=5)
        eq_(a2.first, 5)
        eq_(a2.array, [5])

    def test_array_longinit(self):

0 Source : test_indexable.py
with MIT License
from sqlalchemy

    def test_array_longinit(self):
        Base = declarative_base()

        class A(Base):
            __tablename__ = "a"
            id = Column("id", Integer, primary_key=True)
            array = Column("_array", ARRAY(Integer), default=[])
            first = index_property("array", 0)

            fifth = index_property("array", 4)

        a1 = A(fifth=10)
        a2 = A(first=5)

        eq_(a1.array, [None, None, None, None, 10])
        eq_(a2.array, [5])

        assert_raises(IndexError, setattr, a2, "fifth", 10)

    def test_json(self):

0 Source : test_indexable.py
with MIT License
from sqlalchemy

    def test_json(self):
        Base = declarative_base()

        class J(Base):
            __tablename__ = "j"
            id = Column("id", Integer, primary_key=True)
            json = Column("_json", JSON, default={})
            field = index_property("json", "field")

        j = J(json={"a": 1, "b": 2})
        assert_raises(AttributeError, lambda: j.field)
        j.field = "test"
        eq_(j.field, "test")
        eq_(j.json, {"a": 1, "b": 2, "field": "test"})

        j2 = J(field="test")
        eq_(j2.json, {"field": "test"})
        eq_(j2.field, "test")

    def test_value_is_none_attributeerror(self):

0 Source : test_indexable.py
with MIT License
from sqlalchemy

    def test_set_mutable_dict(self):
        Base = declarative_base()

        class J(Base):
            __tablename__ = "j"
            id = Column(Integer, primary_key=True)
            json = Column(JSON, default={})
            field = index_property("json", "field")

        j = J()

        j.field = 10

        j.json = {}
        assert_raises(AttributeError, lambda: j.field)
        assert_raises(AttributeError, delattr, j, "field")

        j.field = 10
        eq_(j.field, 10)

    def test_get_default_value(self):

See More Examples