|
| 1 | +from typing import ( |
| 2 | + Tuple, |
| 3 | + TypeVar, |
| 4 | + Union, |
| 5 | +) |
| 6 | + |
| 7 | +from sqlalchemy.sql._typing import ( |
| 8 | + _ColumnExpressionArgument, |
| 9 | +) |
| 10 | +from sqlalchemy.sql.expression import Select as _Select |
| 11 | +from typing_extensions import Self |
| 12 | + |
| 13 | +_T = TypeVar("_T") |
| 14 | + |
| 15 | + |
| 16 | +# Separate this class in SelectBase, Select, and SelectOfScalar so that they can share |
| 17 | +# where and having without having type overlap incompatibility in session.exec(). |
| 18 | +class SelectBase(_Select[Tuple[_T]]): |
| 19 | + inherit_cache = True |
| 20 | + |
| 21 | + def where(self, *whereclause: Union[_ColumnExpressionArgument[bool], bool]) -> Self: |
| 22 | + """Return a new `Select` construct with the given expression added to |
| 23 | + its `WHERE` clause, joined to the existing clause via `AND`, if any. |
| 24 | + """ |
| 25 | + return super().where(*whereclause) # type: ignore[arg-type] |
| 26 | + |
| 27 | + def having(self, *having: Union[_ColumnExpressionArgument[bool], bool]) -> Self: |
| 28 | + """Return a new `Select` construct with the given expression added to |
| 29 | + its `HAVING` clause, joined to the existing clause via `AND`, if any. |
| 30 | + """ |
| 31 | + return super().having(*having) # type: ignore[arg-type] |
| 32 | + |
| 33 | + |
| 34 | +class Select(SelectBase[_T]): |
| 35 | + inherit_cache = True |
| 36 | + |
| 37 | + |
| 38 | +# This is not comparable to sqlalchemy.sql.selectable.ScalarSelect, that has a different |
| 39 | +# purpose. This is the same as a normal SQLAlchemy Select class where there's only one |
| 40 | +# entity, so the result will be converted to a scalar by default. This way writing |
| 41 | +# for loops on the results will feel natural. |
| 42 | +class SelectOfScalar(SelectBase[_T]): |
| 43 | + inherit_cache = True |
0 commit comments