def test_strict_from_clause_role(self): stmt = select([t]).subquery() is_true( expect(roles.StrictFromClauseRole, stmt).compare( select([t]).subquery() ) )
def test_compare_col_identity(self): stmt1 = ( select([table_a.c.a, table_b.c.b]) .where(table_a.c.a == table_b.c.b) .alias() ) stmt1_c = ( select([table_a.c.a, table_b.c.b]) .where(table_a.c.a == table_b.c.b) .alias() ) stmt2 = union(select([table_a]), select([table_b])) stmt3 = select([table_b]) equivalents = {table_a.c.a: [table_b.c.a]} is_false( stmt1.compare(stmt2, use_proxies=True, equivalents=equivalents) ) is_true( stmt1.compare(stmt1_c, use_proxies=True, equivalents=equivalents) ) is_true( (table_a.c.a == table_b.c.b).compare( stmt1.c.a == stmt1.c.b, use_proxies=True, equivalents=equivalents, ) )
def test_use_get_reverseorder(self): mapper(self.classes.A, self.tables.a) m_b = mapper(self.classes.B, self.tables.b_differentorder, properties={ 'a': relationship(self.classes.A) }) configure_mappers() is_true(m_b.relationships.a.strategy.use_get)
def test_as_scalar(self): with testing.expect_deprecated( r"The SelectBase.as_scalar\(\) method is deprecated and " "will be removed in a future release." ): stmt = select([table1.c.myid]).as_scalar() is_true(stmt.compare(select([table1.c.myid]).scalar_subquery()))
def test_compare_comparison_associative(self): l1 = table_c.c.x == table_d.c.y l2 = table_d.c.y == table_c.c.x l3 = table_c.c.x == table_d.c.z is_true(l1.compare(l1)) is_true(l1.compare(l2)) is_false(l1.compare(l3))
def test_use_get_reverseorder(self): mapper(self.classes.A, self.tables.a) m_b = mapper( self.classes.B, self.tables.b_differentorder, properties={"a": relationship(self.classes.A)}, ) configure_mappers() is_true(m_b.relationships.a.strategy.use_get)
def test_compare_clauselist_not_associative(self): l1 = ClauseList( self.a.c.x, self.a.c.y, self.b.c.y, operator=operators.sub) l2 = ClauseList( self.b.c.y, self.a.c.x, self.a.c.y, operator=operators.sub) is_true(l1.compare(l1)) is_false(l1.compare(l2))
def test_fromclause_subquery(self): stmt = select([self.table1.c.myid]) with testing.expect_deprecated( "Implicit coercion of SELECT and textual SELECT constructs " "into FROM clauses is deprecated"): coerced = coercions.expect(roles.StrictFromClauseRole, stmt, allow_select=True) is_true(coerced.compare(stmt.subquery()))
def test_engine_has_table(self): with testing.expect_deprecated( r"The Engine.has_table\(\) method is deprecated" ): is_false(testing.db.has_table("dont_exist")) with testing.expect_deprecated( r"The Engine.has_table\(\) method is deprecated" ): is_true(testing.db.has_table("user"))
def test_compare_labels(self): is_true(column("q").label(None).compare(column("q").label(None))) is_false(column("q").label("foo").compare(column("q").label(None))) is_false(column("q").label(None).compare(column("q").label("foo"))) is_false(column("q").label("foo").compare(column("q").label("bar"))) is_true(column("q").label("foo").compare(column("q").label("foo")))
def test_use_get_sameorder(self): mapper(self.classes.A, self.tables.a) m_b = mapper( self.classes.B, self.tables.b_sameorder, properties={"a": relationship(self.classes.A)}, ) configure_mappers() is_true(m_b.relationships.a.strategy.use_get)
def test_exists(self): dont_exist = Table("dont_exist", MetaData()) with testing.expect_deprecated( r"The Table.exists\(\) method is deprecated"): is_false(dont_exist.exists(testing.db)) user = self.tables.user with testing.expect_deprecated( r"The Table.exists\(\) method is deprecated"): is_true(user.exists(testing.db))
def test_compare_clauselist_associative(self): l1 = and_(table_c.c.x == table_d.c.y, table_c.c.y == table_d.c.z) l2 = and_(table_c.c.y == table_d.c.z, table_c.c.x == table_d.c.y) l3 = and_(table_c.c.x == table_d.c.z, table_c.c.y == table_d.c.y) is_true(l1.compare(l1)) is_true(l1.compare(l2)) is_false(l1.compare(l3))
def test_compare_clauselist_associative(self): l1 = and_(self.a.c.x == self.b.c.y, self.a.c.y == self.b.c.z) l2 = and_(self.a.c.y == self.b.c.z, self.a.c.x == self.b.c.y) l3 = and_(self.a.c.x == self.b.c.z, self.a.c.y == self.b.c.y) is_true(l1.compare(l1)) is_true(l1.compare(l2)) is_false(l1.compare(l3))
def test_create_drop_explicit(self): metadata = MetaData() table = Table("test_table", metadata, Column("foo", Integer)) for bind in (testing.db, testing.db.connect()): for args in [([], {"bind": bind}), ([bind], {})]: metadata.create_all(*args[0], **args[1]) is_true(inspect(bind).has_table(table.name)) metadata.drop_all(*args[0], **args[1]) table.create(*args[0], **args[1]) table.drop(*args[0], **args[1]) is_false(inspect(bind).has_table(table.name))
def test_anonymized_from_clause_role(self): is_true(expect(roles.AnonymizedFromClauseRole, t).compare(t.alias())) # note the compare for subquery().alias(), even if it is two # plain Alias objects (which it won't be once we introduce the # Subquery class), still compares based on alias() being present # twice, that is, alias().alias() builds an alias of an alias, rather # than just replacing the outer alias. is_true( expect(roles.AnonymizedFromClauseRole, select(t).subquery()).compare(select(t).subquery().alias()))
def test_fromclause_subquery(self): stmt = select([table1.c.myid]) with testing.expect_deprecated( "Implicit coercion of SELECT and textual SELECT constructs " "into FROM clauses is deprecated" ): coerced = coercions.expect( roles.StrictFromClauseRole, stmt, allow_select=True ) is_true(coerced.compare(stmt.subquery()))
def test_plain_fromclause_select_to_subquery(self): with testing.expect_deprecated( "Implicit coercion of SELECT and textual SELECT " "constructs into FROM clauses is deprecated;"): element = coercions.expect( roles.FromClauseRole, SelectStatementGrouping(select([self.table1])), ) is_true( element.compare( SelectStatementGrouping(select([self.table1])).subquery()))
def test_construct_lhs_separate_name(self, decl_base): class User(decl_base): __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() data: Mapped[Optional[str]] = mapped_column("the_data") self.assert_compile(select(User.data), "SELECT users.the_data FROM users") is_true(User.__table__.c.the_data.nullable)
def test_reflect_views(self, connection): try: with testing.db.connect() as conn: conn.exec_driver_sql("CREATE VIEW view1 AS SELECT * FROM t1") insp = inspect(testing.db) for col in insp.get_columns("view1"): is_true("dialect_options" not in col) is_true("identity" in col) eq_(col["identity"], {}) finally: with testing.db.connect() as conn: conn.exec_driver_sql("DROP VIEW view1")
async def test_invalidate(self, async_session): await async_session.execute(select(1)) conn = async_session.sync_session.connection() fairy = conn.connection connection_rec = fairy._connection_record is_false(conn.closed) is_false(connection_rec._is_hard_or_soft_invalidated()) await async_session.invalidate() is_true(conn.closed) is_true(connection_rec._is_hard_or_soft_invalidated()) eq_(async_session.in_transaction(), False)
def test_anonymized_from_clause_role(self): is_true(expect(roles.AnonymizedFromClauseRole, t).compare(t.alias())) # note the compare for subquery().alias(), even if it is two # plain Alias objects (which it won't be once we introduce the # Subquery class), still compares based on alias() being present # twice, that is, alias().alias() builds an alias of an alias, rather # than just replacing the outer alias. is_true( expect( roles.AnonymizedFromClauseRole, select([t]).subquery() ).compare(select([t]).subquery().alias()) )
def test_select_is_coerced_into_fromclause_w_deprecation(self): with testing.expect_deprecated( "Implicit coercion of SELECT and textual SELECT " "constructs into FROM clauses is deprecated;" ): element = expect( roles.FromClauseRole, SelectStatementGrouping(select([t])) ) is_true( element.compare( SelectStatementGrouping(select([t])).subquery() ) )
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_labeled_role(self): stmt = select(self.table1.c.myid) with testing.expect_warnings( "implicitly coercing SELECT object to scalar subquery"): coerced = coercions.expect(roles.LabeledColumnExprRole, stmt) is_true(coerced.compare(stmt.scalar_subquery().label(None))) with testing.expect_warnings( "implicitly coercing SELECT object to scalar subquery"): coerced = coercions.expect(roles.LabeledColumnExprRole, stmt.alias()) is_true(coerced.compare(stmt.scalar_subquery().label(None)))
async def test_transaction_accessor(self, async_engine): async with async_engine.connect() as conn: is_none(conn.get_transaction()) is_false(conn.in_transaction()) is_false(conn.in_nested_transaction()) trans = await conn.begin() is_true(conn.in_transaction()) is_false(conn.in_nested_transaction()) is_( trans.sync_transaction, conn.get_transaction().sync_transaction ) nested = await conn.begin_nested() is_true(conn.in_transaction()) is_true(conn.in_nested_transaction()) is_( trans.sync_transaction, conn.get_transaction().sync_transaction ) await nested.commit() is_true(conn.in_transaction()) is_false(conn.in_nested_transaction()) await trans.rollback() is_none(conn.get_transaction()) is_false(conn.in_transaction()) is_false(conn.in_nested_transaction())
def test_compare_binds(self): b1 = bindparam("foo", type_=Integer()) b2 = bindparam("foo", type_=Integer()) b3 = bindparam("bar", type_=Integer()) b4 = bindparam("foo", type_=String()) def c1(): return 5 def c2(): return 6 b5 = bindparam("foo", type_=Integer(), callable_=c1) b6 = bindparam("foo", type_=Integer(), callable_=c2) b7 = bindparam("foo", type_=Integer(), callable_=c1) b8 = bindparam("foo", type_=Integer, value=5) b9 = bindparam("foo", type_=Integer, value=6) is_false(b1.compare(b5)) is_true(b5.compare(b7)) is_false(b5.compare(b6)) is_true(b1.compare(b2)) # currently not comparing "key", as we often have to compare # anonymous names. however we should really check for that is_true(b1.compare(b3)) is_false(b1.compare(b4)) is_false(b1.compare(b8)) is_false(b8.compare(b9)) is_true(b8.compare(b8))
def test_ok(self): class Foo(object): __tablename__ = "foo" id = sa.Column(sa.Integer, primary_key=True) meta = sa.MetaData() reg = {} with expect_deprecated_20( "the instrument_declarative function is deprecated"): instrument_declarative(Foo, reg, meta) mapper = sa.inspect(Foo) is_true(isinstance(mapper, Mapper)) is_(mapper.class_, Foo)
def test_comparison(self): common_url = ( "dbtype://*****:*****@[2001:da8:2004:1000:202:116:160:90]:80/database?foo=bar") other_url = "dbtype://*****:*****@host/" url1 = url.make_url(common_url) url2 = url.make_url(common_url) url3 = url.make_url(other_url) is_true(url1 == url2) is_false(url1 != url2) is_true(url1 != url3) is_false(url1 == url3)
def test_compare_tables(self): is_true(table_a.compare(table_a_2)) # the "proxy" version compares schema tables on metadata identity is_false(table_a.compare(table_a_2, use_proxies=True)) # same for lower case tables since it compares lower case columns # using proxies, which makes it very unlikely to have multiple # table() objects with columns that compare equally is_false( table("a", column("x", Integer), column("q", String)).compare( table("a", column("x", Integer), column("q", String)), use_proxies=True, ))
def test_construct_lhs(self, decl_base): class User(decl_base): __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() data: Mapped[Optional[str]] = mapped_column() self.assert_compile( select(User), "SELECT users.id, users.name, users.data FROM users") eq_(User.__mapper__.primary_key, (User.__table__.c.id, )) is_false(User.__table__.c.id.nullable) is_false(User.__table__.c.name.nullable) is_true(User.__table__.c.data.nullable)
def test_collection_class_uselist(self, decl_base): class A(decl_base): __tablename__ = "a" id: Mapped[int] = mapped_column(primary_key=True) data: Mapped[str] = mapped_column() bs_list: Mapped[List["B"]] = relationship(viewonly=True) bs_set: Mapped[Set["B"]] = relationship(viewonly=True) bs_list_warg: Mapped[List["B"]] = relationship("B", viewonly=True) bs_set_warg: Mapped[Set["B"]] = relationship("B", viewonly=True) class B(decl_base): __tablename__ = "b" id: Mapped[int] = mapped_column(Integer, primary_key=True) a_id: Mapped[int] = mapped_column(ForeignKey("a.id")) a: Mapped["A"] = relationship(viewonly=True) a_warg: Mapped["A"] = relationship("A", viewonly=True) is_(A.__mapper__.attrs["bs_list"].collection_class, list) is_(A.__mapper__.attrs["bs_set"].collection_class, set) is_(A.__mapper__.attrs["bs_list_warg"].collection_class, list) is_(A.__mapper__.attrs["bs_set_warg"].collection_class, set) is_true(A.__mapper__.attrs["bs_list"].uselist) is_true(A.__mapper__.attrs["bs_set"].uselist) is_true(A.__mapper__.attrs["bs_list_warg"].uselist) is_true(A.__mapper__.attrs["bs_set_warg"].uselist) is_false(B.__mapper__.attrs["a"].uselist) is_false(B.__mapper__.attrs["a_warg"].uselist)
def test_compare_tables(self): is_true(table_a.compare(table_a_2)) # the "proxy" version compares schema tables on metadata identity is_false(table_a.compare(table_a_2, use_proxies=True)) # same for lower case tables since it compares lower case columns # using proxies, which makes it very unlikely to have multiple # table() objects with columns that compare equally is_false( table("a", column("x", Integer), column("q", String)).compare( table("a", column("x", Integer), column("q", String)), use_proxies=True, ) )
def test_labeled_role(self): stmt = select([table1.c.myid]) with testing.expect_deprecated( "coercing SELECT object to scalar " "subquery in a column-expression context is deprecated"): coerced = coercions.expect(roles.LabeledColumnExprRole, stmt) is_true(coerced.compare(stmt.scalar_subquery().label(None))) with testing.expect_deprecated( "coercing SELECT object to scalar " "subquery in a column-expression context is deprecated"): coerced = coercions.expect(roles.LabeledColumnExprRole, stmt.alias()) is_true(coerced.compare(stmt.scalar_subquery().label(None)))
def test_component_set(self, component): common_url = ( "dbtype://*****:*****@[2001:da8:2004:1000:202:116:160:90]:80/database?foo=bar") url1 = url.make_url(common_url) url2 = url.make_url(common_url) url3 = url2.set(**{component: "new_changed_value"}) is_true(url1 != url3) is_false(url1 == url3) url4 = url3.set(**{component: getattr(url1, component)}) is_true(url4 == url1) is_false(url4 != url1)
def test_has_inherited_table(self, registry): @registry.mapped class Foo: __tablename__ = "foo" id = sa.Column(sa.Integer, primary_key=True) @registry.mapped class Bar(Foo): __tablename__ = "bar" id = sa.Column(sa.ForeignKey("foo.id"), primary_key=True) with self._expect_warning("has_inherited_table"): is_true(legacy_decl.has_inherited_table(Bar)) with self._expect_warning("has_inherited_table"): is_false(legacy_decl.has_inherited_table(Foo))
def test_single_cols_on_sub_to_joined(self): """test [ticket:3797]""" class BaseUser(Base): __tablename__ = "root" id = Column(Integer, primary_key=True) row_type = Column(String) __mapper_args__ = { "polymorphic_on": row_type, "polymorphic_identity": "baseuser", } class User(BaseUser): __tablename__ = "user" __mapper_args__ = {"polymorphic_identity": "user"} baseuser_id = Column(Integer, ForeignKey("root.id"), primary_key=True) class Bat(Base): __tablename__ = "bat" id = Column(Integer, primary_key=True) class Thing(Base): __tablename__ = "thing" id = Column(Integer, primary_key=True) owner_id = Column(Integer, ForeignKey("user.baseuser_id")) owner = relationship("User") class SubUser(User): __mapper_args__ = {"polymorphic_identity": "subuser"} sub_user_custom_thing = Column(Integer, ForeignKey("bat.id")) eq_( User.__table__.foreign_keys, User.baseuser_id.foreign_keys.union( SubUser.sub_user_custom_thing.foreign_keys), ) is_true( Thing.owner.property.primaryjoin.compare( Thing.owner_id == User.baseuser_id))
def test_create_drop_constructor_bound(self): for bind in (testing.db, testing.db.connect()): try: for args in (([bind], {}), ([], {"bind": bind})): metadata = MetaData(*args[0], **args[1]) table = Table("test_table", metadata, Column("foo", Integer)) assert metadata.bind is table.bind is bind metadata.create_all() is_true(inspect(bind).has_table(table.name)) metadata.drop_all() table.create() table.drop() is_false(inspect(bind).has_table(table.name)) finally: if isinstance(bind, engine.Connection): bind.close()
def test_compare_annotated_clears_mapping(self): t = table("t", column("x"), column("y")) x_a = t.c.x._annotate({"foo": True}) x_b = t.c.x._annotate({"foo": True}) is_true(x_a.compare(x_b, compare_annotations=True)) is_false( x_a.compare(x_b._annotate({"bar": True}), compare_annotations=True)) s1 = select([t.c.x])._annotate({"foo": True}) s2 = select([t.c.x])._annotate({"foo": True}) is_true(s1.compare(s2, compare_annotations=True)) is_false( s1.compare(s2._annotate({"bar": True}), compare_annotations=True))
def test_labeled_role(self): stmt = select([table1.c.myid]) with testing.expect_deprecated( "coercing SELECT object to scalar " "subquery in a column-expression context is deprecated" ): coerced = coercions.expect(roles.LabeledColumnExprRole, stmt) is_true(coerced.compare(stmt.scalar_subquery().label(None))) with testing.expect_deprecated( "coercing SELECT object to scalar " "subquery in a column-expression context is deprecated" ): coerced = coercions.expect( roles.LabeledColumnExprRole, stmt.alias() ) is_true(coerced.compare(stmt.scalar_subquery().label(None)))
def test_comparison(self): components = ( "drivername", "username", "password", "host", "database", "query", "port", ) common_url = ( "dbtype://*****:*****@[2001:da8:2004:1000:202:116:160:90]:80/database?foo=bar" ) other_url = "dbtype://*****:*****@host/" url1 = url.make_url(common_url) url2 = url.make_url(common_url) url3 = url.make_url(other_url) is_true(url1 == url2) is_false(url1 != url2) is_true(url1 != url3) is_false(url1 == url3) for curr_component in components: setattr(url2, curr_component, "new_changed_value") is_true(url1 != url2) is_false(url1 == url2) setattr(url2, curr_component, getattr(url1, curr_component))
def test_column_roles(self): stmt = select([table1.c.myid]) for role in [ roles.WhereHavingRole, roles.ExpressionElementRole, roles.ByOfRole, roles.OrderByRole, # roles.LabeledColumnExprRole ]: with testing.expect_deprecated( "coercing SELECT object to scalar " "subquery in a column-expression context is deprecated" ): coerced = coercions.expect(role, stmt) is_true(coerced.compare(stmt.scalar_subquery())) with testing.expect_deprecated( "coercing SELECT object to scalar " "subquery in a column-expression context is deprecated" ): coerced = coercions.expect(role, stmt.alias()) is_true(coerced.compare(stmt.scalar_subquery()))
def test_compare(self): for fixture in self.fixtures: case_a = fixture() case_b = fixture() for a, b in itertools.combinations_with_replacement( range(len(case_a)), 2 ): if a == b: is_true( case_a[a].compare( case_b[b], arbitrary_expression=True ), "%r != %r" % (case_a[a], case_b[b]), ) else: is_false( case_a[a].compare( case_b[b], arbitrary_expression=True ), "%r == %r" % (case_a[a], case_b[b]), )
def test_labeled_column_expr_role(self): c = column("q") is_true(expect(roles.LabeledColumnExprRole, c).compare(c)) is_true( expect(roles.LabeledColumnExprRole, c.label("foo")).compare( c.label("foo") ) ) is_true( expect( roles.LabeledColumnExprRole, select([column("q")]).scalar_subquery(), ).compare(select([column("q")]).label(None)) ) is_true( expect(roles.LabeledColumnExprRole, not_a_thing1).compare( literal(not_a_thing1).label(None) ) )
def test_statement_coercion_select(self): is_true( expect(roles.CoerceTextStatementRole, select([t])).compare( select([t]) ) )
def test_statement_text_coercion(self): is_true( expect( roles.CoerceTextStatementRole, "select * from table" ).compare(text("select * from table")) )