Skip to content

Commit 600deb4

Browse files
committed
rename sqlalchemy.orm to sa_orm.
1 parent 48462d1 commit 600deb4

File tree

11 files changed

+70
-72
lines changed

11 files changed

+70
-72
lines changed

src/flask_sqlalchemy/extension.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
from weakref import WeakKeyDictionary
66

77
import sqlalchemy as sa
8-
import sqlalchemy.event
9-
import sqlalchemy.exc
10-
import sqlalchemy.orm
8+
import sqlalchemy.event as sa_event
9+
import sqlalchemy.exc as sa_exc
10+
import sqlalchemy.orm as sa_orm
1111
from flask import abort
1212
from flask import current_app
1313
from flask import Flask
@@ -127,7 +127,7 @@ def __init__(
127127
metadata: sa.MetaData | None = None,
128128
session_options: dict[str, t.Any] | None = None,
129129
query_class: type[Query] = Query,
130-
model_class: type[Model] | sqlalchemy.orm.DeclarativeMeta = Model,
130+
model_class: type[Model] | sa_orm.DeclarativeMeta = Model,
131131
engine_options: dict[str, t.Any] | None = None,
132132
add_models_to_shell: bool = True,
133133
):
@@ -338,7 +338,7 @@ def init_app(self, app: Flask) -> None:
338338

339339
def _make_scoped_session(
340340
self, options: dict[str, t.Any]
341-
) -> sqlalchemy.orm.scoped_session[Session]:
341+
) -> sa_orm.scoped_session[Session]:
342342
"""Create a :class:`sqlalchemy.orm.scoping.scoped_session` around the factory
343343
from :meth:`_make_session_factory`. The result is available as :attr:`session`.
344344
@@ -361,11 +361,11 @@ def _make_scoped_session(
361361
"""
362362
scope = options.pop("scopefunc", _app_ctx_id)
363363
factory = self._make_session_factory(options)
364-
return sqlalchemy.orm.scoped_session(factory, scope)
364+
return sa_orm.scoped_session(factory, scope)
365365

366366
def _make_session_factory(
367367
self, options: dict[str, t.Any]
368-
) -> sqlalchemy.orm.sessionmaker[Session]:
368+
) -> sa_orm.sessionmaker[Session]:
369369
"""Create the SQLAlchemy :class:`sqlalchemy.orm.sessionmaker` used by
370370
:meth:`_make_scoped_session`.
371371
@@ -388,7 +388,7 @@ def _make_session_factory(
388388
"""
389389
options.setdefault("class_", Session)
390390
options.setdefault("query_cls", self.Query)
391-
return sqlalchemy.orm.sessionmaker(db=self, **options)
391+
return sa_orm.sessionmaker(db=self, **options)
392392

