From: Federico Caselli Date: Tue, 30 May 2023 19:40:21 +0000 (+0200) Subject: Update black to v23.3.0 and flake8 to v6 X-Git-Tag: rel_2_0_16~15^2 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=058c230cea83811c3bebdd8259988c5c501f4f7e;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git Update black to v23.3.0 and flake8 to v6 This change could be added to .git-blame-ignore-revs Change-Id: I7ba10052b26bc3c178d23fb50a1123d0aae965ca --- diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 12b627005e..7f12edcf07 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,7 +2,7 @@ # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/python/black - rev: 22.8.0 + rev: 23.3.0 hooks: - id: black diff --git a/doc/build/changelog/migration_10.rst b/doc/build/changelog/migration_10.rst index c7988b3cd5..5a016140ae 100644 --- a/doc/build/changelog/migration_10.rst +++ b/doc/build/changelog/migration_10.rst @@ -73,7 +73,6 @@ once, a query as a pre-compiled unit begins to be feasible:: def search_for_user(session, username, email=None): - baked_query = bakery(lambda session: session.query(User)) baked_query += lambda q: q.filter(User.name == bindparam("username")) diff --git a/doc/build/changelog/migration_20.rst b/doc/build/changelog/migration_20.rst index 6582b6811c..a830122554 100644 --- a/doc/build/changelog/migration_20.rst +++ b/doc/build/changelog/migration_20.rst @@ -512,6 +512,7 @@ that descend from ``Base``:: Base = declarative_base(cls=Base) + # existing mapping proceeds, Declarative will ignore any annotations # which don't include ``Mapped[]`` class Foo(Base): diff --git a/doc/build/changelog/whatsnew_20.rst b/doc/build/changelog/whatsnew_20.rst index 366c9c0ffb..1a0f29c4a9 100644 --- a/doc/build/changelog/whatsnew_20.rst +++ b/doc/build/changelog/whatsnew_20.rst @@ -198,7 +198,6 @@ helper): :: with engine.connect() as conn: - # (variable) stmt: Select[Tuple[str, int]] stmt = select(str_col, int_col) @@ -262,7 +261,6 @@ helper): all the way from statement to result set:: with Session(engine) as session: - # (variable) stmt: Select[Tuple[int, str]] stmt_1 = select(User.id, User.name) @@ -277,7 +275,6 @@ helper): as a SELECT against two mapped classes:: with Session(engine) as session: - # (variable) stmt: Select[Tuple[User, Address]] stmt_2 = select(User, Address).join_from(User, Address) @@ -293,7 +290,6 @@ helper): class as well as the return type expected from a statement:: with Session(engine) as session: - # this is in fact an Annotated type, but typing tools don't # generally display this @@ -621,6 +617,7 @@ of :class:`_types.String`, as below where use of an ``Annotated`` ``str`` called str50 = Annotated[str, 50] + # declarative base with a type-level override, using a type that is # expected to be used in multiple places class Base(DeclarativeBase): @@ -1844,19 +1841,16 @@ declared class itself to place columns from the declared class first, followed by mixin columns. The following mapping:: class Foo: - col1 = mapped_column(Integer) col3 = mapped_column(Integer) class Bar: - col2 = mapped_column(Integer) col4 = mapped_column(Integer) class Model(Base, Foo, Bar): - id = mapped_column(Integer, primary_key=True) __tablename__ = "model" @@ -1892,14 +1886,12 @@ this is no comfort for the application that defined models the other way around, as:: class Foo: - id = mapped_column(Integer, primary_key=True) col1 = mapped_column(Integer) col3 = mapped_column(Integer) class Model(Foo, Base): - col2 = mapped_column(Integer) col4 = mapped_column(Integer) __tablename__ = "model" @@ -1930,7 +1922,6 @@ before or after other columns, as in the example below:: class Model(Foo, Base): - col2 = mapped_column(Integer) col4 = mapped_column(Integer) __tablename__ = "model" diff --git a/doc/build/core/connections.rst b/doc/build/core/connections.rst index 38a97afac4..f2d0f4f5ae 100644 --- a/doc/build/core/connections.rst +++ b/doc/build/core/connections.rst @@ -542,7 +542,6 @@ before we call upon :meth:`_engine.Connection.begin`:: # which... we usually don't. with engine.connect() as connection: - connection.execution_options(isolation_level="AUTOCOMMIT") # run statement(s) in autocommit mode @@ -568,7 +567,6 @@ use two blocks :: # use an autocommit block with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as connection: - # run statement in autocommit mode connection.execute("") @@ -742,7 +740,6 @@ of 1000 rows. The maximum size of this buffer can be affected using the with conn.execution_options(stream_results=True, max_row_buffer=100).execute( text("select * from table") ) as result: - for row in result: print(f"{row}") diff --git a/doc/build/core/custom_types.rst b/doc/build/core/custom_types.rst index 44187ee4c1..d084b428c8 100644 --- a/doc/build/core/custom_types.rst +++ b/doc/build/core/custom_types.rst @@ -342,7 +342,6 @@ method:: class JSONEncodedDict(TypeDecorator): - impl = VARCHAR cache_ok = True diff --git a/doc/build/dialects/postgresql.rst b/doc/build/dialects/postgresql.rst index fce0e4610e..53659fb54e 100644 --- a/doc/build/dialects/postgresql.rst +++ b/doc/build/dialects/postgresql.rst @@ -172,7 +172,6 @@ E.g. an example of a fully typed model using the class RoomBooking(Base): - __tablename__ = "room_booking" id: Mapped[int] = mapped_column(primary_key=True) @@ -246,7 +245,6 @@ datatype:: class EventCalendar(Base): - __tablename__ = "event_calendar" id: Mapped[int] = mapped_column(primary_key=True) @@ -515,7 +513,6 @@ For example:: class RoomBooking(Base): - __tablename__ = "room_booking" room = Column(Integer(), primary_key=True) diff --git a/doc/build/faq/connections.rst b/doc/build/faq/connections.rst index 66e878c898..d93a4b1af7 100644 --- a/doc/build/faq/connections.rst +++ b/doc/build/faq/connections.rst @@ -306,7 +306,6 @@ using the following proof of concept script. Once run, it will emit a from sqlalchemy import select if __name__ == "__main__": - engine = create_engine("mysql+mysqldb://scott:tiger@localhost/test", echo_pool=True) def do_a_thing(engine): diff --git a/doc/build/faq/ormconfiguration.rst b/doc/build/faq/ormconfiguration.rst index 47e9e2a494..90d74d23ee 100644 --- a/doc/build/faq/ormconfiguration.rst +++ b/doc/build/faq/ormconfiguration.rst @@ -234,6 +234,7 @@ The same idea applies to all the other arguments, such as ``foreign_keys``:: # also correct ! foo = relationship(Dest, foreign_keys=[Dest.foo_id, Dest.bar_id]) + # if you're using columns from the class that you're inside of, just use the column objects ! class MyClass(Base): foo_id = Column(...) diff --git a/doc/build/orm/dataclasses.rst b/doc/build/orm/dataclasses.rst index bbd05fcd5e..240ec75892 100644 --- a/doc/build/orm/dataclasses.rst +++ b/doc/build/orm/dataclasses.rst @@ -348,7 +348,6 @@ hierarchy, such as in the example below using a mixin:: class Mixin(MappedAsDataclass): - create_user: Mapped[int] = mapped_column() update_user: Mapped[Optional[int]] = mapped_column(default=None, init=False) diff --git a/doc/build/orm/declarative_mixins.rst b/doc/build/orm/declarative_mixins.rst index cf721cb4a7..b8e17afdac 100644 --- a/doc/build/orm/declarative_mixins.rst +++ b/doc/build/orm/declarative_mixins.rst @@ -634,7 +634,6 @@ for inheriting subclasses by default:: class Manager(Person): - __mapper_args__ = {"polymorphic_identity": "manager"} .. _mixin_inheritance_columns: diff --git a/doc/build/orm/declarative_styles.rst b/doc/build/orm/declarative_styles.rst index a02391004b..48897ee6d6 100644 --- a/doc/build/orm/declarative_styles.rst +++ b/doc/build/orm/declarative_styles.rst @@ -22,6 +22,7 @@ subclassing the :class:`_orm.DeclarativeBase` superclass:: from sqlalchemy.orm import DeclarativeBase + # declarative base class class Base(DeclarativeBase): pass diff --git a/doc/build/orm/declarative_tables.rst b/doc/build/orm/declarative_tables.rst index 0ee40cd07f..3d032b9a62 100644 --- a/doc/build/orm/declarative_tables.rst +++ b/doc/build/orm/declarative_tables.rst @@ -562,7 +562,6 @@ of the ``NULL`` / ``NOT NULL`` setting that takes place in the database:: class SomeClass(Base): - # ... # pep-484 type will be Optional, but column will be diff --git a/doc/build/orm/extensions/asyncio.rst b/doc/build/orm/extensions/asyncio.rst index 0dff980e26..016a3d908e 100644 --- a/doc/build/orm/extensions/asyncio.rst +++ b/doc/build/orm/extensions/asyncio.rst @@ -187,7 +187,6 @@ illustrates a complete example including mapper and session configuration:: async def insert_objects(async_session: async_sessionmaker[AsyncSession]) -> None: - async with async_session() as session: async with session.begin(): session.add_all( @@ -202,7 +201,6 @@ illustrates a complete example including mapper and session configuration:: async def select_and_update_objects( async_session: async_sessionmaker[AsyncSession], ) -> None: - async with async_session() as session: stmt = select(A).options(selectinload(A.bs)) @@ -317,7 +315,7 @@ this are below, many of which are illustrated in the preceding example. as an awaitable by indicating the :attr:`_asyncio.AsyncAttrs.awaitable_attrs` prefix:: - a1 = await (session.scalars(select(A))).one() + a1 = (await session.scalars(select(A))).one() for b1 in await a1.awaitable_attrs.bs: print(b1) diff --git a/doc/build/orm/mapping_styles.rst b/doc/build/orm/mapping_styles.rst index b4c21a353d..72d540090f 100644 --- a/doc/build/orm/mapping_styles.rst +++ b/doc/build/orm/mapping_styles.rst @@ -73,6 +73,7 @@ the use of a declarative base which is then used in a declarative table mapping: from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column + # declarative base class class Base(DeclarativeBase): pass diff --git a/doc/build/orm/quickstart.rst b/doc/build/orm/quickstart.rst index 652ed235a5..9c693e027d 100644 --- a/doc/build/orm/quickstart.rst +++ b/doc/build/orm/quickstart.rst @@ -201,7 +201,6 @@ is used: >>> from sqlalchemy.orm import Session >>> with Session(engine) as session: - ... ... spongebob = User( ... name="spongebob", ... fullname="Spongebob Squarepants", diff --git a/doc/build/orm/self_referential.rst b/doc/build/orm/self_referential.rst index 763e2d6a35..e1b0bfbf25 100644 --- a/doc/build/orm/self_referential.rst +++ b/doc/build/orm/self_referential.rst @@ -116,8 +116,7 @@ to a specific folder within that account:: name = mapped_column(String) parent_folder = relationship( - "Folder", back_populates="child_folders", - remote_side=[account_id, folder_id] + "Folder", back_populates="child_folders", remote_side=[account_id, folder_id] ) child_folders = relationship("Folder", back_populates="parent_folder") diff --git a/doc/build/orm/session_events.rst b/doc/build/orm/session_events.rst index f61421ea92..8ab2842bae 100644 --- a/doc/build/orm/session_events.rst +++ b/doc/build/orm/session_events.rst @@ -89,7 +89,6 @@ may be used on its own, or is ideally suited to be used within the @event.listens_for(Session, "do_orm_execute") def _do_orm_execute(orm_execute_state): - if ( orm_execute_state.is_select and not orm_execute_state.is_column_load diff --git a/doc/build/orm/session_transaction.rst b/doc/build/orm/session_transaction.rst index 153d4ea054..cb0f0fac24 100644 --- a/doc/build/orm/session_transaction.rst +++ b/doc/build/orm/session_transaction.rst @@ -689,7 +689,6 @@ data changes throughout the test are reverted:: self.session.commit() def test_something_with_rollbacks(self): - self.session.add(Bar()) self.session.flush() self.session.rollback() diff --git a/examples/asyncio/basic.py b/examples/asyncio/basic.py index efdb7e9e87..6cfa9ed014 100644 --- a/examples/asyncio/basic.py +++ b/examples/asyncio/basic.py @@ -33,7 +33,6 @@ async def async_main(): # conn is an instance of AsyncConnection async with engine.begin() as conn: - # to support SQLAlchemy DDL methods as well as legacy functions, the # AsyncConnection.run_sync() awaitable method will pass a "sync" # version of the AsyncConnection object to any synchronous method, @@ -49,7 +48,6 @@ async def async_main(): ) async with engine.connect() as conn: - # the default result object is the # sqlalchemy.engine.Result object result = await conn.execute(t1.select()) diff --git a/examples/asyncio/gather_orm_statements.py b/examples/asyncio/gather_orm_statements.py index a67b5e669d..334521f0e4 100644 --- a/examples/asyncio/gather_orm_statements.py +++ b/examples/asyncio/gather_orm_statements.py @@ -47,7 +47,6 @@ async def run_out_of_band( """ async with async_sessionmaker() as oob_session: - # use AUTOCOMMIT for each connection to reduce transaction # overhead / contention await oob_session.connection( @@ -83,7 +82,6 @@ async def run_out_of_band( async def async_main(): - engine = create_async_engine( "postgresql+asyncpg://scott:tiger@localhost/test", echo=True, diff --git a/examples/custom_attributes/active_column_defaults.py b/examples/custom_attributes/active_column_defaults.py index d5322d331b..2a151b2bfd 100644 --- a/examples/custom_attributes/active_column_defaults.py +++ b/examples/custom_attributes/active_column_defaults.py @@ -22,7 +22,6 @@ def configure_listener(mapper, class_): # iterate through ColumnProperty objects for col_attr in mapper.column_attrs: - # look at the Column mapped by the ColumnProperty # (we look at the first column in the less common case # of a property mapped to multiple columns at once) @@ -46,7 +45,6 @@ def default_listener(col_attr, default): @event.listens_for(col_attr, "init_scalar", retval=True, propagate=True) def init_scalar(target, value, dict_): - if default.is_callable: # the callable of ColumnDefault always accepts a context # argument; we can pass it as None here. @@ -74,7 +72,6 @@ def default_listener(col_attr, default): if __name__ == "__main__": - Base = declarative_base() event.listen(Base, "mapper_configured", configure_listener, propagate=True) diff --git a/examples/dogpile_caching/caching_query.py b/examples/dogpile_caching/caching_query.py index 4533dce005..937bf51d55 100644 --- a/examples/dogpile_caching/caching_query.py +++ b/examples/dogpile_caching/caching_query.py @@ -42,7 +42,6 @@ class ORMCache: event.listen(session_factory, "do_orm_execute", self._do_orm_execute) def _do_orm_execute(self, orm_context): - for opt in orm_context.user_defined_options: if isinstance(opt, RelationshipCache): opt = opt._process_orm_context(orm_context) diff --git a/examples/dogpile_caching/local_session_caching.py b/examples/dogpile_caching/local_session_caching.py index 1bcb3bb9a0..f317446968 100644 --- a/examples/dogpile_caching/local_session_caching.py +++ b/examples/dogpile_caching/local_session_caching.py @@ -64,7 +64,6 @@ register_backend("sqlalchemy.session", __name__, "ScopedSessionBackend") if __name__ == "__main__": - # set up a region based on the ScopedSessionBackend, # pointing to the scoped_session declared in the example # environment. diff --git a/examples/extending_query/filter_public.py b/examples/extending_query/filter_public.py index 1ac8115834..1321afe34e 100644 --- a/examples/extending_query/filter_public.py +++ b/examples/extending_query/filter_public.py @@ -65,7 +65,6 @@ class HasPrivate: if __name__ == "__main__": - Base = declarative_base() class User(HasPrivate, Base): diff --git a/examples/extending_query/temporal_range.py b/examples/extending_query/temporal_range.py index dc6d8166f8..50cbb66459 100644 --- a/examples/extending_query/temporal_range.py +++ b/examples/extending_query/temporal_range.py @@ -36,7 +36,6 @@ def temporal_range(range_lower, range_upper): if __name__ == "__main__": - Base = declarative_base() class Parent(HasTemporal, Base): diff --git a/examples/inheritance/concrete.py b/examples/inheritance/concrete.py index 899b045b18..f7f6b3ac64 100644 --- a/examples/inheritance/concrete.py +++ b/examples/inheritance/concrete.py @@ -93,7 +93,6 @@ engine = create_engine("sqlite://", echo=True) Base.metadata.create_all(engine) with Session(engine) as session: - c = Company( name="company1", employees=[ diff --git a/examples/inheritance/joined.py b/examples/inheritance/joined.py index c2ce76252a..7dee935fab 100644 --- a/examples/inheritance/joined.py +++ b/examples/inheritance/joined.py @@ -91,7 +91,6 @@ engine = create_engine("sqlite://", echo=True) Base.metadata.create_all(engine) with Session(engine) as session: - c = Company( name="company1", employees=[ diff --git a/examples/inheritance/single.py b/examples/inheritance/single.py index 09a5e2879a..8da75dd7c4 100644 --- a/examples/inheritance/single.py +++ b/examples/inheritance/single.py @@ -63,7 +63,6 @@ class Person(Base): class Engineer(Person): - # illustrate a single-inh "conflicting" mapped_column declaration, # where both subclasses want to share the same column that is nonetheless # not "local" to the base class @@ -111,7 +110,6 @@ engine = create_engine("sqlite://", echo=True) Base.metadata.create_all(engine) with Session(engine) as session: - c = Company( name="company1", employees=[ diff --git a/examples/performance/__init__.py b/examples/performance/__init__.py index 31b1a152a2..7e24b9b8fd 100644 --- a/examples/performance/__init__.py +++ b/examples/performance/__init__.py @@ -318,7 +318,6 @@ class Profiler: @classmethod def main(cls): - parser = argparse.ArgumentParser("python -m examples.performance") if cls.name is None: diff --git a/examples/performance/short_selects.py b/examples/performance/short_selects.py index afe11e1416..d0e5f6e9d2 100644 --- a/examples/performance/short_selects.py +++ b/examples/performance/short_selects.py @@ -100,7 +100,6 @@ def test_orm_query_new_style_using_external_lambdas(n): session = Session(bind=engine) for id_ in random.sample(ids, n): - stmt = lambdas.lambda_stmt(lambda: future_select(Customer)) stmt += lambda s: s.where(Customer.id == id_) session.execute(stmt).scalar_one() @@ -185,7 +184,6 @@ def test_core_reuse_stmt(n): stmt = select(Customer.__table__).where(Customer.id == bindparam("id")) with engine.connect() as conn: for id_ in random.sample(ids, n): - row = conn.execute(stmt, {"id": id_}).first() tuple(row) diff --git a/examples/sharding/asyncio.py b/examples/sharding/asyncio.py index a66689a5bc..4b32034c9f 100644 --- a/examples/sharding/asyncio.py +++ b/examples/sharding/asyncio.py @@ -283,7 +283,6 @@ async def main(): quito.reports.append(Report(85)) async with Session() as sess: - sess.add_all( [tokyo, newyork, toronto, london, dublin, brasilia, quito] ) diff --git a/examples/sharding/separate_databases.py b/examples/sharding/separate_databases.py index 65364773b7..f836aaec00 100644 --- a/examples/sharding/separate_databases.py +++ b/examples/sharding/separate_databases.py @@ -266,7 +266,6 @@ def main(): quito.reports.append(Report(85)) with Session() as sess: - sess.add_all( [tokyo, newyork, toronto, london, dublin, brasilia, quito] ) diff --git a/examples/sharding/separate_schema_translates.py b/examples/sharding/separate_schema_translates.py index 0b5b08e57f..095ae1cc69 100644 --- a/examples/sharding/separate_schema_translates.py +++ b/examples/sharding/separate_schema_translates.py @@ -191,7 +191,6 @@ def main(): quito.reports.append(Report(85)) with Session() as sess: - sess.add_all( [tokyo, newyork, toronto, london, dublin, brasilia, quito] ) diff --git a/examples/sharding/separate_tables.py b/examples/sharding/separate_tables.py index 98db3771f7..1caaaf329b 100644 --- a/examples/sharding/separate_tables.py +++ b/examples/sharding/separate_tables.py @@ -279,7 +279,6 @@ def main(): quito.reports.append(Report(85)) with Session() as sess: - sess.add_all( [tokyo, newyork, toronto, london, dublin, brasilia, quito] ) diff --git a/examples/space_invaders/space_invaders.py b/examples/space_invaders/space_invaders.py index 60c3969301..5ad59db8f3 100644 --- a/examples/space_invaders/space_invaders.py +++ b/examples/space_invaders/space_invaders.py @@ -154,7 +154,6 @@ class GlyphCoordinate(Base): for color, char in [ (data[i], data[i + 1]) for i in range(0, len(data), 2) ]: - x = self.x + col y = self.y + row if 0 <= x <= MAX_X and 0 <= y <= MAX_Y: @@ -448,7 +447,7 @@ def init_positions(session): ("enemy2", 25), ("enemy1", 10), ) - for (ship_vert, (etype, score)) in zip( + for ship_vert, (etype, score) in zip( range(5, 30, ENEMY_VERT_SPACING), arrangement ): for ship_horiz in range(0, 50, 10): diff --git a/examples/versioned_history/history_meta.py b/examples/versioned_history/history_meta.py index cc3ef2b0a5..c70a5bfa1c 100644 --- a/examples/versioned_history/history_meta.py +++ b/examples/versioned_history/history_meta.py @@ -28,7 +28,6 @@ def _is_versioning_col(col): def _history_mapper(local_mapper): - cls = local_mapper.class_ if cls.__dict__.get("_history_mapper_configured", False): diff --git a/examples/versioned_history/test_versioning.py b/examples/versioned_history/test_versioning.py index 392a415ff4..7b9c82c60f 100644 --- a/examples/versioned_history/test_versioning.py +++ b/examples/versioned_history/test_versioning.py @@ -39,7 +39,6 @@ class TestVersioning(AssertsCompiledSQL): __dialect__ = "default" def setUp(self): - self.engine = engine = create_engine("sqlite://") self.session = Session(engine) self.make_base() @@ -520,7 +519,6 @@ class TestVersioning(AssertsCompiledSQL): } class SubClass(BaseClass): - subname = Column(String(50), unique=True) __mapper_args__ = {"polymorphic_identity": "sub"} diff --git a/examples/versioned_rows/versioned_map.py b/examples/versioned_rows/versioned_map.py index fd457946f8..90bcb95b1b 100644 --- a/examples/versioned_rows/versioned_map.py +++ b/examples/versioned_rows/versioned_map.py @@ -54,7 +54,6 @@ def before_flush(session, flush_context, instances): """ for instance in session.dirty: if hasattr(instance, "new_version") and session.is_modified(instance): - # make it transient instance.new_version(session) diff --git a/examples/versioned_rows/versioned_update_old_row.py b/examples/versioned_rows/versioned_update_old_row.py index 41d3046a74..e4c45b9508 100644 --- a/examples/versioned_rows/versioned_update_old_row.py +++ b/examples/versioned_rows/versioned_update_old_row.py @@ -48,7 +48,6 @@ class VersionedStartEnd: super().__init__(**kw) def new_version(self, session): - # our current identity key, which will be used on the "old" # version of us to emit an UPDATE. this is just for assertion purposes old_identity_key = inspect(self).key @@ -153,7 +152,6 @@ class Child(VersionedStartEnd, Base): data = Column(String) def new_version(self, session): - # expire parent's reference to us session.expire(self.parent, ["child"]) diff --git a/examples/vertical/dictlike-polymorphic.py b/examples/vertical/dictlike-polymorphic.py index a3873da2a3..69f32cf4a8 100644 --- a/examples/vertical/dictlike-polymorphic.py +++ b/examples/vertical/dictlike-polymorphic.py @@ -134,7 +134,6 @@ def on_new_class(mapper, cls_): if __name__ == "__main__": - Base = declarative_base() class AnimalFact(PolymorphicVerticalProperty, Base): diff --git a/examples/vertical/dictlike.py b/examples/vertical/dictlike.py index dd19b9ee31..f561499e8f 100644 --- a/examples/vertical/dictlike.py +++ b/examples/vertical/dictlike.py @@ -74,7 +74,6 @@ class ProxiedDictMixin: if __name__ == "__main__": - Base = declarative_base() class AnimalFact(Base): diff --git a/lib/sqlalchemy/dialects/mssql/base.py b/lib/sqlalchemy/dialects/mssql/base.py index 3fd683172e..ebf2ce2d3e 100644 --- a/lib/sqlalchemy/dialects/mssql/base.py +++ b/lib/sqlalchemy/dialects/mssql/base.py @@ -1309,7 +1309,6 @@ class DATETIMEOFFSET(_DateTimeBase, sqltypes.DateTime): class _UnicodeLiteral: def literal_processor(self, dialect): def process(value): - value = value.replace("'", "''") if dialect.identifier_preparer._double_percents: @@ -1838,9 +1837,7 @@ class MSExecutionContext(default.DefaultExecutionContext): dialect: MSDialect def _opt_encode(self, statement): - if self.compiled and self.compiled.schema_translate_map: - rst = self.compiled.preparer._render_schema_translates statement = rst(statement, self.compiled.schema_translate_map) diff --git a/lib/sqlalchemy/dialects/mssql/provision.py b/lib/sqlalchemy/dialects/mssql/provision.py index 336e10cd9c..d01ed073a1 100644 --- a/lib/sqlalchemy/dialects/mssql/provision.py +++ b/lib/sqlalchemy/dialects/mssql/provision.py @@ -22,7 +22,6 @@ from ...testing.provision import temp_table_keyword_args @generate_driver_url.for_db("mssql") def generate_driver_url(url, driver, query_str): - backend = url.get_backend_name() new_url = url.set(drivername="%s+%s" % (backend, driver)) @@ -84,7 +83,6 @@ def _reap_mssql_dbs(url, idents): log.info("db reaper connecting to %r", url) eng = create_engine(url) with eng.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: - log.info("identifiers in file: %s", ", ".join(idents)) to_reap = conn.exec_driver_sql( diff --git a/lib/sqlalchemy/dialects/mssql/pyodbc.py b/lib/sqlalchemy/dialects/mssql/pyodbc.py index 6af527e735..49d203ee6e 100644 --- a/lib/sqlalchemy/dialects/mssql/pyodbc.py +++ b/lib/sqlalchemy/dialects/mssql/pyodbc.py @@ -377,7 +377,6 @@ class _ms_numeric_pyodbc: """ def bind_processor(self, dialect): - super_process = super().bind_processor(dialect) if not dialect._need_decimal_fix: diff --git a/lib/sqlalchemy/dialects/mysql/aiomysql.py b/lib/sqlalchemy/dialects/mysql/aiomysql.py index bc079ba17a..4533353253 100644 --- a/lib/sqlalchemy/dialects/mysql/aiomysql.py +++ b/lib/sqlalchemy/dialects/mysql/aiomysql.py @@ -285,7 +285,6 @@ class MySQLDialect_aiomysql(MySQLDialect_pymysql): @classmethod def get_pool_class(cls, url): - async_fallback = url.query.get("async_fallback", False) if util.asbool(async_fallback): diff --git a/lib/sqlalchemy/dialects/mysql/asyncmy.py b/lib/sqlalchemy/dialects/mysql/asyncmy.py index d3f809e6ae..8289daa7d1 100644 --- a/lib/sqlalchemy/dialects/mysql/asyncmy.py +++ b/lib/sqlalchemy/dialects/mysql/asyncmy.py @@ -295,7 +295,6 @@ class MySQLDialect_asyncmy(MySQLDialect_pymysql): @classmethod def get_pool_class(cls, url): - async_fallback = url.query.get("async_fallback", False) if util.asbool(async_fallback): diff --git a/lib/sqlalchemy/dialects/mysql/base.py b/lib/sqlalchemy/dialects/mysql/base.py index ae40fea99c..18e64f1b48 100644 --- a/lib/sqlalchemy/dialects/mysql/base.py +++ b/lib/sqlalchemy/dialects/mysql/base.py @@ -1179,7 +1179,6 @@ class MySQLExecutionContext(default.DefaultExecutionContext): class MySQLCompiler(compiler.SQLCompiler): - render_table_with_column_in_update_from = True """Overridden from base SQLCompiler value""" @@ -1581,7 +1580,6 @@ class MySQLCompiler(compiler.SQLCompiler): tmp = " FOR UPDATE" if select._for_update_arg.of and self.dialect.supports_for_update_of: - tables = util.OrderedSet() for c in select._for_update_arg.of: tables.update(sql_util.surface_selectables_only(c)) @@ -1848,7 +1846,6 @@ class MySQLDDLCompiler(compiler.DDLCompiler): ): arg = opts[opt] if opt in _reflection._options_of_type_string: - arg = self.sql_compiler.render_literal_value( arg, sqltypes.String() ) @@ -1940,7 +1937,6 @@ class MySQLDDLCompiler(compiler.DDLCompiler): length = index.dialect_options[self.dialect.name]["length"] if length is not None: - if isinstance(length, dict): # length value can be a (column_name --> integer value) # mapping specifying the prefix length for each column of the @@ -2909,7 +2905,6 @@ class MySQLDialect(default.DefaultDialect): @reflection.cache def get_table_options(self, connection, table_name, schema=None, **kw): - parsed_state = self._parsed_state_or_create( connection, table_name, schema, **kw ) @@ -2942,7 +2937,6 @@ class MySQLDialect(default.DefaultDialect): @reflection.cache def get_foreign_keys(self, connection, table_name, schema=None, **kw): - parsed_state = self._parsed_state_or_create( connection, table_name, schema, **kw ) @@ -3021,7 +3015,6 @@ class MySQLDialect(default.DefaultDialect): ] if col_tuples: - correct_for_wrong_fk_case = connection.execute( sql.text( """ @@ -3092,7 +3085,6 @@ class MySQLDialect(default.DefaultDialect): @reflection.cache def get_indexes(self, connection, table_name, schema=None, **kw): - parsed_state = self._parsed_state_or_create( connection, table_name, schema, **kw ) @@ -3168,7 +3160,6 @@ class MySQLDialect(default.DefaultDialect): @reflection.cache def get_view_definition(self, connection, view_name, schema=None, **kw): - charset = self._connection_charset full_name = ".".join( self.identifier_preparer._quote_free_identifiers(schema, view_name) diff --git a/lib/sqlalchemy/dialects/oracle/base.py b/lib/sqlalchemy/dialects/oracle/base.py index d20175b0ab..194b5a56df 100644 --- a/lib/sqlalchemy/dialects/oracle/base.py +++ b/lib/sqlalchemy/dialects/oracle/base.py @@ -699,7 +699,6 @@ class OracleTypeCompiler(compiler.GenericTypeCompiler): **kw, ): if precision is None: - precision = getattr(type_, "precision", None) if _requires_binary_precision: @@ -1098,7 +1097,6 @@ class OracleCompiler(compiler.SQLCompiler): # add expressions to accommodate FOR UPDATE OF if for_update is not None and for_update.of: - adapter = sql_util.ClauseAdapter(inner_subquery) for_update.of = [ adapter.traverse(elem) for elem in for_update.of @@ -1352,7 +1350,6 @@ class OracleDDLCompiler(compiler.DDLCompiler): class OracleIdentifierPreparer(compiler.IdentifierPreparer): - reserved_words = {x.lower() for x in RESERVED_WORDS} illegal_initial_characters = {str(dig) for dig in range(0, 10)}.union( ["_", "$"] diff --git a/lib/sqlalchemy/dialects/oracle/cx_oracle.py b/lib/sqlalchemy/dialects/oracle/cx_oracle.py index c0e308383b..da51f35a81 100644 --- a/lib/sqlalchemy/dialects/oracle/cx_oracle.py +++ b/lib/sqlalchemy/dialects/oracle/cx_oracle.py @@ -736,7 +736,6 @@ class OracleCompiler_cx_oracle(OracleCompiler): # Oracle parameters and use the custom escaping here escaped_from = kw.get("escaped_from", None) if not escaped_from: - if self._bind_translate_re.search(name): # not quite the translate use case as we want to # also get a quick boolean if we even found @@ -764,7 +763,6 @@ class OracleExecutionContext_cx_oracle(OracleExecutionContext): # check for has_out_parameters or RETURNING, create cx_Oracle.var # objects if so if self.compiled.has_out_parameters or self.compiled._oracle_returning: - out_parameters = self.out_parameters assert out_parameters is not None @@ -841,7 +839,7 @@ class OracleExecutionContext_cx_oracle(OracleExecutionContext): def _generate_cursor_outputtype_handler(self): output_handlers = {} - for (keyname, name, objects, type_) in self.compiled._result_columns: + for keyname, name, objects, type_ in self.compiled._result_columns: handler = type_._cached_custom_processor( self.dialect, "cx_oracle_outputtypehandler", @@ -892,7 +890,6 @@ class OracleExecutionContext_cx_oracle(OracleExecutionContext): and is_sql_compiler(self.compiled) and self.compiled._oracle_returning ): - initial_buffer = self.fetchall_for_returning( self.cursor, _internal=True ) @@ -1038,7 +1035,6 @@ class OracleDialect_cx_oracle(OracleDialect): threaded=None, **kwargs, ): - OracleDialect.__init__(self, **kwargs) self.arraysize = arraysize self.encoding_errors = encoding_errors @@ -1240,7 +1236,6 @@ class OracleDialect_cx_oracle(OracleDialect): def output_type_handler( cursor, name, default_type, size, precision, scale ): - if ( default_type == cx_Oracle.NUMBER and default_type is not cx_Oracle.NATIVE_FLOAT @@ -1307,7 +1302,6 @@ class OracleDialect_cx_oracle(OracleDialect): return output_type_handler def on_connect(self): - output_type_handler = self._generate_connection_outputtype_handler() def on_connect(conn): @@ -1453,7 +1447,6 @@ class OracleDialect_cx_oracle(OracleDialect): def do_commit_twophase( self, connection, xid, is_prepared=True, recover=False ): - if not is_prepared: self.do_commit(connection.connection) else: diff --git a/lib/sqlalchemy/dialects/oracle/oracledb.py b/lib/sqlalchemy/dialects/oracle/oracledb.py index 3ead846b15..7defbc9f06 100644 --- a/lib/sqlalchemy/dialects/oracle/oracledb.py +++ b/lib/sqlalchemy/dialects/oracle/oracledb.py @@ -67,7 +67,6 @@ class OracleDialect_oracledb(_OracleDialect_cx_oracle): thick_mode=None, **kwargs, ): - super().__init__( auto_convert_lobs, coerce_to_decimal, diff --git a/lib/sqlalchemy/dialects/oracle/provision.py b/lib/sqlalchemy/dialects/oracle/provision.py index 6644c6eab3..c8599e8e22 100644 --- a/lib/sqlalchemy/dialects/oracle/provision.py +++ b/lib/sqlalchemy/dialects/oracle/provision.py @@ -62,7 +62,6 @@ def _ora_drop_all_schema_objects_pre_tables(cfg, eng): @drop_all_schema_objects_post_tables.for_db("oracle") def _ora_drop_all_schema_objects_post_tables(cfg, eng): - with eng.begin() as conn: for syn in conn.dialect._get_synonyms(conn, None, None, None): conn.exec_driver_sql(f"drop synonym {syn['synonym_name']}") @@ -93,7 +92,6 @@ def _oracle_drop_db(cfg, eng, ident): @stop_test_class_outside_fixtures.for_db("oracle") def _ora_stop_test_class_outside_fixtures(config, db, cls): - try: _purge_recyclebin(db) except exc.DatabaseError as err: @@ -155,7 +153,6 @@ def _reap_oracle_dbs(url, idents): log.info("db reaper connecting to %r", url) eng = create_engine(url) with eng.begin() as conn: - log.info("identifiers in file: %s", ", ".join(idents)) to_reap = conn.exec_driver_sql( diff --git a/lib/sqlalchemy/dialects/postgresql/array.py b/lib/sqlalchemy/dialects/postgresql/array.py index bbfcecdc91..3496ed6b63 100644 --- a/lib/sqlalchemy/dialects/postgresql/array.py +++ b/lib/sqlalchemy/dialects/postgresql/array.py @@ -102,7 +102,6 @@ class array(expression.ExpressionClauseList[_T]): inherit_cache = True def __init__(self, clauses, **kw): - type_arg = kw.pop("type_", None) super().__init__(operators.comma_op, *clauses, **kw) @@ -404,7 +403,6 @@ class ARRAY(sqltypes.ARRAY): def _split_enum_values(array_string): - if '"' not in array_string: # no escape char is present so it can just split on the comma return array_string.split(",") if array_string else [] diff --git a/lib/sqlalchemy/dialects/postgresql/asyncpg.py b/lib/sqlalchemy/dialects/postgresql/asyncpg.py index 6827151f36..53e27fb746 100644 --- a/lib/sqlalchemy/dialects/postgresql/asyncpg.py +++ b/lib/sqlalchemy/dialects/postgresql/asyncpg.py @@ -234,7 +234,6 @@ class AsyncPgInterval(INTERVAL): @classmethod def adapt_emulated_to_native(cls, interval, **kw): - return AsyncPgInterval(precision=interval.second_precision) @@ -495,7 +494,6 @@ class AsyncAdapt_asyncpg_cursor: adapt_connection = self._adapt_connection async with adapt_connection._execute_mutex: - if not adapt_connection._started: await adapt_connection._start_transaction() @@ -597,7 +595,6 @@ class AsyncAdapt_asyncpg_cursor: class AsyncAdapt_asyncpg_ss_cursor(AsyncAdapt_asyncpg_cursor): - server_side = True __slots__ = ("_rowbuffer",) @@ -1074,7 +1071,6 @@ class PGDialect_asyncpg(PGDialect): @classmethod def get_pool_class(cls, url): - async_fallback = url.query.get("async_fallback", False) if util.asbool(async_fallback): diff --git a/lib/sqlalchemy/dialects/postgresql/dml.py b/lib/sqlalchemy/dialects/postgresql/dml.py index e17b87d1e7..829237bfe4 100644 --- a/lib/sqlalchemy/dialects/postgresql/dml.py +++ b/lib/sqlalchemy/dialects/postgresql/dml.py @@ -199,7 +199,6 @@ class OnConflictClause(ClauseElement): stringify_dialect = "postgresql" def __init__(self, constraint=None, index_elements=None, index_where=None): - if constraint is not None: if not isinstance(constraint, str) and isinstance( constraint, diff --git a/lib/sqlalchemy/dialects/postgresql/ext.py b/lib/sqlalchemy/dialects/postgresql/ext.py index c79e90034d..151bd809d0 100644 --- a/lib/sqlalchemy/dialects/postgresql/ext.py +++ b/lib/sqlalchemy/dialects/postgresql/ext.py @@ -297,7 +297,6 @@ class _regconfig_fn(functions.GenericFunction[_T]): def __init__(self, *args, **kwargs): args = list(args) if len(args) > 1: - initial_arg = coercions.expect( roles.ExpressionElementRole, args.pop(0), diff --git a/lib/sqlalchemy/dialects/postgresql/psycopg.py b/lib/sqlalchemy/dialects/postgresql/psycopg.py index 3f11556cf5..db3bd6d8b3 100644 --- a/lib/sqlalchemy/dialects/postgresql/psycopg.py +++ b/lib/sqlalchemy/dialects/postgresql/psycopg.py @@ -705,7 +705,6 @@ class PGDialectAsync_psycopg(PGDialect_psycopg): @classmethod def get_pool_class(cls, url): - async_fallback = url.query.get("async_fallback", False) if util.asbool(async_fallback): diff --git a/lib/sqlalchemy/dialects/postgresql/psycopg2.py b/lib/sqlalchemy/dialects/postgresql/psycopg2.py index 5cdd341833..112e9578e7 100644 --- a/lib/sqlalchemy/dialects/postgresql/psycopg2.py +++ b/lib/sqlalchemy/dialects/postgresql/psycopg2.py @@ -804,7 +804,6 @@ class PGDialect_psycopg2(_PGDialect_common_psycopg): @util.memoized_instancemethod def _hstore_oids(self, dbapi_connection): - extras = self._psycopg2_extras oids = extras.HstoreAdapter.get_oids(dbapi_connection) if oids is not None and oids[0]: diff --git a/lib/sqlalchemy/dialects/sqlite/aiosqlite.py b/lib/sqlalchemy/dialects/sqlite/aiosqlite.py index 2981976acc..78c7e08b9a 100644 --- a/lib/sqlalchemy/dialects/sqlite/aiosqlite.py +++ b/lib/sqlalchemy/dialects/sqlite/aiosqlite.py @@ -190,7 +190,6 @@ class AsyncAdapt_aiosqlite_connection(AdaptedConnection): @isolation_level.setter def isolation_level(self, value): - # aiosqlite's isolation_level setter works outside the Thread # that it's supposed to, necessitating setting check_same_thread=False. # for improved stability, we instead invent our own awaitable version diff --git a/lib/sqlalchemy/dialects/sqlite/base.py b/lib/sqlalchemy/dialects/sqlite/base.py index 6200cee5a3..835ec27731 100644 --- a/lib/sqlalchemy/dialects/sqlite/base.py +++ b/lib/sqlalchemy/dialects/sqlite/base.py @@ -1450,7 +1450,6 @@ class SQLiteCompiler(compiler.SQLCompiler): return target_text def visit_on_conflict_do_nothing(self, on_conflict, **kw): - target_text = self._on_conflict_target(on_conflict, **kw) if target_text: @@ -1528,7 +1527,6 @@ class SQLiteCompiler(compiler.SQLCompiler): class SQLiteDDLCompiler(compiler.DDLCompiler): def get_column_specification(self, column, **kwargs): - coltype = self.dialect.type_compiler_instance.process( column.type, type_expression=column ) @@ -1650,7 +1648,6 @@ class SQLiteDDLCompiler(compiler.DDLCompiler): return text def visit_foreign_key_constraint(self, constraint, **kw): - local_table = constraint.elements[0].parent.table remote_table = constraint.elements[0].column.table @@ -2263,7 +2260,6 @@ class SQLiteDialect(default.DefaultDialect): persisted, tablesql, ): - if generated: # the type of a column "cc INTEGER GENERATED ALWAYS AS (1 + 42)" # somehow is "INTEGER GENERATED ALWAYS" @@ -2541,7 +2537,6 @@ class SQLiteDialect(default.DefaultDialect): def get_unique_constraints( self, connection, table_name, schema=None, **kw ): - auto_index_by_sig = {} for idx in self.get_indexes( connection, diff --git a/lib/sqlalchemy/dialects/sqlite/dml.py b/lib/sqlalchemy/dialects/sqlite/dml.py index 3f829076be..23066c7bee 100644 --- a/lib/sqlalchemy/dialects/sqlite/dml.py +++ b/lib/sqlalchemy/dialects/sqlite/dml.py @@ -173,7 +173,6 @@ class OnConflictClause(ClauseElement): stringify_dialect = "sqlite" def __init__(self, index_elements=None, index_where=None): - if index_elements is not None: self.constraint_target = None self.inferred_target_elements = index_elements diff --git a/lib/sqlalchemy/dialects/sqlite/pysqlite.py b/lib/sqlalchemy/dialects/sqlite/pysqlite.py index 71da4d0ef5..3cd6e5f231 100644 --- a/lib/sqlalchemy/dialects/sqlite/pysqlite.py +++ b/lib/sqlalchemy/dialects/sqlite/pysqlite.py @@ -532,7 +532,6 @@ class SQLiteDialect_pysqlite(SQLiteDialect): ) def set_isolation_level(self, dbapi_connection, level): - if level == "AUTOCOMMIT": dbapi_connection.isolation_level = None else: diff --git a/lib/sqlalchemy/engine/base.py b/lib/sqlalchemy/engine/base.py index 0ef057471d..b0cd721f1c 100644 --- a/lib/sqlalchemy/engine/base.py +++ b/lib/sqlalchemy/engine/base.py @@ -1117,7 +1117,6 @@ class Connection(ConnectionEventsTarget, inspection.Inspectable["Inspector"]): self._handle_dbapi_exception(e, None, None, None, None) def _commit_impl(self) -> None: - if self._has_events or self.engine._has_events: self.dispatch.commit(self) @@ -1552,7 +1551,6 @@ class Connection(ConnectionEventsTarget, inspection.Inspectable["Inspector"]): _CoreMultiExecuteParams, _CoreSingleExecuteParams, ]: - event_multiparams: _CoreMultiExecuteParams event_params: _CoreSingleExecuteParams @@ -1896,7 +1894,6 @@ class Connection(ConnectionEventsTarget, inspection.Inspectable["Inspector"]): ) if self._echo: - self._log_info(str_statement) stats = context._get_cache_stats() @@ -2033,7 +2030,6 @@ class Connection(ConnectionEventsTarget, inspection.Inspectable["Inspector"]): generic_setinputsizes, context, ): - if imv_batch.processed_setinputsizes: try: dialect.do_set_input_sizes( @@ -2065,7 +2061,6 @@ class Connection(ConnectionEventsTarget, inspection.Inspectable["Inspector"]): ) if self._echo: - self._log_info(sql_util._long_statement(sub_stmt)) imv_stats = f""" { diff --git a/lib/sqlalchemy/engine/create.py b/lib/sqlalchemy/engine/create.py index bddf51fb63..684550e558 100644 --- a/lib/sqlalchemy/engine/create.py +++ b/lib/sqlalchemy/engine/create.py @@ -693,7 +693,6 @@ def create_engine(url: Union[str, _url.URL], **kwargs: Any) -> Engine: engine = engineclass(pool, dialect, u, **engine_args) if _initialize: - do_on_connect = dialect.on_connect_url(u) if do_on_connect: diff --git a/lib/sqlalchemy/engine/cursor.py b/lib/sqlalchemy/engine/cursor.py index 7491afc3e2..246cf6fe78 100644 --- a/lib/sqlalchemy/engine/cursor.py +++ b/lib/sqlalchemy/engine/cursor.py @@ -217,7 +217,6 @@ class CursorResultMetaData(ResultMetaData): def _splice_horizontally( self, other: CursorResultMetaData ) -> CursorResultMetaData: - assert not self._tuplefilter keymap = dict(self._keymap) @@ -453,7 +452,6 @@ class CursorResultMetaData(ResultMetaData): ) else: - # no dupes - copy secondary elements from compiled # columns into self._keymap. this is the most common # codepath for Core / ORM statement executions before the @@ -593,7 +591,6 @@ class CursorResultMetaData(ResultMetaData): for idx, rmap_entry in enumerate(result_columns) ] else: - # name-based or text-positional cases, where we need # to read cursor.description names @@ -816,7 +813,6 @@ class CursorResultMetaData(ResultMetaData): def _key_fallback( self, key: Any, err: Optional[Exception], raiseerr: bool = True ) -> Optional[NoReturn]: - if raiseerr: if self._unpickled and isinstance(key, elements.ColumnElement): raise exc.NoSuchColumnError( @@ -857,7 +853,6 @@ class CursorResultMetaData(ResultMetaData): return index def _indexes_for_keys(self, keys): - try: return [self._keymap[key][0] for key in keys] except KeyError as ke: @@ -1484,7 +1479,6 @@ class CursorResult(Result[_T]): self._metadata = self._no_result_metadata def _init_metadata(self, context, cursor_description): - if context.compiled: compiled = context.compiled diff --git a/lib/sqlalchemy/engine/default.py b/lib/sqlalchemy/engine/default.py index 0d61e2a9bc..ff34acc667 100644 --- a/lib/sqlalchemy/engine/default.py +++ b/lib/sqlalchemy/engine/default.py @@ -431,7 +431,6 @@ class DefaultDialect(Dialect): return self.bind_typing is interfaces.BindTyping.RENDER_CASTS def _ensure_has_table_connection(self, arg): - if not isinstance(arg, Connection): raise exc.ArgumentError( "The argument passed to Dialect.has_table() should be a " @@ -651,7 +650,6 @@ class DefaultDialect(Dialect): self._set_connection_characteristics(connection, characteristics) def _set_connection_characteristics(self, connection, characteristics): - characteristic_values = [ (name, self.connection_characteristics[name], value) for name, value in characteristics.items() @@ -930,7 +928,6 @@ class DefaultDialect(Dialect): @util.memoized_instancemethod def _gen_allowed_isolation_levels(self, dbapi_conn): - try: raw_levels = list(self.get_isolation_level_values(dbapi_conn)) except NotImplementedError: @@ -1036,7 +1033,6 @@ class DefaultDialect(Dialect): scope, **kw, ): - names_fns = [] temp_names_fns = [] if ObjectKind.TABLE in kind: @@ -1138,7 +1134,6 @@ class DefaultDialect(Dialect): class StrCompileDialect(DefaultDialect): - statement_compiler = compiler.StrSQLCompiler ddl_compiler = compiler.DDLCompiler type_compiler_cls = compiler.StrSQLTypeCompiler @@ -1834,7 +1829,6 @@ class DefaultExecutionContext(ExecutionContext): [name for param, name in out_bindparams] ), ): - type_ = bindparam.type impl_type = type_.dialect_impl(self.dialect) dbapi_type = impl_type.get_dbapi_type(self.dialect.loaded_dbapi) @@ -1977,7 +1971,6 @@ class DefaultExecutionContext(ExecutionContext): return [getter(None, param) for param in self.compiled_parameters] def _setup_ins_pk_from_implicit_returning(self, result, rows): - if not rows: return [] diff --git a/lib/sqlalchemy/engine/events.py b/lib/sqlalchemy/engine/events.py index c1b182a0ae..848f39733a 100644 --- a/lib/sqlalchemy/engine/events.py +++ b/lib/sqlalchemy/engine/events.py @@ -658,7 +658,6 @@ class DialectEvents(event.Events[Dialect]): target: Union[Engine, Type[Engine], Dialect, Type[Dialect]], identifier: str, ) -> Optional[Union[Dialect, Type[Dialect]]]: - if isinstance(target, type): if issubclass(target, Engine): return Dialect diff --git a/lib/sqlalchemy/engine/reflection.py b/lib/sqlalchemy/engine/reflection.py index 6e1ec18f2a..775abc4332 100644 --- a/lib/sqlalchemy/engine/reflection.py +++ b/lib/sqlalchemy/engine/reflection.py @@ -229,7 +229,6 @@ class Inspector(inspection.Inspectable["Inspector"]): def _construct( cls, init: Callable[..., Any], bind: Union[Engine, Connection] ) -> Inspector: - if hasattr(bind.dialect, "inspector"): cls = bind.dialect.inspector # type: ignore[attr-defined] @@ -1625,7 +1624,6 @@ class Inspector(inspection.Inspectable["Inspector"]): exclude_columns: Collection[str], cols_by_orig_name: Dict[str, sa_schema.Column[Any]], ) -> None: - orig_name = col_d["name"] table.metadata.dispatch.column_reflect(self, table, col_d) diff --git a/lib/sqlalchemy/engine/result.py b/lib/sqlalchemy/engine/result.py index cf34c195af..e7f9b30b9e 100644 --- a/lib/sqlalchemy/engine/result.py +++ b/lib/sqlalchemy/engine/result.py @@ -169,7 +169,6 @@ class ResultMetaData: def _getter( self, key: Any, raiseerr: bool = True ) -> Optional[Callable[[Row[Any]], Any]]: - index = self._index_for_key(key, raiseerr) if index is not None: @@ -508,7 +507,6 @@ class ResultInternal(InPlaceGenerative, Generic[_R]): @HasMemoized_ro_memoized_attribute def _iterator_getter(self) -> Callable[..., Iterator[_R]]: - make_row = self._row_getter post_creational_filter = self._post_creational_filter @@ -549,7 +547,6 @@ class ResultInternal(InPlaceGenerative, Generic[_R]): return [make_row(row) for row in rows] def _allrows(self) -> List[_R]: - post_creational_filter = self._post_creational_filter make_row = self._row_getter diff --git a/lib/sqlalchemy/event/base.py b/lib/sqlalchemy/event/base.py index 2e61d84c02..8507df9d0e 100644 --- a/lib/sqlalchemy/event/base.py +++ b/lib/sqlalchemy/event/base.py @@ -340,7 +340,6 @@ class Events(_HasEventsDispatch[_ET]): return all(isinstance(target.dispatch, t) for t in types) def dispatch_parent_is(t: Type[Any]) -> bool: - return isinstance( cast("_JoinedDispatcher[_ET]", target.dispatch).parent, t ) diff --git a/lib/sqlalchemy/event/legacy.py b/lib/sqlalchemy/event/legacy.py index 89fd5a8e0d..f3a7d04ace 100644 --- a/lib/sqlalchemy/event/legacy.py +++ b/lib/sqlalchemy/event/legacy.py @@ -72,7 +72,6 @@ def _wrap_fn_for_legacy( if len(argnames) == len(argspec.args) and has_kw is bool( argspec.varkw ): - formatted_def = "def %s(%s%s)" % ( dispatch_collection.name, ", ".join(dispatch_collection.arg_names), diff --git a/lib/sqlalchemy/event/registry.py b/lib/sqlalchemy/event/registry.py index d2da6d7243..8e4a266154 100644 --- a/lib/sqlalchemy/event/registry.py +++ b/lib/sqlalchemy/event/registry.py @@ -338,7 +338,6 @@ class _EventKey(Generic[_ET]): retval: Optional[bool] = None, asyncio: bool = False, ) -> None: - target, identifier = self.dispatch_target, self.identifier dispatch_collection = getattr(target.dispatch, identifier) diff --git a/lib/sqlalchemy/ext/associationproxy.py b/lib/sqlalchemy/ext/associationproxy.py index 243c140f8c..76605e26e3 100644 --- a/lib/sqlalchemy/ext/associationproxy.py +++ b/lib/sqlalchemy/ext/associationproxy.py @@ -1240,7 +1240,6 @@ class ObjectAssociationProxyInstance(AssociationProxyInstance[_T]): "contains() doesn't apply to a scalar object endpoint; use ==" ) else: - return self._comparator._criterion_exists( **{self.value_attr: other} ) diff --git a/lib/sqlalchemy/ext/asyncio/engine.py b/lib/sqlalchemy/ext/asyncio/engine.py index 531abdde52..fdf9580f48 100644 --- a/lib/sqlalchemy/ext/asyncio/engine.py +++ b/lib/sqlalchemy/ext/asyncio/engine.py @@ -233,7 +233,7 @@ class AsyncConnection( if self.sync_connection: raise exc.InvalidRequestError("connection is already started") self.sync_connection = self._assign_proxied( - await (greenlet_spawn(self.sync_engine.connect)) + await greenlet_spawn(self.sync_engine.connect) ) return self @@ -301,7 +301,6 @@ class AsyncConnection( async def invalidate( self, exception: Optional[BaseException] = None ) -> None: - """Invalidate the underlying DBAPI connection associated with this :class:`_engine.Connection`. @@ -1075,7 +1074,6 @@ class AsyncEngine(ProxyComparable[Engine], AsyncConnectable): return AsyncEngine(self.sync_engine.execution_options(**opt)) async def dispose(self, close: bool = True) -> None: - """Dispose of the connection pool used by this :class:`_asyncio.AsyncEngine`. diff --git a/lib/sqlalchemy/ext/asyncio/session.py b/lib/sqlalchemy/ext/asyncio/session.py index 6150033025..c42a84954a 100644 --- a/lib/sqlalchemy/ext/asyncio/session.py +++ b/lib/sqlalchemy/ext/asyncio/session.py @@ -570,7 +570,6 @@ class AsyncSession(ReversibleProxy[Session]): identity_token: Optional[Any] = None, execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT, ) -> Optional[_O]: - """Return an instance based on the given primary key identifier, or ``None`` if not found. @@ -625,7 +624,6 @@ class AsyncSession(ReversibleProxy[Session]): bind_arguments: Optional[_BindArguments] = None, **kw: Any, ) -> AsyncResult[Any]: - """Execute a statement and return a streaming :class:`_asyncio.AsyncResult` object. diff --git a/lib/sqlalchemy/ext/automap.py b/lib/sqlalchemy/ext/automap.py index f378f729a0..18568c7f28 100644 --- a/lib/sqlalchemy/ext/automap.py +++ b/lib/sqlalchemy/ext/automap.py @@ -1290,7 +1290,6 @@ class AutomapBase: by_module_properties: ByModuleProperties = cls.by_module for token in map_config.cls.__module__.split("."): - if token not in by_module_properties: by_module_properties[token] = util.Properties({}) @@ -1571,7 +1570,6 @@ def _m2m_relationship( name_for_collection_relationship: NameForCollectionRelationshipType, generate_relationship: GenerateRelationshipType, ) -> None: - map_config = table_to_map_config.get(lcl_m2m, None) referred_cfg = table_to_map_config.get(rem_m2m, None) if map_config is None or referred_cfg is None: diff --git a/lib/sqlalchemy/ext/declarative/extensions.py b/lib/sqlalchemy/ext/declarative/extensions.py index 62a0e07540..acc9d08cfb 100644 --- a/lib/sqlalchemy/ext/declarative/extensions.py +++ b/lib/sqlalchemy/ext/declarative/extensions.py @@ -330,7 +330,6 @@ class AbstractConcreteBase(ConcreteBase): for sup_ in scls.__mro__[1:]: sup_sm = _mapper_or_none(sup_) if sup_sm: - sm._set_concrete_base(sup_sm) break @@ -447,7 +446,6 @@ class DeferredReflection: # first collect the primary __table__ for each class into a # collection of metadata/schemaname -> table names for thingy in to_map: - if thingy.local_table is not None: metadata_to_table[ (thingy.local_table.metadata, thingy.local_table.schema) @@ -487,12 +485,10 @@ class DeferredReflection: metadata = mapper.class_.metadata for rel in mapper._props.values(): - if ( isinstance(rel, relationships.RelationshipProperty) and rel._init_args.secondary._is_populated() ): - secondary_arg = rel._init_args.secondary if isinstance(secondary_arg.argument, Table): diff --git a/lib/sqlalchemy/ext/horizontal_shard.py b/lib/sqlalchemy/ext/horizontal_shard.py index e1741fe526..963bd005a4 100644 --- a/lib/sqlalchemy/ext/horizontal_shard.py +++ b/lib/sqlalchemy/ext/horizontal_shard.py @@ -450,7 +450,6 @@ def execute_and_instances( def iter_for_shard( shard_id: ShardIdentifier, ) -> Union[Result[_T], IteratorResult[_TP]]: - bind_arguments = dict(orm_context.bind_arguments) bind_arguments["shard_id"] = shard_id diff --git a/lib/sqlalchemy/ext/hybrid.py b/lib/sqlalchemy/ext/hybrid.py index 4e0fd46049..5dfc529389 100644 --- a/lib/sqlalchemy/ext/hybrid.py +++ b/lib/sqlalchemy/ext/hybrid.py @@ -876,7 +876,6 @@ _T_con = TypeVar("_T_con", bound=Any, contravariant=True) class HybridExtensionType(InspectionAttrExtensionType): - HYBRID_METHOD = "HYBRID_METHOD" """Symbol indicating an :class:`InspectionAttr` that's of type :class:`.hybrid_method`. @@ -1412,7 +1411,6 @@ class hybrid_property(interfaces.InspectionAttrInfo, ORMDescriptor[_T]): def _get_comparator( self, comparator: Any ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]: - proxy_attr = attributes.create_proxied_attribute(self) def expr_comparator( diff --git a/lib/sqlalchemy/ext/mypy/apply.py b/lib/sqlalchemy/ext/mypy/apply.py index 2211561b1b..1bfaf1d7b0 100644 --- a/lib/sqlalchemy/ext/mypy/apply.py +++ b/lib/sqlalchemy/ext/mypy/apply.py @@ -118,7 +118,6 @@ def re_apply_declarative_assignments( and stmt.lvalues[0].name in mapped_attr_lookup and isinstance(stmt.lvalues[0].node, Var) ): - left_node = stmt.lvalues[0].node python_type_for_type = mapped_attr_lookup[ @@ -145,7 +144,6 @@ def re_apply_declarative_assignments( and isinstance(stmt.rvalue.args[0].callee, RefExpr) ) ): - new_python_type_for_type = ( infer.infer_type_from_right_hand_nameexpr( api, diff --git a/lib/sqlalchemy/ext/mypy/decl_class.py b/lib/sqlalchemy/ext/mypy/decl_class.py index 13ba2e6662..9c7b44b758 100644 --- a/lib/sqlalchemy/ext/mypy/decl_class.py +++ b/lib/sqlalchemy/ext/mypy/decl_class.py @@ -50,7 +50,6 @@ def scan_declarative_assignments_and_apply_types( api: SemanticAnalyzerPluginInterface, is_mixin_scan: bool = False, ) -> Optional[List[util.SQLAlchemyAttribute]]: - info = util.info_for_cls(cls, api) if info is None: @@ -161,7 +160,6 @@ def _scan_symbol_table_entry( sym = api.lookup_qualified(typeengine_arg.name, typeengine_arg) if sym is not None and isinstance(sym.node, TypeInfo): if names.has_base_type_id(sym.node, names.TYPEENGINE): - left_hand_explicit_type = UnionType( [ infer.extract_python_type_from_typeengine( @@ -457,7 +455,6 @@ def _scan_declarative_assignment_stmt( elif isinstance(stmt.rvalue, CallExpr) and isinstance( stmt.rvalue.callee, RefExpr ): - python_type_for_type = infer.infer_type_from_right_hand_nameexpr( api, stmt, node, left_hand_explicit_type, stmt.rvalue.callee ) diff --git a/lib/sqlalchemy/ext/mypy/infer.py b/lib/sqlalchemy/ext/mypy/infer.py index 479be40c36..3313795935 100644 --- a/lib/sqlalchemy/ext/mypy/infer.py +++ b/lib/sqlalchemy/ext/mypy/infer.py @@ -442,7 +442,6 @@ def _infer_type_from_decl_column( ) if left_hand_explicit_type is not None: - return _infer_type_from_left_and_inferred_right( api, node, left_hand_explicit_type, python_type_for_type ) diff --git a/lib/sqlalchemy/ext/mypy/plugin.py b/lib/sqlalchemy/ext/mypy/plugin.py index 22e5283872..862d7d2166 100644 --- a/lib/sqlalchemy/ext/mypy/plugin.py +++ b/lib/sqlalchemy/ext/mypy/plugin.py @@ -72,7 +72,6 @@ class SQLAlchemyPlugin(Plugin): def get_class_decorator_hook( self, fullname: str ) -> Optional[Callable[[ClassDefContext], None]]: - sym = self.lookup_fully_qualified(fullname) if sym is not None and sym.node is not None: diff --git a/lib/sqlalchemy/log.py b/lib/sqlalchemy/log.py index 581ed4eb2a..f1e2cf12c7 100644 --- a/lib/sqlalchemy/log.py +++ b/lib/sqlalchemy/log.py @@ -202,7 +202,6 @@ class InstanceLogger: selected_level = self.logger.getEffectiveLevel() if level >= selected_level: - if STACKLEVEL: kwargs["stacklevel"] = ( kwargs.get("stacklevel", 1) + STACKLEVEL_OFFSET diff --git a/lib/sqlalchemy/orm/__init__.py b/lib/sqlalchemy/orm/__init__.py index 7d70d3c7f1..f6888aeee4 100644 --- a/lib/sqlalchemy/orm/__init__.py +++ b/lib/sqlalchemy/orm/__init__.py @@ -163,7 +163,6 @@ from .. import util as _sa_util def __go(lcls: Any) -> None: - _sa_util.preloaded.import_prefix("sqlalchemy.orm") _sa_util.preloaded.import_prefix("sqlalchemy.ext") diff --git a/lib/sqlalchemy/orm/attributes.py b/lib/sqlalchemy/orm/attributes.py index 6a979219ca..b3129d4bf2 100644 --- a/lib/sqlalchemy/orm/attributes.py +++ b/lib/sqlalchemy/orm/attributes.py @@ -990,7 +990,6 @@ class AttributeImpl: last_parent is not False and last_parent.key != parent_state.key ): - if last_parent.obj() is None: raise orm_exc.StaleDataError( "Removing state %s from parent " @@ -1370,7 +1369,6 @@ class ScalarObjectAttributeImpl(ScalarAttributeImpl): else: original = state.committed_state.get(self.key, _NO_HISTORY) if original is PASSIVE_NO_RESULT: - loader_passive = passive | ( PASSIVE_ONLY_PERSISTENT | NO_AUTOFLUSH @@ -1418,7 +1416,6 @@ class ScalarObjectAttributeImpl(ScalarAttributeImpl): and original is not NO_VALUE and original is not current ): - ret.append((instance_state(original), original)) return ret @@ -1828,7 +1825,6 @@ class CollectionAttributeImpl(HasCollectionAdapter, AttributeImpl): def _initialize_collection( self, state: InstanceState[Any] ) -> Tuple[CollectionAdapter, _AdaptedCollectionProtocol]: - adapter, collection = state.manager.initialize_collection( self.key, state, self.collection_factory ) @@ -2255,7 +2251,6 @@ def backref_listeners( initiator is not check_remove_token and initiator is not check_replace_token ): - if not check_for_dupes_on_remove or not util.has_dupes( # when this event is called, the item is usually # present in the list, except for a pop() operation. @@ -2478,7 +2473,6 @@ class History(NamedTuple): elif original is _NO_HISTORY: return cls((), list(current), ()) else: - current_states = [ ((c is not None) and instance_state(c) or None, c) for c in current @@ -2582,7 +2576,6 @@ def register_attribute_impl( backref: Optional[str] = None, **kw: Any, ) -> QueryableAttribute[Any]: - manager = manager_of_class(class_) if uselist: factory = kw.pop("typecallable", None) diff --git a/lib/sqlalchemy/orm/bulk_persistence.py b/lib/sqlalchemy/orm/bulk_persistence.py index 58dfd5e32a..2181cd296f 100644 --- a/lib/sqlalchemy/orm/bulk_persistence.py +++ b/lib/sqlalchemy/orm/bulk_persistence.py @@ -149,7 +149,6 @@ def _bulk_insert( bookkeeping = False for table, super_mapper in mappers_to_run: - # find bindparams in the statement. For bulk, we don't really know if # a key in the params applies to a different table since we are # potentially inserting for multiple tables here; looking at the @@ -368,7 +367,6 @@ class ORMDMLState(AbstractORMCompileState): def _get_orm_crud_kv_pairs( cls, mapper, statement, kv_iterator, needs_to_be_cacheable ): - core_get_crud_kv_pairs = UpdateDMLState._get_crud_kv_pairs for k, v in kv_iterator: @@ -522,7 +520,6 @@ class ORMDMLState(AbstractORMCompileState): """ if orm_level_statement._returning: - fs = FromStatement( orm_level_statement._returning, dml_level_statement, @@ -578,7 +575,6 @@ class ORMDMLState(AbstractORMCompileState): bind_arguments, result, ): - execution_context = result.context compile_state = execution_context.compiled.compile_state @@ -638,7 +634,6 @@ class BulkUDCompileState(ORMDMLState): bind_arguments, is_pre_event, ): - ( update_options, execution_options, @@ -697,7 +692,6 @@ class BulkUDCompileState(ORMDMLState): session._autoflush() if update_options._dml_strategy == "orm": - if update_options._synchronize_session == "auto": update_options = cls._do_pre_synchronize_auto( session, @@ -760,7 +754,6 @@ class BulkUDCompileState(ORMDMLState): bind_arguments, result, ): - # this stage of the execution is called after the # do_orm_execute event hook. meaning for an extension like # horizontal sharding, this step happens *within* the horizontal @@ -1007,7 +1000,6 @@ class BulkUDCompileState(ORMDMLState): bind_arguments, update_options, ): - try: eval_condition = cls._eval_condition_from_statement( update_options, statement @@ -1157,7 +1149,6 @@ class BulkORMInsert(ORMDMLState, InsertDMLState): bind_arguments, is_pre_event, ): - ( insert_options, execution_options, @@ -1226,7 +1217,6 @@ class BulkORMInsert(ORMDMLState, InsertDMLState): bind_arguments: _BindArguments, conn: Connection, ) -> _result.Result: - insert_options = execution_options.get( "_sa_orm_insert_options", cls.default_insert_options ) @@ -1308,7 +1298,6 @@ class BulkORMInsert(ORMDMLState, InsertDMLState): @classmethod def create_for_statement(cls, statement, compiler, **kw) -> BulkORMInsert: - self = cast( BulkORMInsert, super().create_for_statement(statement, compiler, **kw), @@ -1392,7 +1381,6 @@ class BulkORMInsert(ORMDMLState, InsertDMLState): class BulkORMUpdate(BulkUDCompileState, UpdateDMLState): @classmethod def create_for_statement(cls, statement, compiler, **kw): - self = cls.__new__(cls) dml_strategy = statement._annotations.get( @@ -1558,7 +1546,6 @@ class BulkORMUpdate(BulkUDCompileState, UpdateDMLState): bind_arguments: _BindArguments, conn: Connection, ) -> _result.Result: - update_options = execution_options.get( "_sa_orm_update_options", cls.default_update_options ) @@ -1636,7 +1623,6 @@ class BulkORMUpdate(BulkUDCompileState, UpdateDMLState): is_delete_using: bool = False, is_executemany: bool = False, ) -> bool: - # normal answer for "should we use RETURNING" at all. normal_answer = ( dialect.update_returning and mapper.local_table.implicit_returning @@ -1710,7 +1696,6 @@ class BulkORMUpdate(BulkUDCompileState, UpdateDMLState): def _do_post_synchronize_evaluate( cls, session, statement, result, update_options ): - matched_objects = cls._get_matched_objects_on_criteria( update_options, session.identity_map.all_states(), @@ -1806,7 +1791,6 @@ class BulkORMUpdate(BulkUDCompileState, UpdateDMLState): states = set() for obj, state, dict_ in matched_objects: - to_evaluate = state.unmodified.intersection(evaluated_keys) for key in to_evaluate: @@ -1931,7 +1915,6 @@ class BulkORMDelete(BulkUDCompileState, DeleteDMLState): bind_arguments: _BindArguments, conn: Connection, ) -> _result.Result: - update_options = execution_options.get( "_sa_orm_update_options", cls.default_update_options ) @@ -1965,7 +1948,6 @@ class BulkORMDelete(BulkUDCompileState, DeleteDMLState): is_delete_using: bool = False, is_executemany: bool = False, ) -> bool: - # normal answer for "should we use RETURNING" at all. normal_answer = ( dialect.delete_returning and mapper.local_table.implicit_returning diff --git a/lib/sqlalchemy/orm/clsregistry.py b/lib/sqlalchemy/orm/clsregistry.py index c4d6c29ebe..10f1db03b6 100644 --- a/lib/sqlalchemy/orm/clsregistry.py +++ b/lib/sqlalchemy/orm/clsregistry.py @@ -548,7 +548,6 @@ def _resolver( Callable[[str], Callable[[], Union[Type[Any], Table, _ModNS]]], Callable[[str, bool], _class_resolver], ]: - global _fallback_dict if _fallback_dict is None: diff --git a/lib/sqlalchemy/orm/collections.py b/lib/sqlalchemy/orm/collections.py index 9abeb913eb..1155fc6cf5 100644 --- a/lib/sqlalchemy/orm/collections.py +++ b/lib/sqlalchemy/orm/collections.py @@ -796,7 +796,6 @@ def prepare_instrumentation( # Did factory callable return a builtin? if cls in __canned_instrumentation: - # if so, just convert. # in previous major releases, this codepath wasn't working and was # not covered by tests. prior to that it supplied a "wrapper" @@ -1548,7 +1547,6 @@ __interfaces: util.immutabledict[ def __go(lcls): - global keyfunc_mapping, mapped_collection global column_keyed_dict, column_mapped_collection global MappedCollection, KeyFuncDict diff --git a/lib/sqlalchemy/orm/context.py b/lib/sqlalchemy/orm/context.py index 397e90fadb..dfb7b3ef62 100644 --- a/lib/sqlalchemy/orm/context.py +++ b/lib/sqlalchemy/orm/context.py @@ -328,7 +328,6 @@ class AutoflushOnlyORMCompileState(AbstractORMCompileState): bind_arguments, is_pre_event, ): - # consume result-level load_options. These may have been set up # in an ORMExecuteState hook ( @@ -446,7 +445,6 @@ class ORMCompileState(AbstractORMCompileState): def _column_naming_convention( cls, label_style: SelectLabelStyle, legacy: bool ) -> _LabelConventionCallable: - if legacy: def name(col, col_name=None): @@ -473,7 +471,6 @@ class ORMCompileState(AbstractORMCompileState): bind_arguments, is_pre_event, ): - # consume result-level load_options. These may have been set up # in an ORMExecuteState hook ( @@ -705,7 +702,6 @@ class ORMFromStatementCompileState(ORMCompileState): compiler: Optional[SQLCompiler], **kw: Any, ) -> ORMFromStatementCompileState: - assert isinstance(statement_container, FromStatement) if compiler is not None and compiler.stack: @@ -900,7 +896,6 @@ class FromStatement(GroupedElement, Generative, TypedReturnsRows[_TP]): self._adapt_on_names = _adapt_on_names def _compiler_dispatch(self, compiler, **kw): - """provide a fixed _compiler_dispatch method. This is roughly similar to using the sqlalchemy.ext.compiler @@ -1100,7 +1095,6 @@ class ORMSelectCompileState(ORMCompileState, SelectState): select_statement._with_options or select_statement._memoized_select_entities ): - for ( memoized_entities ) in select_statement._memoized_select_entities: @@ -1370,7 +1364,6 @@ class ORMSelectCompileState(ORMCompileState, SelectState): @classmethod def from_statement(cls, statement, from_statement): - from_statement = coercions.expect( roles.ReturnsRowsRole, from_statement, @@ -1570,7 +1563,6 @@ class ORMSelectCompileState(ORMCompileState, SelectState): return statement def _simple_statement(self): - statement = self._select_statement( self.primary_columns + self.secondary_columns, tuple(self.from_clauses) + tuple(self.eager_joins.values()), @@ -1613,7 +1605,6 @@ class ORMSelectCompileState(ORMCompileState, SelectState): suffixes, group_by, ): - statement = Select._create_raw_select( _raw_columns=raw_columns, _from_obj=from_obj, @@ -1689,7 +1680,6 @@ class ORMSelectCompileState(ORMCompileState, SelectState): return cols def _get_current_adapter(self): - adapters = [] if self._from_obj_alias: @@ -1738,7 +1728,7 @@ class ORMSelectCompileState(ORMCompileState, SelectState): return _adapt_clause def _join(self, args, entities_collection): - for (right, onclause, from_, flags) in args: + for right, onclause, from_, flags in args: isouter = flags["isouter"] full = flags["full"] @@ -2163,7 +2153,6 @@ class ORMSelectCompileState(ORMCompileState, SelectState): # test for joining to an unmapped selectable as the target if r_info.is_clause_element: - if prop: right_mapper = prop.mapper @@ -2362,7 +2351,6 @@ class ORMSelectCompileState(ORMCompileState, SelectState): ) and ext_info not in self.extra_criteria_entities ): - self.extra_criteria_entities[ext_info] = ( ext_info, ext_info._adapter if ext_info.is_aliased_class else None, @@ -2370,7 +2358,7 @@ class ORMSelectCompileState(ORMCompileState, SelectState): search = set(self.extra_criteria_entities.values()) - for (ext_info, adapter) in search: + for ext_info, adapter in search: if ext_info in self._join_entities: continue @@ -2507,7 +2495,6 @@ class _QueryEntity: def to_compile_state( cls, compile_state, entities, entities_collection, is_current_entities ): - for idx, entity in enumerate(entities): if entity._is_lambda_element: if entity._is_sequence: @@ -2647,7 +2634,6 @@ class _MapperEntity(_QueryEntity): return _entity_corresponds_to(self.entity_zero, entity) def _get_entity_clauses(self, compile_state): - adapter = None if not self.is_aliased_class: @@ -2744,7 +2730,6 @@ class _MapperEntity(_QueryEntity): class _BundleEntity(_QueryEntity): - _extra_entities = () __slots__ = ( @@ -3175,7 +3160,6 @@ class _ORMColumnEntity(_ColumnEntity): or ("additional_entity_criteria", self.mapper) in compile_state.global_attributes ): - compile_state.extra_criteria_entities[ezero] = ( ezero, ezero._adapter if ezero.is_aliased_class else None, diff --git a/lib/sqlalchemy/orm/decl_api.py b/lib/sqlalchemy/orm/decl_api.py index a3a817162f..8e6539d57b 100644 --- a/lib/sqlalchemy/orm/decl_api.py +++ b/lib/sqlalchemy/orm/decl_api.py @@ -902,7 +902,6 @@ class DeclarativeBaseNoMeta(inspection.Inspectable[InstanceState[Any]]): """ if typing.TYPE_CHECKING: - __tablename__: Any """String name to assign to the generated :class:`_schema.Table` object, if not specified directly via @@ -1220,7 +1219,6 @@ class registry: def _resolve_type( self, python_type: _MatchedOnType ) -> Optional[sqltypes.TypeEngine[Any]]: - search: Iterable[Tuple[_MatchedOnType, Type[Any]]] python_type_type: Type[Any] diff --git a/lib/sqlalchemy/orm/decl_base.py b/lib/sqlalchemy/orm/decl_base.py index 71b93de8f7..816c7a8fd4 100644 --- a/lib/sqlalchemy/orm/decl_base.py +++ b/lib/sqlalchemy/orm/decl_base.py @@ -242,7 +242,6 @@ def _dive_for_cls_manager(cls: Type[_O]) -> Optional[ClassManager[_O]]: def _as_declarative( registry: _RegistryType, cls: Type[Any], dict_: _ClassDict ) -> Optional[_MapperConfig]: - # declarative scans the class for attributes. no table or mapper # args passed separately. return _MapperConfig.setup_mapping(registry, cls, dict_, None, {}) @@ -359,7 +358,6 @@ class _MapperConfig: ) def set_cls_attribute(self, attrname: str, value: _T) -> _T: - manager = instrumentation.manager_of_class(self.cls) manager.install_member(attrname, value) return value @@ -514,7 +512,6 @@ class _ClassScanMapperConfig(_MapperConfig): table: Optional[FromClause], mapper_kw: _MapperKwArgs, ): - # grab class dict before the instrumentation manager has been added. # reduces cycles self.clsdict_view = ( @@ -622,7 +619,6 @@ class _ClassScanMapperConfig(_MapperConfig): return getattr(cls, key, obj) is not obj else: - all_datacls_fields = { f.name: f.metadata[sa_dataclass_metadata_key] for f in util.dataclass_fields(cls) @@ -719,9 +715,9 @@ class _ClassScanMapperConfig(_MapperConfig): if not sa_dataclass_metadata_key: - def local_attributes_for_class() -> Iterable[ - Tuple[str, Any, Any, bool] - ]: + def local_attributes_for_class() -> ( + Iterable[Tuple[str, Any, Any, bool]] + ): return ( ( name, @@ -739,9 +735,9 @@ class _ClassScanMapperConfig(_MapperConfig): fixed_sa_dataclass_metadata_key = sa_dataclass_metadata_key - def local_attributes_for_class() -> Iterable[ - Tuple[str, Any, Any, bool] - ]: + def local_attributes_for_class() -> ( + Iterable[Tuple[str, Any, Any, bool]] + ): for name in names: field = dataclass_fields.get(name, None) if field and sa_dataclass_metadata_key in field.metadata: @@ -810,7 +806,6 @@ class _ClassScanMapperConfig(_MapperConfig): local_attributes_for_class, locally_collected_columns, ) in bases: - # this transfer can also take place as we scan each name # for finer-grained control of how collected_attributes is # populated, as this is what impacts column ordering. @@ -1041,7 +1036,6 @@ class _ClassScanMapperConfig(_MapperConfig): self.mapper_args_fn = mapper_args_fn def _setup_dataclasses_transforms(self) -> None: - dataclass_setup_arguments = self.dataclass_setup_arguments if not dataclass_setup_arguments: return @@ -1160,7 +1154,6 @@ class _ClassScanMapperConfig(_MapperConfig): new_anno = {} for name, annotation in cls_annotations.items(): if _is_mapped_annotation(annotation, klass, klass): - extracted = _extract_mapped_subtype( annotation, klass, @@ -1258,7 +1251,6 @@ class _ClassScanMapperConfig(_MapperConfig): expect_mapped: Optional[bool], attr_value: Any, ) -> Optional[_CollectedAnnotation]: - if name in self.collected_annotations: return self.collected_annotations[name] @@ -1356,7 +1348,6 @@ class _ClassScanMapperConfig(_MapperConfig): # copy mixin columns to the mapped class for name, obj, annotation, is_dataclass in attributes_for_class(): - if ( not fixed_table and obj is None @@ -1387,7 +1378,6 @@ class _ClassScanMapperConfig(_MapperConfig): setattr(cls, name, obj) elif isinstance(obj, (Column, MappedColumn)): - if attribute_is_overridden(name, obj): # if column has been overridden # (like by the InstrumentedAttribute of the @@ -1452,7 +1442,6 @@ class _ClassScanMapperConfig(_MapperConfig): look_for_dataclass_things = bool(self.dataclass_setup_arguments) for k in list(collected_attributes): - if k in _include_dunders: continue @@ -1570,7 +1559,6 @@ class _ClassScanMapperConfig(_MapperConfig): assert expect_annotations_wo_mapped if isinstance(value, _DCAttributeOptions): - if ( value._has_dataclass_arguments and not look_for_dataclass_things @@ -1633,7 +1621,6 @@ class _ClassScanMapperConfig(_MapperConfig): for key, c in list(our_stuff.items()): if isinstance(c, _MapsColumns): - mp_to_assign = c.mapper_property_to_assign if mp_to_assign: our_stuff[key] = mp_to_assign @@ -1705,7 +1692,6 @@ class _ClassScanMapperConfig(_MapperConfig): table_cls = Table if tablename is not None: - args: Tuple[Any, ...] = () table_kw: Dict[str, Any] = {} @@ -1804,7 +1790,6 @@ class _ClassScanMapperConfig(_MapperConfig): and self.inherits is None and not _get_immediate_cls_attr(cls, "__no_table__") ): - raise exc.InvalidRequestError( "Class %r does not have a __table__ or __tablename__ " "specified and does not inherit from an existing " @@ -1819,7 +1804,6 @@ class _ClassScanMapperConfig(_MapperConfig): ) if table is None: - # single table inheritance. # ensure no table args if table_args: diff --git a/lib/sqlalchemy/orm/dependency.py b/lib/sqlalchemy/orm/dependency.py index dd31a77b50..9f57f31ca6 100644 --- a/lib/sqlalchemy/orm/dependency.py +++ b/lib/sqlalchemy/orm/dependency.py @@ -377,9 +377,7 @@ class OneToManyDP(DependencyProcessor): isdelete, childisdelete, ): - if self.post_update: - child_post_updates = unitofwork.PostUpdateAll( uow, self.mapper.primary_base_mapper, False ) @@ -645,7 +643,6 @@ class ManyToOneDP(DependencyProcessor): after_save, before_delete, ): - if self.post_update: parent_post_updates = unitofwork.PostUpdateAll( uow, self.parent.primary_base_mapper, False @@ -686,9 +683,7 @@ class ManyToOneDP(DependencyProcessor): isdelete, childisdelete, ): - if self.post_update: - if not isdelete: parent_post_updates = unitofwork.PostUpdateAll( uow, self.parent.primary_base_mapper, False @@ -784,7 +779,6 @@ class ManyToOneDP(DependencyProcessor): and not self.cascade.delete_orphan and not self.passive_deletes == "all" ): - # post_update means we have to update our # row to not reference the child object # before we can DELETE the row @@ -986,7 +980,6 @@ class ManyToManyDP(DependencyProcessor): after_save, before_delete, ): - uow.dependencies.update( [ (parent_saves, after_save), @@ -1160,7 +1153,6 @@ class ManyToManyDP(DependencyProcessor): tmp.update((c, state) for c in history.added + history.deleted) if need_cascade_pks: - for child in history.unchanged: associationrow = {} sync.update( @@ -1251,7 +1243,6 @@ class ManyToManyDP(DependencyProcessor): def _synchronize( self, state, child, associationrow, clearkeys, uowcommit, operation ): - # this checks for None if uselist=True self._verify_canload(child) diff --git a/lib/sqlalchemy/orm/descriptor_props.py b/lib/sqlalchemy/orm/descriptor_props.py index 2e57fd0f4e..e7c9de2a62 100644 --- a/lib/sqlalchemy/orm/descriptor_props.py +++ b/lib/sqlalchemy/orm/descriptor_props.py @@ -639,7 +639,6 @@ class CompositeProperty( def _populate_composite_bulk_save_mappings_fn( self, ) -> Callable[[Dict[str, Any]], None]: - if self._generated_composite_accessor: get_values = self._generated_composite_accessor else: @@ -886,7 +885,6 @@ class ConcreteInheritedProperty(DescriptorProperty[_T]): def _comparator_factory( self, mapper: Mapper[Any] ) -> Type[PropComparator[_T]]: - comparator_callable = None for m in self.parent.iterate_to_root(): diff --git a/lib/sqlalchemy/orm/events.py b/lib/sqlalchemy/orm/events.py index 9a1fd569a3..e7e3e32a7f 100644 --- a/lib/sqlalchemy/orm/events.py +++ b/lib/sqlalchemy/orm/events.py @@ -1601,7 +1601,6 @@ class SessionEvents(event.Events[Session]): cls, target: Any, identifier: str ) -> Union[Session, type]: if isinstance(target, scoped_session): - target = target.session_factory if not isinstance(target, sessionmaker) and ( not isinstance(target, type) or not issubclass(target, Session) @@ -1642,7 +1641,6 @@ class SessionEvents(event.Events[Session]): if is_instance_event: if not raw or restore_load_context: - fn = event_key._listen_fn def wrap( @@ -2537,7 +2535,6 @@ class AttributeEvents(event.Events[QueryableAttribute[Any]]): propagate: bool = False, include_key: bool = False, ) -> None: - target, fn = event_key.dispatch_target, event_key._listen_fn if active_history: diff --git a/lib/sqlalchemy/orm/instrumentation.py b/lib/sqlalchemy/orm/instrumentation.py index 4c911f3748..1b755a27ab 100644 --- a/lib/sqlalchemy/orm/instrumentation.py +++ b/lib/sqlalchemy/orm/instrumentation.py @@ -203,7 +203,6 @@ class ClassManager( ] = None, init_method: Optional[Callable[..., None]] = None, ) -> None: - if mapper: self.mapper = mapper # type: ignore[assignment] if registry: diff --git a/lib/sqlalchemy/orm/interfaces.py b/lib/sqlalchemy/orm/interfaces.py index 4da8f63e68..9d4a6a6a57 100644 --- a/lib/sqlalchemy/orm/interfaces.py +++ b/lib/sqlalchemy/orm/interfaces.py @@ -969,7 +969,6 @@ class StrategizedProperty(MapperProperty[_T]): def _get_context_loader( self, context: ORMCompileState, path: AbstractEntityRegistry ) -> Optional[_LoadElement]: - load: Optional[_LoadElement] = None search_path = path[self] diff --git a/lib/sqlalchemy/orm/loading.py b/lib/sqlalchemy/orm/loading.py index 3d9ff7b0ab..aca6fcc088 100644 --- a/lib/sqlalchemy/orm/loading.py +++ b/lib/sqlalchemy/orm/loading.py @@ -430,7 +430,6 @@ def get_from_identity( """ instance = session.identity_map.get(key) if instance is not None: - state = attributes.instance_state(instance) if mapper.inherits and not state.mapper.isa(mapper): @@ -512,7 +511,6 @@ def load_on_pk_identity( require_pk_cols: bool = False, is_user_refresh: bool = False, ): - """Load the given primary key identity from the database.""" query = statement @@ -691,7 +689,6 @@ def _set_get_options( identity_token=None, is_user_refresh=None, ): - compile_options = {} load_options = {} if version_check: @@ -728,7 +725,6 @@ def _setup_entity_query( polymorphic_discriminator=None, **kw, ): - if with_polymorphic: poly_properties = mapper._iterate_polymorphic_properties( with_polymorphic @@ -766,7 +762,6 @@ def _setup_entity_query( polymorphic_discriminator is not None and polymorphic_discriminator is not mapper.polymorphic_on ): - if adapter: pd = adapter.columns[polymorphic_discriminator] else: @@ -1026,7 +1021,6 @@ def _instance_processor( is_not_primary_key = _none_set.intersection def _instance(row): - # determine the state that we'll be populating if refresh_identity_key: # fixed state that we're refreshing @@ -1335,7 +1329,6 @@ def _populate_full( def _populate_partial( context, row, state, dict_, isnew, load_path, unloaded, populators ): - if not isnew: if unloaded: # extra pass, see #8166 @@ -1371,7 +1364,6 @@ def _populate_partial( def _validate_version_id(mapper, state, dict_, row, getter): - if mapper._get_state_attr_by_column( state, dict_, mapper.version_id_col ) != getter(row): @@ -1577,7 +1569,6 @@ def load_scalar_attributes(mapper, state, attribute_names, passive): # currently use state.key statement = mapper._optimized_get_statement(state, attribute_names) if statement is not None: - # undefer() isn't needed here because statement has the # columns needed already, this implicitly undefers that column stmt = FromStatement(mapper, statement) diff --git a/lib/sqlalchemy/orm/mapped_collection.py b/lib/sqlalchemy/orm/mapped_collection.py index 056f14f405..fb6b05d78e 100644 --- a/lib/sqlalchemy/orm/mapped_collection.py +++ b/lib/sqlalchemy/orm/mapped_collection.py @@ -31,7 +31,6 @@ from ..sql import roles from ..util.typing import Literal if TYPE_CHECKING: - from . import AttributeEventToken from . import Mapper from ..sql.elements import ColumnElement @@ -134,7 +133,7 @@ class _SerializableColumnGetterV2(_PlainColumnGetter[_KT]): def _cols(self, mapper: Mapper[_KT]) -> Sequence[ColumnElement[_KT]]: cols: List[ColumnElement[_KT]] = [] metadata = getattr(mapper.local_table, "metadata", None) - for (ckey, tkey) in self.colkeys: + for ckey, tkey in self.colkeys: if tkey is None or metadata is None or tkey not in metadata: cols.append(mapper.local_table.c[ckey]) # type: ignore else: diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py index 88cbe8f4ef..7bc5de449d 100644 --- a/lib/sqlalchemy/orm/mapper.py +++ b/lib/sqlalchemy/orm/mapper.py @@ -840,7 +840,6 @@ class Mapper( # while a configure_mappers() is occurring (and defer a # configure_mappers() until construction succeeds) with _CONFIGURE_MUTEX: - cast("MapperEvents", self.dispatch._events)._new_mapper_instance( class_, self ) @@ -1603,7 +1602,6 @@ class Mapper( ) if self._primary_key_argument: - coerced_pk_arg = [ self._str_arg_to_mapped_col("primary_key", c) if isinstance(c, str) @@ -1701,7 +1699,6 @@ class Mapper( } def _configure_properties(self) -> None: - self.columns = self.c = sql_base.ColumnCollection() # type: ignore # object attribute names mapped to MapperProperty objects @@ -1761,7 +1758,6 @@ class Mapper( incoming_prop = explicit_col_props_by_key.get(key) if incoming_prop: - new_prop = self._reconcile_prop_with_incoming_columns( key, inherited_prop, @@ -2240,7 +2236,6 @@ class Mapper( Sequence[KeyedColumnElement[Any]], KeyedColumnElement[Any] ], ) -> ColumnProperty[Any]: - columns = util.to_list(column) mapped_column = [] for c in columns: @@ -2273,7 +2268,6 @@ class Mapper( incoming_prop: Optional[ColumnProperty[Any]] = None, single_column: Optional[KeyedColumnElement[Any]] = None, ) -> ColumnProperty[Any]: - if incoming_prop and ( self.concrete or not isinstance(existing_prop, properties.ColumnProperty) @@ -2467,7 +2461,7 @@ class Mapper( def _is_orphan(self, state: InstanceState[_O]) -> bool: orphan_possible = False for mapper in self.iterate_to_root(): - for (key, cls) in mapper._delete_orphans: + for key, cls in mapper._delete_orphans: orphan_possible = True has_parent = attributes.manager_of_class(cls).has_parent( @@ -2836,7 +2830,6 @@ class Mapper( @HasMemoized.memoized_instancemethod def __clause_element__(self): - annotations: Dict[str, Any] = { "entity_namespace": self, "parententity": self, @@ -3588,7 +3581,6 @@ class Mapper( def _get_committed_state_attr_by_column( self, state, dict_, column, passive=PassiveFlag.PASSIVE_RETURN_NO_VALUE ): - prop = self._columntoproperty[column] return state.manager[prop.key].impl.get_committed_value( state, dict_, passive=passive @@ -3820,7 +3812,6 @@ class Mapper( m = m.inherits for prop in self.attrs: - # skip prop keys that are not instrumented on the mapped class. # this is primarily the "_sa_polymorphic_on" property that gets # created for an ad-hoc polymorphic_on SQL expression, issue #8704 @@ -3879,7 +3870,6 @@ class Mapper( in_expr.in_(sql.bindparam("primary_keys", expanding=True)) ).order_by(*primary_key) else: - q = sql.select(self).set_label_style( LABEL_STYLE_TABLENAME_PLUS_COL ) @@ -4180,7 +4170,6 @@ def _configure_registries( return _already_compiling = True try: - # double-check inside mutex for reg in registries: if reg._new_mappers: @@ -4204,7 +4193,6 @@ def _configure_registries( def _do_configure_registries( registries: Set[_RegistryType], cascade: bool ) -> None: - registry = util.preloaded.orm_decl_api.registry orig = set(registries) @@ -4256,7 +4244,6 @@ def _do_configure_registries( @util.preload_module("sqlalchemy.orm.decl_api") def _dispose_registries(registries: Set[_RegistryType], cascade: bool) -> None: - registry = util.preloaded.orm_decl_api.registry orig = set(registries) diff --git a/lib/sqlalchemy/orm/persistence.py b/lib/sqlalchemy/orm/persistence.py index 6fa338ced6..87d7ee7312 100644 --- a/lib/sqlalchemy/orm/persistence.py +++ b/lib/sqlalchemy/orm/persistence.py @@ -221,7 +221,6 @@ def _organize_states_for_save(base_mapper, states, uowtransaction): for state, dict_, mapper, connection in _connections_for_states( base_mapper, uowtransaction, states ): - has_identity = bool(state.key) instance_key = state.key or mapper._identity_key_from_state(state) @@ -310,7 +309,6 @@ def _organize_states_for_delete(base_mapper, states, uowtransaction): for state, dict_, mapper, connection in _connections_for_states( base_mapper, uowtransaction, states ): - mapper.dispatch.before_delete(mapper, connection, state) if mapper.version_id_col is not None: @@ -451,7 +449,6 @@ def _collect_update_commands( connection, update_version_id, ) in states_to_update: - if table not in mapper._pks_by_table: continue @@ -512,7 +509,6 @@ def _collect_update_commands( update_version_id is not None and mapper.version_id_col in mapper._cols_by_table[table] ): - if not bulk and not (params or value_params): # HACK: check for history in other tables, in case the # history is only in a different table than the one @@ -637,7 +633,6 @@ def _collect_post_update_commands( connection, update_version_id, ) in states_to_update: - # assert table in mapper._pks_by_table pks = mapper._pks_by_table[table] @@ -664,7 +659,6 @@ def _collect_post_update_commands( update_version_id is not None and mapper.version_id_col in mapper._cols_by_table[table] ): - col = mapper.version_id_col params[col._label] = update_version_id @@ -691,7 +685,6 @@ def _collect_delete_commands( connection, update_version_id, ) in states_to_delete: - if table not in mapper._pks_by_table: continue @@ -1002,7 +995,6 @@ def _emit_insert_statements( rec[7], ), ): - statement = cached_stmt if use_orm_insert_stmt is not None: @@ -1029,7 +1021,6 @@ def _emit_insert_statements( and has_all_pks and not hasvalue ): - # the "we don't need newly generated values back" section. # here we have all the PKs, all the defaults or we don't want # to fetch them, or the dialect doesn't support RETURNING at all @@ -1333,7 +1324,6 @@ def _emit_post_update_statements( if not allow_executemany: check_rowcount = assert_singlerow for state, state_dict, mapper_rec, connection, params in records: - c = connection.execute( statement, params, execution_options=execution_options ) @@ -1437,7 +1427,6 @@ def _emit_delete_statements( # execute deletes individually so that versioned # rows can be verified for params in del_objects: - c = connection.execute( statement, params, execution_options=execution_options ) @@ -1496,7 +1485,6 @@ def _finalize_insert_update_commands(base_mapper, uowtransaction, states): """ for state, state_dict, mapper, connection, has_identity in states: - if mapper._readonly_props: readonly = state.unmodified_intersection( [ diff --git a/lib/sqlalchemy/orm/properties.py b/lib/sqlalchemy/orm/properties.py index dd53a95362..e215e061d5 100644 --- a/lib/sqlalchemy/orm/properties.py +++ b/lib/sqlalchemy/orm/properties.py @@ -788,7 +788,6 @@ class MappedColumn( checks = [our_type] for check_type in checks: - new_sqltype = registry._resolve_type(check_type) if new_sqltype is not None: break diff --git a/lib/sqlalchemy/orm/relationships.py b/lib/sqlalchemy/orm/relationships.py index e5a6b9afaa..610be37e92 100644 --- a/lib/sqlalchemy/orm/relationships.py +++ b/lib/sqlalchemy/orm/relationships.py @@ -762,7 +762,6 @@ class RelationshipProperty( criterion: Optional[_ColumnExpressionArgument[bool]] = None, **kwargs: Any, ) -> Exists: - where_criteria = ( coercions.expect(roles.WhereHavingRole, criterion) if criterion is not None @@ -1371,7 +1370,6 @@ class RelationshipProperty( _recursive: Dict[Any, object], _resolve_conflict_map: Dict[_IdentityKeyType[Any], object], ) -> None: - if load: for r in self._reverse_property: if (source_state, r) in _recursive: @@ -1669,7 +1667,6 @@ class RelationshipProperty( "foreign_keys", "remote_side", ): - rel_arg = getattr(init_args, attr) rel_arg._resolve_against_registry(self._clsregistry_resolvers[1]) @@ -1740,7 +1737,6 @@ class RelationshipProperty( argument = extracted_mapped_annotation if extracted_mapped_annotation is None: - if self.argument is None: self._raise_for_required(key, cls) else: @@ -2168,7 +2164,6 @@ class RelationshipProperty( Optional[FromClause], Optional[ClauseAdapter], ]: - aliased = False if alias_secondary and self.secondary is not None: @@ -2251,7 +2246,6 @@ def _annotate_columns(element: _CE, annotations: _AnnotationDict) -> _CE: class JoinCondition: - primaryjoin_initial: Optional[ColumnElement[bool]] primaryjoin: ColumnElement[bool] secondaryjoin: Optional[ColumnElement[bool]] @@ -2289,7 +2283,6 @@ class JoinCondition: support_sync: bool = True, can_be_synced_fn: Callable[..., bool] = lambda *c: True, ): - self.parent_persist_selectable = parent_persist_selectable self.parent_local_selectable = parent_local_selectable self.child_persist_selectable = child_persist_selectable @@ -2878,7 +2871,6 @@ class JoinCondition: "the relationship." % (self.prop,) ) else: - not_target = util.column_set( self.parent_persist_selectable.c ).difference(self.child_persist_selectable.c) @@ -3166,7 +3158,6 @@ class JoinCondition: or not self.prop.parent.common_parent(pr.parent) ) ): - other_props.append((pr, fr_)) if other_props: @@ -3399,7 +3390,6 @@ class JoinCondition: def col_to_bind( element: ColumnElement[Any], **kw: Any ) -> Optional[BindParameter[Any]]: - if ( (not reverse_direction and "local" in element._annotations) or reverse_direction diff --git a/lib/sqlalchemy/orm/scoping.py b/lib/sqlalchemy/orm/scoping.py index 83ce6e44e6..4230a890c1 100644 --- a/lib/sqlalchemy/orm/scoping.py +++ b/lib/sqlalchemy/orm/scoping.py @@ -167,7 +167,6 @@ class scoped_session(Generic[_S]): session_factory: sessionmaker[_S], scopefunc: Optional[Callable[[], Any]] = None, ): - """Construct a new :class:`.scoped_session`. :param session_factory: a factory to create new :class:`.Session` diff --git a/lib/sqlalchemy/orm/session.py b/lib/sqlalchemy/orm/session.py index 0ce53bcab6..c41fff1df7 100644 --- a/lib/sqlalchemy/orm/session.py +++ b/lib/sqlalchemy/orm/session.py @@ -980,7 +980,6 @@ class SessionTransaction(_StateChange, TransactionalContext): def _iterate_self_and_parents( self, upto: Optional[SessionTransaction] = None ) -> Iterable[SessionTransaction]: - current = self result: Tuple[SessionTransaction, ...] = () while current: @@ -1083,7 +1082,6 @@ class SessionTransaction(_StateChange, TransactionalContext): bind: _SessionBind, execution_options: Optional[_ExecuteOptions], ) -> Connection: - if bind in self._connections: if execution_options: util.warn( @@ -1179,7 +1177,6 @@ class SessionTransaction(_StateChange, TransactionalContext): (SessionTransactionState.ACTIVE,), SessionTransactionState.PREPARED ) def _prepare_impl(self) -> None: - if self._parent is None or self.nested: self.session.dispatch.before_commit(self.session) @@ -1249,7 +1246,6 @@ class SessionTransaction(_StateChange, TransactionalContext): def rollback( self, _capture_exception: bool = False, _to_root: bool = False ) -> None: - stx = self.session._transaction assert stx is not None if stx is not self: @@ -1285,7 +1281,6 @@ class SessionTransaction(_StateChange, TransactionalContext): sess = self.session if not rollback_err and not sess._is_clean(): - # if items were added, deleted, or mutated # here, we need to re-restore the snapshot util.warn( @@ -1313,7 +1308,6 @@ class SessionTransaction(_StateChange, TransactionalContext): _StateChangeStates.ANY, SessionTransactionState.CLOSED ) def close(self, invalidate: bool = False) -> None: - if self.nested: self.session._nested_transaction = ( self._previous_nested_transaction @@ -1749,7 +1743,6 @@ class Session(_SessionClassMethods, EventTarget): def _autobegin_t(self, begin: bool = False) -> SessionTransaction: if self._transaction is None: - if not begin and not self.autobegin: raise sa_exc.InvalidRequestError( "Autobegin is disabled on this Session; please call " @@ -3191,7 +3184,6 @@ class Session(_SessionClassMethods, EventTarget): # prevent against last minute dereferences of the object obj = state.obj() if obj is not None: - instance_key = mapper._identity_key_from_state(state) if ( @@ -3389,7 +3381,6 @@ class Session(_SessionClassMethods, EventTarget): def _delete_impl( self, state: InstanceState[Any], obj: object, head: bool ) -> None: - if state.key is None: if head: raise sa_exc.InvalidRequestError( @@ -3565,7 +3556,6 @@ class Session(_SessionClassMethods, EventTarget): execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT, bind_arguments: Optional[_BindArguments] = None, ) -> Optional[_O]: - # convert composite types to individual args if ( is_composite_class(primary_key_identity) @@ -3598,7 +3588,6 @@ class Session(_SessionClassMethods, EventTarget): ) if is_dict: - pk_synonyms = mapper._pk_synonyms if pk_synonyms: @@ -3635,7 +3624,6 @@ class Session(_SessionClassMethods, EventTarget): and not mapper.always_refresh and with_for_update is None ): - instance = self._identity_lookup( mapper, primary_key_identity, @@ -4171,7 +4159,6 @@ class Session(_SessionClassMethods, EventTarget): ) def _flush(self, objects: Optional[Sequence[object]] = None) -> None: - dirty = self._dirty_states if not dirty and not self._deleted and not self._new: self.identity_map._modified.clear() diff --git a/lib/sqlalchemy/orm/state_changes.py b/lib/sqlalchemy/orm/state_changes.py index 6734efdb8d..61a94d3f9d 100644 --- a/lib/sqlalchemy/orm/state_changes.py +++ b/lib/sqlalchemy/orm/state_changes.py @@ -93,7 +93,6 @@ class _StateChange: @util.decorator def _go(fn: _F, self: Any, *arg: Any, **kw: Any) -> Any: - current_state = self._state if ( diff --git a/lib/sqlalchemy/orm/strategies.py b/lib/sqlalchemy/orm/strategies.py index 96b1d053e0..2ce313a43b 100644 --- a/lib/sqlalchemy/orm/strategies.py +++ b/lib/sqlalchemy/orm/strategies.py @@ -75,7 +75,6 @@ def _register_attribute( impl_class=None, **kw, ): - listen_hooks = [] uselist = useobject and prop.uselist @@ -120,7 +119,6 @@ def _register_attribute( if prop is m._props.get( prop.key ) and not m.class_manager._attr_has_impl(prop.key): - desc = attributes.register_attribute_impl( m.class_, prop.key, @@ -402,7 +400,6 @@ class DeferredColumnLoader(LoaderStrategy): adapter, populators, ): - # for a DeferredColumnLoader, this method is only used during a # "row processor only" query; see test_deferred.py -> # tests with "rowproc_only" in their name. As of the 1.0 series, @@ -467,7 +464,6 @@ class DeferredColumnLoader(LoaderStrategy): only_load_props=None, **kw, ): - if ( ( compile_state.compile_options._render_for_subquery @@ -799,7 +795,6 @@ class LazyLoader( ) def _memoized_attr__simple_lazy_clause(self): - lazywhere = sql_util._deep_annotate( self._lazywhere, {"_orm_adapt": True} ) @@ -912,7 +907,6 @@ class LazyLoader( or passive & PassiveFlag.RELATED_OBJECT_OK ) ): - self._invoke_raise_load(state, passive, "raise") session = _state_session(state) @@ -1103,7 +1097,6 @@ class LazyLoader( lazy_clause, params = self._generate_lazy_clause(state, passive) if execution_options: - execution_options = util.EMPTY_DICT.merge_with( execution_options, { @@ -1173,7 +1166,6 @@ class LazyLoader( and context.query._compile_options._only_load_props and self.key in context.query._compile_options._only_load_props ): - return self._immediateload_create_row_processor( context, query_entity, @@ -1284,7 +1276,6 @@ class PostLoader(AbstractRelationshipLoader): __slots__ = () def _setup_for_recursion(self, context, path, loadopt, join_depth=None): - effective_path = ( context.compile_state.current_path or orm_util.PathRegistry.root ) + path @@ -1375,7 +1366,6 @@ class ImmediateLoader(PostLoader): adapter, populators, ): - ( effective_path, run_loader, @@ -1414,7 +1404,6 @@ class ImmediateLoader(PostLoader): recursion_depth, execution_options, ): - if recursion_depth: new_opt = Load(loadopt.path.entity) new_opt.context = ( @@ -1660,7 +1649,6 @@ class SubqueryLoader(PostLoader): def _apply_joins( self, q, to_join, left_alias, parent_alias, effective_entity ): - ltj = len(to_join) if ltj == 1: to_join = [ @@ -1720,7 +1708,6 @@ class SubqueryLoader(PostLoader): effective_entity, loadopt, ): - # note that because the subqueryload object # does not re-use the cached query, instead always making # use of the current invoked query, while we have two queries @@ -1731,7 +1718,6 @@ class SubqueryLoader(PostLoader): new_options = orig_query._with_options if loadopt and loadopt._extra_criteria: - new_options += ( orm_util.LoaderCriteriaOption( self.entity, @@ -1958,7 +1944,6 @@ class SubqueryLoader(PostLoader): adapter, populators, ): - if context.refresh_state: return self._immediateload_create_row_processor( context, @@ -2140,7 +2125,6 @@ class JoinedLoader(AbstractRelationshipLoader): ) if user_defined_adapter is not False: - # setup an adapter but dont create any JOIN, assume it's already # in the query ( @@ -2231,7 +2215,6 @@ class JoinedLoader(AbstractRelationshipLoader): def _init_user_defined_eager_proc( self, loadopt, compile_state, target_attributes ): - # check if the opt applies at all if "eager_from_alias" not in loadopt.local_opts: # nope @@ -2289,7 +2272,6 @@ class JoinedLoader(AbstractRelationshipLoader): def _setup_query_on_user_defined_adapter( self, context, entity, path, adapter, user_defined_adapter ): - # apply some more wrapping to the "user defined adapter" # if we are setting up the query for SQL render. adapter = entity._get_entity_clauses(context) @@ -2421,7 +2403,6 @@ class JoinedLoader(AbstractRelationshipLoader): and not should_nest_selectable and compile_state.from_clauses ): - indexes = sql_util.find_left_clause_that_matches_given( compile_state.from_clauses, query_entity.selectable ) @@ -2552,7 +2533,6 @@ class JoinedLoader(AbstractRelationshipLoader): def _splice_nested_inner_join( self, path, join_obj, clauses, onclause, extra_criteria, splicing=False ): - # recursive fn to splice a nested join into an existing one. # splicing=False means this is the outermost call, and it # should return a value. splicing= is the recursive @@ -2941,7 +2921,6 @@ class SelectInLoader(PostLoader, util.MemoizedSlots): adapter, populators, ): - if context.refresh_state: return self._immediateload_create_row_processor( context, @@ -3300,7 +3279,6 @@ class SelectInLoader(PostLoader, util.MemoizedSlots): data[k].extend(vv[1] for vv in v) for key, state, state_dict, overwrite in chunk: - if not overwrite and self.key in state_dict: continue diff --git a/lib/sqlalchemy/orm/strategy_options.py b/lib/sqlalchemy/orm/strategy_options.py index 2e073f326c..90b8dda8b0 100644 --- a/lib/sqlalchemy/orm/strategy_options.py +++ b/lib/sqlalchemy/orm/strategy_options.py @@ -1089,7 +1089,6 @@ class Load(_AbstractLoad): mapper_entities: Sequence[_MapperEntity], raiseerr: bool, ) -> None: - reconciled_lead_entity = self._reconcile_query_entities_with_us( mapper_entities, raiseerr ) @@ -1947,7 +1946,6 @@ class _AttributeStrategyLoad(_LoadElement): ) start_path = self._path_with_polymorphic_path if current_path: - new_path = self._adjust_effective_path_for_current_path( start_path, current_path ) diff --git a/lib/sqlalchemy/orm/sync.py b/lib/sqlalchemy/orm/sync.py index b48a16b066..036c26dd6b 100644 --- a/lib/sqlalchemy/orm/sync.py +++ b/lib/sqlalchemy/orm/sync.py @@ -85,7 +85,6 @@ def clear(dest, dest_mapper, synchronize_pairs): and dest_mapper._get_state_attr_by_column(dest, dest.dict, r) not in orm_util._none_set ): - raise AssertionError( "Dependency rule tried to blank-out primary key " "column '%s' on instance '%s'" % (r, orm_util.state_str(dest)) diff --git a/lib/sqlalchemy/orm/unitofwork.py b/lib/sqlalchemy/orm/unitofwork.py index 924bd79dab..20fe022076 100644 --- a/lib/sqlalchemy/orm/unitofwork.py +++ b/lib/sqlalchemy/orm/unitofwork.py @@ -112,7 +112,6 @@ def track_cascade_events(descriptor, prop): sess = state.session if sess: - if sess._warn_on_events: sess._flush_warning("related attribute set") @@ -489,7 +488,6 @@ class UOWTransaction: class IterateMappersMixin: - __slots__ = () def _mappers(self, uow): diff --git a/lib/sqlalchemy/orm/util.py b/lib/sqlalchemy/orm/util.py index d3e36a4945..65101b8d24 100644 --- a/lib/sqlalchemy/orm/util.py +++ b/lib/sqlalchemy/orm/util.py @@ -957,7 +957,6 @@ class AliasedInsp( represents_outer_join: bool, nest_adapters: bool, ): - mapped_class_or_ac = inspected.entity mapper = inspected.mapper @@ -1029,7 +1028,6 @@ class AliasedInsp( flat: bool = False, adapt_on_names: bool = False, ) -> Union[AliasedClass[_O], FromClause]: - if isinstance(element, FromClause): if adapt_on_names: raise sa_exc.ArgumentError( @@ -1063,7 +1061,6 @@ class AliasedInsp( adapt_on_names: bool = False, _use_mapper_path: bool = False, ) -> AliasedClass[_O]: - primary_mapper = _class_to_mapper(base) if selectable not in (None, False) and flat: @@ -1440,7 +1437,6 @@ class LoaderCriteriaOption(CriteriaOption): ) def _all_mappers(self) -> Iterator[Mapper[Any]]: - if self.entity: yield from self.entity.mapper.self_and_descendants else: @@ -1516,14 +1512,12 @@ inspection._inspects(AliasedClass)(lambda target: target._aliased_insp) def _inspect_mc( class_: Type[_O], ) -> Optional[Mapper[_O]]: - try: class_manager = opt_manager_of_class(class_) if class_manager is None or not class_manager.is_mapped: return None mapper = class_manager.mapper except exc.NO_STATE: - return None else: return mapper @@ -1536,7 +1530,6 @@ GenericAlias = type(List[Any]) def _inspect_generic_alias( class_: Type[_O], ) -> Optional[Mapper[_O]]: - origin = cast("Type[_O]", typing_get_origin(class_)) return _inspect_mc(origin) @@ -2316,7 +2309,6 @@ def _extract_mapped_subtype( """ if raw_annotation is None: - if required: raise sa_exc.ArgumentError( f"Python typing annotation is required for attribute " @@ -2354,7 +2346,6 @@ def _extract_mapped_subtype( if not hasattr(annotated, "__origin__") or not is_origin_of_cls( annotated, _MappedAnnotationBase ): - if expect_mapped: if getattr(annotated, "__origin__", None) is typing.ClassVar: return None diff --git a/lib/sqlalchemy/orm/writeonly.py b/lib/sqlalchemy/orm/writeonly.py index a362750f60..9f0dbeead2 100644 --- a/lib/sqlalchemy/orm/writeonly.py +++ b/lib/sqlalchemy/orm/writeonly.py @@ -248,7 +248,6 @@ class WriteOnlyAttributeImpl( fn(state, value, initiator or self._remove_token) def _modified_event(self, state, dict_): - if self.key not in state.committed_state: state.committed_state[self.key] = self.collection_history_cls( self, state, PassiveFlag.PASSIVE_NO_FETCH @@ -445,7 +444,6 @@ class AbstractCollectionWriter(Generic[_T]): __slots__ = () def __init__(self, attr, state): - self.instance = instance = state.obj() self.attr = attr diff --git a/lib/sqlalchemy/pool/base.py b/lib/sqlalchemy/pool/base.py index 7600c196b0..7f542ae013 100644 --- a/lib/sqlalchemy/pool/base.py +++ b/lib/sqlalchemy/pool/base.py @@ -1263,7 +1263,6 @@ class _ConnectionFairy(PoolProxiedConnection): threadconns: Optional[threading.local] = None, fairy: Optional[_ConnectionFairy] = None, ) -> _ConnectionFairy: - if not fairy: fairy = _ConnectionRecord.checkout(pool) @@ -1472,7 +1471,6 @@ class _ConnectionFairy(PoolProxiedConnection): def invalidate( self, e: Optional[BaseException] = None, soft: bool = False ) -> None: - if self.dbapi_connection is None: util.warn("Can't invalidate an already-closed connection.") return diff --git a/lib/sqlalchemy/sql/_py_util.py b/lib/sqlalchemy/sql/_py_util.py index 41aed8cd6e..edff0d6691 100644 --- a/lib/sqlalchemy/sql/_py_util.py +++ b/lib/sqlalchemy/sql/_py_util.py @@ -57,7 +57,6 @@ class cache_anon_map( _index = 0 def get_anon(self, object_: Any) -> Tuple[str, bool]: - idself = id(object_) if idself in self: s_val = self[idself] diff --git a/lib/sqlalchemy/sql/_typing.py b/lib/sqlalchemy/sql/_typing.py index 513ce78d4f..b4f6fc71cf 100644 --- a/lib/sqlalchemy/sql/_typing.py +++ b/lib/sqlalchemy/sql/_typing.py @@ -331,7 +331,6 @@ if TYPE_CHECKING: ... else: - is_sql_compiler = operator.attrgetter("is_sql") is_ddl_compiler = operator.attrgetter("is_ddl") is_named_from_clause = operator.attrgetter("named_with_column") diff --git a/lib/sqlalchemy/sql/annotation.py b/lib/sqlalchemy/sql/annotation.py index e6dee7d17e..016608a381 100644 --- a/lib/sqlalchemy/sql/annotation.py +++ b/lib/sqlalchemy/sql/annotation.py @@ -426,7 +426,6 @@ def _deep_annotate( cloned_ids: Dict[int, SupportsAnnotations] = {} def clone(elem: SupportsAnnotations, **kw: Any) -> SupportsAnnotations: - # ind_cols_on_fromclause means make sure an AnnotatedFromClause # has its own .c collection independent of that which its proxying. # this is used specifically by orm.LoaderCriteriaOption to break diff --git a/lib/sqlalchemy/sql/base.py b/lib/sqlalchemy/sql/base.py index ee80b0514e..8ff11cc781 100644 --- a/lib/sqlalchemy/sql/base.py +++ b/lib/sqlalchemy/sql/base.py @@ -1036,7 +1036,6 @@ class Executable(roles.StatementRole): is_dml = False if TYPE_CHECKING: - __visit_name__: str def _compile_w_cache( @@ -1872,7 +1871,6 @@ class ColumnCollection(Generic[_COLKEY, _COL_co]): ) if len(current_intersection) > len(selected_intersection): - # 'current' has a larger field of correspondence than # 'selected'. i.e. selectable.c.a1_x->a1.c.x->table.c.x # matches a1.c.x->table.c.x better than @@ -1949,7 +1947,6 @@ class DedupeColumnCollection(ColumnCollection[str, _NAMEDCOL]): ) if key in self._index: - existing = self._index[key][1] if existing is named_column: diff --git a/lib/sqlalchemy/sql/cache_key.py b/lib/sqlalchemy/sql/cache_key.py index c039b1d007..e92167cef4 100644 --- a/lib/sqlalchemy/sql/cache_key.py +++ b/lib/sqlalchemy/sql/cache_key.py @@ -472,7 +472,6 @@ class CacheKey(NamedTuple): return ck1._diff(ck2) def _whats_different(self, other: CacheKey) -> Iterator[str]: - k1 = self.key k2 = other.key diff --git a/lib/sqlalchemy/sql/coercions.py b/lib/sqlalchemy/sql/coercions.py index 78954a082a..ead564ea30 100644 --- a/lib/sqlalchemy/sql/coercions.py +++ b/lib/sqlalchemy/sql/coercions.py @@ -373,7 +373,6 @@ def expect( if impl._resolve_literal_only: resolved = impl._literal_coercion(element, **kw) else: - original_element = element is_clause_element = False @@ -802,7 +801,6 @@ class ExpressionElementImpl(_ColumnCoercions, RoleImpl): class BinaryElementImpl(ExpressionElementImpl, RoleImpl): - __slots__ = () def _literal_coercion( @@ -961,7 +959,6 @@ class StrAsPlainColumnImpl(_CoerceLiterals, RoleImpl): class ByOfImpl(_CoerceLiterals, _ColumnCoercions, RoleImpl, roles.ByOfRole): - __slots__ = () _coerce_consts = True @@ -1053,7 +1050,6 @@ class TruncatedLabelImpl(_StringOnly, RoleImpl): class DDLExpressionImpl(_Deannotate, _CoerceLiterals, RoleImpl): - __slots__ = () _coerce_consts = True diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py index d4809ef934..f12de97632 100644 --- a/lib/sqlalchemy/sql/compiler.py +++ b/lib/sqlalchemy/sql/compiler.py @@ -715,7 +715,6 @@ class FromLinter(collections.namedtuple("FromLinter", ["froms", "edges"])): # FROMS left over? boom if the_rest: - froms = the_rest if froms: template = ( @@ -1763,7 +1762,6 @@ class SQLCompiler(Compiled): ) -> MutableMapping[ str, Union[_BindProcessorType[Any], Sequence[_BindProcessorType[Any]]] ]: - # mypy is not able to see the two value types as the above Union, # it just sees "object". don't know how to resolve return { @@ -1856,7 +1854,6 @@ class SQLCompiler(Compiled): has_escaped_names = escape_names and bool(self.escaped_bind_names) if extracted_parameters: - # related the bound parameters collected in the original cache key # to those collected in the incoming cache key. They will not have # matching names but they will line up positionally in the same @@ -1883,7 +1880,6 @@ class SQLCompiler(Compiled): resolved_extracted = None if params: - pd = {} for bindparam, name in self.bind_names.items(): escaped_name = ( @@ -2631,7 +2627,6 @@ class SQLCompiler(Compiled): def visit_textual_select( self, taf, compound_index=None, asfrom=False, **kw ): - toplevel = not self.stack entry = self._default_stack_entry if toplevel else self.stack[-1] @@ -2704,7 +2699,6 @@ class SQLCompiler(Compiled): ) def _generate_delimited_and_list(self, clauses, **kw): - lcc, clauses = elements.BooleanClauseList._process_clauses_for_boolean( operators.and_, elements.True_._singleton, @@ -2780,7 +2774,6 @@ class SQLCompiler(Compiled): ) def _format_frame_clause(self, range_, **kw): - return "%s AND %s" % ( "UNBOUNDED PRECEDING" if range_[0] is elements.RANGE_UNBOUNDED @@ -2995,7 +2988,6 @@ class SQLCompiler(Compiled): def visit_unary( self, unary, add_to_result_map=None, result_map_targets=(), **kw ): - if add_to_result_map is not None: result_map_targets += (unary,) kw["add_to_result_map"] = add_to_result_map @@ -3130,7 +3122,6 @@ class SQLCompiler(Compiled): def _literal_execute_expanding_parameter_literal_binds( self, parameter, values, bind_expression_template=None ): - typ_dialect_impl = parameter.type._unwrapped_dialect_impl(self.dialect) if not values: @@ -3155,7 +3146,6 @@ class SQLCompiler(Compiled): and isinstance(values[0], collections_abc.Sequence) and not isinstance(values[0], (str, bytes)) ): - if typ_dialect_impl._has_bind_expression: raise NotImplementedError( "bind_expression() on TupleType not supported with " @@ -3204,7 +3194,6 @@ class SQLCompiler(Compiled): return (), replacement_expression def _literal_execute_expanding_parameter(self, name, parameter, values): - if parameter.literal_execute: return self._literal_execute_expanding_parameter_literal_binds( parameter, values @@ -3238,7 +3227,6 @@ class SQLCompiler(Compiled): if not values: to_update = [] if typ_dialect_impl._is_tuple_type: - replacement_expression = self.visit_empty_set_op_expr( parameter.type.types, parameter.expand_op ) @@ -3373,7 +3361,6 @@ class SQLCompiler(Compiled): def _generate_generic_binary( self, binary, opstring, eager_grouping=False, **kw ): - _in_binary = kw.get("_in_binary", False) kw["_in_binary"] = True @@ -3839,7 +3826,6 @@ class SQLCompiler(Compiled): visited_bindparam: Optional[List[str]] = None, **kw: Any, ) -> str: - # TODO: accumulate_bind_names is passed by crud.py to gather # names on a per-value basis, visited_bindparam is passed by # visit_insert() to collect all parameters in the statement. @@ -3850,7 +3836,6 @@ class SQLCompiler(Compiled): visited_bindparam.append(name) if not escaped_from: - if self._bind_translate_re.search(name): # not quite the translate use case as we want to # also get a quick boolean if we even found @@ -4132,7 +4117,6 @@ class SQLCompiler(Compiled): from_linter=None, **kwargs, ): - if lateral: if "enclosing_lateral" not in kwargs: # if lateral is set and enclosing_lateral is not @@ -5046,7 +5030,6 @@ class SQLCompiler(Compiled): populate_result_map: bool, **kw: Any, ) -> str: - columns = [ self._label_returning_column( stmt, @@ -5568,7 +5551,6 @@ class SQLCompiler(Compiled): replaced_parameters = base_parameters.copy() for i, param in enumerate(batch): - fmv = formatted_values_clause.replace( "EXECMANY_INDEX__", str(i) ) @@ -5599,7 +5581,6 @@ class SQLCompiler(Compiled): batchnum += 1 def visit_insert(self, insert_stmt, visited_bindparam=None, **kw): - compile_state = insert_stmt._compile_state_factory( insert_stmt, self, **kw ) @@ -5727,7 +5708,6 @@ class SQLCompiler(Compiled): returning_cols = self.implicit_returning or insert_stmt._returning if returning_cols: - add_sentinel_cols = crud_params_struct.use_sentinel_columns if add_sentinel_cols is not None: @@ -5822,7 +5802,6 @@ class SQLCompiler(Compiled): elif not crud_params_single and supports_default_values: text += " DEFAULT VALUES" if use_insertmanyvalues: - self._insertmanyvalues = _InsertManyValues( True, self.dialect.default_metavalue_token, @@ -5862,7 +5841,6 @@ class SQLCompiler(Compiled): ) if use_insertmanyvalues: - if ( implicit_sentinel and ( @@ -5998,7 +5976,6 @@ class SQLCompiler(Compiled): ) def visit_update(self, update_stmt, **kw): - compile_state = update_stmt._compile_state_factory( update_stmt, self, **kw ) @@ -6537,7 +6514,6 @@ class DDLCompiler(Compiled): def create_table_constraints( self, table, _include_foreign_key_constraints=None, **kw ): - # On some DB order is significant: visit PK first, then the # other constraints (engine.ReflectionTest.testbasic failed on FB2) constraints = [] @@ -7002,7 +6978,6 @@ class GenericTypeCompiler(TypeCompiler): return "NCLOB" def _render_string_type(self, type_, name, length_override=None): - text = name if length_override: text += "(%d)" % length_override diff --git a/lib/sqlalchemy/sql/crud.py b/lib/sqlalchemy/sql/crud.py index 16d5ce4941..4191069fb4 100644 --- a/lib/sqlalchemy/sql/crud.py +++ b/lib/sqlalchemy/sql/crud.py @@ -534,7 +534,6 @@ def _scan_insert_from_select_cols( toplevel, kw, ): - cols = [stmt.table.c[_column_as_key(name)] for name in stmt._select_names] assert compiler.stack[-1]["selectable"] is stmt @@ -823,7 +822,6 @@ def _append_param_parameter( accumulated_bind_names: Set[str] = set() if coercions._is_literal(value): - if ( insert_null_pk_still_autoincrements and c.primary_key @@ -890,7 +888,6 @@ def _append_param_parameter( compiler.postfetch.append(c) else: if c.primary_key: - if implicit_returning: compiler.implicit_returning.append(c) elif compiler.dialect.postfetch_lastrowid: @@ -1111,7 +1108,6 @@ def _append_param_insert_select_hasdefault( values: List[_CrudParamElementSQLExpr], kw: Dict[str, Any], ) -> None: - if default_is_sequence(c.default): if compiler.dialect.supports_sequences and ( not c.default.optional or not compiler.dialect.sequences_optional @@ -1149,7 +1145,6 @@ def _append_param_insert_select_hasdefault( def _append_param_update( compiler, compile_state, stmt, c, implicit_return_defaults, values, kw ): - include_table = compile_state.include_table_with_column_exprs if c.onupdate is not None and not c.onupdate.is_sequence: if c.onupdate.is_clause_element: @@ -1220,7 +1215,6 @@ def _create_insert_prefetch_bind_param( name: Optional[str] = None, **kw: Any, ) -> Union[elements.BindParameter[Any], str]: - param = _create_bind_param( compiler, c, None, process=process, name=name, **kw ) @@ -1431,7 +1425,7 @@ def _extend_values_for_multiparams( row = {_column_as_key(key): v for key, v in row.items()} - for (col, col_expr, param, accumulated_names) in values_0: + for col, col_expr, param, accumulated_names in values_0: if col.key in row: key = col.key @@ -1466,7 +1460,6 @@ def _get_stmt_parameter_tuples_params( values, kw, ): - for k, v in stmt_parameter_tuples: colkey = _column_as_key(k) if colkey is not None: diff --git a/lib/sqlalchemy/sql/ddl.py b/lib/sqlalchemy/sql/ddl.py index b87049e076..09cc54d546 100644 --- a/lib/sqlalchemy/sql/ddl.py +++ b/lib/sqlalchemy/sql/ddl.py @@ -944,7 +944,6 @@ class SchemaGenerator(InvokeCreateDDLBase): checkfirst=self.checkfirst, _is_metadata_operation=_is_metadata_operation, ): - for column in table.columns: if column.default is not None: self.traverse_single(column.default) @@ -1074,7 +1073,6 @@ class SchemaDropper(InvokeDropDDLBase): tables=event_collection, checkfirst=self.checkfirst, ): - for table, fkcs in collection: if table is not None: self.traverse_single( @@ -1144,7 +1142,6 @@ class SchemaDropper(InvokeDropDDLBase): checkfirst=self.checkfirst, _is_metadata_operation=_is_metadata_operation, ): - DropTable(table)._invoke_with(self.connection) # traverse client side defaults which may refer to server-side @@ -1168,7 +1165,6 @@ class SchemaDropper(InvokeDropDDLBase): DropConstraint(constraint)._invoke_with(self.connection) def visit_sequence(self, sequence, drop_ok=False): - if not drop_ok and not self._can_drop_sequence(sequence): return with self.with_ddl_events(sequence): diff --git a/lib/sqlalchemy/sql/default_comparator.py b/lib/sqlalchemy/sql/default_comparator.py index 57460b0365..645114aedf 100644 --- a/lib/sqlalchemy/sql/default_comparator.py +++ b/lib/sqlalchemy/sql/default_comparator.py @@ -171,7 +171,6 @@ def _binary_operate( result_type: Optional[TypeEngine[_T]] = None, **kw: Any, ) -> OperatorExpression[_T]: - coerced_obj = coercions.expect( roles.BinaryElementRole, obj, expr=expr, operator=op ) diff --git a/lib/sqlalchemy/sql/dml.py b/lib/sqlalchemy/sql/dml.py index 987910f0ca..4047ba4133 100644 --- a/lib/sqlalchemy/sql/dml.py +++ b/lib/sqlalchemy/sql/dml.py @@ -1113,7 +1113,6 @@ class ValuesBase(UpdateBase): ) elif isinstance(arg, collections_abc.Sequence): - if arg and isinstance(arg[0], dict): multi_kv_generator = DMLState.get_plugin_class( self @@ -1283,7 +1282,6 @@ class Insert(ValuesBase): return self if TYPE_CHECKING: - # START OVERLOADED FUNCTIONS self.returning ReturningInsert 1-8 ", *, sort_by_parameter_order: bool = False" # noqa: E501 # code within this block is **programmatically, @@ -1725,7 +1723,6 @@ class Delete(DMLWhereBase, UpdateBase): ) if TYPE_CHECKING: - # START OVERLOADED FUNCTIONS self.returning ReturningDelete 1-8 # code within this block is **programmatically, diff --git a/lib/sqlalchemy/sql/functions.py b/lib/sqlalchemy/sql/functions.py index 30ef0b7e34..30e280c61f 100644 --- a/lib/sqlalchemy/sql/functions.py +++ b/lib/sqlalchemy/sql/functions.py @@ -911,7 +911,6 @@ class _FunctionGenerator: ) if TYPE_CHECKING: - # START GENERATED FUNCTION ACCESSORS # code within this block is **programmatically, @@ -1602,7 +1601,6 @@ class array_agg(GenericFunction[_T]): default_array_type = kwargs.pop("_default_array_type", sqltypes.ARRAY) if "type_" not in kwargs: - type_from_args = _type_from_args(fn_args) if isinstance(type_from_args, sqltypes.ARRAY): kwargs["type_"] = type_from_args diff --git a/lib/sqlalchemy/sql/lambdas.py b/lib/sqlalchemy/sql/lambdas.py index 12175c75d1..455649cb96 100644 --- a/lib/sqlalchemy/sql/lambdas.py +++ b/lib/sqlalchemy/sql/lambdas.py @@ -351,7 +351,6 @@ class LambdaElement(elements.ClauseElement): element: Optional[visitors.ExternallyTraversible], **kw: Any ) -> Optional[visitors.ExternallyTraversible]: if isinstance(element, elements.BindParameter): - if element.key in bindparam_lookup: bind = bindparam_lookup[element.key] if element.expanding: @@ -988,7 +987,6 @@ class AnalyzedCode: if isinstance(cell_contents, _cache_key.HasCacheKey): def get(closure, opts, anon_map, bindparams): - obj = closure[idx].cell_contents if use_inspect: obj = inspection.inspect(obj) @@ -1427,7 +1425,6 @@ class PyWrapper(ColumnOperators): return self._sa__add_getter(key, operator.itemgetter) def _add_getter(self, key, getter_fn): - bind_paths = object.__getattribute__(self, "_bind_paths") bind_path_key = (key, getter_fn) diff --git a/lib/sqlalchemy/sql/naming.py b/lib/sqlalchemy/sql/naming.py index 3520b8dc21..03c9aab67b 100644 --- a/lib/sqlalchemy/sql/naming.py +++ b/lib/sqlalchemy/sql/naming.py @@ -140,7 +140,6 @@ _prefix_dict = { def _get_convention(dict_, key): - for super_ in key.__mro__: if super_ in _prefix_dict and _prefix_dict[super_] in dict_: return dict_[_prefix_dict[super_]] diff --git a/lib/sqlalchemy/sql/schema.py b/lib/sqlalchemy/sql/schema.py index 1920964691..e17d194459 100644 --- a/lib/sqlalchemy/sql/schema.py +++ b/lib/sqlalchemy/sql/schema.py @@ -124,7 +124,6 @@ _ServerDefaultArgument = Union[ class SchemaConst(Enum): - RETAIN_SCHEMA = 1 """Symbol indicating that a :class:`_schema.Table`, :class:`.Sequence` or in some cases a :class:`_schema.ForeignKey` object, in situations @@ -1058,7 +1057,6 @@ class Table( if the_sentinel: the_sentinel_zero = the_sentinel[0] if the_sentinel_zero.identity: - if the_sentinel_zero.identity._increment_is_negative: if sentinel_is_explicit: raise exc.InvalidRequestError( @@ -1095,7 +1093,6 @@ class Table( _SentinelDefaultCharacterization.SENTINEL_DEFAULT ) elif default_is_sequence(the_sentinel_zero.default): - if the_sentinel_zero.default._increment_is_negative: if sentinel_is_explicit: raise exc.InvalidRequestError( @@ -3166,7 +3163,6 @@ class ForeignKey(DialectKWArgs, SchemaItem): _column: Column[Any] if isinstance(self._colspec, str): - parenttable, tablekey, colname = self._resolve_col_tokens() if self._unresolvable or tablekey not in parenttable.metadata: diff --git a/lib/sqlalchemy/sql/selectable.py b/lib/sqlalchemy/sql/selectable.py index c7df0b8016..060b03b503 100644 --- a/lib/sqlalchemy/sql/selectable.py +++ b/lib/sqlalchemy/sql/selectable.py @@ -2318,7 +2318,6 @@ class SelectsRows(ReturnsRows): # c, use hash(), so that an annotated version of the column # is seen as the same as the non-annotated if hash(names[effective_name]) != hash(c): - # different column under the same name. apply # disambiguating label if table_qualified: @@ -3185,7 +3184,6 @@ class Values(roles.InElementRole, Generative, LateralFromClause): @_generative def alias(self, name: Optional[str] = None, flat: bool = False) -> Self: - """Return a new :class:`_expression.Values` construct that is a copy of this one with the given name. @@ -4385,7 +4383,6 @@ class CompoundSelect(HasCompileState, GenerativeSelect, ExecutableReturnsRows): Iterable[Sequence[ColumnElement[Any]]] ] = None, ) -> None: - # this is a slightly hacky thing - the union exports a # column that resembles just that of the *first* selectable. # to get at a "composite" column, particularly foreign keys, @@ -4548,7 +4545,6 @@ class SelectState(util.MemoizedSlots, CompileState): def _column_naming_convention( cls, label_style: SelectLabelStyle ) -> _LabelConventionCallable: - table_qualified = label_style is LABEL_STYLE_TABLENAME_PLUS_COL dedupe = label_style is not LABEL_STYLE_NONE @@ -4635,7 +4631,6 @@ class SelectState(util.MemoizedSlots, CompileState): froms: List[FromClause] = [] for item in iterable_of_froms: - if is_subquery(item) and item.element is check_statement: raise exc.InvalidRequestError( "select() construct refers to itself as a FROM" @@ -4705,7 +4700,6 @@ class SelectState(util.MemoizedSlots, CompileState): ] if self.statement._correlate_except is not None: - froms = [ f for f in froms @@ -4723,7 +4717,6 @@ class SelectState(util.MemoizedSlots, CompileState): and implicit_correlate_froms and len(froms) > 1 ): - froms = [ f for f in froms @@ -4784,7 +4777,7 @@ class SelectState(util.MemoizedSlots, CompileState): args: Tuple[_SetupJoinsElement, ...], raw_columns: List[_ColumnsClauseElement], ) -> None: - for (right, onclause, left, flags) in args: + for right, onclause, left, flags in args: if TYPE_CHECKING: if onclause is not None: assert isinstance(onclause, ColumnElement) @@ -4859,7 +4852,6 @@ class SelectState(util.MemoizedSlots, CompileState): from_clauses = self.from_clauses if from_clauses: - indexes: List[int] = sql_util.find_left_clause_to_join_from( from_clauses, right, onclause ) @@ -4882,7 +4874,6 @@ class SelectState(util.MemoizedSlots, CompileState): ] ), ): - potential[from_clause] = () all_clauses = list(potential.keys()) @@ -6290,7 +6281,6 @@ class Select( if is_column_element(c) ] else: - prox = [ c._make_proxy( subquery, @@ -6525,7 +6515,6 @@ class ScalarSelect( def self_group( self, against: Optional[OperatorType] = None ) -> ColumnElement[Any]: - return self if TYPE_CHECKING: @@ -6801,7 +6790,6 @@ class TextualSelect(SelectBase, ExecutableReturnsRows, Generative): columns: List[_ColumnExpressionArgument[Any]], positional: bool = False, ) -> None: - self._init( text, # convert for ORM attributes->columns, etc diff --git a/lib/sqlalchemy/sql/sqltypes.py b/lib/sqlalchemy/sql/sqltypes.py index c8d3e3b7e0..f4ce48fcb2 100644 --- a/lib/sqlalchemy/sql/sqltypes.py +++ b/lib/sqlalchemy/sql/sqltypes.py @@ -804,7 +804,6 @@ class DateTime( @util.memoized_property def _expression_adaptations(self): - # Based on # https://www.postgresql.org/docs/current/static/functions-datetime.html. @@ -1515,7 +1514,6 @@ class Enum(String, SchemaType, Emulated, TypeEngine[Union[str, enum.Enum]]): matched_on: _MatchedOnType, matched_on_flattened: Type[Any], ) -> Optional[Enum]: - # "generic form" indicates we were placed in a type map # as ``sqlalchemy.Enum(enum.Enum)`` which indicates we need to # get enumerated values from the datatype @@ -2868,7 +2866,6 @@ class ARRAY( type: ARRAY def _setup_getitem(self, index): - arr_type = self.type return_type: TypeEngine[Any] @@ -3159,7 +3156,6 @@ class TupleType(TypeEngine[Tuple[Any, ...]]): def coerce_compared_value( self, op: Optional[OperatorType], value: Any ) -> TypeEngine[Any]: - if value is type_api._NO_VALUE_IN_LIST: return super().coerce_compared_value(op, value) else: @@ -3674,7 +3670,6 @@ class Uuid(Emulated, TypeEngine[_UUID_RETURN]): return process else: - if not self.as_uuid: def process(value): diff --git a/lib/sqlalchemy/sql/traversals.py b/lib/sqlalchemy/sql/traversals.py index 96758a7ad4..5c782f1db6 100644 --- a/lib/sqlalchemy/sql/traversals.py +++ b/lib/sqlalchemy/sql/traversals.py @@ -416,7 +416,7 @@ class _GetChildrenTraversal(HasTraversalDispatch): return element def visit_setup_join_tuple(self, element, **kw): - for (target, onclause, from_, flags) in element: + for target, onclause, from_, flags in element: if from_ is not None: yield from_ @@ -713,7 +713,6 @@ class TraversalComparatorStrategy(HasTraversalDispatch, util.MemoizedSlots): def visit_string_multi_dict( self, attrname, left_parent, left, right_parent, right, **kw ): - for lk, rk in zip_longest( sorted(left.keys()), sorted(right.keys()), fillvalue=(None, None) ): @@ -737,7 +736,6 @@ class TraversalComparatorStrategy(HasTraversalDispatch, util.MemoizedSlots): def visit_multi( self, attrname, left_parent, left, right_parent, right, **kw ): - lhc = isinstance(left, HasCacheKey) rhc = isinstance(right, HasCacheKey) if lhc and rhc: diff --git a/lib/sqlalchemy/sql/type_api.py b/lib/sqlalchemy/sql/type_api.py index 312034e9d2..a1588dc174 100644 --- a/lib/sqlalchemy/sql/type_api.py +++ b/lib/sqlalchemy/sql/type_api.py @@ -966,7 +966,6 @@ class TypeEngine(Visitable, Generic[_T]): def _cached_sentinel_value_processor( self, dialect: Dialect ) -> Optional[_SentinelProcessorType[_T]]: - try: return dialect._type_memos[self]["sentinel"] except KeyError: @@ -1114,7 +1113,6 @@ class TypeEngine(Visitable, Generic[_T]): @util.preload_module("sqlalchemy.engine.default") def _default_dialect(self) -> Dialect: - default = util.preloaded.engine_default # dmypy / mypy seems to sporadically keep thinking this line is @@ -1523,7 +1521,6 @@ class NativeForEmulated(TypeEngineMixin): impl: Union[TypeEngine[Any], TypeEngineMixin], **kw: Any, ) -> TypeEngine[Any]: - """Given an impl, adapt this type's class to the impl assuming "native". @@ -2028,7 +2025,6 @@ class TypeDecorator(SchemaEventTarget, ExternalType, TypeEngine[_T]): if process_literal_param is not None: impl_processor = self.impl_instance.literal_processor(dialect) if impl_processor: - fixed_impl_processor = impl_processor fixed_process_literal_param = process_literal_param @@ -2165,7 +2161,6 @@ class TypeDecorator(SchemaEventTarget, ExternalType, TypeEngine[_T]): @util.memoized_property def _has_bind_expression(self) -> bool: - return ( util.method_is_overridden(self, TypeDecorator.bind_expression) or self.impl_instance._has_bind_expression diff --git a/lib/sqlalchemy/sql/util.py b/lib/sqlalchemy/sql/util.py index 18caf5de4b..0a50197a0d 100644 --- a/lib/sqlalchemy/sql/util.py +++ b/lib/sqlalchemy/sql/util.py @@ -1343,7 +1343,6 @@ class ColumnAdapter(ClauseAdapter): def traverse( self, obj: Optional[ExternallyTraversible] ) -> Optional[ExternallyTraversible]: - return self.columns[obj] def chain(self, visitor: ExternalTraversal) -> ColumnAdapter: diff --git a/lib/sqlalchemy/sql/visitors.py b/lib/sqlalchemy/sql/visitors.py index 79a163f677..69dc6a827c 100644 --- a/lib/sqlalchemy/sql/visitors.py +++ b/lib/sqlalchemy/sql/visitors.py @@ -1049,7 +1049,6 @@ def cloned_traverse( return elem else: if id(elem) not in cloned: - if "replace" in kw: newelem = cast( Optional[ExternallyTraversible], kw["replace"](elem) diff --git a/lib/sqlalchemy/testing/assertsql.py b/lib/sqlalchemy/testing/assertsql.py index 1f677b41bd..85e424655c 100644 --- a/lib/sqlalchemy/testing/assertsql.py +++ b/lib/sqlalchemy/testing/assertsql.py @@ -21,7 +21,6 @@ from ..schema import BaseDDLElement class AssertRule: - is_consumed = False errormessage = None consume_statement = True @@ -128,7 +127,6 @@ class CompiledSQL(SQLMatchRule): map_ = None if isinstance(execute_observed.clauseelement, BaseDDLElement): - compiled = execute_observed.clauseelement.compile( dialect=compare_dialect, schema_translate_map=map_, diff --git a/lib/sqlalchemy/testing/asyncio.py b/lib/sqlalchemy/testing/asyncio.py index 10d3d079d7..4236dcf92e 100644 --- a/lib/sqlalchemy/testing/asyncio.py +++ b/lib/sqlalchemy/testing/asyncio.py @@ -84,7 +84,6 @@ def _maybe_async(fn, *args, **kwargs): """ if not ENABLE_ASYNCIO: - return fn(*args, **kwargs) is_async = config._current.is_async diff --git a/lib/sqlalchemy/testing/config.py b/lib/sqlalchemy/testing/config.py index 8559183656..d2bda4d83c 100644 --- a/lib/sqlalchemy/testing/config.py +++ b/lib/sqlalchemy/testing/config.py @@ -120,11 +120,7 @@ def combinations( def combinations_list( - arg_iterable: Iterable[ - Tuple[ - Any, - ] - ], + arg_iterable: Iterable[Tuple[Any,]], **kw, ): "As combination, but takes a single iterable" diff --git a/lib/sqlalchemy/testing/engines.py b/lib/sqlalchemy/testing/engines.py index fa70de6f0d..749f9c160e 100644 --- a/lib/sqlalchemy/testing/engines.py +++ b/lib/sqlalchemy/testing/engines.py @@ -230,7 +230,6 @@ class ReconnectFixture: return getattr(self.dbapi, key) def connect(self, *args, **kwargs): - conn = self.dbapi.connect(*args, **kwargs) if self.is_stopped: self._safe(conn.close) diff --git a/lib/sqlalchemy/testing/fixtures.py b/lib/sqlalchemy/testing/fixtures.py index bff251b0f7..cb08380f2e 100644 --- a/lib/sqlalchemy/testing/fixtures.py +++ b/lib/sqlalchemy/testing/fixtures.py @@ -262,7 +262,6 @@ class TestBase: def run_test(subject, trans_on_subject, execute_on_subject): with subject.begin() as trans: - if begin_nested: if not config.requirements.savepoints.enabled: config.skip_test("savepoints not enabled") @@ -391,7 +390,6 @@ class FutureEngineMixin: class TablesTest(TestBase): - # 'once', None run_setup_bind = "once" @@ -915,7 +913,6 @@ class CacheKeyFixture: assert b_key is None else: - eq_(a_key.key, b_key.key) eq_(hash(a_key.key), hash(b_key.key)) @@ -1011,7 +1008,6 @@ class CacheKeyFixture: def insertmanyvalues_fixture( connection, randomize_rows=False, warn_on_downgraded=False ): - dialect = connection.dialect orig_dialect = dialect._deliver_insertmanyvalues_batches orig_conn = connection._exec_insertmany_context diff --git a/lib/sqlalchemy/testing/plugin/plugin_base.py b/lib/sqlalchemy/testing/plugin/plugin_base.py index bf10134cc8..cff53ea727 100644 --- a/lib/sqlalchemy/testing/plugin/plugin_base.py +++ b/lib/sqlalchemy/testing/plugin/plugin_base.py @@ -411,13 +411,11 @@ def _init_symbols(options, file_config): @pre def _set_disable_asyncio(opt, file_config): if opt.disable_asyncio: - asyncio.ENABLE_ASYNCIO = False @post def _engine_uri(options, file_config): - from sqlalchemy import testing from sqlalchemy.testing import config from sqlalchemy.testing import provision @@ -466,7 +464,6 @@ def _engine_uri(options, file_config): @post def _requirements(options, file_config): - requirement_cls = file_config.get("sqla_testing", "requirement_cls") _setup_requirements(requirement_cls) @@ -608,7 +605,6 @@ def _setup_engine(cls): def before_test(test, test_module_name, test_class, test_name): - # format looks like: # "test.aaa_profiling.test_compiler.CompileTest.test_update_whereclause" diff --git a/lib/sqlalchemy/testing/plugin/pytestplugin.py b/lib/sqlalchemy/testing/plugin/pytestplugin.py index b5d2485524..17bd038d38 100644 --- a/lib/sqlalchemy/testing/plugin/pytestplugin.py +++ b/lib/sqlalchemy/testing/plugin/pytestplugin.py @@ -220,7 +220,6 @@ class XDistHooks: def pytest_collection_modifyitems(session, config, items): - # look for all those classes that specify __backend__ and # expand them out into per-database test cases. @@ -255,7 +254,6 @@ def pytest_collection_modifyitems(session, config, items): def setup_test_classes(): for test_class in test_classes: - # transfer legacy __backend__ and __sparse_backend__ symbols # to be markers add_markers = set() @@ -611,7 +609,6 @@ def _pytest_fn_decorator(target): return env[fn_name] def decorate(fn, add_positional_parameters=()): - spec = inspect_getfullargspec(fn) if add_positional_parameters: spec.args.extend(add_positional_parameters) @@ -742,7 +739,6 @@ class PytestFixtureFunctions(plugin_base.FixtureFunctions): ) else: - for arg in arg_sets: if not isinstance(arg, tuple): arg = (arg,) diff --git a/lib/sqlalchemy/testing/profiling.py b/lib/sqlalchemy/testing/profiling.py index 818482b25d..5471b1cfd4 100644 --- a/lib/sqlalchemy/testing/profiling.py +++ b/lib/sqlalchemy/testing/profiling.py @@ -90,7 +90,6 @@ class ProfileStatsFile: @property def platform_key(self): - dbapi_key = config.db.name + "_" + config.db.driver if config.db.name == "sqlite" and config.db.dialect._is_url_file_db( @@ -216,7 +215,6 @@ class ProfileStatsFile: profile_f = open(self.fname, "w") profile_f.write(self._header()) for test_key in sorted(self.data): - per_fn = self.data[test_key] profile_f.write("\n# TEST: %s\n\n" % test_key) for platform_key in sorted(per_fn): @@ -245,7 +243,6 @@ def function_call_count(variance=0.05, times=1, warmup=0): @decorator def wrap(fn, *args, **kw): - for warm in range(warmup): fn(*args, **kw) diff --git a/lib/sqlalchemy/testing/provision.py b/lib/sqlalchemy/testing/provision.py index 66ccb3ee8f..0ff564e245 100644 --- a/lib/sqlalchemy/testing/provision.py +++ b/lib/sqlalchemy/testing/provision.py @@ -170,9 +170,7 @@ def _generate_driver_urls(url, extra_drivers): yield url for drv in list(extra_drivers): - if "?" in drv: - driver_only, query_str = drv.split("?", 1) else: @@ -234,7 +232,6 @@ def drop_all_schema_objects_post_tables(cfg, eng): def drop_all_schema_objects(cfg, eng): - drop_all_schema_objects_pre_tables(cfg, eng) drop_views(cfg, eng) diff --git a/lib/sqlalchemy/testing/requirements.py b/lib/sqlalchemy/testing/requirements.py index 45568eac4f..8eef9fc7b4 100644 --- a/lib/sqlalchemy/testing/requirements.py +++ b/lib/sqlalchemy/testing/requirements.py @@ -1028,7 +1028,6 @@ class SuiteRequirements(Requirements): } """ with config.db.connect() as conn: - try: supported = conn.dialect.get_isolation_level_values( conn.connection.dbapi_connection diff --git a/lib/sqlalchemy/testing/schema.py b/lib/sqlalchemy/testing/schema.py index a057c7fd0c..72ef9754ef 100644 --- a/lib/sqlalchemy/testing/schema.py +++ b/lib/sqlalchemy/testing/schema.py @@ -88,7 +88,6 @@ def _schema_column(factory, args, kw): if test_opts.get("test_needs_autoincrement", False) and kw.get( "primary_key", False ): - if col.default is None and col.server_default is None: col.autoincrement = True diff --git a/lib/sqlalchemy/testing/suite/test_cte.py b/lib/sqlalchemy/testing/suite/test_cte.py index c52b30e03a..fb767e4635 100644 --- a/lib/sqlalchemy/testing/suite/test_cte.py +++ b/lib/sqlalchemy/testing/suite/test_cte.py @@ -175,7 +175,6 @@ class CTETest(fixtures.TablesTest): @testing.requires.ctes_with_update_delete def test_delete_scalar_subq_round_trip(self, connection): - some_table = self.tables.some_table some_other_table = self.tables.some_other_table diff --git a/lib/sqlalchemy/testing/suite/test_dialect.py b/lib/sqlalchemy/testing/suite/test_dialect.py index 58a6483260..7cbbfd8ead 100644 --- a/lib/sqlalchemy/testing/suite/test_dialect.py +++ b/lib/sqlalchemy/testing/suite/test_dialect.py @@ -109,9 +109,7 @@ class ExceptionTest(fixtures.TablesTest): @requirements.duplicate_key_raises_integrity_error def test_integrity_error(self): - with config.db.connect() as conn: - trans = conn.begin() conn.execute( self.tables.manual_pk.insert(), {"id": 1, "data": "d1"} @@ -251,7 +249,6 @@ class IsolationLevelTest(fixtures.TestBase): class AutocommitIsolationTest(fixtures.TablesTest): - run_deletes = "each" __requires__ = ("autocommit",) @@ -542,7 +539,6 @@ class ReturningGuardsTest(fixtures.TablesTest): @classmethod def define_tables(cls, metadata): - Table( "t", metadata, diff --git a/lib/sqlalchemy/testing/suite/test_insert.py b/lib/sqlalchemy/testing/suite/test_insert.py index 283e67f8dc..e164605e4f 100644 --- a/lib/sqlalchemy/testing/suite/test_insert.py +++ b/lib/sqlalchemy/testing/suite/test_insert.py @@ -62,14 +62,12 @@ class LastrowidTest(fixtures.TablesTest): ) def test_autoincrement_on_insert(self, connection): - connection.execute( self.tables.autoinc_pk.insert(), dict(data="some data") ) self._assert_round_trip(self.tables.autoinc_pk, connection) def test_last_inserted_id(self, connection): - r = connection.execute( self.tables.autoinc_pk.insert(), dict(data="some data") ) @@ -356,14 +354,12 @@ class ReturningTest(fixtures.TablesTest): eq_(fetched_pk, pk) def test_autoincrement_on_insert_implicit_returning(self, connection): - connection.execute( self.tables.autoinc_pk.insert(), dict(data="some data") ) self._assert_round_trip(self.tables.autoinc_pk, connection) def test_last_inserted_id_implicit_returning(self, connection): - r = connection.execute( self.tables.autoinc_pk.insert(), dict(data="some data") ) diff --git a/lib/sqlalchemy/testing/suite/test_reflection.py b/lib/sqlalchemy/testing/suite/test_reflection.py index 0162799d7e..05b68e7aef 100644 --- a/lib/sqlalchemy/testing/suite/test_reflection.py +++ b/lib/sqlalchemy/testing/suite/test_reflection.py @@ -345,7 +345,6 @@ class QuotedNameArgumentTest(fixtures.TablesTest): ) if testing.requires.view_column_reflection.enabled: - if testing.requires.symbol_names_w_double_quote.enabled: names = [ "quote ' one", @@ -1430,7 +1429,6 @@ class ComponentReflectionTest(ComparesTables, OneConnectionTablesTest): (True, testing.requires.schemas), False, argnames="use_schema" ) def test_get_table_names(self, connection, order_by, use_schema): - if use_schema: schema = config.test_schema else: @@ -1540,7 +1538,6 @@ class ComponentReflectionTest(ComparesTables, OneConnectionTablesTest): argnames="use_views,use_schema", ) def test_get_columns(self, connection, use_views, use_schema): - if use_schema: schema = config.test_schema else: @@ -1607,7 +1604,6 @@ class ComponentReflectionTest(ComparesTables, OneConnectionTablesTest): @testing.requires.temp_table_reflection def test_reflect_table_temp_table(self, connection): - table_name = self.temp_table_name() user_tmp = self.tables[table_name] @@ -1755,7 +1751,6 @@ class ComponentReflectionTest(ComparesTables, OneConnectionTablesTest): ) @testing.requires.index_reflection def test_get_indexes(self, connection, use_schema): - if use_schema: schema = config.test_schema else: @@ -2322,7 +2317,6 @@ class ComponentReflectionTest(ComparesTables, OneConnectionTablesTest): @testing.requires.comment_reflection_full_unicode def test_comments_unicode_full(self, connection, metadata): - Table( "unicode_comments", metadata, @@ -2393,7 +2387,6 @@ class TableNoColumnsTest(fixtures.TestBase): class ComponentReflectionTestExtra(ComparesIndexes, fixtures.TestBase): - __backend__ = True @testing.combinations( @@ -2744,7 +2737,6 @@ class NormalizedNameTest(fixtures.TablesTest): ) def test_reflect_lowercase_forced_tables(self): - m2 = MetaData() t2_ref = Table( quoted_name("t2", quote=True), m2, autoload_with=config.db diff --git a/lib/sqlalchemy/testing/suite/test_results.py b/lib/sqlalchemy/testing/suite/test_results.py index 7d79c67ae9..c0f5e40012 100644 --- a/lib/sqlalchemy/testing/suite/test_results.py +++ b/lib/sqlalchemy/testing/suite/test_results.py @@ -242,7 +242,6 @@ class PercentSchemaNamesTest(fixtures.TablesTest): class ServerSideCursorsTest( fixtures.TestBase, testing.AssertsExecutionResults ): - __requires__ = ("server_side_cursors",) __backend__ = True diff --git a/lib/sqlalchemy/testing/suite/test_select.py b/lib/sqlalchemy/testing/suite/test_select.py index 6394e4b9a1..a0aa147f9c 100644 --- a/lib/sqlalchemy/testing/suite/test_select.py +++ b/lib/sqlalchemy/testing/suite/test_select.py @@ -1729,7 +1729,6 @@ class IdentityColumnTest(fixtures.TablesTest): eq_(res, [(-5, "b"), (0, "a"), (42, "c")]) def test_select_columns(self, connection): - res = connection.execute( select(self.tables.tbl_a.c.id).order_by(self.tables.tbl_a.c.id) ).fetchall() diff --git a/lib/sqlalchemy/testing/suite/test_sequence.py b/lib/sqlalchemy/testing/suite/test_sequence.py index a605e4f42f..43e2d066bb 100644 --- a/lib/sqlalchemy/testing/suite/test_sequence.py +++ b/lib/sqlalchemy/testing/suite/test_sequence.py @@ -120,7 +120,6 @@ class SequenceTest(fixtures.TablesTest): @testing.combinations((True,), (False,), argnames="implicit_returning") @testing.requires.schemas def test_insert_roundtrip_translate(self, connection, implicit_returning): - seq_no_returning = Table( "seq_no_returning_sch", MetaData(), diff --git a/lib/sqlalchemy/testing/suite/test_types.py b/lib/sqlalchemy/testing/suite/test_types.py index 92781cc1b3..0a1419f253 100644 --- a/lib/sqlalchemy/testing/suite/test_types.py +++ b/lib/sqlalchemy/testing/suite/test_types.py @@ -683,7 +683,6 @@ class IntegerTest(_LiteralRoundTripFixture, fixtures.TestBase): literal_round_trip(Integer, [5], [5]) def _huge_ints(): - return testing.combinations( 2147483649, # 32 bits 2147483648, # 32 bits @@ -1216,7 +1215,6 @@ class JSONTest(_LiteralRoundTripFixture, fixtures.TablesTest): ) @testing.combinations(100, 1999, 3000, 4000, 5000, 9000, argnames="length") def test_round_trip_pretty_large_data(self, connection, unicode_, length): - if unicode_: data = "réve🐍illé" * ((length // 9) + 1) data = data[0 : (length // 2)] @@ -1239,7 +1237,6 @@ class JSONTest(_LiteralRoundTripFixture, fixtures.TablesTest): eq_(row, (data_element,)) def _index_fixtures(include_comparison): - if include_comparison: # basically SQL Server and MariaDB can kind of do json # comparison, MySQL, PG and SQLite can't. not worth it. @@ -1302,7 +1299,6 @@ class JSONTest(_LiteralRoundTripFixture, fixtures.TablesTest): def _json_value_insert(self, connection, datatype, value, data_element): data_table = self.tables.data_table if datatype == "_decimal": - # Python's builtin json serializer basically doesn't support # Decimal objects without implicit float conversion period. # users can otherwise use simplejson which supports @@ -1380,7 +1376,6 @@ class JSONTest(_LiteralRoundTripFixture, fixtures.TablesTest): data_element = {"key1": value} with config.db.begin() as conn: - datatype, compare_value, p_s = self._json_value_insert( conn, datatype, value, data_element ) @@ -1425,7 +1420,6 @@ class JSONTest(_LiteralRoundTripFixture, fixtures.TablesTest): data_table = self.tables.data_table data_element = {"key1": {"subkey1": value}} with config.db.begin() as conn: - datatype, compare_value, p_s = self._json_value_insert( conn, datatype, value, data_element ) @@ -1639,7 +1633,6 @@ class JSONTest(_LiteralRoundTripFixture, fixtures.TablesTest): ) def test_eval_none_flag_orm(self, connection): - Base = declarative_base() class Data(Base): diff --git a/lib/sqlalchemy/testing/util.py b/lib/sqlalchemy/testing/util.py index d061f26a28..ccd06716e0 100644 --- a/lib/sqlalchemy/testing/util.py +++ b/lib/sqlalchemy/testing/util.py @@ -122,7 +122,6 @@ def all_partial_orderings(tuples, elements): edges[child].add(parent) def _all_orderings(elements): - if len(elements) == 1: yield list(elements) else: @@ -325,7 +324,6 @@ def metadata_fixture(ddl="function"): def decorate(fn): def run_ddl(self): - metadata = self.metadata = schema.MetaData() try: result = fn(self, metadata) @@ -349,7 +347,6 @@ def force_drop_names(*names): @decorator def go(fn, *args, **kw): - try: return fn(*args, **kw) finally: @@ -403,7 +400,6 @@ def drop_all_tables( consider_schemas=(None,), include_names=None, ): - if include_names is not None: include_names = set(include_names) diff --git a/lib/sqlalchemy/util/_concurrency_py3k.py b/lib/sqlalchemy/util/_concurrency_py3k.py index 3544a0fd59..2b6ae8750a 100644 --- a/lib/sqlalchemy/util/_concurrency_py3k.py +++ b/lib/sqlalchemy/util/_concurrency_py3k.py @@ -30,7 +30,6 @@ _T = TypeVar("_T") if typing.TYPE_CHECKING: class greenlet(Protocol): - dead: bool gr_context: Optional[Context] @@ -141,7 +140,6 @@ def await_fallback(awaitable: Awaitable[_T]) -> _T: if not isinstance(current, _AsyncIoGreenlet): loop = get_event_loop() if loop.is_running(): - _safe_cancel_awaitable(awaitable) raise exc.MissingGreenlet( @@ -237,7 +235,6 @@ def _util_async_run_coroutine_function( def _util_async_run( fn: Callable[..., Coroutine[Any, Any, Any]], *args: Any, **kwargs: Any ) -> Any: - """for test suite/ util only""" loop = get_event_loop() diff --git a/lib/sqlalchemy/util/compat.py b/lib/sqlalchemy/util/compat.py index 0c760e38d7..ab346083e5 100644 --- a/lib/sqlalchemy/util/compat.py +++ b/lib/sqlalchemy/util/compat.py @@ -116,7 +116,6 @@ else: if py310: anext_ = anext else: - _NOT_PROVIDED = object() from collections.abc import AsyncIterator diff --git a/lib/sqlalchemy/util/deprecations.py b/lib/sqlalchemy/util/deprecations.py index e32ab9e0d0..dd5851cb3c 100644 --- a/lib/sqlalchemy/util/deprecations.py +++ b/lib/sqlalchemy/util/deprecations.py @@ -226,7 +226,6 @@ def deprecated_params(**specs: Tuple[str, str]) -> Callable[[_F], _F]: check_defaults: Union[Set[str], Tuple[()]] if spec.defaults is not None: - defaults = dict( zip( spec.args[(len(spec.args) - len(spec.defaults)) :], @@ -236,7 +235,6 @@ def deprecated_params(**specs: Tuple[str, str]) -> Callable[[_F], _F]: check_defaults = set(defaults).intersection(messages) check_kw = set(messages).difference(defaults) elif spec.kwonlydefaults is not None: - defaults = spec.kwonlydefaults check_defaults = set(defaults).intersection(messages) check_kw = set(messages).difference(defaults) @@ -320,7 +318,6 @@ def _decorate_cls_with_warning( ) -> Type[_T]: doc = cls.__doc__ is not None and cls.__doc__ or "" if docstring_header is not None: - if constructor is not None: docstring_header %= dict(func=constructor) diff --git a/lib/sqlalchemy/util/langhelpers.py b/lib/sqlalchemy/util/langhelpers.py index 903d8bdeb4..8314a36fc5 100644 --- a/lib/sqlalchemy/util/langhelpers.py +++ b/lib/sqlalchemy/util/langhelpers.py @@ -1161,7 +1161,6 @@ class _memoized_property(generic_fn_descriptor[_T_co]): # additional issues, RO properties: # https://github.com/python/mypy/issues/12440 if TYPE_CHECKING: - # allow memoized and non-memoized to be freely mixed by having them # be the same class memoized_property = generic_fn_descriptor @@ -1850,7 +1849,6 @@ def _warnings_warn( category: Optional[Type[Warning]] = None, stacklevel: int = 2, ) -> None: - # adjust the given stacklevel to be outside of SQLAlchemy try: frame = sys._getframe(stacklevel) diff --git a/lib/sqlalchemy/util/topological.py b/lib/sqlalchemy/util/topological.py index 35b7573cb2..8c6a663f60 100644 --- a/lib/sqlalchemy/util/topological.py +++ b/lib/sqlalchemy/util/topological.py @@ -30,7 +30,6 @@ __all__ = ["sort", "sort_as_subsets", "find_cycles"] def sort_as_subsets( tuples: Collection[Tuple[_T, _T]], allitems: Collection[_T] ) -> Iterator[Sequence[_T]]: - edges: DefaultDict[_T, Set[_T]] = util.defaultdict(set) for parent, child in tuples: edges[child].add(parent) diff --git a/lib/sqlalchemy/util/typing.py b/lib/sqlalchemy/util/typing.py index 3ac67aad9a..597549ce77 100644 --- a/lib/sqlalchemy/util/typing.py +++ b/lib/sqlalchemy/util/typing.py @@ -162,7 +162,6 @@ def de_stringify_annotation( and is_generic(annotation) and not is_literal(annotation) ): - if _already_seen is None: _already_seen = set() diff --git a/setup.py b/setup.py index e301cdb29b..ad4e4002db 100644 --- a/setup.py +++ b/setup.py @@ -63,7 +63,6 @@ if HAS_CYTHON and IS_CPYTHON and not DISABLE_EXTENSION: cmdclass = {"build_ext": _cy_build_ext} elif REQUIRE_EXTENSION: - reasons = [] if not HAS_CYTHON: reasons.append("Cython is missing") diff --git a/test/aaa_profiling/test_compiler.py b/test/aaa_profiling/test_compiler.py index 5db422fd52..dced8dee06 100644 --- a/test/aaa_profiling/test_compiler.py +++ b/test/aaa_profiling/test_compiler.py @@ -20,7 +20,6 @@ class CompileTest(fixtures.TestBase, AssertsExecutionResults): @classmethod def setup_test_class(cls): - global t1, t2, metadata metadata = MetaData() t1 = Table( diff --git a/test/aaa_profiling/test_misc.py b/test/aaa_profiling/test_misc.py index a0f56ef25a..c51648c677 100644 --- a/test/aaa_profiling/test_misc.py +++ b/test/aaa_profiling/test_misc.py @@ -265,7 +265,6 @@ class CCLookupTest(fixtures.RemoveORMEventsGlobally, fixtures.TestBase): ("require_embedded",), ("no_embedded",), argnames="require_embedded" ) def test_corresponding_column_isolated(self, t1, require_embedded): - subq = select(t1).union_all(select(t1)).subquery() target = subq.c.x7 @@ -292,7 +291,6 @@ class CCLookupTest(fixtures.RemoveORMEventsGlobally, fixtures.TestBase): def test_gen_subq_to_table_single_corresponding_column( self, t1, require_embedded ): - src = t1.c.x7 require_embedded = require_embedded == "require_embedded" @@ -317,7 +315,6 @@ class CCLookupTest(fixtures.RemoveORMEventsGlobally, fixtures.TestBase): def test_gen_subq_to_table_many_corresponding_column( self, t1, require_embedded ): - require_embedded = require_embedded == "require_embedded" @profiling.function_call_count(variance=0.15, warmup=1) @@ -325,7 +322,6 @@ class CCLookupTest(fixtures.RemoveORMEventsGlobally, fixtures.TestBase): subq = select(t1).union_all(select(t1)).subquery() for name in ("x%d" % i for i in range(1, 10)): - target = subq.c[name] src = t1.c[name] @@ -344,14 +340,12 @@ class CCLookupTest(fixtures.RemoveORMEventsGlobally, fixtures.TestBase): def test_gen_subq_aliased_class_select( self, t1, require_embedded, inheritance_model ): - A = inheritance_model require_embedded = require_embedded == "require_embedded" @profiling.function_call_count(variance=0.15, warmup=1) def go(): - a1a1 = aliased(A) a1a2 = aliased(A) subq = select(a1a1).union_all(select(a1a2)).subquery() @@ -368,14 +362,12 @@ class CCLookupTest(fixtures.RemoveORMEventsGlobally, fixtures.TestBase): def test_gen_subq_aliased_class_select_cols( self, t1, require_embedded, inheritance_model ): - A = inheritance_model require_embedded = require_embedded == "require_embedded" @profiling.function_call_count(variance=0.15, warmup=1) def go(): - a1a1 = aliased(A) a1a2 = aliased(A) subq = select(a1a1).union_all(select(a1a2)).subquery() diff --git a/test/aaa_profiling/test_orm.py b/test/aaa_profiling/test_orm.py index a2d98fd53d..3a5a200d80 100644 --- a/test/aaa_profiling/test_orm.py +++ b/test/aaa_profiling/test_orm.py @@ -625,7 +625,6 @@ class SelectInEagerLoadTest(NoCache, fixtures.MappedTest): @classmethod def define_tables(cls, metadata): - Table( "a", metadata, diff --git a/test/base/test_concurrency_py3k.py b/test/base/test_concurrency_py3k.py index 17a0fafb5a..b4fb34d025 100644 --- a/test/base/test_concurrency_py3k.py +++ b/test/base/test_concurrency_py3k.py @@ -38,7 +38,6 @@ class TestAsyncioCompat(fixtures.TestBase): @async_test async def test_ok(self): - eq_(await greenlet_spawn(go, run1, run2), 3) @async_test diff --git a/test/base/test_dependency.py b/test/base/test_dependency.py index ac95d7ab3c..5dcae9fbf8 100644 --- a/test/base/test_dependency.py +++ b/test/base/test_dependency.py @@ -136,7 +136,6 @@ class DependencySortTest(fixtures.TestBase): ) def test_raise_on_cycle_two(self): - # this condition was arising from ticket:362 and was not treated # properly by topological sort @@ -201,7 +200,6 @@ class DependencySortTest(fixtures.TestBase): self.assert_sort(tuples) def test_ticket_1380(self): - # ticket:1380 regression: would raise a KeyError tuples = [(id(i), i) for i in range(3)] diff --git a/test/base/test_events.py b/test/base/test_events.py index 67933a5fe0..6f8456274f 100644 --- a/test/base/test_events.py +++ b/test/base/test_events.py @@ -227,7 +227,6 @@ class EventsTest(TearDownLocalEventsFixture, fixtures.TestBase): pass class E2(event.Events): - _dispatch_target = T2 def event_four(self, x): diff --git a/test/base/test_result.py b/test/base/test_result.py index 83017c1652..b3f519bbef 100644 --- a/test/base/test_result.py +++ b/test/base/test_result.py @@ -182,7 +182,6 @@ class ResultTupleTest(fixtures.TestBase): assert_raises(TypeError, should_raise) def test_serialize(self): - keyed_tuple = self._fixture([1, 2, 3], ["a", None, "b"]) for loads, dumps in picklers(): @@ -270,7 +269,6 @@ class ResultTest(fixtures.TestBase): default_filters=None, data=None, ): - if data is None: data = [(1, 1, 1), (2, 1, 2), (1, 3, 2), (4, 1, 2)] if num_rows is not None: @@ -958,7 +956,6 @@ class ResultTest(fixtures.TestBase): class MergeResultTest(fixtures.TestBase): @testing.fixture def merge_fixture(self): - r1 = result.IteratorResult( result.SimpleResultMetaData(["user_id", "user_name"]), iter([(7, "u1"), (8, "u2")]), @@ -980,7 +977,6 @@ class MergeResultTest(fixtures.TestBase): @testing.fixture def dupe_fixture(self): - r1 = result.IteratorResult( result.SimpleResultMetaData(["x", "y", "z"]), iter([(1, 2, 1), (2, 2, 1)]), diff --git a/test/base/test_utils.py b/test/base/test_utils.py index d77e1b0ae8..91b58d1718 100644 --- a/test/base/test_utils.py +++ b/test/base/test_utils.py @@ -682,7 +682,6 @@ class ToListTest(fixtures.TestBase): eq_(util.to_list((1, 2, 3)), [1, 2, 3]) def test_from_bytes(self): - eq_(util.to_list(compat.b("abc")), [compat.b("abc")]) eq_( @@ -891,7 +890,6 @@ class ColumnCollectionTest(ColumnCollectionCommon, fixtures.TestBase): assert "kcol2" in cc def test_dupes_add(self): - c1, c2a, c3, c2b = ( column("c1"), column("c2"), @@ -925,7 +923,6 @@ class ColumnCollectionTest(ColumnCollectionCommon, fixtures.TestBase): eq_(ci.keys(), ["c1", "c2", "c3", "c2"]) def test_dupes_construct(self): - c1, c2a, c3, c2b = ( column("c1"), column("c2"), @@ -956,7 +953,6 @@ class ColumnCollectionTest(ColumnCollectionCommon, fixtures.TestBase): eq_(ci.keys(), ["c1", "c2", "c3", "c2"]) def test_identical_dupe_construct(self): - c1, c2, c3 = (column("c1"), column("c2"), column("c3")) cc = sql.ColumnCollection( @@ -1069,7 +1065,6 @@ class DedupeColumnCollectionTest(ColumnCollectionCommon, fixtures.TestBase): self._assert_collection_integrity(cc) def test_dupes_construct_dedupe(self): - c1, c2a, c3, c2b = ( column("c1"), column("c2"), @@ -1114,7 +1109,6 @@ class DedupeColumnCollectionTest(ColumnCollectionCommon, fixtures.TestBase): eq_(list(ci), [c1, c2, c3]) def test_identical_dupe_construct_dedupes(self): - c1, c2, c3 = (column("c1"), column("c2"), column("c3")) cc = DedupeColumnCollection( @@ -1304,7 +1298,6 @@ class DedupeColumnCollectionTest(ColumnCollectionCommon, fixtures.TestBase): self._assert_collection_integrity(cc) def test_remove(self): - c1, c2, c3 = column("c1"), column("c2"), column("c3") cc = DedupeColumnCollection( @@ -1342,7 +1335,6 @@ class DedupeColumnCollectionTest(ColumnCollectionCommon, fixtures.TestBase): assert_raises(IndexError, lambda: ci[2]) def test_remove_doesnt_change_iteration(self): - c1, c2, c3, c4, c5 = ( column("c1"), column("c2"), @@ -2924,7 +2916,6 @@ class TestFormatArgspec(_Py3KFixtures, fixtures.TestBase): argnames="fn,wanted,grouped", ) def test_specs(self, fn, wanted, grouped): - # test direct function if grouped is None: parsed = util.format_argspec_plus(fn) diff --git a/test/dialect/mssql/test_deprecations.py b/test/dialect/mssql/test_deprecations.py index 019712376b..21550e405f 100644 --- a/test/dialect/mssql/test_deprecations.py +++ b/test/dialect/mssql/test_deprecations.py @@ -207,7 +207,6 @@ class LegacySchemaAliasingBackendTest( ) with eng.begin() as conn: - tbl.create(conn) conn.execute(tbl.insert(), {"id": 1}) eq_(conn.scalar(tbl.select()), 1) diff --git a/test/dialect/mssql/test_engine.py b/test/dialect/mssql/test_engine.py index 799452adea..e87b9825f1 100644 --- a/test/dialect/mssql/test_engine.py +++ b/test/dialect/mssql/test_engine.py @@ -534,7 +534,6 @@ class FastExecutemanyTest(fixtures.TestBase): ) with engine.begin() as conn: - if expect_failure: with expect_raises(DBAPIError): conn.execute(observations.insert(), records) diff --git a/test/dialect/mssql/test_query.py b/test/dialect/mssql/test_query.py index 35575bc13a..b68b21339e 100644 --- a/test/dialect/mssql/test_query.py +++ b/test/dialect/mssql/test_query.py @@ -136,7 +136,6 @@ class IdentityInsertTest(fixtures.TablesTest, AssertsCompiledSQL): @testing.requires.schemas def test_insert_using_schema_translate(self, connection, metadata): - t = Table( "t", metadata, @@ -411,7 +410,6 @@ def full_text_search_missing(): class MatchTest(AssertsCompiledSQL, fixtures.TablesTest): - __only_on__ = "mssql" __skip_if__ = (full_text_search_missing,) __backend__ = True diff --git a/test/dialect/mssql/test_reflection.py b/test/dialect/mssql/test_reflection.py index d1cade7b08..e360568f77 100644 --- a/test/dialect/mssql/test_reflection.py +++ b/test/dialect/mssql/test_reflection.py @@ -104,7 +104,6 @@ class ReflectionTest(fixtures.TestBase, ComparesTables, AssertsCompiledSQL): argnames="type_obj,ddl", ) def test_assorted_types(self, metadata, connection, type_obj, ddl): - table = Table("type_test", metadata, Column("col1", type_obj)) table.create(connection) @@ -318,7 +317,6 @@ class ReflectionTest(fixtures.TestBase, ComparesTables, AssertsCompiledSQL): """test #6910""" with testing.db.connect() as c1, testing.db.connect() as c2: - try: with c1.begin(): c1.exec_driver_sql( @@ -535,7 +533,6 @@ class ReflectionTest(fixtures.TestBase, ComparesTables, AssertsCompiledSQL): ) def test_indexes_cols(self, metadata, connection): - t1 = Table("t", metadata, Column("x", Integer), Column("y", Integer)) Index("foo", t1.c.x, t1.c.y) metadata.create_all(connection) @@ -546,7 +543,6 @@ class ReflectionTest(fixtures.TestBase, ComparesTables, AssertsCompiledSQL): eq_(set(list(t2.indexes)[0].columns), {t2.c["x"], t2.c.y}) def test_indexes_cols_with_commas(self, metadata, connection): - t1 = Table( "t", metadata, @@ -562,7 +558,6 @@ class ReflectionTest(fixtures.TestBase, ComparesTables, AssertsCompiledSQL): eq_(set(list(t2.indexes)[0].columns), {t2.c["x, col"], t2.c.y}) def test_indexes_cols_with_spaces(self, metadata, connection): - t1 = Table( "t", metadata, @@ -578,7 +573,6 @@ class ReflectionTest(fixtures.TestBase, ComparesTables, AssertsCompiledSQL): eq_(set(list(t2.indexes)[0].columns), {t2.c["x col"], t2.c.y}) def test_indexes_with_filtered(self, metadata, connection): - t1 = Table( "t", metadata, @@ -1047,7 +1041,6 @@ class IdentityReflectionTest(fixtures.TablesTest): @classmethod def define_tables(cls, metadata): - for i, col in enumerate( [ Column( diff --git a/test/dialect/mssql/test_types.py b/test/dialect/mssql/test_types.py index 916d4252fc..2939c097c3 100644 --- a/test/dialect/mssql/test_types.py +++ b/test/dialect/mssql/test_types.py @@ -674,7 +674,6 @@ class TypeRoundTripTest( eq_(value, returned) def test_float(self, metadata, connection): - float_table = Table( "float_table", metadata, @@ -1365,7 +1364,6 @@ class StringRoundTripTest(fixtures.TestBase): use_returning, insertmany, ): - if datatype is NVARCHAR and length != "max" and length > 4000: return elif unicode_ and datatype not in (NVARCHAR, UnicodeText): diff --git a/test/dialect/mysql/test_compiler.py b/test/dialect/mysql/test_compiler.py index cd7205163a..15650f3c77 100644 --- a/test/dialect/mysql/test_compiler.py +++ b/test/dialect/mysql/test_compiler.py @@ -99,7 +99,6 @@ class ReservedWordFixture(AssertsCompiledSQL): try: yield table, expected_mysql, expected_mdb finally: - reserved_words.RESERVED_WORDS_MARIADB.discard("mdb_reserved") reserved_words.RESERVED_WORDS_MYSQL.discard("mysql_reserved") reserved_words.RESERVED_WORDS_MYSQL.discard("mdb_mysql_reserved") @@ -107,7 +106,6 @@ class ReservedWordFixture(AssertsCompiledSQL): class CompileTest(ReservedWordFixture, fixtures.TestBase, AssertsCompiledSQL): - __dialect__ = mysql.dialect() @testing.combinations( @@ -819,7 +817,6 @@ class SQLTest(fixtures.TestBase, AssertsCompiledSQL): (m.MSSet("1", "2"), "t.col"), ) def test_unsupported_casts(self, type_, expected): - t = sql.table("t", sql.column("col")) with expect_warnings( "Datatype .* does not support CAST on MySQL/MariaDb;" @@ -838,7 +835,6 @@ class SQLTest(fixtures.TestBase, AssertsCompiledSQL): ) @testing.combinations(True, False, argnames="maria_db") def test_float_cast(self, type_, expected, maria_db): - dialect = mysql.dialect() if maria_db: dialect.is_mariadb = maria_db @@ -1172,7 +1168,6 @@ class InsertOnDuplicateTest(fixtures.TestBase, AssertsCompiledSQL): ) dialect = None elif version.mysql8: - expected_sql = ( "INSERT INTO foos (id, bar) VALUES (%s, %s), (%s, %s) " "AS new ON DUPLICATE KEY UPDATE bar = " @@ -1363,7 +1358,6 @@ class RegexpTestMariaDb(fixtures.TestBase, RegexpCommon): class MatchExpressionTest(fixtures.TestBase, AssertsCompiledSQL): - __dialect__ = mysql.dialect() match_table = table( diff --git a/test/dialect/mysql/test_deprecations.py b/test/dialect/mysql/test_deprecations.py index e66037d90a..78f66c1288 100644 --- a/test/dialect/mysql/test_deprecations.py +++ b/test/dialect/mysql/test_deprecations.py @@ -7,7 +7,6 @@ from sqlalchemy.testing import fixtures class CompileTest(AssertsCompiledSQL, fixtures.TestBase): - __dialect__ = mysql.dialect() def test_distinct_string(self): diff --git a/test/dialect/mysql/test_dialect.py b/test/dialect/mysql/test_dialect.py index ed0fc6faca..c50755df41 100644 --- a/test/dialect/mysql/test_dialect.py +++ b/test/dialect/mysql/test_dialect.py @@ -82,7 +82,6 @@ class BackendDialectTest( ) def test_no_show_variables(self): - engine = engines.testing_engine() def my_execute(self, statement, *args, **kw): @@ -101,7 +100,6 @@ class BackendDialectTest( engine.connect() def test_no_default_isolation_level(self): - engine = engines.testing_engine() real_isolation_level = testing.db.dialect.get_isolation_level @@ -346,7 +344,6 @@ class DialectTest(fixtures.TestBase): ("utf8",), ) def test_special_encodings(self, enc): - eng = engines.testing_engine( options={"connect_args": {"charset": enc, "use_unicode": 0}} ) @@ -360,7 +357,6 @@ class DialectTest(fixtures.TestBase): @testing.only_on("mariadb+mariadbconnector") def test_mariadb_connector_special_encodings(self): - eng = engines.testing_engine() conn = eng.connect() diff --git a/test/dialect/mysql/test_reflection.py b/test/dialect/mysql/test_reflection.py index a75c05f094..e5e35c9504 100644 --- a/test/dialect/mysql/test_reflection.py +++ b/test/dialect/mysql/test_reflection.py @@ -238,14 +238,12 @@ class TypeReflectionTest(fixtures.TestBase): metadata, connection, ): - specs = [(mysql.ENUM("", "fleem"), mysql.ENUM("", "fleem"))] self._run_test(metadata, connection, specs, ["enums"]) class ReflectionTest(fixtures.TestBase, AssertsCompiledSQL): - __only_on__ = "mysql", "mariadb" __backend__ = True @@ -432,7 +430,6 @@ class ReflectionTest(fixtures.TestBase, AssertsCompiledSQL): eq_(ref_kw["partitions"], "6") def test_reflection_with_subpartition_options(self, connection, metadata): - subpartititon_text = """HASH (TO_DAYS (c2)) SUBPARTITIONS 2( PARTITION p0 VALUES LESS THAN (1990), diff --git a/test/dialect/mysql/test_types.py b/test/dialect/mysql/test_types.py index 989d50d494..af68a24c5a 100644 --- a/test/dialect/mysql/test_types.py +++ b/test/dialect/mysql/test_types.py @@ -464,7 +464,6 @@ class TypeCompileTest(fixtures.TestBase, AssertsCompiledSQL): class TypeRoundTripTest(fixtures.TestBase, AssertsExecutionResults): - __dialect__ = mysql.dialect() __only_on__ = "mysql", "mariadb" __backend__ = True @@ -552,7 +551,6 @@ class TypeRoundTripTest(fixtures.TestBase, AssertsExecutionResults): argnames="store, expected", ) def test_bit_50_roundtrip(self, connection, bit_table, store, expected): - reflected = Table("mysql_bits", MetaData(), autoload_with=connection) expected = expected or store @@ -747,7 +745,6 @@ class JSONTest(fixtures.TestBase): @testing.requires.reflects_json_type def test_reflection(self, metadata, connection): - Table("mysql_json", metadata, Column("foo", mysql.JSON)) metadata.create_all(connection) @@ -772,7 +769,6 @@ class JSONTest(fixtures.TestBase): class EnumSetTest( fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL ): - __only_on__ = "mysql", "mariadb" __dialect__ = mysql.dialect() __backend__ = True @@ -1216,7 +1212,6 @@ class EnumSetTest( ) def test_enum_parse(self, metadata, connection): - enum_table = Table( "mysql_enum", metadata, diff --git a/test/dialect/oracle/test_dialect.py b/test/dialect/oracle/test_dialect.py index 4587fe6c09..ae4f6fe9d4 100644 --- a/test/dialect/oracle/test_dialect.py +++ b/test/dialect/oracle/test_dialect.py @@ -173,7 +173,6 @@ class DialectWBackendTest(fixtures.TestBase): ) @testing.only_on(["oracle+cx_oracle", "oracle+oracledb"]) def test_is_disconnect(self, message, code, expected): - dialect = testing.db.dialect exception_obj = dialect.dbapi.InterfaceError() @@ -267,7 +266,6 @@ class DefaultSchemaNameTest(fixtures.TestBase): eng = engines.testing_engine() with eng.connect() as conn: - trans = conn.begin() eq_( testing.db.dialect._get_default_schema_name(conn), @@ -359,7 +357,6 @@ class EncodingErrorsTest(fixtures.TestBase): utf8_w_errors = data.encode("utf-16") if has_errorhandler: - eq_( outconverter(utf8_w_errors), data.encode("utf-16").decode("utf-8", "ignore"), @@ -551,7 +548,6 @@ end; class QuotedBindRoundTripTest(fixtures.TestBase): - __only_on__ = "oracle" __backend__ = True @@ -839,7 +835,6 @@ class CompatFlagsTest(fixtures.TestBase, AssertsCompiledSQL): class ExecuteTest(fixtures.TestBase): - __only_on__ = "oracle" __backend__ = True diff --git a/test/dialect/oracle/test_reflection.py b/test/dialect/oracle/test_reflection.py index 6c6f1f21f7..35af2f573a 100644 --- a/test/dialect/oracle/test_reflection.py +++ b/test/dialect/oracle/test_reflection.py @@ -348,7 +348,6 @@ class MultiSchemaTest(fixtures.TestBase, AssertsCompiledSQL): class ConstraintTest(AssertsCompiledSQL, fixtures.TestBase): - __only_on__ = "oracle" __backend__ = True @@ -361,7 +360,6 @@ class ConstraintTest(AssertsCompiledSQL, fixtures.TestBase): def test_oracle_has_no_on_update_cascade( self, metadata, connection, plain_foo_table ): - bar = Table( "bar", metadata, @@ -384,7 +382,6 @@ class ConstraintTest(AssertsCompiledSQL, fixtures.TestBase): def test_reflect_check_include_all( self, metadata, connection, plain_foo_table ): - insp = inspect(connection) eq_(insp.get_check_constraints("foo"), []) eq_( @@ -545,7 +542,6 @@ class SystemTableTablenamesTest(fixtures.TestBase): __backend__ = True def setup_test(self): - with testing.db.begin() as conn: conn.exec_driver_sql("create table my_table (id integer)") conn.exec_driver_sql( @@ -649,7 +645,6 @@ class TableReflectionTest(fixtures.TestBase): @testing.fails_if(all_tables_compression_missing) def test_reflect_basic_compression(self, metadata, connection): - tbl = Table( "test_compress", metadata, @@ -940,7 +935,6 @@ class RoundTripIndexTest(fixtures.TestBase): def test_include_indexes_resembling_pk( self, metadata, connection, explicit_pk ): - t = Table( "sometable", metadata, @@ -1086,7 +1080,6 @@ class RoundTripIndexTest(fixtures.TestBase): eq_(inspect(connection).get_indexes("sometable"), expected) def test_basic(self, metadata, connection): - s_table = Table( "sometable", metadata, diff --git a/test/dialect/oracle/test_types.py b/test/dialect/oracle/test_types.py index e77bde19e9..55fe368656 100644 --- a/test/dialect/oracle/test_types.py +++ b/test/dialect/oracle/test_types.py @@ -861,7 +861,6 @@ class TypesTest(fixtures.TestBase): eq_(t2.c.c4.type.length, 180) def test_long_type(self, metadata, connection): - t = Table("t", metadata, Column("data", oracle.LONG)) metadata.create_all(connection) connection.execute(t.insert(), dict(data="xyz")) diff --git a/test/dialect/postgresql/test_async_pg_py3k.py b/test/dialect/postgresql/test_async_pg_py3k.py index 49014fcaf9..ed3d63d833 100644 --- a/test/dialect/postgresql/test_async_pg_py3k.py +++ b/test/dialect/postgresql/test_async_pg_py3k.py @@ -77,7 +77,6 @@ class AsyncPgTest(fixtures.TestBase): r"will now invalidate all prepared caches in response " r"to this exception\)", ): - result = await conn.execute( t1.select() .where(t1.c.name.like("some name%")) @@ -168,7 +167,6 @@ class AsyncPgTest(fixtures.TestBase): @async_test async def test_failed_commit_recover(self, metadata, async_testing_engine): - Table("t1", metadata, Column("id", Integer, primary_key=True)) t2 = Table( @@ -202,11 +200,9 @@ class AsyncPgTest(fixtures.TestBase): async def test_rollback_twice_no_problem( self, metadata, async_testing_engine ): - engine = async_testing_engine() async with engine.connect() as conn: - trans = await conn.begin() await trans.rollback() @@ -215,7 +211,6 @@ class AsyncPgTest(fixtures.TestBase): @async_test async def test_closed_during_execute(self, metadata, async_testing_engine): - engine = async_testing_engine() async with engine.connect() as conn: @@ -232,7 +227,6 @@ class AsyncPgTest(fixtures.TestBase): async def test_failed_rollback_recover( self, metadata, async_testing_engine ): - engine = async_testing_engine() async with engine.connect() as conn: diff --git a/test/dialect/postgresql/test_compiler.py b/test/dialect/postgresql/test_compiler.py index 25b02ade9b..2f57c69315 100644 --- a/test/dialect/postgresql/test_compiler.py +++ b/test/dialect/postgresql/test_compiler.py @@ -109,7 +109,6 @@ class SequenceTest(fixtures.TestBase, AssertsCompiledSQL): class CompileTest(fixtures.TestBase, AssertsCompiledSQL): - __dialect__ = postgresql.dialect() def test_plain_stringify_returning(self): @@ -644,7 +643,6 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_create_index_with_ops(self): - m = MetaData() tbl = Table( "testtbl", @@ -2094,26 +2092,22 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_pg_array_agg_implicit_pg_array(self): - expr = pg_array_agg(column("data", Integer)) assert isinstance(expr.type, PG_ARRAY) is_(expr.type.item_type._type_affinity, Integer) def test_pg_array_agg_uses_base_array(self): - expr = pg_array_agg(column("data", sqltypes.ARRAY(Integer))) assert isinstance(expr.type, sqltypes.ARRAY) assert not isinstance(expr.type, PG_ARRAY) is_(expr.type.item_type._type_affinity, Integer) def test_pg_array_agg_uses_pg_array(self): - expr = pg_array_agg(column("data", PG_ARRAY(Integer))) assert isinstance(expr.type, PG_ARRAY) is_(expr.type.item_type._type_affinity, Integer) def test_pg_array_agg_explicit_base_array(self): - expr = pg_array_agg( column("data", sqltypes.ARRAY(Integer)), type_=sqltypes.ARRAY(Integer), @@ -2123,7 +2117,6 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL): is_(expr.type.item_type._type_affinity, Integer) def test_pg_array_agg_explicit_pg_array(self): - expr = pg_array_agg( column("data", sqltypes.ARRAY(Integer)), type_=PG_ARRAY(Integer) ) @@ -2605,7 +2598,6 @@ class InsertOnConflictTest(fixtures.TablesTest, AssertsCompiledSQL): stmt.on_conflict_do_nothing, stmt.on_conflict_do_update, ): - with testing.expect_raises_message( exc.InvalidRequestError, "This Insert construct already has an " @@ -2636,7 +2628,6 @@ class InsertOnConflictTest(fixtures.TablesTest, AssertsCompiledSQL): ) def test_do_nothing_no_target(self): - i = ( insert(self.table1) .values(dict(name="foo")) @@ -2649,7 +2640,6 @@ class InsertOnConflictTest(fixtures.TablesTest, AssertsCompiledSQL): ) def test_do_nothing_index_elements_target(self): - i = ( insert(self.table1) .values(dict(name="foo")) @@ -3209,7 +3199,6 @@ class DistinctOnTest(fixtures.MappedTest, AssertsCompiledSQL): ) def test_distinct_on_subquery_anon(self): - sq = select(self.table).alias() q = ( select(self.table.c.id, sq.c.id) diff --git a/test/dialect/postgresql/test_dialect.py b/test/dialect/postgresql/test_dialect.py index 78f561a352..08a1cd8f6b 100644 --- a/test/dialect/postgresql/test_dialect.py +++ b/test/dialect/postgresql/test_dialect.py @@ -138,7 +138,6 @@ class DialectTest(fixtures.TestBase): def test_ensure_version_is_qualified( self, future_connection, testing_engine, metadata ): - default_schema_name = future_connection.dialect.default_schema_name event.listen( metadata, @@ -570,7 +569,6 @@ class ExecutemanyFlagOptionsTest(fixtures.TablesTest): class MiscBackendTest( fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL ): - __only_on__ = "postgresql" __backend__ = True @@ -637,13 +635,11 @@ class MiscBackendTest( with testing.db.connect().execution_options( isolation_level="SERIALIZABLE" ) as conn: - dbapi_conn = conn.connection.dbapi_connection is_false(dbapi_conn.autocommit) with conn.begin(): - existing_isolation = conn.exec_driver_sql( "show transaction isolation level" ).scalar() @@ -665,7 +661,6 @@ class MiscBackendTest( dbapi_conn.autocommit = False with conn.begin(): - existing_isolation = conn.exec_driver_sql( "show transaction isolation level" ).scalar() diff --git a/test/dialect/postgresql/test_on_conflict.py b/test/dialect/postgresql/test_on_conflict.py index 8ef0f158ef..a9320f2c50 100644 --- a/test/dialect/postgresql/test_on_conflict.py +++ b/test/dialect/postgresql/test_on_conflict.py @@ -15,7 +15,6 @@ from sqlalchemy.testing.assertions import eq_ class OnConflictTest(fixtures.TablesTest): - __only_on__ = ("postgresql >= 9.5",) __backend__ = True run_define_tables = "each" diff --git a/test/dialect/postgresql/test_query.py b/test/dialect/postgresql/test_query.py index 8b8a800530..8d8d9a7ec9 100644 --- a/test/dialect/postgresql/test_query.py +++ b/test/dialect/postgresql/test_query.py @@ -53,7 +53,6 @@ class FunctionTypingTest(fixtures.TestBase, AssertsExecutionResults): class InsertTest(fixtures.TestBase, AssertsExecutionResults): - __only_on__ = "postgresql" __backend__ = True @@ -61,7 +60,6 @@ class InsertTest(fixtures.TestBase, AssertsExecutionResults): def test_foreignkey_missing_insert( self, metadata, connection, implicit_returning ): - Table( "t1", metadata, @@ -162,7 +160,6 @@ class InsertTest(fixtures.TestBase, AssertsExecutionResults): self._assert_data_noautoincrement(connection, table) def _ints_and_strs_setinputsizes(self, connection): - return ( connection.dialect._bind_typing_render_casts and String().dialect_impl(connection.dialect).render_bind_cast @@ -914,7 +911,6 @@ class InsertTest(fixtures.TestBase, AssertsExecutionResults): class MatchTest(fixtures.TablesTest, AssertsCompiledSQL): - __only_on__ = "postgresql >= 8.3" __backend__ = True @@ -969,7 +965,6 @@ class MatchTest(fixtures.TablesTest, AssertsCompiledSQL): ) def _strs_render_bind_casts(self, connection): - return ( connection.dialect._bind_typing_render_casts and String().dialect_impl(connection.dialect).render_bind_cast @@ -1214,7 +1209,6 @@ class TupleTest(fixtures.TestBase): __backend__ = True def test_tuple_containment(self, connection): - for test, exp in [ ([("a", "b")], True), ([("a", "c")], False), @@ -1292,7 +1286,6 @@ class ExtractTest(fixtures.TablesTest): @classmethod def insert_data(cls, connection): - connection.execute( cls.tables.t.insert(), { @@ -1550,7 +1543,6 @@ class TableValuedRoundTripTest(fixtures.TestBase): ) def test_table_valued(self, assets_transactions, connection): - jb = func.jsonb_each(assets_transactions.c.contents).table_valued( "key", "value" ) @@ -1625,13 +1617,11 @@ class TableValuedRoundTripTest(fixtures.TestBase): ) def test_function_against_row_constructor(self, connection): - stmt = select(func.row_to_json(func.row(1, "foo"))) eq_(connection.scalar(stmt), {"f1": 1, "f2": "foo"}) def test_with_ordinality_named(self, connection): - stmt = select( func.generate_series(4, 1, -1) .table_valued("gs", with_ordinality="ordinality") @@ -1641,7 +1631,6 @@ class TableValuedRoundTripTest(fixtures.TestBase): eq_(connection.execute(stmt).all(), [(4, 1), (3, 2), (2, 3), (1, 4)]) def test_with_ordinality_star(self, connection): - stmt = select("*").select_from( func.generate_series(4, 1, -1).table_valued( with_ordinality="ordinality" @@ -1663,7 +1652,6 @@ class TableValuedRoundTripTest(fixtures.TestBase): ) def test_unnest_with_ordinality(self, connection): - array_val = postgresql.array( [postgresql.array([14, 41, 7]), postgresql.array([54, 9, 49])] ) @@ -1679,7 +1667,6 @@ class TableValuedRoundTripTest(fixtures.TestBase): ) def test_unnest_with_ordinality_named(self, connection): - array_val = postgresql.array( [postgresql.array([14, 41, 7]), postgresql.array([54, 9, 49])] ) @@ -1718,7 +1705,6 @@ class TableValuedRoundTripTest(fixtures.TestBase): argnames="cast_fn", ) def test_render_derived_quoting_text(self, connection, cast_fn): - value = ( '[{"CaseSensitive":1,"the % value":"foo"}, ' '{"CaseSensitive":"2","the % value":"bar"}]' @@ -1755,7 +1741,6 @@ class TableValuedRoundTripTest(fixtures.TestBase): argnames="cast_fn", ) def test_render_derived_quoting_text_to_json(self, connection, cast_fn): - value = ( '[{"CaseSensitive":1,"the % value":"foo"}, ' '{"CaseSensitive":"2","the % value":"bar"}]' diff --git a/test/dialect/postgresql/test_reflection.py b/test/dialect/postgresql/test_reflection.py index eacb4b1491..49838ec6ab 100644 --- a/test/dialect/postgresql/test_reflection.py +++ b/test/dialect/postgresql/test_reflection.py @@ -821,7 +821,6 @@ class ReflectionTest( assert inspect(connection).has_table("some_temp_table") def test_cross_schema_reflection_one(self, metadata, connection): - meta1 = metadata users = Table( @@ -1127,7 +1126,6 @@ class ReflectionTest( ) def test_uppercase_lowercase_table(self, metadata, connection): - a_table = Table("a", metadata, Column("x", Integer)) A_table = Table("A", metadata, Column("x", Integer)) @@ -1138,7 +1136,6 @@ class ReflectionTest( assert inspect(connection).has_table("A") def test_uppercase_lowercase_sequence(self, connection): - a_seq = Sequence("a") A_seq = Sequence("A") @@ -1634,7 +1631,6 @@ class ReflectionTest( is_false(inspector.has_type("mood")) def test_inspect_enums(self, metadata, inspect_fixture): - inspector, conn = inspect_fixture enum_type = postgresql.ENUM( @@ -1698,7 +1694,6 @@ class ReflectionTest( for enum in "lower_case", "UpperCase", "Name.With.Dot": for schema in None, "test_schema", "TestSchema": - postgresql.ENUM( "CapsOne", "CapsTwo", @@ -1753,7 +1748,6 @@ class ReflectionTest( counter = itertools.count() for enum in "lower_case", "UpperCase", "Name.With.Dot": for schema in None, "test_schema", "TestSchema": - enum_type = postgresql.ENUM( "CapsOne", "CapsTwo", diff --git a/test/dialect/postgresql/test_types.py b/test/dialect/postgresql/test_types.py index ca1b35a76a..b813885337 100644 --- a/test/dialect/postgresql/test_types.py +++ b/test/dialect/postgresql/test_types.py @@ -487,7 +487,6 @@ class NamedTypeTest( ], ) elif datatype == "domain": - def_schame = testing.config.db.dialect.default_schema_name eq_( inspect(connection).get_domains(schema=assert_schema), @@ -604,7 +603,6 @@ class NamedTypeTest( argnames="datatype", ) def test_name_required(self, metadata, connection, datatype): - assert_raises(exc.CompileError, datatype.create, connection) assert_raises( exc.CompileError, datatype.compile, dialect=connection.dialect @@ -890,7 +888,6 @@ class NamedTypeTest( ] def test_generate_multiple_on_metadata(self, connection, metadata): - e1 = Enum("one", "two", "three", name="myenum", metadata=metadata) t1 = Table("e1", metadata, Column("c1", e1)) @@ -911,7 +908,6 @@ class NamedTypeTest( def test_generate_multiple_schemaname_on_metadata( self, metadata, connection ): - Enum("one", "two", "three", name="myenum", metadata=metadata) Enum( "one", @@ -938,7 +934,6 @@ class NamedTypeTest( ] def test_create_drop_schema_translate_map(self, connection): - conn = connection.execution_options( schema_translate_map={None: testing.config.test_schema} ) @@ -1353,7 +1348,6 @@ class NumericInterpretationTest(fixtures.TestBase): __backend__ = True def test_numeric_codes(self): - dialects = ( pg8000.dialect(), psycopg2.dialect(), @@ -1470,7 +1464,6 @@ class TimezoneTest(fixtures.TablesTest): assert row[0] >= somedate def test_without_timezone(self, connection): - # get a date without a tzinfo tztable, notztable = self.tables("tztable", "notztable") @@ -1520,7 +1513,6 @@ class TimePrecisionCompileTest(fixtures.TestBase, AssertsCompiledSQL): class TimePrecisionTest(fixtures.TestBase): - __only_on__ = "postgresql" __backend__ = True @@ -1875,7 +1867,6 @@ class ArrayTest(AssertsCompiledSQL, fixtures.TestBase): argnames="with_enum, using_aggregate_order_by", ) def test_array_agg_specific(self, with_enum, using_aggregate_order_by): - element = ENUM(name="pgenum") if with_enum else Integer() element_type = type(element) expr = ( @@ -1898,7 +1889,6 @@ AnEnum("Baz", 3) class ArrayRoundTripTest: - __only_on__ = "postgresql" __backend__ = True @@ -2334,7 +2324,6 @@ class ArrayRoundTripTest: ) def test_tuple_flag(self, connection, metadata): - t1 = Table( "t1", metadata, @@ -2721,7 +2710,6 @@ class ArrayRoundTripTest: class CoreArrayRoundTripTest( ArrayRoundTripTest, fixtures.TablesTest, AssertsExecutionResults ): - ARRAY = sqltypes.ARRAY @@ -3192,7 +3180,6 @@ class SpecialTypesTest(fixtures.TablesTest, ComparesTables): @testing.metadata_fixture() def special_types_table(self, metadata): - # create these types so that we can issue # special SQL92 INTERVAL syntax class y2m(types.UserDefinedType, postgresql.INTERVAL): @@ -3382,7 +3369,6 @@ class HStoreTest(AssertsCompiledSQL, fixtures.TestBase): ) def test_bind_serialize_default(self): - dialect = postgresql.dialect(use_native_hstore=False) proc = self.test_table.c.hash.type._cached_bind_processor(dialect) eq_( @@ -4722,7 +4708,6 @@ class _RangeTypeRoundTrip(_RangeComparisonFixtures, fixtures.TablesTest): class _Int4RangeTests: - _col_type = INT4RANGE _col_str = "INT4RANGE" _col_str_arr = "INT8RANGE" @@ -4743,7 +4728,6 @@ class _Int4RangeTests: class _Int8RangeTests: - _col_type = INT8RANGE _col_str = "INT8RANGE" @@ -4763,7 +4747,6 @@ class _Int8RangeTests: class _NumRangeTests: - _col_type = NUMRANGE _col_str = "NUMRANGE" @@ -4783,7 +4766,6 @@ class _NumRangeTests: class _DateRangeTests: - _col_type = DATERANGE _col_str = "DATERANGE" @@ -4803,7 +4785,6 @@ class _DateRangeTests: class _DateTimeRangeTests: - _col_type = TSRANGE _col_str = "TSRANGE" @@ -4826,7 +4807,6 @@ class _DateTimeRangeTests: class _DateTimeTZRangeTests: - _col_type = TSTZRANGE _col_str = "TSTZRANGE" @@ -5208,7 +5188,6 @@ class _MultiRangeTypeRoundTrip(fixtures.TablesTest): class _Int4MultiRangeTests: - _col_type = INT4MULTIRANGE _col_str = "INT4MULTIRANGE" @@ -5224,7 +5203,6 @@ class _Int4MultiRangeTests: class _Int8MultiRangeTests: - _col_type = INT8MULTIRANGE _col_str = "INT8MULTIRANGE" @@ -5242,7 +5220,6 @@ class _Int8MultiRangeTests: class _NumMultiRangeTests: - _col_type = NUMMULTIRANGE _col_str = "NUMMULTIRANGE" @@ -5258,7 +5235,6 @@ class _NumMultiRangeTests: class _DateMultiRangeTests: - _col_type = DATEMULTIRANGE _col_str = "DATEMULTIRANGE" @@ -5273,7 +5249,6 @@ class _DateMultiRangeTests: class _DateTimeMultiRangeTests: - _col_type = TSMULTIRANGE _col_str = "TSMULTIRANGE" @@ -5297,7 +5272,6 @@ class _DateTimeMultiRangeTests: class _DateTimeTZMultiRangeTests: - _col_type = TSTZMULTIRANGE _col_str = "TSTZMULTIRANGE" @@ -5583,7 +5557,6 @@ class JSONRoundTripTest(fixtures.TablesTest): return self.tables.data_table def _fixture_data(self, connection): - data = [ {"name": "r1", "data": {"k1": "r1v1", "k2": "r1v2"}}, {"name": "r2", "data": {"k1": "r2v1", "k2": "r2v2"}}, diff --git a/test/dialect/test_sqlite.py b/test/dialect/test_sqlite.py index 0817bdbf36..d6e444bb30 100644 --- a/test/dialect/test_sqlite.py +++ b/test/dialect/test_sqlite.py @@ -68,7 +68,6 @@ def exec_sql(engine, sql, *args, **kwargs): class TestTypes(fixtures.TestBase, AssertsExecutionResults): - __only_on__ = "sqlite" __backend__ = True @@ -109,7 +108,7 @@ class TestTypes(fixtures.TestBase, AssertsExecutionResults): ) def test_cant_parse_datetime_message(self, connection): - for (typ, disp) in [ + for typ, disp in [ (Time, "time"), (DateTime, "datetime"), (Date, "date"), @@ -282,7 +281,6 @@ class TestTypes(fixtures.TestBase, AssertsExecutionResults): class JSONTest(fixtures.TestBase): - __requires__ = ("json_type",) __only_on__ = "sqlite" __backend__ = True @@ -441,12 +439,10 @@ class TimeTest(fixtures.TestBase, AssertsCompiledSQL): class DefaultsTest(fixtures.TestBase, AssertsCompiledSQL): - __only_on__ = "sqlite" __backend__ = True def test_default_reflection(self, connection, metadata): - specs = [ (String(3), '"foo"'), (sqltypes.NUMERIC(10, 2), "100.50"), @@ -474,7 +470,6 @@ class DefaultsTest(fixtures.TestBase, AssertsCompiledSQL): "table_info()", ) def test_default_reflection_2(self): - db = testing.db m = MetaData() expected = ["'my_default'", "0"] @@ -576,7 +571,6 @@ class DefaultsTest(fixtures.TestBase, AssertsCompiledSQL): class DialectTest( fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL ): - __only_on__ = "sqlite" __backend__ = True @@ -892,7 +886,6 @@ class AttachedDBTest(fixtures.TablesTest): eq_(len(c2.c), 2) def test_crud(self, connection): - (ct,) = self.tables("test_schema.created") connection.execute(ct.insert(), {"id": 1, "name": "foo"}) eq_(connection.execute(ct.select()).fetchall(), [(1, "foo")]) @@ -1039,7 +1032,6 @@ class SQLTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_column_defaults_ddl(self): - t = Table( "t", MetaData(), @@ -1154,7 +1146,6 @@ class SQLTest(fixtures.TestBase, AssertsCompiledSQL): class OnConflictDDLTest(fixtures.TestBase, AssertsCompiledSQL): - __dialect__ = sqlite.dialect() def test_on_conflict_clause_column_not_null(self): @@ -1208,7 +1199,6 @@ class OnConflictDDLTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_on_conflict_clause_unique_constraint(self): - meta = MetaData() t = Table( "n", @@ -1226,7 +1216,6 @@ class OnConflictDDLTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_on_conflict_clause_primary_key(self): - meta = MetaData() t = Table( "n", @@ -1248,7 +1237,6 @@ class OnConflictDDLTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_on_conflict_clause_primary_key_constraint_from_column(self): - meta = MetaData() t = Table( "n", @@ -1269,7 +1257,6 @@ class OnConflictDDLTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_on_conflict_clause_check_constraint(self): - meta = MetaData() t = Table( "n", @@ -1287,7 +1274,6 @@ class OnConflictDDLTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_on_conflict_clause_check_constraint_from_column(self): - meta = MetaData() t = Table( "n", @@ -1308,7 +1294,6 @@ class OnConflictDDLTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_on_conflict_clause_primary_key_constraint(self): - meta = MetaData() t = Table( "n", @@ -1499,7 +1484,6 @@ metadata = cattable = matchtable = None class MatchTest(fixtures.TestBase, AssertsCompiledSQL): - __only_on__ = "sqlite" __skip_if__ = (full_text_search_missing,) __backend__ = True @@ -1744,7 +1728,6 @@ class ConstraintReflectionTest(fixtures.TestBase): @classmethod def setup_test_class(cls): with testing.db.begin() as conn: - conn.exec_driver_sql("CREATE TABLE a1 (id INTEGER PRIMARY KEY)") conn.exec_driver_sql("CREATE TABLE a2 (id INTEGER PRIMARY KEY)") conn.exec_driver_sql( @@ -1933,7 +1916,6 @@ class ConstraintReflectionTest(fixtures.TestBase): @testing.fixture def temp_table_fixture(self, connection): - connection.exec_driver_sql( "CREATE TEMPORARY TABLE g " "(x INTEGER, CONSTRAINT foo_gx UNIQUE(x))" @@ -1983,7 +1965,6 @@ class ConstraintReflectionTest(fixtures.TestBase): with mock.patch.object( dialect, "_get_table_sql", _get_table_sql ): - fkeys = dialect.get_foreign_keys(None, "foo") eq_( fkeys, @@ -2401,7 +2382,6 @@ class ConstraintReflectionTest(fixtures.TestBase): def test_unique_constraint_named_broken_temp( self, connection, temp_table_fixture ): - inspector = inspect(connection) eq_( inspector.get_unique_constraints("g"), @@ -2598,7 +2578,6 @@ class SavepointTest(fixtures.TablesTest): class TypeReflectionTest(fixtures.TestBase): - __only_on__ = "sqlite" __backend__ = True @@ -2863,7 +2842,6 @@ class RegexpTest(fixtures.TestBase, testing.AssertsCompiledSQL): class OnConflictTest(AssertsCompiledSQL, fixtures.TablesTest): - __only_on__ = ("sqlite >= 3.24.0",) __backend__ = True @@ -2980,7 +2958,6 @@ class OnConflictTest(AssertsCompiledSQL, fixtures.TablesTest): stmt.on_conflict_do_nothing, stmt.on_conflict_do_update, ): - with testing.expect_raises_message( exc.InvalidRequestError, "This Insert construct already has an " @@ -3578,7 +3555,6 @@ class ReflectInternalSchemaTables(fixtures.TablesTest): eq_(res, ["sqlitetemptable"]) def test_get_temp_view_names(self, connection): - view = ( "CREATE TEMPORARY VIEW sqlitetempview AS " "SELECT * FROM sqliteatable" diff --git a/test/engine/test_ddlevents.py b/test/engine/test_ddlevents.py index 1fa17c889d..fd7e5a8172 100644 --- a/test/engine/test_ddlevents.py +++ b/test/engine/test_ddlevents.py @@ -464,7 +464,6 @@ class DDLEventHarness: class DDLEventWCreateHarness(DDLEventHarness): - requires_table_to_exist = True def test_straight_create_drop( @@ -779,7 +778,6 @@ class DDLExecutionTest(AssertsCompiledSQL, fixtures.TestBase): )[0] if ddl_if_type in ("callable", "callable_w_state"): - if ddl_if_type == "callable": check_state = None else: diff --git a/test/engine/test_execute.py b/test/engine/test_execute.py index 2c5f091b47..692a51b910 100644 --- a/test/engine/test_execute.py +++ b/test/engine/test_execute.py @@ -1283,7 +1283,6 @@ class SchemaTranslateTest(fixtures.TestBase, testing.AssertsExecutionResults): ) def test_ddl_hastable(self, plain_tables, connection): - map_ = { None: config.test_schema, "foo": config.test_schema, @@ -1465,7 +1464,6 @@ class SchemaTranslateTest(fixtures.TestBase, testing.AssertsExecutionResults): ) def test_via_engine(self, plain_tables, metadata): - with config.db.begin() as connection: metadata.create_all(connection) @@ -1876,7 +1874,6 @@ class EngineEventsTest(fixtures.TestBase): stmt = str(select(1).compile(dialect=e1.dialect)) with e1.connect() as conn: - result = conn.exec_driver_sql(stmt) eq_(result.scalar(), 1) @@ -2046,7 +2043,6 @@ class EngineEventsTest(fixtures.TestBase): @testing.emits_warning("The garbage collector is trying to clean up") def test_execute_events(self): - stmts = [] cursor_stmts = [] @@ -2954,7 +2950,6 @@ class HandleErrorTest(fixtures.TestBase): with patch.object( engine.dialect, "is_disconnect", Mock(return_value=orig_error) ): - with engine.connect() as c: try: c.exec_driver_sql("SELECT x FROM nonexistent") @@ -2994,7 +2989,6 @@ class HandleErrorTest(fixtures.TestBase): with patch.object( engine.dialect, "is_disconnect", Mock(return_value=orig_error) ): - with engine.connect() as c: target_crec = c.connection._connection_record try: @@ -3035,7 +3029,6 @@ class HandleErrorTest(fixtures.TestBase): assert_raises(MySpecialException, conn.get_isolation_level) def test_handle_error_not_on_connection(self, connection): - with expect_raises_message( tsa.exc.InvalidRequestError, r"The handle_error\(\) event hook as of SQLAlchemy 2.0 is " diff --git a/test/engine/test_parseconnect.py b/test/engine/test_parseconnect.py index 65cf6b5f1f..334b7aeb9c 100644 --- a/test/engine/test_parseconnect.py +++ b/test/engine/test_parseconnect.py @@ -692,7 +692,7 @@ class CreateEngineTest(fixtures.TestBase): dbapi = MockDBAPI( foober=12, lala=18, hoho={"this": "dict"}, fooz="somevalue" ) - for (value, expected) in [ + for value, expected in [ ("rollback", pool.reset_rollback), ("commit", pool.reset_commit), (None, pool.reset_none), diff --git a/test/engine/test_reconnect.py b/test/engine/test_reconnect.py index 8ff34da987..48c5af8df7 100644 --- a/test/engine/test_reconnect.py +++ b/test/engine/test_reconnect.py @@ -1048,7 +1048,6 @@ class RealPrePingEventHandlerTest(fixtures.TestBase): with mock.patch.object( engine.dialect.loaded_dbapi, "connect", mock_connect ): - # set up initial connection. pre_ping works on subsequent connects engine.connect().close() @@ -1166,7 +1165,6 @@ class RealReconnectTest(fixtures.TestBase): def test_reconnect(self): with self.engine.connect() as conn: - eq_(conn.execute(select(1)).scalar(), 1) assert not conn.closed diff --git a/test/engine/test_reflection.py b/test/engine/test_reflection.py index 1678e81439..003b457a51 100644 --- a/test/engine/test_reflection.py +++ b/test/engine/test_reflection.py @@ -1149,7 +1149,6 @@ class ReflectionTest(fixtures.TestBase, ComparesTables): @testing.crashes("oracle", "FIXME: unknown, confirm not fails_on") @testing.requires.check_constraints def test_reserved(self, connection, metadata): - # check a table that uses a SQL reserved name doesn't cause an # error @@ -1632,7 +1631,6 @@ class UnicodeReflectionTest(fixtures.TablesTest): @classmethod def define_tables(cls, metadata): - no_multibyte_period = {("plain", "col_plain", "ix_plain")} no_has_table = [ ( @@ -1720,7 +1718,6 @@ class UnicodeReflectionTest(fixtures.TablesTest): reflected = set(inspect(connection).get_table_names()) if not names.issubset(reflected) and hasattr(unicodedata, "normalize"): - # Python source files in the utf-8 coding seem to # normalize literals as NFC (and the above are # explicitly NFC). Maybe this database normalizes NFD @@ -1773,7 +1770,6 @@ class SchemaTest(fixtures.TestBase): @testing.requires.cross_schema_fk_reflection @testing.requires.implicit_default_schema def test_blank_schema_arg(self, connection, metadata): - Table( "some_table", metadata, @@ -1803,7 +1799,6 @@ class SchemaTest(fixtures.TestBase): @testing.requires.schemas def test_explicit_default_schema(self, connection, metadata): - schema = connection.dialect.default_schema_name assert bool(schema) @@ -2164,7 +2159,6 @@ class ColumnEventsTest(fixtures.RemovesEvents, fixtures.TablesTest): m = MetaData() def column_reflect(insp, table, column_info): - if column_info["name"] == "q": column_info["key"] = "qyz" elif column_info["name"] == "x": diff --git a/test/engine/test_transaction.py b/test/engine/test_transaction.py index 1b3c4c17ea..4ae87c4ad1 100644 --- a/test/engine/test_transaction.py +++ b/test/engine/test_transaction.py @@ -276,7 +276,6 @@ class TransactionTest(fixtures.TablesTest): savepoint = [None] def go(): - with connection.begin_nested() as sp: savepoint[0] = sp # force the "commit" of the savepoint that occurs @@ -614,7 +613,6 @@ class TransactionTest(fixtures.TablesTest): @testing.requires.autocommit def test_no_autocommit_w_begin(self): - with testing.db.begin() as conn: assert_raises_message( exc.InvalidRequestError, @@ -628,7 +626,6 @@ class TransactionTest(fixtures.TablesTest): @testing.requires.autocommit def test_no_autocommit_w_autobegin(self): - with testing.db.connect() as conn: conn.execute(select(1)) @@ -650,7 +647,6 @@ class TransactionTest(fixtures.TablesTest): users = self.tables.users with testing.db.connect() as conn: - assert not conn.in_transaction() conn.execute(users.insert(), {"user_id": 1, "user_name": "name"}) @@ -745,7 +741,6 @@ class TransactionTest(fixtures.TablesTest): def test_rollback_inactive(self): users = self.tables.users with testing.db.connect() as conn: - conn.execute(users.insert(), {"user_id": 1, "user_name": "name"}) conn.commit() @@ -1161,7 +1156,6 @@ class IsolationLevelTest(fixtures.TestBase): assert False, "no non-default isolation level available" def test_engine_param_stays(self): - eng = testing_engine() with eng.connect() as conn: isolation_level = eng.dialect.get_isolation_level( @@ -1480,11 +1474,9 @@ class ConnectionCharacteristicTest(fixtures.TestBase): transactional = True def reset_characteristic(self, dialect, dbapi_conn): - dialect.reset_foo(dbapi_conn) def set_characteristic(self, dialect, dbapi_conn, value): - dialect.set_foo(dbapi_conn, value) def get_characteristic(self, dialect, dbapi_conn): @@ -1515,7 +1507,6 @@ class ConnectionCharacteristicTest(fixtures.TestBase): return base.Engine(pool, FooDialect(), u), connection def test_engine_param_stays(self, characteristic_fixture): - engine, connection = characteristic_fixture foo_level = engine.dialect.get_foo(engine.connect().connection) @@ -1594,7 +1585,6 @@ class ConnectionCharacteristicTest(fixtures.TestBase): ) def test_per_engine(self, characteristic_fixture): - engine, connection = characteristic_fixture pool, dialect, url = engine.pool, engine.dialect, engine.url @@ -1607,7 +1597,6 @@ class ConnectionCharacteristicTest(fixtures.TestBase): eq_(eng.dialect.get_foo(conn.connection), "new_value") def test_per_option_engine(self, characteristic_fixture): - engine, connection = characteristic_fixture eng = engine.execution_options(foo="new_value") diff --git a/test/ext/asyncio/test_engine_py3k.py b/test/ext/asyncio/test_engine_py3k.py index 786f841ee4..ff4fcbf28e 100644 --- a/test/ext/asyncio/test_engine_py3k.py +++ b/test/ext/asyncio/test_engine_py3k.py @@ -66,7 +66,6 @@ class AsyncFixture: async def run_test(subject, trans_on_subject, execute_on_subject): async with subject.begin() as trans: - if begin_nested: if not config.requirements.savepoints.enabled: config.skip_test("savepoints not enabled") @@ -305,7 +304,6 @@ class AsyncEngineTest(EngineFixture): @async_test async def test_connection_info(self, async_engine): - async with async_engine.connect() as conn: conn.info["foo"] = "bar" @@ -313,7 +311,6 @@ class AsyncEngineTest(EngineFixture): @async_test async def test_connection_eq_ne(self, async_engine): - async with async_engine.connect() as conn: c2 = _async_engine.AsyncConnection( async_engine, conn.sync_connection @@ -328,7 +325,6 @@ class AsyncEngineTest(EngineFixture): @async_test async def test_transaction_eq_ne(self, async_engine): - async with async_engine.connect() as conn: t1 = await conn.begin() @@ -374,7 +370,6 @@ class AsyncEngineTest(EngineFixture): "do_rollback", mock.Mock(side_effect=Exception("can't run rollback")), ), mock.patch("sqlalchemy.util.warn") as m: - _finalize_fairy( None, rec, pool, ref, echo, transaction_was_reset=False ) @@ -506,7 +501,6 @@ class AsyncEngineTest(EngineFixture): @async_test async def test_get_raw_connection(self, async_connection): - pooled = await async_connection.get_raw_connection() is_(pooled, async_connection.sync_connection.connection) @@ -590,7 +584,6 @@ class AsyncEngineTest(EngineFixture): @async_test async def test_connection_not_started(self, async_engine): - conn = async_engine.connect() testing.assert_raises_message( asyncio_exc.AsyncContextNotStarted, @@ -614,7 +607,6 @@ class AsyncEngineTest(EngineFixture): users = self.tables.users async with async_engine.begin() as conn: - savepoint = await conn.begin_nested() await conn.execute(delete(users)) await savepoint.rollback() @@ -627,7 +619,6 @@ class AsyncEngineTest(EngineFixture): users = self.tables.users async with async_engine.begin() as conn: - savepoint = await conn.begin_nested() await conn.execute(delete(users)) await savepoint.commit() @@ -650,7 +641,6 @@ class AsyncEngineTest(EngineFixture): @async_test async def test_conn_transaction_not_started(self, async_engine): - async with async_engine.connect() as conn: trans = conn.begin() with expect_raises_message( @@ -1214,7 +1204,6 @@ class AsyncProxyTest(EngineFixture, fixtures.TestBase): async def test_get_transaction(self, async_engine): async with async_engine.connect() as conn: async with conn.begin() as trans: - is_(trans.connection, conn) is_(conn.get_transaction(), trans) @@ -1247,7 +1236,6 @@ class AsyncProxyTest(EngineFixture, fixtures.TestBase): ) def test_regenerate_connection(self, connection): - async_connection = AsyncConnection._retrieve_proxy_for_target( connection ) @@ -1300,9 +1288,7 @@ class AsyncProxyTest(EngineFixture, fixtures.TestBase): eq_(len(ReversibleProxy._proxy_objects), 0) def test_regen_conn_but_not_engine(self, async_engine): - with async_engine.sync_engine.connect() as sync_conn: - async_conn = AsyncConnection._retrieve_proxy_for_target(sync_conn) async_conn2 = AsyncConnection._retrieve_proxy_for_target(sync_conn) diff --git a/test/ext/asyncio/test_session_py3k.py b/test/ext/asyncio/test_session_py3k.py index e1991493bf..1767f2f4e3 100644 --- a/test/ext/asyncio/test_session_py3k.py +++ b/test/ext/asyncio/test_session_py3k.py @@ -271,7 +271,6 @@ class AsyncSessionTransactionTest(AsyncFixture): @async_test async def test_orm_sessionmaker_block_one(self, async_engine): - User = self.classes.User maker = sessionmaker(async_engine, class_=AsyncSession) @@ -295,7 +294,6 @@ class AsyncSessionTransactionTest(AsyncFixture): @async_test async def test_orm_sessionmaker_block_two(self, async_engine): - User = self.classes.User maker = sessionmaker(async_engine, class_=AsyncSession) @@ -317,7 +315,6 @@ class AsyncSessionTransactionTest(AsyncFixture): @async_test async def test_async_sessionmaker_block_one(self, async_engine): - User = self.classes.User maker = async_sessionmaker(async_engine) @@ -341,7 +338,6 @@ class AsyncSessionTransactionTest(AsyncFixture): @async_test async def test_async_sessionmaker_block_two(self, async_engine): - User = self.classes.User maker = async_sessionmaker(async_engine) @@ -364,11 +360,9 @@ class AsyncSessionTransactionTest(AsyncFixture): @async_test async def test_trans(self, async_session, async_engine): async with async_engine.connect() as outer_conn: - User = self.classes.User async with async_session.begin(): - eq_(await outer_conn.scalar(select(func.count(User.id))), 0) u1 = User(name="u1") @@ -384,7 +378,6 @@ class AsyncSessionTransactionTest(AsyncFixture): @async_test async def test_commit_as_you_go(self, async_session, async_engine): async with async_engine.connect() as outer_conn: - User = self.classes.User eq_(await outer_conn.scalar(select(func.count(User.id))), 0) @@ -404,7 +397,6 @@ class AsyncSessionTransactionTest(AsyncFixture): @async_test async def test_trans_noctx(self, async_session, async_engine): async with async_engine.connect() as outer_conn: - User = self.classes.User trans = await async_session.begin() @@ -571,7 +563,6 @@ class AsyncSessionTransactionTest(AsyncFixture): User = self.classes.User async with async_engine.connect() as conn: - await conn.begin() await conn.begin_nested() @@ -737,7 +728,6 @@ class AsyncORMBehaviorsTest(AsyncFixture): async def test_new_style_active_history( self, async_session, one_to_one_fixture, _legacy_inactive_history_style ): - A, B = await one_to_one_fixture(_legacy_inactive_history_style) a1 = A() @@ -845,7 +835,6 @@ class AsyncProxyTest(AsyncFixture): @async_test async def test_get_transaction(self, async_session): - is_(async_session.get_transaction(), None) is_(async_session.get_nested_transaction(), None) @@ -952,7 +941,6 @@ class AsyncProxyTest(AsyncFixture): def test_inspect_session_no_asyncio_imported(self): with mock.patch("sqlalchemy.orm.state._async_provider", None): - User = self.classes.User s1 = Session(testing.db) diff --git a/test/ext/declarative/test_inheritance.py b/test/ext/declarative/test_inheritance.py index d7cac669b0..62e15a124b 100644 --- a/test/ext/declarative/test_inheritance.py +++ b/test/ext/declarative/test_inheritance.py @@ -145,12 +145,10 @@ class ConcreteInhTest( ) class Employee(Base, fixtures.ComparableEntity): - __table__ = punion __mapper_args__ = {"polymorphic_on": punion.c.type} class Engineer(Employee): - __table__ = engineers __mapper_args__ = { "polymorphic_identity": "engineer", @@ -158,7 +156,6 @@ class ConcreteInhTest( } class Manager(Employee): - __table__ = managers __mapper_args__ = { "polymorphic_identity": "manager", @@ -178,7 +175,6 @@ class ConcreteInhTest( """test the example from the declarative docs.""" class Employee(Base, fixtures.ComparableEntity): - __tablename__ = "people" id = Column( Integer, primary_key=True, test_needs_autoincrement=True @@ -186,7 +182,6 @@ class ConcreteInhTest( name = Column(String(50)) class Engineer(Employee): - __tablename__ = "engineers" __mapper_args__ = {"concrete": True} id = Column( @@ -196,7 +191,6 @@ class ConcreteInhTest( name = Column(String(50)) class Manager(Employee): - __tablename__ = "manager" __mapper_args__ = {"concrete": True} id = Column( diff --git a/test/ext/declarative/test_reflection.py b/test/ext/declarative/test_reflection.py index 1a4effa644..103d3d07ff 100644 --- a/test/ext/declarative/test_reflection.py +++ b/test/ext/declarative/test_reflection.py @@ -108,7 +108,6 @@ class DeferredReflectionTest(testing.AssertsCompiledSQL, DeferredReflectBase): ) def _roundtrip(self): - User = Base.registry._class_registry["User"] Address = Base.registry._class_registry["Address"] @@ -326,7 +325,6 @@ class DeferredSecondaryReflectionTest(DeferredReflectBase): ) def _roundtrip(self): - User = Base.registry._class_registry["User"] Item = Base.registry._class_registry["Item"] diff --git a/test/ext/mypy/plain_files/async_sessionmaker.py b/test/ext/mypy/plain_files/async_sessionmaker.py index e28e9499b4..c253774e2e 100644 --- a/test/ext/mypy/plain_files/async_sessionmaker.py +++ b/test/ext/mypy/plain_files/async_sessionmaker.py @@ -79,7 +79,6 @@ async def async_main() -> None: ) async with async_session() as session: - result = await session.execute(select(A).order_by(A.id)) r: ScalarResult[A] = result.scalars() diff --git a/test/ext/mypy/plain_files/declared_attr_one.py b/test/ext/mypy/plain_files/declared_attr_one.py index d4f3c826e6..86f8cf7704 100644 --- a/test/ext/mypy/plain_files/declared_attr_one.py +++ b/test/ext/mypy/plain_files/declared_attr_one.py @@ -74,7 +74,6 @@ class Manager(Employee): def do_something_with_mapped_class( cls_: MappedClassProtocol[Employee], ) -> None: - # EXPECTED_TYPE: Select[Any] reveal_type(cls_.__table__.select()) @@ -90,7 +89,6 @@ do_something_with_mapped_class(Engineer) if typing.TYPE_CHECKING: - # EXPECTED_TYPE: InstrumentedAttribute[datetime] reveal_type(Engineer.start_date) diff --git a/test/ext/mypy/plain_files/declared_attr_two.py b/test/ext/mypy/plain_files/declared_attr_two.py index d2653a9208..c8e12ee931 100644 --- a/test/ext/mypy/plain_files/declared_attr_two.py +++ b/test/ext/mypy/plain_files/declared_attr_two.py @@ -39,7 +39,6 @@ class Foo(Base): u1 = User() if typing.TYPE_CHECKING: - # EXPECTED_TYPE: str reveal_type(User.__tablename__) diff --git a/test/ext/mypy/plain_files/dynamic_rel.py b/test/ext/mypy/plain_files/dynamic_rel.py index 1766c610c8..3aee8f3204 100644 --- a/test/ext/mypy/plain_files/dynamic_rel.py +++ b/test/ext/mypy/plain_files/dynamic_rel.py @@ -36,20 +36,17 @@ with Session() as session: session.commit() if typing.TYPE_CHECKING: - # EXPECTED_TYPE: AppenderQuery[Address] reveal_type(u.addresses) count = u.addresses.count() if typing.TYPE_CHECKING: - # EXPECTED_TYPE: int reveal_type(count) address = u.addresses.filter(Address.email_address.like("xyz")).one() if typing.TYPE_CHECKING: - # EXPECTED_TYPE: Address reveal_type(address) @@ -59,7 +56,6 @@ with Session() as session: current_addresses = list(u.addresses) if typing.TYPE_CHECKING: - # EXPECTED_TYPE: list[Address] reveal_type(current_addresses) diff --git a/test/ext/mypy/plain_files/engine_inspection.py b/test/ext/mypy/plain_files/engine_inspection.py index 20e252cddc..0ca331f189 100644 --- a/test/ext/mypy/plain_files/engine_inspection.py +++ b/test/ext/mypy/plain_files/engine_inspection.py @@ -13,7 +13,6 @@ cols = insp.get_columns("some_table") c1 = cols[0] if typing.TYPE_CHECKING: - # EXPECTED_RE_TYPE: sqlalchemy.engine.base.Engine reveal_type(e) diff --git a/test/ext/mypy/plain_files/engines.py b/test/ext/mypy/plain_files/engines.py index c920ad55dc..b7621aca42 100644 --- a/test/ext/mypy/plain_files/engines.py +++ b/test/ext/mypy/plain_files/engines.py @@ -4,14 +4,12 @@ from sqlalchemy.ext.asyncio import create_async_engine def regular() -> None: - e = create_engine("sqlite://") # EXPECTED_TYPE: Engine reveal_type(e) with e.connect() as conn: - # EXPECTED_TYPE: Connection reveal_type(conn) @@ -21,7 +19,6 @@ def regular() -> None: reveal_type(result) with e.begin() as conn: - # EXPECTED_TYPE: Connection reveal_type(conn) @@ -38,7 +35,6 @@ async def asyncio() -> None: reveal_type(e) async with e.connect() as conn: - # EXPECTED_TYPE: AsyncConnection reveal_type(conn) @@ -76,7 +72,6 @@ async def asyncio() -> None: reveal_type(ctx_async_scalar_result) async with e.begin() as conn: - # EXPECTED_TYPE: AsyncConnection reveal_type(conn) diff --git a/test/ext/mypy/plain_files/hybrid_four.py b/test/ext/mypy/plain_files/hybrid_four.py index a81ad96c41..c4ee15bc83 100644 --- a/test/ext/mypy/plain_files/hybrid_four.py +++ b/test/ext/mypy/plain_files/hybrid_four.py @@ -52,7 +52,6 @@ class FirstNameOnly(Base): class FirstNameLastName(FirstNameOnly): - last_name: Mapped[str] @FirstNameOnly.name.getter diff --git a/test/ext/mypy/plain_files/lambda_stmt.py b/test/ext/mypy/plain_files/lambda_stmt.py index 7e15778c1d..bce5557db8 100644 --- a/test/ext/mypy/plain_files/lambda_stmt.py +++ b/test/ext/mypy/plain_files/lambda_stmt.py @@ -49,7 +49,6 @@ s6 = lambda_stmt(lambda: select(User)) + (lambda s: s.where(User.id == 5)) if TYPE_CHECKING: - # EXPECTED_TYPE: StatementLambdaElement reveal_type(s5) diff --git a/test/ext/mypy/plain_files/session.py b/test/ext/mypy/plain_files/session.py index dfebdd5a9a..7a26835d32 100644 --- a/test/ext/mypy/plain_files/session.py +++ b/test/ext/mypy/plain_files/session.py @@ -86,12 +86,10 @@ with Session(e) as sess: # test #9125 for row in sess.query(User.id, User.name): - # EXPECTED_TYPE: Row[Tuple[int, str]] reveal_type(row) for uobj1 in sess.query(User): - # EXPECTED_TYPE: User reveal_type(uobj1) diff --git a/test/ext/mypy/plain_files/sql_operations.py b/test/ext/mypy/plain_files/sql_operations.py index 95993f6284..4d3775293e 100644 --- a/test/ext/mypy/plain_files/sql_operations.py +++ b/test/ext/mypy/plain_files/sql_operations.py @@ -118,7 +118,6 @@ def test_issue_9650_bitwise() -> None: if typing.TYPE_CHECKING: - # as far as if this is ColumnElement, BinaryElement, SQLCoreOperations, # that might change. main thing is it's SomeSQLColThing[bool] and # not 'bool' or 'Any'. diff --git a/test/ext/mypy/plain_files/typed_queries.py b/test/ext/mypy/plain_files/typed_queries.py index 2de565e6a4..8030fcff84 100644 --- a/test/ext/mypy/plain_files/typed_queries.py +++ b/test/ext/mypy/plain_files/typed_queries.py @@ -259,7 +259,6 @@ def t_legacy_query_cols_2() -> None: def t_legacy_query_cols_2_with_entities() -> None: - q1 = session.query(User) # EXPECTED_TYPE: Query[User] @@ -459,7 +458,6 @@ def t_dml_delete() -> None: def t_from_statement() -> None: - t = text("select * from user") # EXPECTED_TYPE: TextClause diff --git a/test/ext/mypy/plain_files/typed_results.py b/test/ext/mypy/plain_files/typed_results.py index 12bfcddf0c..3596099cb8 100644 --- a/test/ext/mypy/plain_files/typed_results.py +++ b/test/ext/mypy/plain_files/typed_results.py @@ -117,7 +117,6 @@ def t_core_mappings() -> None: def t_entity_varieties() -> None: - a1 = aliased(User) s1 = select(User.id, User, User.name).where(User.name == "foo") @@ -184,7 +183,6 @@ def t_ambiguous_result_type_one() -> None: def t_ambiguous_result_type_two() -> None: - stmt = select(column("q")) # EXPECTED_TYPE: Select[Tuple[Any]] @@ -196,7 +194,6 @@ def t_ambiguous_result_type_two() -> None: def t_aliased() -> None: - a1 = aliased(User) s1 = select(a1) diff --git a/test/ext/mypy/plain_files/write_only.py b/test/ext/mypy/plain_files/write_only.py index 672630ee66..5d322a606b 100644 --- a/test/ext/mypy/plain_files/write_only.py +++ b/test/ext/mypy/plain_files/write_only.py @@ -34,7 +34,6 @@ with Session() as session: session.commit() if typing.TYPE_CHECKING: - # EXPECTED_TYPE: WriteOnlyCollection[Address] reveal_type(u.addresses) @@ -43,7 +42,6 @@ with Session() as session: ).one() if typing.TYPE_CHECKING: - # EXPECTED_TYPE: Address reveal_type(address) diff --git a/test/ext/mypy/test_mypy_plugin_py3k.py b/test/ext/mypy/test_mypy_plugin_py3k.py index 3df669912e..6a04f2730a 100644 --- a/test/ext/mypy/test_mypy_plugin_py3k.py +++ b/test/ext/mypy/test_mypy_plugin_py3k.py @@ -204,7 +204,6 @@ class MypyPluginTest(fixtures.TestBase): id_="isaa", ) def test_files(self, mypy_runner, filename, path, use_plugin): - expected_messages = [] expected_re = re.compile(r"\s*# EXPECTED(_MYPY)?(_RE)?(_TYPE)?: (.+)") py_ver_re = re.compile(r"^#\s*PYTHON_VERSION\s?>=\s?(\d+\.\d+)") diff --git a/test/ext/test_associationproxy.py b/test/ext/test_associationproxy.py index 4731ff0b61..d7b7b0bb20 100644 --- a/test/ext/test_associationproxy.py +++ b/test/ext/test_associationproxy.py @@ -748,7 +748,6 @@ class SetTest(_CollectionOperations): {"e", "f", "g"}, set(), ): - eq_(p1.children.union(other), control.union(other)) eq_(p1.children.difference(other), control.difference(other)) eq_((p1.children - other), (control - other)) @@ -1194,7 +1193,6 @@ class ScalarTest(fixtures.MappedTest): class LazyLoadTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): - Table( "Parent", metadata, @@ -2373,7 +2371,6 @@ class DictOfTupleUpdateTest(fixtures.MappedTest): cls.mapper_registry.map_imperatively(B, b) def test_update_one_elem_dict(self): - a1 = self.classes.A() a1.elements.update({("B", 3): "elem2"}) eq_(a1.elements, {("B", 3): "elem2"}) @@ -2884,7 +2881,6 @@ class ScalarRemoveTest: class ScalarRemoveListObjectCascade( ScalarRemoveTest, fixtures.DeclarativeMappedTest ): - run_create_tables = None useobject = True cascade_scalar_deletes = True @@ -2894,7 +2890,6 @@ class ScalarRemoveListObjectCascade( class ScalarRemoveScalarObjectCascade( ScalarRemoveTest, fixtures.DeclarativeMappedTest ): - run_create_tables = None useobject = True cascade_scalar_deletes = True @@ -2904,7 +2899,6 @@ class ScalarRemoveScalarObjectCascade( class ScalarRemoveListScalarCascade( ScalarRemoveTest, fixtures.DeclarativeMappedTest ): - run_create_tables = None useobject = False cascade_scalar_deletes = True @@ -2914,7 +2908,6 @@ class ScalarRemoveListScalarCascade( class ScalarRemoveScalarScalarCascade( ScalarRemoveTest, fixtures.DeclarativeMappedTest ): - run_create_tables = None useobject = False cascade_scalar_deletes = True @@ -2924,7 +2917,6 @@ class ScalarRemoveScalarScalarCascade( class ScalarRemoveListObjectNoCascade( ScalarRemoveTest, fixtures.DeclarativeMappedTest ): - run_create_tables = None useobject = True cascade_scalar_deletes = False @@ -2934,7 +2926,6 @@ class ScalarRemoveListObjectNoCascade( class ScalarRemoveScalarObjectNoCascade( ScalarRemoveTest, fixtures.DeclarativeMappedTest ): - run_create_tables = None useobject = True cascade_scalar_deletes = False @@ -2944,7 +2935,6 @@ class ScalarRemoveScalarObjectNoCascade( class ScalarRemoveListScalarNoCascade( ScalarRemoveTest, fixtures.DeclarativeMappedTest ): - run_create_tables = None useobject = False cascade_scalar_deletes = False @@ -2954,7 +2944,6 @@ class ScalarRemoveListScalarNoCascade( class ScalarRemoveScalarScalarNoCascade( ScalarRemoveTest, fixtures.DeclarativeMappedTest ): - run_create_tables = None useobject = False cascade_scalar_deletes = False @@ -3521,7 +3510,6 @@ class ProxyPlainPropertyTest(fixtures.DeclarativeMappedTest): @classmethod def setup_classes(cls): - Base = cls.DeclarativeBasic class A(Base): diff --git a/test/ext/test_baked.py b/test/ext/test_baked.py index d502277925..8dce86db00 100644 --- a/test/ext/test_baked.py +++ b/test/ext/test_baked.py @@ -422,7 +422,6 @@ class ResultPostCriteriaTest(BakedTest): def test_spoiled(self): with self._fixture() as (sess, bq): - result = bq.spoil()(sess).with_post_criteria( lambda q: q.execution_options(yes=True) ) diff --git a/test/ext/test_extendedattr.py b/test/ext/test_extendedattr.py index c222a0a933..dd5b715829 100644 --- a/test/ext/test_extendedattr.py +++ b/test/ext/test_extendedattr.py @@ -159,7 +159,6 @@ class UserDefinedExtensionTest(_ExtBase, fixtures.ORMTest): ) class MyClass: - # This proves that a staticmethod will work here; don't # flatten this back to a class assignment! def __sa_instrumentation_manager__(cls): diff --git a/test/ext/test_horizontal_shard.py b/test/ext/test_horizontal_shard.py index 467c61f160..389dbe00a0 100644 --- a/test/ext/test_horizontal_shard.py +++ b/test/ext/test_horizontal_shard.py @@ -662,7 +662,6 @@ class DistinctEngineShardTest(ShardTest, fixtures.MappedTest): return self.dbs def teardown_test(self): - testing_reaper.checkin_all() for i in range(1, 5): os.remove("shard%d_%s.db" % (i, provision.FOLLOWER_IDENT)) diff --git a/test/ext/test_indexable.py b/test/ext/test_indexable.py index a55a16ac4a..e68f9c0351 100644 --- a/test/ext/test_indexable.py +++ b/test/ext/test_indexable.py @@ -169,7 +169,6 @@ class IndexPropertyTest(fixtures.TestBase): class IndexPropertyArrayTest(fixtures.DeclarativeMappedTest): - __requires__ = ("array_type",) __backend__ = True @@ -250,7 +249,6 @@ class IndexPropertyArrayTest(fixtures.DeclarativeMappedTest): class IndexPropertyJsonTest(fixtures.DeclarativeMappedTest): - # TODO: remove reliance on "astext" for these tests __requires__ = ("json_type",) __only_on__ = "postgresql" @@ -324,7 +322,6 @@ class IndexPropertyJsonTest(fixtures.DeclarativeMappedTest): eq_(j.other, 42) def test_modified(self): - Json = self.classes.Json s = Session(testing.db) diff --git a/test/ext/test_serializer.py b/test/ext/test_serializer.py index d41e56b82a..8318484c02 100644 --- a/test/ext/test_serializer.py +++ b/test/ext/test_serializer.py @@ -38,7 +38,6 @@ class Address(fixtures.ComparableEntity): class SerializeTest(AssertsCompiledSQL, fixtures.MappedTest): - run_setup_mappers = "once" run_inserts = "once" run_deletes = None diff --git a/test/orm/declarative/test_basic.py b/test/orm/declarative/test_basic.py index 130f3da455..3ad7db0799 100644 --- a/test/orm/declarative/test_basic.py +++ b/test/orm/declarative/test_basic.py @@ -376,7 +376,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): assert A.__mapper__.primary_key[1] is A.__table__.c.b def test_mapper_pk_arg_degradation_no_col(self, decl_base): - with expect_raises_message( exc.ArgumentError, "Can't determine primary_key column 'q' - no attribute is " @@ -393,7 +392,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): @testing.variation("proptype", ["relationship", "colprop"]) def test_mapper_pk_arg_degradation_is_not_a_col(self, decl_base, proptype): - with expect_raises_message( exc.ArgumentError, "Can't determine primary_key column 'b'; property does " @@ -546,7 +544,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): Base = declarative_base() class User(Base): - __tablename__ = "users" __table_args__ = {"schema": "fooschema"} @@ -561,7 +558,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): ) class Prop(Base): - __tablename__ = "props" __table_args__ = {"schema": "fooschema"} @@ -592,7 +588,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): @reg.mapped class User: - __tablename__ = "users" __table_args__ = {"schema": "fooschema"} @@ -608,7 +603,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): @reg.mapped class Prop: - __tablename__ = "props" __table_args__ = {"schema": "fooschema"} @@ -712,7 +706,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): def test_as_declarative(self, metadata): class User(fixtures.ComparableEntity): - __tablename__ = "users" id = Column( "id", Integer, primary_key=True, test_needs_autoincrement=True @@ -721,7 +714,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): addresses = relationship("Address", backref="user") class Address(fixtures.ComparableEntity): - __tablename__ = "addresses" id = Column( "id", Integer, primary_key=True, test_needs_autoincrement=True @@ -753,7 +745,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): def test_map_declaratively(self, metadata): class User(fixtures.ComparableEntity): - __tablename__ = "users" id = Column( "id", Integer, primary_key=True, test_needs_autoincrement=True @@ -762,7 +753,6 @@ class DeclarativeBaseSetupsTest(fixtures.TestBase): addresses = relationship("Address", backref="user") class Address(fixtures.ComparableEntity): - __tablename__ = "addresses" id = Column( "id", Integer, primary_key=True, test_needs_autoincrement=True @@ -1387,7 +1377,6 @@ class DeclarativeMultiBaseTest( id = Column(Integer, primary_key=True) def test_non_sql_expression_warning_five(self): - # test for #9537 with assertions.expect_warnings( r"Attribute 'x' on class 9, 1), else_=2) # include entities in the statement so that we test that diff --git a/test/orm/test_cascade.py b/test/orm/test_cascade.py index 8a545b03b1..3c49fc8dcd 100644 --- a/test/orm/test_cascade.py +++ b/test/orm/test_cascade.py @@ -440,7 +440,6 @@ class O2MCascadeDeleteOrphanTest(fixtures.MappedTest): User, Order = self.classes.User, self.classes.Order with fixture_session() as sess: - u = User(name="jack") sess.add(u) sess.commit() @@ -457,7 +456,6 @@ class O2MCascadeDeleteOrphanTest(fixtures.MappedTest): User, Order = self.classes.User, self.classes.Order with fixture_session() as sess: - u = User(name="jack") o1 = Order() @@ -1149,7 +1147,6 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): o2m=False, m2o=False, ): - Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, @@ -1204,7 +1201,6 @@ class NoSaveCascadeFlushTest(_fixtures.FixtureTest): fwd=False, bkd=False, ): - keywords, items, item_keywords, Keyword, Item = ( self.tables.keywords, self.tables.items, diff --git a/test/orm/test_collection.py b/test/orm/test_collection.py index 85efbe0a37..3afc79c918 100644 --- a/test/orm/test_collection.py +++ b/test/orm/test_collection.py @@ -351,7 +351,6 @@ class CollectionsTest(OrderedDictFixture, fixtures.ORMTest): assert_eq() if hasattr(direct, "__setitem__") or hasattr(direct, "__setslice__"): - values = [creator(), creator()] direct[:] = values control[:] = values @@ -548,7 +547,6 @@ class CollectionsTest(OrderedDictFixture, fixtures.ORMTest): self.assert_(e7 not in canary.removed) def _test_list_dataclasses(self, typecallable): - creator = self.SimpleComparableEntity @dataclasses.dataclass @@ -584,7 +582,6 @@ class CollectionsTest(OrderedDictFixture, fixtures.ORMTest): self._test_list_dataclasses(list) def test_list_setitem_with_slices(self): - # this is a "list" that has no __setslice__ # or __delslice__ methods. The __setitem__ # and __delitem__ must therefore accept @@ -1082,7 +1079,6 @@ class CollectionsTest(OrderedDictFixture, fixtures.ORMTest): self.assert_(e3 in canary.data) def _test_set_dataclasses(self, typecallable): - creator = self.SimpleComparableEntity @dataclasses.dataclass @@ -1471,7 +1467,6 @@ class CollectionsTest(OrderedDictFixture, fixtures.ORMTest): ) def _test_dict_dataclasses(self, typecallable): - creator = self.SimpleComparableEntity @dataclasses.dataclass diff --git a/test/orm/test_core_compilation.py b/test/orm/test_core_compilation.py index f24b97c7d4..f66fc7a48e 100644 --- a/test/orm/test_core_compilation.py +++ b/test/orm/test_core_compilation.py @@ -476,7 +476,6 @@ class PropagateAttrsTest(QueryTest): stmt = resolve_lambda(test_case, User=User, user_table=user_table) with Session(testing.db) as s: - with mock.patch.object(s, "_autoflush", wrap=True) as before_flush: r = s.execute(stmt) r.close() @@ -1735,7 +1734,6 @@ class InheritedTest(_poly_fixtures._Polymorphic): class ExplicitWithPolymorhpicTest( _poly_fixtures._PolymorphicUnions, AssertsCompiledSQL ): - __dialect__ = "default" default_punion = ( @@ -1942,7 +1940,6 @@ class ImplicitWithPolymorphicTest( ) def test_select_where_subclass(self): - Engineer = self.classes.Engineer # what will *not* work with Core, that the ORM does for now, @@ -1993,7 +1990,6 @@ class ImplicitWithPolymorphicTest( ) def test_select_where_columns_subclass(self): - Engineer = self.classes.Engineer # what will *not* work with Core, that the ORM does for now, @@ -2261,7 +2257,6 @@ class RelationshipNaturalInheritedTest(InheritedTest, AssertsCompiledSQL): class RelNaturalAliasedJoinsTest( _poly_fixtures._PolymorphicAliasedJoins, RelationshipNaturalInheritedTest ): - # this is the label style for the polymorphic selectable, not the # outside query label_style = LABEL_STYLE_TABLENAME_PLUS_COL diff --git a/test/orm/test_dataclasses_py3k.py b/test/orm/test_dataclasses_py3k.py index 13cd6dec5e..6153cae9e9 100644 --- a/test/orm/test_dataclasses_py3k.py +++ b/test/orm/test_dataclasses_py3k.py @@ -255,7 +255,6 @@ class PlainDeclarativeDataclassesTest(DataclassesTest): @declarative @dataclasses.dataclass class SpecialWidget(Widget): - magic: bool = False __mapper_args__ = dict( @@ -393,7 +392,6 @@ class FieldEmbeddedWMixinTest(FieldEmbeddedDeclarativeDataclassesTest): @dataclasses.dataclass class SurrogateWidgetPK: - __sa_dataclass_metadata_key__ = "sa" widget_id: int = dataclasses.field( @@ -438,7 +436,6 @@ class FieldEmbeddedWMixinTest(FieldEmbeddedDeclarativeDataclassesTest): @dataclasses.dataclass class SurrogateAccountPK: - __sa_dataclass_metadata_key__ = "sa" account_id = Column( @@ -521,7 +518,6 @@ class FieldEmbeddedMixinWLambdaTest(fixtures.DeclarativeMappedTest): @dataclasses.dataclass class WidgetDC: - __sa_dataclass_metadata_key__ = "sa" widget_id: int = dataclasses.field( @@ -589,7 +585,6 @@ class FieldEmbeddedMixinWLambdaTest(fixtures.DeclarativeMappedTest): @dataclasses.dataclass class AccountDC: - __sa_dataclass_metadata_key__ = "sa" # relationship on mixin @@ -697,7 +692,6 @@ class FieldEmbeddedMixinWDeclaredAttrTest(FieldEmbeddedMixinWLambdaTest): @dataclasses.dataclass class WidgetDC: - __sa_dataclass_metadata_key__ = "sa" widget_id: int = dataclasses.field( @@ -766,7 +760,6 @@ class FieldEmbeddedMixinWDeclaredAttrTest(FieldEmbeddedMixinWLambdaTest): @dataclasses.dataclass class AccountDC: - __sa_dataclass_metadata_key__ = "sa" # relationship on mixin @@ -889,7 +882,6 @@ class PropagationFromMixinTest(fixtures.TestBase): @declarative @dataclasses.dataclass class BaseType(CommonMixin): - discriminator = Column("type", String(50)) __mapper_args__ = dict(polymorphic_on=discriminator) id = Column(Integer, primary_key=True) @@ -898,14 +890,12 @@ class PropagationFromMixinTest(fixtures.TestBase): @declarative @dataclasses.dataclass class Single(BaseType): - __tablename__ = None __mapper_args__ = dict(polymorphic_identity="type1") @declarative @dataclasses.dataclass class Joined(BaseType): - __mapper_args__ = dict(polymorphic_identity="type2") id = Column( Integer, ForeignKey("basetype.id"), primary_key=True @@ -991,7 +981,6 @@ class PropagationFromAbstractTest(fixtures.TestBase): @declarative @dataclasses.dataclass class Single(BaseType): - __tablename__ = "single" __mapper_args__ = dict(polymorphic_identity="type1") diff --git a/test/orm/test_default_strategies.py b/test/orm/test_default_strategies.py index 8b3cd84193..657875aa9d 100644 --- a/test/orm/test_default_strategies.py +++ b/test/orm/test_default_strategies.py @@ -652,7 +652,6 @@ class NoLoadTest(_fixtures.FixtureTest): run_deletes = None def test_o2m_noload(self): - Address, addresses, users, User = ( self.classes.Address, self.tables.addresses, diff --git a/test/orm/test_deferred.py b/test/orm/test_deferred.py index e1eb6e9e1d..7435299240 100644 --- a/test/orm/test_deferred.py +++ b/test/orm/test_deferred.py @@ -1546,7 +1546,6 @@ class MultiPathTest(fixtures.DeclarativeMappedTest): session.commit() def test_data_loaded(self): - User, Task = self.classes("User", "Task") session = fixture_session() diff --git a/test/orm/test_deprecations.py b/test/orm/test_deprecations.py index 2ab046cdab..82aad07ba7 100644 --- a/test/orm/test_deprecations.py +++ b/test/orm/test_deprecations.py @@ -1182,7 +1182,6 @@ class NonPrimaryRelationshipLoaderTest(_fixtures.FixtureTest): self._run_double_test(1) def test_selectin(self): - users, orders, User, Address, Order, addresses = ( self.tables.users, self.tables.orders, @@ -1239,7 +1238,6 @@ class NonPrimaryRelationshipLoaderTest(_fixtures.FixtureTest): self._run_double_test(4) def test_subqueryload(self): - users, orders, User, Address, Order, addresses = ( self.tables.users, self.tables.orders, diff --git a/test/orm/test_dynamic.py b/test/orm/test_dynamic.py index 714878f4ea..83f3101f20 100644 --- a/test/orm/test_dynamic.py +++ b/test/orm/test_dynamic.py @@ -1375,7 +1375,6 @@ class DynamicUOWTest( _fixtures.FixtureTest, testing.AssertsExecutionResults, ): - run_inserts = None @testing.combinations( @@ -1975,7 +1974,6 @@ class _HistoryTest: if sess: sess.autoflush = False try: - if self.lazy == "write_only" and compare_passive is not None: eq_( attributes.get_history( diff --git a/test/orm/test_events.py b/test/orm/test_events.py index 5b575fd7cf..56d16dfcd7 100644 --- a/test/orm/test_events.py +++ b/test/orm/test_events.py @@ -66,7 +66,6 @@ class ORMExecuteTest(RemoveORMEventsGlobally, _fixtures.FixtureTest): cls._setup_stock_mapping() def _caching_session_fixture(self): - cache = {} maker = sessionmaker(testing.db, future=True) @@ -102,7 +101,6 @@ class ORMExecuteTest(RemoveORMEventsGlobally, _fixtures.FixtureTest): User, Address = self.classes("User", "Address") with self.sql_execution_asserter(testing.db) as asserter: - with self._caching_session_fixture() as session: stmt = ( select(User) @@ -341,7 +339,6 @@ class ORMExecuteTest(RemoveORMEventsGlobally, _fixtures.FixtureTest): sess.execute(insert(User), orig_params) def test_chained_events_one(self): - sess = Session(testing.db, future=True) @event.listens_for(sess, "do_orm_execute") @@ -377,7 +374,6 @@ class ORMExecuteTest(RemoveORMEventsGlobally, _fixtures.FixtureTest): @event.listens_for(session, "do_orm_execute") def do_orm_execute(ctx): - if not ctx.is_select: assert_raises_message( sa.exc.InvalidRequestError, @@ -466,7 +462,6 @@ class ORMExecuteTest(RemoveORMEventsGlobally, _fixtures.FixtureTest): ) def test_all_mappers_accessor_two(self): - sess = Session(testing.db, future=True) canary = self._flag_fixture(sess) @@ -726,7 +721,6 @@ class ORMExecuteTest(RemoveORMEventsGlobally, _fixtures.FixtureTest): ) def test_chained_events_two(self): - sess = Session(testing.db, future=True) def added(ctx): @@ -1353,7 +1347,6 @@ class MapperEventsTest(RemoveORMEventsGlobally, _fixtures.FixtureTest): ["listen_on_mapper", "listen_on_base", "listen_on_mixin"], ) def test_mapper_config_sequence(self, decl_base, listen_type): - canary = Mock() if listen_type.listen_on_mapper: diff --git a/test/orm/test_expire.py b/test/orm/test_expire.py index 906771f16b..22f6156331 100644 --- a/test/orm/test_expire.py +++ b/test/orm/test_expire.py @@ -715,7 +715,6 @@ class ExpireTest(_fixtures.FixtureTest): sess = fixture_session(autoflush=False) with self.sql_execution_asserter(testing.db) as asserter: - if case == "contains,joined": a1 = ( sess.query(Address) @@ -1170,7 +1169,6 @@ class ExpireTest(_fixtures.FixtureTest): "with a refresh" ), ): - sess.refresh(u, ["name"]) # id was not expired diff --git a/test/orm/test_froms.py b/test/orm/test_froms.py index 6609d9d186..6b28a637ad 100644 --- a/test/orm/test_froms.py +++ b/test/orm/test_froms.py @@ -528,7 +528,6 @@ class EntityFromSubqueryTest(QueryTest, AssertsCompiledSQL): ) def test_no_joinedload(self): - User = self.classes.User s = fixture_session() @@ -1023,7 +1022,6 @@ class ColumnAccessTest(QueryTest, AssertsCompiledSQL): ) def test_anonymous_expression_plus_flag_aliased_join_newstyle(self): - User = self.classes.User Address = self.classes.Address addresses = self.tables.addresses @@ -1733,7 +1731,6 @@ class InstancesTest(QueryTest, AssertsCompiledSQL): sess.expunge_all() def go(): - # same as above, except Order is aliased, so two adapters # are applied by the eager loader @@ -2331,7 +2328,6 @@ class MixedEntitiesTest(QueryTest, AssertsCompiledSQL): q4, q5, ]: - eq_( q.all(), [ @@ -4092,7 +4088,6 @@ class CorrelateORMTest(fixtures.TestBase, testing.AssertsCompiledSQL): Base.registry.dispose() def _combinations(fn): - return testing.combinations( (True,), (False,), argnames="include_property" )( diff --git a/test/orm/test_inspect.py b/test/orm/test_inspect.py index ab2e5ae3ad..bab80502a9 100644 --- a/test/orm/test_inspect.py +++ b/test/orm/test_inspect.py @@ -452,7 +452,6 @@ class TestORMInspection(_fixtures.FixtureTest): return [_random_name() for i in range(random.randint(8, 15))] def _ordered_name_fixture(self, glbls, clsname, base, supercls): - names = self._random_names() if base is supercls: diff --git a/test/orm/test_lazy_relations.py b/test/orm/test_lazy_relations.py index ed636ae422..e3936159ad 100644 --- a/test/orm/test_lazy_relations.py +++ b/test/orm/test_lazy_relations.py @@ -473,7 +473,6 @@ class LazyTest(_fixtures.FixtureTest): ) def test_double_w_ac_against_subquery(self): - ( users, orders, @@ -532,7 +531,6 @@ class LazyTest(_fixtures.FixtureTest): self._run_double_test() def test_double_w_ac(self): - ( users, orders, @@ -754,7 +752,6 @@ class LazyTest(_fixtures.FixtureTest): ) with fixture_session() as sess: - # load address a1 = ( sess.query(Address) diff --git a/test/orm/test_manytomany.py b/test/orm/test_manytomany.py index 1155096a44..078a08037e 100644 --- a/test/orm/test_manytomany.py +++ b/test/orm/test_manytomany.py @@ -144,7 +144,6 @@ class M2MTest(fixtures.MappedTest): ) def test_self_referential_roundtrip(self): - place, Place, place_place = ( self.tables.place, self.classes.Place, diff --git a/test/orm/test_mapper.py b/test/orm/test_mapper.py index 1cc624344f..19caf04487 100644 --- a/test/orm/test_mapper.py +++ b/test/orm/test_mapper.py @@ -660,7 +660,6 @@ class MapperTest(_fixtures.FixtureTest, AssertsCompiledSQL): "sqlalchemy.orm.attributes.register_attribute_impl", side_effect=register_attribute_impl, ) as some_mock: - self.mapper(A, users, properties={"bs": relationship(B)}) self.mapper(B, addresses) @@ -2268,7 +2267,6 @@ class MapperTest(_fixtures.FixtureTest, AssertsCompiledSQL): eq_(recon, ["A", "B", "C"]) def test_reconstructor_init(self): - users = self.tables.users recon = [] @@ -3003,7 +3001,6 @@ class MagicNamesTest(fixtures.MappedTest): class DocumentTest(fixtures.TestBase): def setup_test(self): - self.mapper = registry().map_imperatively def test_doc_propagate(self): diff --git a/test/orm/test_merge.py b/test/orm/test_merge.py index eb5a795e22..6b3a7c1d6d 100644 --- a/test/orm/test_merge.py +++ b/test/orm/test_merge.py @@ -639,7 +639,6 @@ class MergeTest(_fixtures.FixtureTest): self.load_tracker(Address, load) with fixture_session(expire_on_commit=False) as sess, sess.begin(): - # set up data and save u = User( id=7, @@ -965,7 +964,6 @@ class MergeTest(_fixtures.FixtureTest): self.load_tracker(Item, load) with fixture_session(expire_on_commit=False) as sess: - i1 = Item() i1.description = "item 1" diff --git a/test/orm/test_of_type.py b/test/orm/test_of_type.py index 9348032442..99f124fa33 100644 --- a/test/orm/test_of_type.py +++ b/test/orm/test_of_type.py @@ -957,7 +957,6 @@ class SubclassRelationshipTest( class SubclassRelationshipTest2( testing.AssertsCompiledSQL, fixtures.DeclarativeMappedTest ): - run_setup_classes = "once" run_setup_mappers = "once" run_inserts = "once" @@ -1103,7 +1102,6 @@ class SubclassRelationshipTest2( class SubclassRelationshipTest3( testing.AssertsCompiledSQL, fixtures.DeclarativeMappedTest ): - run_setup_classes = "once" run_setup_mappers = "once" run_inserts = "once" diff --git a/test/orm/test_options.py b/test/orm/test_options.py index 3b088b9986..049d861fd6 100644 --- a/test/orm/test_options.py +++ b/test/orm/test_options.py @@ -1236,7 +1236,6 @@ class OptionsNoPropTestInh(_Polymorphic): r'does not link from relationship "Company.employees". Did you ' r'mean to use "Company.employees.of_type\(Engineer\)"\?', ): - if use_options: s.query(Company).options( joinedload(Company.employees).options( @@ -1268,7 +1267,6 @@ class PickleTest(fixtures.MappedTest): @testing.fixture def user_address_fixture(self, registry): - registry.map_imperatively( User, self.tables.users, diff --git a/test/orm/test_pickled.py b/test/orm/test_pickled.py index 710c98ee6d..87461bc102 100644 --- a/test/orm/test_pickled.py +++ b/test/orm/test_pickled.py @@ -650,7 +650,6 @@ class PickleTest(fixtures.MappedTest): class OptionsTest(_Polymorphic): def test_options_of_type(self): - with_poly = with_polymorphic(Person, [Engineer, Manager], flat=True) for opt, serialized_path, serialized_of_type in [ ( diff --git a/test/orm/test_query.py b/test/orm/test_query.py index 05f51a27bd..367f854427 100644 --- a/test/orm/test_query.py +++ b/test/orm/test_query.py @@ -358,7 +358,6 @@ class RowTupleTest(QueryTest, AssertsCompiledSQL): (lambda s, users: select(users.c.id, users.c.name),), ) def test_legacy_tuple_old_select(self, test_case): - User, users = self.classes.User, self.tables.users self.mapper_registry.map_imperatively(User, users) @@ -798,7 +797,6 @@ class RowLabelingTest(QueryTest): @testing.fixture def assert_row_keys(self): def go(stmt, expected, coreorm_exec, selected_columns=None): - if coreorm_exec == "core": with testing.db.connect() as conn: row = conn.execute(stmt).first() @@ -824,7 +822,6 @@ class RowLabelingTest(QueryTest): stmt._label_style is not LABEL_STYLE_NONE and coreorm_exec == "orm" ): - for k in expected: is_not_none(getattr(row, k)) @@ -1608,7 +1605,6 @@ class InvalidGenerationsTest(QueryTest, AssertsCompiledSQL): (Query.order_by, lambda meth, User: meth(User.name)), ) def test_from_statement_text(self, meth, test_case): - User = self.classes.User s = fixture_session() q = s.query(User) @@ -1923,7 +1919,6 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): ) def test_selfref_relationship(self): - Node = self.classes.Node nalias = aliased(Node) @@ -2116,7 +2111,7 @@ class OperatorTest(QueryTest, AssertsCompiledSQL): def test_clauses(self): User, Address = self.classes.User, self.classes.Address - for (expr, compare) in ( + for expr, compare in ( (func.max(User.id), "max(users.id)"), (User.id.desc(), "users.id DESC"), ( @@ -4660,7 +4655,6 @@ class CountTest(QueryTest): eq_(q.distinct().count(), 3) def test_cols_future(self): - User, Address = self.classes.User, self.classes.Address s = fixture_session() @@ -6864,7 +6858,6 @@ class WithTransientOnNone(_fixtures.FixtureTest, AssertsCompiledSQL): Address.special_user == User(id=None, name=None) ) with expect_warnings("Got None for value of column"): - self.assert_compile( q, "SELECT addresses.id AS addresses_id, " @@ -6983,7 +6976,6 @@ class WithTransientOnNone(_fixtures.FixtureTest, AssertsCompiledSQL): ) ) with expect_warnings("Got None for value of column"): - self.assert_compile( q, "SELECT users.id AS users_id, users.name AS users_name " diff --git a/test/orm/test_recursive_loaders.py b/test/orm/test_recursive_loaders.py index 4a66661311..53f0166c0d 100644 --- a/test/orm/test_recursive_loaders.py +++ b/test/orm/test_recursive_loaders.py @@ -52,7 +52,6 @@ class _NodeTest: @classmethod def setup_mappers(cls): - nodes = cls.tables.nodes Node = cls.classes.Node @@ -182,7 +181,6 @@ class DeepRecursiveTest(_NodeTest, fixtures.MappedTest): @testing.fixture def limited_cache_conn(self, connection): - connection.engine._compiled_cache.clear() assert_limit = 0 diff --git a/test/orm/test_rel_fn.py b/test/orm/test_rel_fn.py index f937802c32..5b2a15c13a 100644 --- a/test/orm/test_rel_fn.py +++ b/test/orm/test_rel_fn.py @@ -1137,7 +1137,6 @@ class DetermineJoinTest(_JoinFixtures, fixtures.TestBase, AssertsCompiledSQL): ) def test_determine_join_ambiguous_fks_m2m(self): - self._assert_raises_ambig_join( relationships.JoinCondition, "Whatever.foo", diff --git a/test/orm/test_relationship_criteria.py b/test/orm/test_relationship_criteria.py index c02f7af4c3..d03b79e892 100644 --- a/test/orm/test_relationship_criteria.py +++ b/test/orm/test_relationship_criteria.py @@ -624,7 +624,6 @@ class LoaderCriteriaTest(_Fixtures, testing.AssertsCompiledSQL): ) ) elif style.from_statement: - stmt = ( select(Order.id, Order.description) .from_statement(stmt) @@ -916,7 +915,6 @@ class LoaderCriteriaTest(_Fixtures, testing.AssertsCompiledSQL): s = Session(testing.db, future=True) with self.sql_execution_asserter() as asserter: - s.execute(stmt).all() asserter.assert_( @@ -941,7 +939,6 @@ class LoaderCriteriaTest(_Fixtures, testing.AssertsCompiledSQL): User, Address = user_address_fixture def get_statement(closure="name"): - stmt = select(User).options( selectinload(User.addresses), with_loader_criteria( @@ -1060,7 +1057,6 @@ class LoaderCriteriaTest(_Fixtures, testing.AssertsCompiledSQL): User, Address = user_address_fixture def get_statement(closure="name"): - stmt = ( select(User) .options( @@ -1356,7 +1352,6 @@ class LoaderCriteriaTest(_Fixtures, testing.AssertsCompiledSQL): ) with self.sql_execution_asserter() as asserter: - s.execute(stmt) asserter.assert_( @@ -1878,7 +1873,6 @@ class RelationshipCriteriaTest(_Fixtures, testing.AssertsCompiledSQL): for value in "ed@wood.com", "ed@lala.com": s.close() with self.sql_execution_asserter() as asserter: - result = go(value) eq_( @@ -2208,7 +2202,6 @@ class RelationshipCriteriaTest(_Fixtures, testing.AssertsCompiledSQL): for value in "ed@wood.com", "ed@lala.com": with self.sql_execution_asserter() as asserter: - result = go(value) eq_( @@ -2281,7 +2274,6 @@ class RelationshipCriteriaTest(_Fixtures, testing.AssertsCompiledSQL): for value in "ed@wood.com", "ed@lala.com": with self.sql_execution_asserter() as asserter: - result = go(value) eq_( diff --git a/test/orm/test_selectin_relations.py b/test/orm/test_selectin_relations.py index f1d49890b6..2fdc12574f 100644 --- a/test/orm/test_selectin_relations.py +++ b/test/orm/test_selectin_relations.py @@ -164,7 +164,6 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): for i in range(3): def go(): - sess = fixture_session() u = aliased(User) @@ -202,7 +201,6 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): self.assert_sql_count(testing.db, go, 2) def test_from_aliased_w_cache_three(self): - User, Dingaling, Address = self.user_dingaling_fixture() for i in range(3): @@ -860,7 +858,6 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): ) def test_double_w_ac_against_subquery(self): - ( users, orders, @@ -930,7 +927,6 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): self._run_double_test() def test_double_w_ac(self): - ( users, orders, @@ -1833,7 +1829,6 @@ class BaseRelationFromJoinedSubclassTest(_Polymorphic): @classmethod def insert_data(cls, connection): - e1 = Engineer(primary_language="java") e2 = Engineer(primary_language="c++") e1.paperwork = [ @@ -2168,7 +2163,6 @@ class HeterogeneousSubtypesTest(fixtures.DeclarativeMappedTest): sess.commit() def test_one_to_many(self): - Company, Programmer, Manager, GolfSwing, Language = self.classes( "Company", "Programmer", "Manager", "GolfSwing", "Language" ) @@ -2449,7 +2443,6 @@ class ChunkingTest(fixtures.DeclarativeMappedTest): .offset(offset) .options(selectinload(A.bs)) ): - # this part fails with joined eager loading # (if you enable joined eager w/ yield_per) eq_(a.bs, [B(id=(a.id * 6) + j) for j in range(1, 6)]) @@ -3701,7 +3694,6 @@ class TestCompositePlusNonComposite(fixtures.DeclarativeMappedTest): s.commit() def test_load_composite_then_non_composite(self): - A, B, A2, B2 = self.classes("A", "B", "A2", "B2") s = fixture_session() diff --git a/test/orm/test_subquery_relations.py b/test/orm/test_subquery_relations.py index 6da0e90108..1a83a58be8 100644 --- a/test/orm/test_subquery_relations.py +++ b/test/orm/test_subquery_relations.py @@ -989,7 +989,6 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): ) def test_double_w_ac_against_subquery(self): - ( users, orders, @@ -1053,7 +1052,6 @@ class EagerTest(_fixtures.FixtureTest, testing.AssertsCompiledSQL): self._run_double_test() def test_double_w_ac(self): - ( users, orders, @@ -1894,7 +1892,6 @@ class BaseRelationFromJoinedSubclassTest(_Polymorphic): @classmethod def insert_data(cls, connection): - e1 = Engineer(primary_language="java") e2 = Engineer(primary_language="c++") e1.paperwork = [ @@ -3090,7 +3087,6 @@ class SubqueryloadDistinctTest( self._run_test_m2o(None, False) def _run_test_m2o(self, director_strategy_level, photo_strategy_level): - # test where the innermost is m2o, e.g. # Movie->director @@ -3538,7 +3534,6 @@ class FromSubqTest(fixtures.DeclarativeMappedTest): cache = {} for i in range(3): - subq = ( s.query(B) .join(B.a) @@ -3616,7 +3611,6 @@ class FromSubqTest(fixtures.DeclarativeMappedTest): s.close() def test_subq_w_from_self_two(self): - A, B, C = self.classes("A", "B", "C") s = fixture_session() @@ -3625,7 +3619,6 @@ class FromSubqTest(fixtures.DeclarativeMappedTest): for i in range(3): def go(): - subq = s.query(B).join(B.a).subquery() bq = aliased(B, subq) diff --git a/test/orm/test_transaction.py b/test/orm/test_transaction.py index c7df66e9d5..d6f22622ea 100644 --- a/test/orm/test_transaction.py +++ b/test/orm/test_transaction.py @@ -172,7 +172,6 @@ class SessionTransactionTest(fixtures.RemovesEvents, FixtureTest): assert not connection.in_transaction() elif external_state.transaction: - assert t1 is not None if ( @@ -626,7 +625,6 @@ class SessionTransactionTest(fixtures.RemovesEvents, FixtureTest): "do_commit", side_effect=testing.db.dialect.do_commit, ) as succeed_mock: - # sess.begin() -> commit(). why would do_rollback() be called? # because of connection pool finalize_fairy *after* the commit. # this will cause the conn.close() in session.commit() to fail, @@ -1009,7 +1007,6 @@ class _LocalFixture(FixtureTest): def subtransaction_recipe_one(self): @contextlib.contextmanager def transaction(session): - if session.in_transaction(): outermost = False else: @@ -1173,12 +1170,10 @@ class SubtransactionRecipeTest(FixtureTest): self.mapper_registry.map_imperatively(User, users) with fixture_session() as sess: - sess.begin() sess.begin_nested() with subtransaction_recipe(sess): - sess.add(User(name="u1")) sess.commit() @@ -2173,7 +2168,6 @@ class ContextManagerPlusFutureTest(FixtureTest): class TransactionFlagsTest(fixtures.TestBase): def test_in_transaction(self): with fixture_session() as s1: - eq_(s1.in_transaction(), False) trans = s1.begin() @@ -2233,7 +2227,6 @@ class TransactionFlagsTest(fixtures.TestBase): def test_in_transaction_nesting(self): with fixture_session() as s1: - eq_(s1.in_transaction(), False) trans = s1.begin() @@ -2685,7 +2678,6 @@ class LegacyJoinIntoAnExternalTransactionTest( @event.listens_for(self.session, "after_transaction_end") def restart_savepoint(session, transaction): if transaction.nested and not transaction._parent.nested: - # ensure that state is expired the way # session.commit() at the top level normally does # (optional step) diff --git a/test/orm/test_unitofwork.py b/test/orm/test_unitofwork.py index 4f49461c24..78b56f1d46 100644 --- a/test/orm/test_unitofwork.py +++ b/test/orm/test_unitofwork.py @@ -1035,7 +1035,6 @@ class ColumnCollisionTest(fixtures.MappedTest): self.mapper_registry.map_imperatively(Book, book) with fixture_session() as sess: - b1 = Book(book_id="abc", title="def") sess.add(b1) sess.flush() @@ -1468,7 +1467,6 @@ class ColumnPropertyTest(fixtures.MappedTest): Data = self.classes.Data with fixture_session() as sess: - d1 = Data(a="hello", b="there") sess.add(d1) sess.flush() diff --git a/test/orm/test_unitofworkv2.py b/test/orm/test_unitofworkv2.py index 4d04ce0a67..5cf8bd573f 100644 --- a/test/orm/test_unitofworkv2.py +++ b/test/orm/test_unitofworkv2.py @@ -3074,7 +3074,6 @@ class EagerDefaultsTest(fixtures.MappedTest): @testing.fixture def selectable_fixture(self, decl_base): - t1, t2 = self.tables("test", "test2") stmt = ( @@ -3768,7 +3767,6 @@ class ORMOnlyPrimaryKeyTest(fixtures.TestBase): @testing.requires.sequences_as_server_defaults @testing.requires.insert_returning def test_b(self, base, run_test): - seq = normalize_sequence(config, Sequence("x_seq")) class A(base): @@ -3871,13 +3869,11 @@ class TryToFoolInsertManyValuesTest(fixtures.TestBase): """ class Datum(decl_base): - __tablename__ = "datum" datum_id = Column(Integer, Identity(), primary_key=True) class Result(decl_base): - __tablename__ = "result" if pk_type.plain_autoinc: @@ -3913,7 +3909,6 @@ class TryToFoolInsertManyValuesTest(fixtures.TestBase): ) class ResultDatum(decl_base): - __tablename__ = "result_datum" result_id = Column(ForeignKey(Result.result_id), primary_key=True) @@ -4024,14 +4019,12 @@ class TryToFoolInsertManyValuesTest(fixtures.TestBase): """ class Datum(decl_base): - __tablename__ = "datum" datum_id = Column(Integer, primary_key=True) data = Column(String(10)) class Result(decl_base): - __tablename__ = "result" result_id = Column(Integer, primary_key=True) diff --git a/test/orm/test_validators.py b/test/orm/test_validators.py index c783b83668..990d6a4c4b 100644 --- a/test/orm/test_validators.py +++ b/test/orm/test_validators.py @@ -333,7 +333,6 @@ class ValidatorTest(_fixtures.FixtureTest): ) class User(fixtures.ComparableEntity): - if need_remove_param: @validates("addresses", **validate_kw) @@ -349,7 +348,6 @@ class ValidatorTest(_fixtures.FixtureTest): return item class Address(fixtures.ComparableEntity): - if need_remove_param: @validates("user", **validate_kw) diff --git a/test/orm/test_versioning.py b/test/orm/test_versioning.py index 7de90fc5cd..7f52af7156 100644 --- a/test/orm/test_versioning.py +++ b/test/orm/test_versioning.py @@ -432,7 +432,6 @@ class VersioningTest(fixtures.MappedTest): with patch.object( config.db.dialect, "supports_sane_multi_rowcount", False ), patch("sqlalchemy.engine.cursor.CursorResult.rowcount", rowcount): - Foo = self.classes.Foo s1 = self._fixture() f1s1 = Foo(value="f1 value") @@ -445,7 +444,6 @@ class VersioningTest(fixtures.MappedTest): eq_(f1s1.version_id, 2) def test_update_delete_no_plain_rowcount(self): - with patch.object( config.db.dialect, "supports_sane_rowcount", False ), patch.object( diff --git a/test/perf/compiled_extensions.py b/test/perf/compiled_extensions.py index 872165d072..0982d96ea7 100644 --- a/test/perf/compiled_extensions.py +++ b/test/perf/compiled_extensions.py @@ -1077,7 +1077,6 @@ class CacheAnonMap(Case): NUMBER = 1000000 def init_objects(self): - self.object_1 = column("x") self.object_2 = bindparam("y") @@ -1139,12 +1138,10 @@ class PrefixAnonMap(Case): @test_case def test_apply_non_present(self): - self.name.apply_map(self.impl_w_non_present) @test_case def test_apply_present(self): - self.name.apply_map(self.impl_w_present) diff --git a/test/perf/many_table_reflection.py b/test/perf/many_table_reflection.py index 8fb654bbe8..b9b941b688 100644 --- a/test/perf/many_table_reflection.py +++ b/test/perf/many_table_reflection.py @@ -398,7 +398,6 @@ def _apply_events(engine): def before_cursor_execute( conn, cursor, statement, parameters, context, executemany ): - nonlocal now now = time.time() diff --git a/test/perf/orm2010.py b/test/perf/orm2010.py index 61b4e9b89c..c069430fb1 100644 --- a/test/perf/orm2010.py +++ b/test/perf/orm2010.py @@ -100,7 +100,6 @@ def runit_persist(status, factor=1, query_runs=5): def runit_query_runs(status, factor=1, query_runs=5): - # do some heavier reading for i in range(query_runs): status("Heavy query run #%d" % (i + 1)) diff --git a/test/requirements.py b/test/requirements.py index 1d359349d7..4e57ff7292 100644 --- a/test/requirements.py +++ b/test/requirements.py @@ -1162,7 +1162,6 @@ class DefaultRequirements(SuiteRequirements): @property def sqlite_partial_indexes(self): - return only_on(self._sqlite_partial_idx) @property diff --git a/test/sql/test_case_statement.py b/test/sql/test_case_statement.py index 6893a94427..6907d21325 100644 --- a/test/sql/test_case_statement.py +++ b/test/sql/test_case_statement.py @@ -222,7 +222,6 @@ class CaseTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_text_doesnt_explode(self, connection): - for s in [ select( case( diff --git a/test/sql/test_compare.py b/test/sql/test_compare.py index 187d797297..8aeaf9b961 100644 --- a/test/sql/test_compare.py +++ b/test/sql/test_compare.py @@ -894,7 +894,6 @@ class CoreFixtures: return stmt def three(): - a1 = table_a.alias() a2 = table_a.alias() ex = exists().where(table_b.c.b == a1.c.a) @@ -921,7 +920,6 @@ class CoreFixtures: fixtures.append(_complex_fixtures) def _statements_w_context_options_fixtures(): - return [ select(table_a)._add_context_option(opt1, True), select(table_a)._add_context_option(opt1, 5), @@ -970,7 +968,6 @@ class CoreFixtures: return anon_col > 5 def three(): - l1, l2 = table_a.c.a.label(None), table_a.c.b.label(None) stmt = select(table_a.c.a, table_a.c.b, l1, l2) @@ -1482,7 +1479,6 @@ class CompareClausesTest(fixtures.TestBase): ) def test_compare_metadata_tables_annotations_two(self): - t1 = Table("a", MetaData(), Column("q", Integer), Column("p", Integer)) t2 = Table("a", MetaData(), Column("q", Integer), Column("p", Integer)) @@ -1516,7 +1512,6 @@ class CompareClausesTest(fixtures.TestBase): ne_(t3._generate_cache_key(), t4._generate_cache_key()) 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 @@ -1535,7 +1530,6 @@ class CompareClausesTest(fixtures.TestBase): is_false(l1.compare(l3)) 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) @@ -1547,7 +1541,6 @@ class CompareClausesTest(fixtures.TestBase): is_false(l1.compare(l3)) def test_compare_clauselist_not_associative(self): - l1 = ClauseList( table_c.c.x, table_c.c.y, table_d.c.y, operator=operators.sub ) @@ -1560,7 +1553,6 @@ class CompareClausesTest(fixtures.TestBase): is_false(l1.compare(l2)) def test_compare_clauselist_assoc_different_operator(self): - l1 = and_(table_c.c.x == table_d.c.y, table_c.c.y == table_d.c.z) l2 = or_(table_c.c.y == table_d.c.z, table_c.c.x == table_d.c.y) @@ -1568,7 +1560,6 @@ class CompareClausesTest(fixtures.TestBase): is_false(l1.compare(l2)) def test_compare_clauselist_not_assoc_different_operator(self): - l1 = ClauseList( table_c.c.x, table_c.c.y, table_d.c.y, operator=operators.sub ) diff --git a/test/sql/test_compiler.py b/test/sql/test_compiler.py index 648056cde5..63ccb961f1 100644 --- a/test/sql/test_compiler.py +++ b/test/sql/test_compiler.py @@ -245,7 +245,6 @@ class SelectTest(fixtures.TestBase, AssertsCompiledSQL): assert not hasattr(c1, "__dict__") def test_compile_label_is_slots(self): - c1 = compiler._CompileLabel(column("q"), "somename") eq_(c1.name, "somename") @@ -1160,7 +1159,6 @@ class SelectTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_dupe_columns_use_labels_from_anon(self): - t = table("t", column("a"), column("b")) a = t.alias() @@ -2302,7 +2300,6 @@ class SelectTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_literal(self): - self.assert_compile( select(literal("foo")), "SELECT :param_1 AS anon_1" ) @@ -3089,7 +3086,6 @@ class SelectTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_over_framespec(self): - expr = table1.c.myid self.assert_compile( select(func.row_number().over(order_by=expr, rows=(0, None))), @@ -3509,7 +3505,6 @@ class SelectTest(fixtures.TestBase, AssertsCompiledSQL): self.assert_compile(stmt, expected, dialect=dialect) def test_statement_hints(self): - stmt = ( select(table1.c.myid) .with_statement_hint("test hint one") @@ -3680,7 +3675,6 @@ class BindParameterTest(AssertsCompiledSQL, fixtures.TestBase): [5, 6], ), ]: - self.assert_compile( stmt, expected_named_stmt, params=expected_default_params_dict ) @@ -3923,7 +3917,6 @@ class BindParameterTest(AssertsCompiledSQL, fixtures.TestBase): ) def test_bind_anon_name_special_chars_uniqueify_two(self): - t = table("t", column("_3foo"), column("4(foo")) self.assert_compile( @@ -4095,7 +4088,6 @@ class BindParameterTest(AssertsCompiledSQL, fixtures.TestBase): def test_construct_params_combine_extracted( self, stmt1, stmt2, param1, param2, extparam1, extparam2 ): - if extparam1: keys = list(extparam1) else: @@ -4548,7 +4540,6 @@ class BindParameterTest(AssertsCompiledSQL, fixtures.TestBase): @testing.variation("scalar_subquery", [True, False]) def test_select_in(self, scalar_subquery): - stmt = select(table2.c.otherid, table2.c.othername) if scalar_subquery: @@ -6032,7 +6023,6 @@ class StringifySpecialTest(fixtures.TestBase): ) def test_dialect_specific_ddl(self): - from sqlalchemy.dialects.postgresql import ExcludeConstraint m = MetaData() @@ -7554,7 +7544,6 @@ class ResultMapTest(fixtures.TestBase): class MyCompiler(compiler.SQLCompiler): def visit_select(self, stmt, *arg, **kw): - if stmt is stmt2.element: with self._nested_result() as nested: contexts[stmt2.element] = nested @@ -7714,7 +7703,6 @@ class ResultMapTest(fixtures.TestBase): proxied = [obj[0] for (k, n, obj, type_) in compiled._result_columns] for orig_obj, proxied_obj in zip(orig, proxied): - is_(orig_obj, proxied_obj) diff --git a/test/sql/test_constraints.py b/test/sql/test_constraints.py index dbdab33077..54fcba576c 100644 --- a/test/sql/test_constraints.py +++ b/test/sql/test_constraints.py @@ -810,7 +810,6 @@ class ConstraintCompilationTest(fixtures.TestBase, AssertsCompiledSQL): ("sometable", "this_name_is_too_long", "ix_sometable_t_09aa"), ("sometable", "this_name_alsois_long", "ix_sometable_t_3cf1"), ]: - t1 = Table( tname, MetaData(), Column(cname, Integer, index=True) ) diff --git a/test/sql/test_cte.py b/test/sql/test_cte.py index 4ba4eddfeb..64e8732b78 100644 --- a/test/sql/test_cte.py +++ b/test/sql/test_cte.py @@ -32,7 +32,6 @@ from sqlalchemy.testing import fixtures class CTETest(fixtures.TestBase, AssertsCompiledSQL): - __dialect__ = "default_enhanced" def test_nonrecursive(self): @@ -1530,7 +1529,6 @@ class CTETest(fixtures.TestBase, AssertsCompiledSQL): eq_(stmt.compile().isupdate, False) def test_pg_example_three(self): - parts = table("parts", column("part"), column("sub_part")) included_parts = ( @@ -1747,7 +1745,6 @@ class CTETest(fixtures.TestBase, AssertsCompiledSQL): ) def test_textual_select_uses_independent_cte_two(self): - foo = table("foo", column("id")) bar = table("bar", column("id"), column("attr"), column("foo_id")) s1 = select(foo.c.id) @@ -1990,7 +1987,6 @@ class CTETest(fixtures.TestBase, AssertsCompiledSQL): class NestingCTETest(fixtures.TestBase, AssertsCompiledSQL): - __dialect__ = "default_enhanced" def test_select_with_nesting_cte_in_cte(self): @@ -2324,7 +2320,6 @@ class NestingCTETest(fixtures.TestBase, AssertsCompiledSQL): def test_nesting_cte_in_recursive_cte_positional( self, nesting_cte_in_recursive_cte ): - self.assert_compile( nesting_cte_in_recursive_cte, "WITH RECURSIVE rec_cte(outer_cte) AS (WITH nesting AS " @@ -2695,7 +2690,6 @@ class NestingCTETest(fixtures.TestBase, AssertsCompiledSQL): def test_recursive_nesting_cte_in_recursive_cte_positional( self, recursive_nesting_cte_in_recursive_cte ): - self.assert_compile( recursive_nesting_cte_in_recursive_cte, "WITH RECURSIVE rec_cte(outer_cte) AS (" diff --git a/test/sql/test_defaults.py b/test/sql/test_defaults.py index 01f6b290cf..bbfb3b0778 100644 --- a/test/sql/test_defaults.py +++ b/test/sql/test_defaults.py @@ -117,7 +117,6 @@ class DDLTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_literal_binds_pgarray(self): - m = MetaData() t = Table( "t", @@ -1098,7 +1097,6 @@ class PKIncrementTest(fixtures.TablesTest): class AutoIncrementTest(fixtures.TestBase): - __backend__ = True @testing.requires.empty_inserts diff --git a/test/sql/test_deprecations.py b/test/sql/test_deprecations.py index 65f6e77768..dbb5644cd1 100644 --- a/test/sql/test_deprecations.py +++ b/test/sql/test_deprecations.py @@ -357,7 +357,6 @@ class SelectableTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_alias_union(self): - # same as testunion, except its an alias of the union u = ( @@ -667,7 +666,6 @@ class PKIncrementTest(fixtures.TablesTest): class TableDeprecationTest(fixtures.TestBase): def test_mustexists(self): with testing.expect_deprecated("Deprecated alias of .*must_exist"): - with testing.expect_raises_message( exc.InvalidRequestError, "Table 'foo' not defined" ): diff --git a/test/sql/test_functions.py b/test/sql/test_functions.py index f7acfb1aec..e961a4e465 100644 --- a/test/sql/test_functions.py +++ b/test/sql/test_functions.py @@ -216,7 +216,6 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL): self.assert_compile(func.random(), ret, dialect=dialect) def test_cube_operators(self): - t = table( "t", column("value"), @@ -458,7 +457,6 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL): assert_raises(TypeError, func.char_length) def test_return_type_detection(self): - for fn in [func.coalesce, func.max, func.min, func.sum]: for args, type_ in [ ( @@ -882,7 +880,6 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_as_comparison(self): - fn = func.substring("foo", "foobar").as_comparison(1, 2) is_(fn.type._type_affinity, Boolean) @@ -900,7 +897,6 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_as_comparison_annotate(self): - fn = func.foobar("x", "y", "q", "p", "r").as_comparison(2, 5) from sqlalchemy.sql import annotation @@ -911,7 +907,6 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL): eq_(fn_annotated.left._annotations, {"token": "yes"}) def test_as_comparison_many_argument(self): - fn = func.some_comparison("x", "y", "z", "p", "q", "r").as_comparison( 2, 5 ) @@ -978,7 +973,6 @@ class ReturnTypeTest(AssertsCompiledSQL, fixtures.TestBase): eq_(expr.type.dimensions, col.type.dimensions) def test_array_agg_array_literal_implicit_type(self): - expr = array([column("data", Integer), column("d2", Integer)]) assert isinstance(expr.type, PG_ARRAY) @@ -1225,7 +1219,6 @@ class RegisterTest(fixtures.TestBase, AssertsCompiledSQL): assert "GenericFunction" not in functions._registry["_default"] def test_register_function(self): - # test generic function registering class registered_func(GenericFunction): _register = True @@ -1390,7 +1383,6 @@ class TableValuedCompileTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_scalar_subquery(self): - a = table( "a", column("id"), @@ -1702,7 +1694,6 @@ class TableValuedCompileTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_named_table_valued(self): - fn = ( func.json_to_recordset( # noqa '[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]' @@ -1721,7 +1712,6 @@ class TableValuedCompileTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_named_table_valued_w_quoting(self): - fn = ( func.json_to_recordset( # noqa '[{"CaseSensitive":1,"the % value":"foo"}, ' @@ -1743,7 +1733,6 @@ class TableValuedCompileTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_named_table_valued_subquery(self): - fn = ( func.json_to_recordset( # noqa '[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]' @@ -1766,7 +1755,6 @@ class TableValuedCompileTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_named_table_valued_alias(self): - """select * from json_to_recordset ('[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]') as x(a int, b text);""" diff --git a/test/sql/test_identity_column.py b/test/sql/test_identity_column.py index 00404dae79..87d5e9f09f 100644 --- a/test/sql/test_identity_column.py +++ b/test/sql/test_identity_column.py @@ -65,7 +65,6 @@ class _IdentityDDLFixture(testing.AssertsCompiledSQL): ), ) def test_create_ddl(self, identity_args, text): - if getattr( self, "__dialect__", None ) != "default_enhanced" and testing.against("oracle"): @@ -198,7 +197,6 @@ class NotSupportingIdentityDDL(testing.AssertsCompiledSQL, fixtures.TestBase): @testing.combinations("sqlite", "mysql", "mariadb", "postgresql", "oracle") def test_identity_is_ignored(self, dialect): - t = Table( "foo_table", MetaData(), diff --git a/test/sql/test_insert.py b/test/sql/test_insert.py index 904271fcb6..ddfb9aea20 100644 --- a/test/sql/test_insert.py +++ b/test/sql/test_insert.py @@ -1477,7 +1477,6 @@ class MultirowTest(_InsertTestBase, fixtures.TablesTest, AssertsCompiledSQL): table1.c.description, ) elif column_style == "inspectables": - myid, name, description = ( ORMExpr(table1.c.myid), ORMExpr(table1.c.name), diff --git a/test/sql/test_insert_exec.py b/test/sql/test_insert_exec.py index 0fee9bd35a..29484696da 100644 --- a/test/sql/test_insert_exec.py +++ b/test/sql/test_insert_exec.py @@ -69,7 +69,6 @@ class InsertExecTest(fixtures.TablesTest): @testing.requires.multivalues_inserts @testing.combinations("string", "column", "expect", argnames="keytype") def test_multivalues_insert(self, connection, keytype): - users = self.tables.users if keytype == "string": @@ -636,7 +635,6 @@ class TableInsertTest(fixtures.TablesTest): @testing.requires.sql_expressions_inserted_as_primary_key def test_sql_expr_lastrowid(self, connection): - # see also test.orm.test_unitofwork.py # ClauseAttributesTest.test_insert_pk_expression t = self.tables.foo_no_seq @@ -1103,7 +1101,6 @@ class InsertManyValuesTest(fixtures.RemovesEvents, fixtures.TablesTest): argnames="paramtype", ) def test_page_size_adjustment(self, testing_engine, batchsize, paramtype): - t = self.tables.data if paramtype == "engine" and batchsize is not None: @@ -1164,7 +1161,6 @@ class InsertManyValuesTest(fixtures.RemovesEvents, fixtures.TablesTest): ) def test_disabled(self, testing_engine): - e = testing_engine( options={"use_insertmanyvalues": False}, share_pool=True, @@ -1201,7 +1197,6 @@ class IMVSentinelTest(fixtures.TestBase): autoincrement_is_sequence=False, connection=None, ): - if connection: dialect = connection.dialect else: @@ -1212,7 +1207,6 @@ class IMVSentinelTest(fixtures.TestBase): and warn_for_downgrades and dialect.use_insertmanyvalues ): - if ( not separate_sentinel and ( @@ -1766,7 +1760,6 @@ class IMVSentinelTest(fixtures.TestBase): default_type, sort_by_parameter_order, ): - t1 = Table( "data", metadata, @@ -1865,7 +1858,6 @@ class IMVSentinelTest(fixtures.TestBase): metadata, connection, ): - if pk_type.plain_autoinc: pk_col = Column("id", Integer, primary_key=True) elif pk_type.sequence: @@ -2304,7 +2296,6 @@ class IMVSentinelTest(fixtures.TestBase): metadata.create_all(connection) return else: - metadata.create_all(connection) fixtures.insertmanyvalues_fixture( @@ -2439,7 +2430,6 @@ class IMVSentinelTest(fixtures.TestBase): sentinel_type, add_sentinel_flag_to_col, ): - if sentinel_type.identity: sentinel_args = [Identity()] elif sentinel_type.sequence: @@ -2761,7 +2751,6 @@ class IMVSentinelTest(fixtures.TestBase): metadata.create_all(engine) with engine.connect() as conn: - fixtures.insertmanyvalues_fixture( conn, randomize_rows=bool(randomize_returning), diff --git a/test/sql/test_inspect.py b/test/sql/test_inspect.py index d2a2c1c484..c420f52595 100644 --- a/test/sql/test_inspect.py +++ b/test/sql/test_inspect.py @@ -44,7 +44,6 @@ class TestCoreInspection(fixtures.TestBase): assert not hasattr(Foo(), "__clause_element__") def test_col_now_has_a_clauseelement(self): - x = Column("foo", Integer) assert hasattr(x, "__clause_element__") diff --git a/test/sql/test_lambdas.py b/test/sql/test_lambdas.py index 002a13db94..eed861fe17 100644 --- a/test/sql/test_lambdas.py +++ b/test/sql/test_lambdas.py @@ -227,7 +227,6 @@ class LambdaElementTest( def test_stale_checker_embedded(self): def go(x): - stmt = select(lambda: x) return stmt @@ -245,7 +244,6 @@ class LambdaElementTest( def test_stale_checker_statement(self): def go(x): - stmt = lambdas.lambda_stmt(lambda: select(x)) return stmt @@ -263,7 +261,6 @@ class LambdaElementTest( def test_stale_checker_linked(self): def go(x, y): - stmt = lambdas.lambda_stmt(lambda: select(x)) + ( lambda s: s.where(y > 5) ) @@ -434,7 +431,6 @@ class LambdaElementTest( ) def test_boolean_conditionals(self): - tab = table("foo", column("id"), column("col")) def run_my_statement(parameter, add_criteria=False): @@ -837,7 +833,6 @@ class LambdaElementTest( ne_(s1key[0], s2key[0]) def test_stmt_lambda_w_set_of_opts(self): - stmt = lambdas.lambda_stmt(lambda: select(column("x"))) class MyUncacheable(ExecutableOption): @@ -1168,7 +1163,6 @@ class LambdaElementTest( ) def test_in_parameters_one(self): - expr1 = select(1).where(column("q").in_(["a", "b", "c"])) self.assert_compile(expr1, "SELECT 1 WHERE q IN (__[POSTCOMPILE_q_1])") @@ -1393,7 +1387,6 @@ class LambdaElementTest( x = 5 def my_lambda(): - y = 10 z = y + 18 @@ -1424,7 +1417,6 @@ class LambdaElementTest( z = 10 def my_lambda(): - y = x + z expr1 = users.c.name > x @@ -1457,7 +1449,6 @@ class LambdaElementTest( z = 10 def my_lambda(): - y = 10 + z expr1 = users.c.name > x diff --git a/test/sql/test_metadata.py b/test/sql/test_metadata.py index a8c6bdbbe9..dce5b9984f 100644 --- a/test/sql/test_metadata.py +++ b/test/sql/test_metadata.py @@ -442,7 +442,6 @@ class MetaDataTest(fixtures.TestBase, ComparesTables): ) def test_fk_mismatched_local_remote_cols(self): - assert_raises_message( exc.ArgumentError, "ForeignKeyConstraint number of constrained columns must " @@ -1518,7 +1517,6 @@ class ToMetaDataTest(fixtures.TestBase, AssertsCompiledSQL, ComparesTables): @emits_warning("Table '.+' already exists within the given MetaData") def test_already_exists(self): - meta1 = MetaData() table1 = Table( "mytable", meta1, Column("myid", Integer, primary_key=True) @@ -1780,7 +1778,6 @@ class TableTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_reset_exported_passes(self): - m = MetaData() t = Table("t", m, Column("foo", Integer)) @@ -1959,7 +1956,6 @@ class TableTest(fixtures.TestBase, AssertsCompiledSQL): "Table 't' specifies columns 'a', 'b', 'c' as primary_key=True, " "not matching locally specified columns 'b', 'c'" ): - Table( "t", m, @@ -2292,7 +2288,6 @@ class SchemaTypeTest(fixtures.TestBase): self._test_before_parent_attach(typ) def test_before_parent_attach_variant_array_schematype(self): - target = Enum("one", "two", "three") typ = ARRAY(target).with_variant(String(), "other") self._test_before_parent_attach(typ, evt_target=target) @@ -2685,7 +2680,6 @@ class SchemaTest(fixtures.TestBase, AssertsCompiledSQL): eq_ignore_whitespace(str(element), expected) def test_create_drop_schema(self): - self.assert_compile( schema.CreateSchema("sa_schema"), "CREATE SCHEMA sa_schema" ) @@ -2766,7 +2760,6 @@ class UseExistingTest(testing.AssertsCompiledSQL, fixtures.TablesTest): def test_table_w_two_same_named_columns( self, empty_meta, scenario: Variation, both_have_keys: Variation ): - if scenario.inplace: with expect_raises_message( exc.DuplicateColumnError, @@ -3742,7 +3735,6 @@ class ConstraintTest(fixtures.TestBase): assert c in t.indexes def test_auto_append_lowercase_table(self): - t = table("t", column("a")) t2 = table("t2", column("a")) for c in ( @@ -4088,7 +4080,6 @@ class ConstraintTest(fixtures.TestBase): return t, ClauseElement(t.c.q) def test_pickle_fk_annotated_col(self, no_pickle_annotated): - t, q_col = no_pickle_annotated t2 = Table("t2", t.metadata, Column("p", ForeignKey(q_col))) @@ -4175,7 +4166,6 @@ class ColumnDefinitionTest(AssertsCompiledSQL, fixtures.TestBase): assert col.name == c[i].name def test_name_none(self): - c = Column(Integer) assert_raises_message( exc.ArgumentError, @@ -4188,7 +4178,6 @@ class ColumnDefinitionTest(AssertsCompiledSQL, fixtures.TestBase): ) def test_name_blank(self): - c = Column("", Integer) assert_raises_message( exc.ArgumentError, @@ -4399,7 +4388,6 @@ class ColumnDefinitionTest(AssertsCompiledSQL, fixtures.TestBase): paramname, value, ): - args = [] params = {} if paramname == "type" or isinstance( @@ -4514,7 +4502,6 @@ class ColumnDefinitionTest(AssertsCompiledSQL, fixtures.TestBase): value, override_value, ): - args = [] params = {} override_args = [] @@ -4716,7 +4703,6 @@ class ColumnOptionsTest(fixtures.TestBase): self._no_error(Column("foo", ForeignKey("bar.id"), Sequence("a"))) def test_column_info(self): - c1 = Column("foo", String, info={"x": "y"}) c2 = Column("bar", String, info={}) c3 = Column("bat", String) diff --git a/test/sql/test_quote.py b/test/sql/test_quote.py index 62ec007503..08c9c4207e 100644 --- a/test/sql/test_quote.py +++ b/test/sql/test_quote.py @@ -530,7 +530,6 @@ class QuoteTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_subquery_four(self): - # Not lower case names, quotes off, should not quote metadata = MetaData() t1 = Table( diff --git a/test/sql/test_roles.py b/test/sql/test_roles.py index d181e0d1ac..09e34691e8 100644 --- a/test/sql/test_roles.py +++ b/test/sql/test_roles.py @@ -420,7 +420,6 @@ class SubqueryCoercionsTest(fixtures.TestBase, AssertsCompiledSQL): is_true(coerced.compare(stmt.scalar_subquery().label(None))) def test_scalar_select(self): - with testing.expect_warnings( "implicitly coercing SELECT object to scalar subquery" ): diff --git a/test/sql/test_select.py b/test/sql/test_select.py index 5268c41dca..e772c5911d 100644 --- a/test/sql/test_select.py +++ b/test/sql/test_select.py @@ -545,11 +545,9 @@ class ColumnCollectionAsSelectTest(fixtures.TestBase, AssertsCompiledSQL): eq_(list(coll), [table1.c.name, table1.c.description]) def test_missing_key(self): - with expect_raises_message(KeyError, "unknown"): table1.c["myid", "unknown"] def test_missing_index(self): - with expect_raises_message(IndexError, "5"): table1.c["myid", 5] diff --git a/test/sql/test_selectable.py b/test/sql/test_selectable.py index baa8d89611..a146a94c60 100644 --- a/test/sql/test_selectable.py +++ b/test/sql/test_selectable.py @@ -907,7 +907,6 @@ class SelectableTest( ) def test_join_against_join(self): - j = outerjoin(table1, table2, table1.c.col1 == table2.c.col2) jj = ( select(table1.c.col1.label("bar_col1")) @@ -975,7 +974,6 @@ class SelectableTest( ) def test_union_correspondence(self): - # tests that we can correspond a column in a Select statement # with a certain Table, against a column in a Union where one of # its underlying Selects matches to that same Table @@ -1069,7 +1067,6 @@ class SelectableTest( assert u.selected_columns.col3 is not None def test_alias_union(self): - # same as testunion, except its an alias of the union u = ( @@ -1347,7 +1344,6 @@ class SelectableTest( assert u1.corresponding_column(table2.c.col3) is u1.c._all_columns[2] def test_select_union(self): - # like testaliasunion, but off a Select off the union. u = ( @@ -1384,7 +1380,6 @@ class SelectableTest( assert s.corresponding_column(s2.c.table2_col2) is s.c.col2 def test_union_against_join(self): - # same as testunion, except its an alias of the union u = ( @@ -2106,7 +2101,7 @@ class JoinConditionTest(fixtures.TestBase, AssertsCompiledSQL): t1t2 = t1.join(t2) t2t3 = t2.join(t3) - for (left, right, a_subset, expected) in [ + for left, right, a_subset, expected in [ (t1, t2, None, t1.c.id == t2.c.t1id), (t1t2, t3, t2, t1t2.c.t2_id == t3.c.t2id), (t2t3, t1, t3, t1.c.id == t3.c.t1id), @@ -3457,7 +3452,6 @@ class AnnotationsTest(fixtures.TestBase): lambda s: visitors.cloned_traverse(s, {}, {}), lambda s: visitors.replacement_traverse(s, {}, lambda x: None), ): - sel = fn(select(fn(select(fn(s.subquery())).subquery()))) eq_(str(assert_s), str(sel)) @@ -3917,7 +3911,6 @@ class ResultMapTest(fixtures.TestBase): ) def test_unary_boolean(self): - s1 = select(not_(True)).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) eq_( [type(entry[-1]) for entry in s1.compile()._result_columns], diff --git a/test/sql/test_sequences.py b/test/sql/test_sequences.py index 8acf030d02..f830d1c292 100644 --- a/test/sql/test_sequences.py +++ b/test/sql/test_sequences.py @@ -162,7 +162,6 @@ class SequenceExecTest(fixtures.TestBase): self._assert_seq_result(connection.scalar(s)) def test_execute_deprecated(self, connection): - s = normalize_sequence(config, Sequence("my_sequence", optional=True)) with expect_deprecated( diff --git a/test/sql/test_text.py b/test/sql/test_text.py index b5d9ae7407..de40c8f429 100644 --- a/test/sql/test_text.py +++ b/test/sql/test_text.py @@ -215,7 +215,6 @@ class SelectCompositionTest(fixtures.TestBase, AssertsCompiledSQL): ), ) def test_select_composition_nine(self, label_style, expected): - s1 = select(table1.c.myid, text("whatever")) if label_style: s1 = s1.set_label_style(label_style) @@ -257,7 +256,6 @@ class SelectCompositionTest(fixtures.TestBase, AssertsCompiledSQL): ), ) def test_select_composition_ten(self, label_style, expected): - s1 = select(table1.c.myid, text("whatever")) if label_style: s1 = s1.set_label_style(label_style) @@ -284,7 +282,6 @@ class SelectCompositionTest(fixtures.TestBase, AssertsCompiledSQL): ), ) def test_select_composition_eleven(self, label_style, expected): - stmt = select(table1.c.myid, text("whatever")) if label_style: stmt = stmt.set_label_style(label_style) @@ -301,7 +298,6 @@ class SelectCompositionTest(fixtures.TestBase, AssertsCompiledSQL): ), ) def test_select_selected_columns_ignores_text(self, label_style, expected): - stmt = select(table1.c.myid, text("whatever"), table1.c.description) if label_style: stmt = stmt.set_label_style(label_style) @@ -494,7 +490,6 @@ class BindParamTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_text_in_select_nonfrom(self): - generate_series = text( "generate_series(:x, :y, :z) as s(a)" ).bindparams(x=None, y=None, z=None) @@ -902,7 +897,6 @@ class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL): (column("q").op("+")(5).label("a"), "a DESC", (desc,)), ) def test_order_by_expr(self, case, expected, modifiers): - order_by = case for mod in modifiers: order_by = mod(order_by) @@ -942,7 +936,6 @@ class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL): self._test_exception(stmt, "foobar") def test_distinct_label(self): - stmt = select(table1.c.myid.label("foo")).distinct("foo") self.assert_compile( stmt, @@ -951,7 +944,6 @@ class OrderByLabelResolutionTest(fixtures.TestBase, AssertsCompiledSQL): ) def test_distinct_label_keyword(self): - stmt = select(table1.c.myid.label("foo")).distinct("foo") self.assert_compile( stmt, diff --git a/test/sql/test_type_expressions.py b/test/sql/test_type_expressions.py index 77502b4888..5585bdf433 100644 --- a/test/sql/test_type_expressions.py +++ b/test/sql/test_type_expressions.py @@ -24,7 +24,6 @@ class _ExprFixture: def _fixture(self): class MyString(String): - # supersedes any processing that might be on # String def bind_expression(self, bindvalue): diff --git a/test/sql/test_types.py b/test/sql/test_types.py index 47fe68354a..b980d75e8c 100644 --- a/test/sql/test_types.py +++ b/test/sql/test_types.py @@ -233,7 +233,6 @@ class AdaptTest(fixtures.TestBase): def _adaptions(): for typ in _all_types(omit_special_types=True): - # up adapt from LowerCase to UPPERCASE, # as well as to all non-sqltypes up_adaptions = [typ] + typ.__subclasses__() @@ -1017,7 +1016,6 @@ class BindProcessorInsertValuesTest(UserDefinedRoundTripTest): class UserDefinedTest( _UserDefinedTypeFixture, fixtures.TablesTest, AssertsCompiledSQL ): - run_create_tables = None run_inserts = None run_deletes = None @@ -3926,7 +3924,6 @@ class NumericRawSQLTest(fixtures.TestBase): class IntervalTest(fixtures.TablesTest, AssertsExecutionResults): - __backend__ = True @classmethod diff --git a/test/sql/test_update.py b/test/sql/test_update.py index d8de5c277b..72980ab55a 100644 --- a/test/sql/test_update.py +++ b/test/sql/test_update.py @@ -413,7 +413,6 @@ class UpdateTest(_UpdateFromTestBase, fixtures.TablesTest, AssertsCompiledSQL): ) def test_labels_no_collision(self): - t = table("foo", column("id"), column("foo_id")) self.assert_compile( @@ -980,7 +979,6 @@ class UpdateTest(_UpdateFromTestBase, fixtures.TablesTest, AssertsCompiledSQL): ) if paramstyle.qmark: - dialect = default.StrCompileDialect(paramstyle="qmark") self.assert_compile( upd, diff --git a/test/sql/test_utils.py b/test/sql/test_utils.py index 615995c731..74cf1eb4f2 100644 --- a/test/sql/test_utils.py +++ b/test/sql/test_utils.py @@ -168,7 +168,6 @@ class MiscTest(fixtures.TestBase): ), ) def test_unwrap_order_by(self, expr, expected): - expr = coercions.expect(roles.OrderByRole, expr) unwrapped = sql_util.unwrap_order_by(expr) diff --git a/tools/format_docs_code.py b/tools/format_docs_code.py index fcb844291c..7bae0126b0 100644 --- a/tools/format_docs_code.py +++ b/tools/format_docs_code.py @@ -167,7 +167,6 @@ def format_file( disable_format = False for line_no, line in enumerate(original.splitlines(), 1): - if ( line and not disable_format diff --git a/tools/generate_proxy_methods.py b/tools/generate_proxy_methods.py index cc039d4d68..857f8eb718 100644 --- a/tools/generate_proxy_methods.py +++ b/tools/generate_proxy_methods.py @@ -182,7 +182,6 @@ def process_class( attributes: Iterable[str], cls: Type[Any], ): - sphinx_symbol_match = re.match(r":class:`(.+)`", target_cls_sphinx_name) if not sphinx_symbol_match: raise Exception( @@ -341,7 +340,6 @@ def process_class( def process_module(modname: str, filename: str, cmd: code_writer_cmd) -> str: - class_entries = classes[modname] # use tempfile in same path as the module, or at least in the @@ -352,7 +350,6 @@ def process_module(modname: str, filename: str, cmd: code_writer_cmd) -> str: delete=False, suffix=".py", ) as buf, open(filename) as orig_py: - in_block = False current_clsname = None for line in orig_py: @@ -382,7 +379,6 @@ def process_module(modname: str, filename: str, cmd: code_writer_cmd) -> str: def run_module(modname: str, cmd: code_writer_cmd) -> None: - cmd.write_status(f"importing module {modname}\n") mod = importlib.import_module(modname) destination_path = mod.__file__ @@ -416,7 +412,6 @@ entries = [ ] if __name__ == "__main__": - cmd = code_writer_cmd(__file__) with cmd.add_arguments() as parser: diff --git a/tools/generate_sql_functions.py b/tools/generate_sql_functions.py index 794b844879..5845e89ad9 100644 --- a/tools/generate_sql_functions.py +++ b/tools/generate_sql_functions.py @@ -22,7 +22,6 @@ def _fns_in_deterministic_order(): def process_functions(filename: str, cmd: code_writer_cmd) -> str: - with NamedTemporaryFile( mode="w", delete=False, @@ -141,7 +140,6 @@ test_functions_py = "test/ext/mypy/plain_files/functions.py" if __name__ == "__main__": - cmd = code_writer_cmd(__file__) with cmd.run_program(): diff --git a/tools/generate_tuple_map_overloads.py b/tools/generate_tuple_map_overloads.py index 22259ebe12..476636b1d0 100644 --- a/tools/generate_tuple_map_overloads.py +++ b/tools/generate_tuple_map_overloads.py @@ -37,7 +37,6 @@ sys.path.append(str(Path(__file__).parent.parent)) def process_module(modname: str, filename: str, cmd: code_writer_cmd) -> str: - # use tempfile in same path as the module, or at least in the # current working directory, so that black / zimports use # local pyproject.toml @@ -115,7 +114,6 @@ def {current_fnname}( def run_module(modname: str, cmd: code_writer_cmd) -> None: - cmd.write_status(f"importing module {modname}\n") mod = importlib.import_module(modname) destination_path = mod.__file__ @@ -143,7 +141,6 @@ entries = [ ] if __name__ == "__main__": - cmd = code_writer_cmd(__file__) with cmd.add_arguments() as parser: diff --git a/tools/sync_test_files.py b/tools/sync_test_files.py index 4afa2dc8e7..f855cd12c2 100644 --- a/tools/sync_test_files.py +++ b/tools/sync_test_files.py @@ -31,7 +31,6 @@ remove_str = "# anno only: " def run_operation( name: str, source: str, dest: str, cmd: code_writer_cmd ) -> None: - source_data = Path(source).read_text().replace(remove_str, "") dest_data = header.format(source=source, this_file=this_file) + source_data diff --git a/tox.ini b/tox.ini index 0bbd76a93c..d2d77353ab 100644 --- a/tox.ini +++ b/tox.ini @@ -190,9 +190,8 @@ setenv= [testenv:lint] basepython = python3 deps= - flake8==5.0.0 - #flake8-import-order - git+https://github.com/sqlalchemyorg/flake8-import-order@fix_options + flake8==6.0.0 + flake8-import-order flake8-builtins flake8-future-annotations>=0.0.5 flake8-docstrings>=1.6.0 @@ -202,7 +201,7 @@ deps= # in case it requires a version pin pydocstyle pygments - black==22.8.0 + black==23.3.0 slotscheck>=0.12,<0.13 # this is to satisfy the mypy plugin dependency