393393
def _teardown_commit(self, exc: BaseException | None) -> None:
394394
"""Commit the session at the end of the request if there was not an unhandled
@@ -482,7 +482,7 @@ def __new__(
482482
return Table
483483

484484
def _make_declarative_base(
485-
self, model: type[Model] | sqlalchemy.orm.DeclarativeMeta
485+
self, model: type[Model] | sa_orm.DeclarativeMeta
486486
) -> type[t.Any]:
487487
"""Create a SQLAlchemy declarative model class. The result is available as
488488
:attr:`Model`.
@@ -503,9 +503,9 @@ def _make_declarative_base(
503503
.. versionchanged:: 2.3
504504
``model`` can be an already created declarative model class.
505505
"""
506-
if not isinstance(model, sqlalchemy.orm.DeclarativeMeta):
506+
if not isinstance(model, sa_orm.DeclarativeMeta):
507507
metadata = self._make_metadata(None)
508-
model = sqlalchemy.orm.declarative_base(
508+
model = sa_orm.declarative_base(
509509
metadata=metadata, cls=model, name="Model", metaclass=DefaultMeta
510510
)
511511

@@ -780,7 +780,7 @@ def one_or_404(
780780
"""
781781
try:
782782
return self.session.execute(statement).scalar_one()
783-
except (sqlalchemy.exc.NoResultFound, sqlalchemy.exc.MultipleResultsFound):
783+
except (sa_exc.NoResultFound, sa_exc.MultipleResultsFound):
784784
abort(404, description=description)
785785

786786
def paginate(
@@ -859,7 +859,7 @@ def _call_for_binds(
859859
if key is None:
860860
message = f"'SQLALCHEMY_DATABASE_URI' config is not set. {message}"
861861

862-
raise sqlalchemy.exc.UnboundExecutionError(message) from None
862+
raise sa_exc.UnboundExecutionError(message) from None
863863

864864
metadata = self.metadatas[key]
865865
getattr(metadata, op_name)(bind=engine)
@@ -936,31 +936,31 @@ def _set_rel_query(self, kwargs: dict[str, t.Any]) -> None:
936936

937937
def relationship(
938938
self, *args: t.Any, **kwargs: t.Any
939-
) -> sqlalchemy.orm.RelationshipProperty[t.Any]:
939+
) -> sa_orm.RelationshipProperty[t.Any]:
940940
"""A :func:`sqlalchemy.orm.relationship` that applies this extension's
941941
:attr:`Query` class for dynamic relationships and backrefs.
942942
943943
.. versionchanged:: 3.0
944944
The :attr:`Query` class is set on ``backref``.
945945
"""
946946
self._set_rel_query(kwargs)
947-
return sqlalchemy.orm.relationship(*args, **kwargs)
947+
return sa_orm.relationship(*args, **kwargs)
948948

949949
def dynamic_loader(
950950
self, argument: t.Any, **kwargs: t.Any
951-
) -> sqlalchemy.orm.RelationshipProperty[t.Any]:
951+
) -> sa_orm.RelationshipProperty[t.Any]:
952952
"""A :func:`sqlalchemy.orm.dynamic_loader` that applies this extension's
953953
:attr:`Query` class for relationships and backrefs.
954954
955955
.. versionchanged:: 3.0
956956
The :attr:`Query` class is set on ``backref``.
957957
"""
958958
self._set_rel_query(kwargs)
959-
return sqlalchemy.orm.dynamic_loader(argument, **kwargs)
959+
return sa_orm.dynamic_loader(argument, **kwargs)
960960

961961
def _relation(
962962
self, *args: t.Any, **kwargs: t.Any
963-
) -> sqlalchemy.orm.RelationshipProperty[t.Any]:
963+
) -> sa_orm.RelationshipProperty[t.Any]:
964964
"""A :func:`sqlalchemy.orm.relationship` that applies this extension's
965965
:attr:`Query` class for dynamic relationships and backrefs.
966966
@@ -973,8 +973,8 @@ def _relation(
973973
"""
974974
# Deprecated, removed in SQLAlchemy 2.0. Accessed through ``__getattr__``.
975975
self._set_rel_query(kwargs)
976-
f = sqlalchemy.orm.relation # type: ignore[attr-defined]
977-
return f(*args, **kwargs) # type: ignore[no-any-return]
976+
f = sa_orm.relationship
977+
return f(*args, **kwargs)
978978

979979
def __getattr__(self, name: str) -> t.Any:
980980
if name == "db":
@@ -993,12 +993,12 @@ def __getattr__(self, name: str) -> t.Any:
993993
return self._relation
994994

995995
if name == "event":
996-
return sqlalchemy.event
996+
return sa_event
997997

998998
if name.startswith("_"):
999999
raise AttributeError(name)
10001000

1001-
for mod in (sa, sqlalchemy.orm):
1001+
for mod in (sa, sa_orm):
10021002
if hasattr(mod, name):
10031003
return getattr(mod, name)
10041004

src/flask_sqlalchemy/model.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import typing as t
55

66
import sqlalchemy as sa
7-
import sqlalchemy.orm
7+
import sqlalchemy.orm as sa_orm
88

99
from .query import Query
1010

@@ -182,21 +182,21 @@ def should_set_tablename(cls: type) -> bool:
182182
joined-table inheritance. If no primary key is found, the name will be unset.
183183
"""
184184
if cls.__dict__.get("__abstract__", False) or not any(
185-
isinstance(b, sqlalchemy.orm.DeclarativeMeta) for b in cls.__mro__[1:]
185+
isinstance(b, sa_orm.DeclarativeMeta) for b in cls.__mro__[1:]
186186
):
187187
return False
188188

189189
for base in cls.__mro__:
190190
if "__tablename__" not in base.__dict__:
191191
continue
192192

193-
if isinstance(base.__dict__["__tablename__"], sqlalchemy.orm.declared_attr):
193+
if isinstance(base.__dict__["__tablename__"], sa_orm.declared_attr):
194194
return False
195195

196196
return not (
197197
base is cls
198198
or base.__dict__.get("__abstract__", False)
199-
or not isinstance(base, sqlalchemy.orm.DeclarativeMeta)
199+
or not isinstance(base, sa_orm.DeclarativeMeta)
200200
)
201201

202202
return True
@@ -208,7 +208,7 @@ def camel_to_snake_case(name: str) -> str:
208208
return name.lower().lstrip("_")
209209

210210

211-
class DefaultMeta(BindMetaMixin, NameMetaMixin, sqlalchemy.orm.DeclarativeMeta):
211+
class DefaultMeta(BindMetaMixin, NameMetaMixin, sa_orm.DeclarativeMeta):
212212
"""SQLAlchemy declarative metaclass that provides ``__bind_key__`` and
213213
``__tablename__`` support.
214214
"""

src/flask_sqlalchemy/pagination.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from math import ceil
55

66
import sqlalchemy as sa
7-
import sqlalchemy.orm
7+
import sqlalchemy.orm as sa_orm
88
from flask import abort
99
from flask import request
1010

@@ -336,7 +336,7 @@ def _query_items(self) -> list[t.Any]:
336336

337337
def _query_count(self) -> int:
338338
select = self._query_args["select"]
339-
sub = select.options(sqlalchemy.orm.lazyload("*")).order_by(None).subquery()
339+
sub = select.options(sa_orm.lazyload("*")).order_by(None).subquery()
340340
session = self._query_args["session"]
341341
out = session.execute(sa.select(sa.func.count()).select_from(sub)).scalar()
342342
return out # type: ignore[no-any-return]

src/flask_sqlalchemy/query.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,15 @@
22

33
import typing as t
44

5-
import sqlalchemy.exc
6-
import sqlalchemy.orm
5+
import sqlalchemy.exc as sa_exc
6+
import sqlalchemy.orm as sa_orm
77
from flask import abort
88

99
from .pagination import Pagination
1010
from .pagination import QueryPagination
1111

1212

13-
class Query(sqlalchemy.orm.Query[t.Any]):
13+
class Query(sa_orm.Query[t.Any]):
1414
"""SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with some extra methods
1515
useful for querying in a web application.
1616
@@ -57,7 +57,7 @@ def one_or_404(self, description: str | None = None) -> t.Any:
5757
"""
5858
try:
5959
return self.one()
60-
except (sqlalchemy.exc.NoResultFound, sqlalchemy.exc.MultipleResultsFound):
60+
except (sa_exc.NoResultFound, sa_exc.MultipleResultsFound):
6161
abort(404, description=description)
6262

6363
def paginate(

src/flask_sqlalchemy/record_queries.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from time import perf_counter
77

88
import sqlalchemy as sa
9-
import sqlalchemy.event
9+
import sqlalchemy.event as sa_event
1010
from flask import current_app
1111
from flask import g
1212
from flask import has_app_context
@@ -96,8 +96,8 @@ def __getitem__(self, key: int) -> object:
9696

9797

9898
def _listen(engine: sa.engine.Engine) -> None:
99-
sqlalchemy.event.listen(engine, "before_cursor_execute", _record_start, named=True)
100-
sqlalchemy.event.listen(engine, "after_cursor_execute", _record_end, named=True)
99+
sa_event.listen(engine, "before_cursor_execute", _record_start, named=True)
100+
sa_event.listen(engine, "after_cursor_execute", _record_end, named=True)
101101

102102

103103
def _record_start(context: sa.engine.ExecutionContext, **kwargs: t.Any) -> None:

src/flask_sqlalchemy/session.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33
import typing as t
44

55
import sqlalchemy as sa
6-
import sqlalchemy.exc
7-
import sqlalchemy.orm
6+
import sqlalchemy.exc as sa_exc
7+
import sqlalchemy.orm as sa_orm
88
from flask.globals import app_ctx
99

1010
if t.TYPE_CHECKING:
1111
from .extension import SQLAlchemy
1212

1313

14-
class Session(sqlalchemy.orm.Session):
14+
class Session(sa_orm.Session):
1515
"""A SQLAlchemy :class:`~sqlalchemy.orm.Session` class that chooses what engine to
1616
use based on the bind key associated with the metadata associated with the thing
1717
being queried.
@@ -55,9 +55,9 @@ def get_bind(
5555
if mapper is not None:
5656
try:
5757
mapper = sa.inspect(mapper)
58-
except sqlalchemy.exc.NoInspectionAvailable as e:
58+
except sa_exc.NoInspectionAvailable as e:
5959
if isinstance(mapper, type):
60-
raise sqlalchemy.orm.exc.UnmappedClassError(mapper) from e
60+
raise sa_orm.exc.UnmappedClassError(mapper) from e
6161

6262
raise
6363

@@ -88,7 +88,7 @@ def _clause_to_engine(
8888
key = clause.metadata.info["bind_key"]
8989

9090
if key not in engines:
91-
raise sqlalchemy.exc.UnboundExecutionError(
91+
raise sa_exc.UnboundExecutionError(
9292
f"Bind key '{key}' is not in 'SQLALCHEMY_BINDS' config."
9393
)
9494

src/flask_sqlalchemy/track_modifications.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
import typing as t
44

55
import sqlalchemy as sa
6-
import sqlalchemy.event
7-
import sqlalchemy.orm
6+
import sqlalchemy.event as sa_event
7+
import sqlalchemy.orm as sa_orm
88
from flask import current_app
99
from flask import has_app_context
1010
from flask.signals import Namespace # type: ignore[attr-defined]
@@ -29,12 +29,12 @@
2929
"""
3030

3131

32-
def _listen(session: sqlalchemy.orm.scoped_session[Session]) -> None:
33-
sqlalchemy.event.listen(session, "before_flush", _record_ops, named=True)
34-
sqlalchemy.event.listen(session, "before_commit", _record_ops, named=True)
35-
sqlalchemy.event.listen(session, "before_commit", _before_commit)
36-
sqlalchemy.event.listen(session, "after_commit", _after_commit)
37-
sqlalchemy.event.listen(session, "after_rollback", _after_rollback)
32+
def _listen(session: sa_orm.scoped_session[Session]) -> None:
33+
sa_event.listen(session, "before_flush", _record_ops, named=True)
34+
sa_event.listen(session, "before_commit", _record_ops, named=True)
35+
sa_event.listen(session, "before_commit", _before_commit)
36+
sa_event.listen(session, "after_commit", _after_commit)
37+
sa_event.listen(session, "after_rollback", _after_rollback)
3838

3939

4040
def _record_ops(session: Session, **kwargs: t.Any) -> None:

tests/test_legacy_query.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import pytest
77
import sqlalchemy as sa
8-
import sqlalchemy.exc
8+
import sqlalchemy.exc as sa_exc
99
from flask import Flask
1010
from werkzeug.exceptions import NotFound
1111

@@ -15,9 +15,9 @@
1515

1616
@pytest.fixture(autouse=True)
1717
def ignore_query_warning() -> t.Generator[None, None, None]:
18-
if hasattr(sqlalchemy.exc, "LegacyAPIWarning"):
18+
if hasattr(sa_exc, "LegacyAPIWarning"):
1919
with warnings.catch_warnings():
20-
exc = sqlalchemy.exc.LegacyAPIWarning
20+
exc = sa_exc.LegacyAPIWarning
2121
warnings.simplefilter("ignore", exc)
2222
yield
2323
else:

0 commit comments

Comments
 (0)