roles.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # sql/roles.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. from __future__ import annotations
  8. from typing import Any
  9. from typing import Generic
  10. from typing import Optional
  11. from typing import TYPE_CHECKING
  12. from typing import TypeVar
  13. from .. import util
  14. from ..util.typing import Literal
  15. if TYPE_CHECKING:
  16. from ._typing import _PropagateAttrsType
  17. from .elements import Label
  18. from .selectable import _SelectIterable
  19. from .selectable import FromClause
  20. from .selectable import Subquery
  21. _T = TypeVar("_T", bound=Any)
  22. _T_co = TypeVar("_T_co", bound=Any, covariant=True)
  23. class SQLRole:
  24. """Define a "role" within a SQL statement structure.
  25. Classes within SQL Core participate within SQLRole hierarchies in order
  26. to more accurately indicate where they may be used within SQL statements
  27. of all types.
  28. .. versionadded:: 1.4
  29. """
  30. __slots__ = ()
  31. allows_lambda = False
  32. uses_inspection = False
  33. class UsesInspection:
  34. __slots__ = ()
  35. _post_inspect: Literal[None] = None
  36. uses_inspection = True
  37. class AllowsLambdaRole:
  38. __slots__ = ()
  39. allows_lambda = True
  40. class HasCacheKeyRole(SQLRole):
  41. __slots__ = ()
  42. _role_name = "Cacheable Core or ORM object"
  43. class ExecutableOptionRole(SQLRole):
  44. __slots__ = ()
  45. _role_name = "ExecutionOption Core or ORM object"
  46. class LiteralValueRole(SQLRole):
  47. __slots__ = ()
  48. _role_name = "Literal Python value"
  49. class ColumnArgumentRole(SQLRole):
  50. __slots__ = ()
  51. _role_name = "Column expression"
  52. class ColumnArgumentOrKeyRole(ColumnArgumentRole):
  53. __slots__ = ()
  54. _role_name = "Column expression or string key"
  55. class StrAsPlainColumnRole(ColumnArgumentRole):
  56. __slots__ = ()
  57. _role_name = "Column expression or string key"
  58. class ColumnListRole(SQLRole):
  59. """Elements suitable for forming comma separated lists of expressions."""
  60. __slots__ = ()
  61. class StringRole(SQLRole):
  62. """mixin indicating a role that results in strings"""
  63. __slots__ = ()
  64. class TruncatedLabelRole(StringRole, SQLRole):
  65. __slots__ = ()
  66. _role_name = "String SQL identifier"
  67. class ColumnsClauseRole(AllowsLambdaRole, UsesInspection, ColumnListRole):
  68. __slots__ = ()
  69. _role_name = (
  70. "Column expression, FROM clause, or other columns clause element"
  71. )
  72. @property
  73. def _select_iterable(self) -> _SelectIterable:
  74. raise NotImplementedError()
  75. class TypedColumnsClauseRole(Generic[_T_co], SQLRole):
  76. """element-typed form of ColumnsClauseRole"""
  77. __slots__ = ()
  78. class LimitOffsetRole(SQLRole):
  79. __slots__ = ()
  80. _role_name = "LIMIT / OFFSET expression"
  81. class ByOfRole(ColumnListRole):
  82. __slots__ = ()
  83. _role_name = "GROUP BY / OF / etc. expression"
  84. class GroupByRole(AllowsLambdaRole, UsesInspection, ByOfRole):
  85. __slots__ = ()
  86. # note there's a special case right now where you can pass a whole
  87. # ORM entity to group_by() and it splits out. we may not want to keep
  88. # this around
  89. _role_name = "GROUP BY expression"
  90. class OrderByRole(AllowsLambdaRole, ByOfRole):
  91. __slots__ = ()
  92. _role_name = "ORDER BY expression"
  93. class StructuralRole(SQLRole):
  94. __slots__ = ()
  95. class StatementOptionRole(StructuralRole):
  96. __slots__ = ()
  97. _role_name = "statement sub-expression element"
  98. class OnClauseRole(AllowsLambdaRole, StructuralRole):
  99. __slots__ = ()
  100. _role_name = (
  101. "ON clause, typically a SQL expression or "
  102. "ORM relationship attribute"
  103. )
  104. class WhereHavingRole(OnClauseRole):
  105. __slots__ = ()
  106. _role_name = "SQL expression for WHERE/HAVING role"
  107. class ExpressionElementRole(TypedColumnsClauseRole[_T_co]):
  108. # note when using generics for ExpressionElementRole,
  109. # the generic type needs to be in
  110. # sqlalchemy.sql.coercions._impl_lookup mapping also.
  111. # these are set up for basic types like int, bool, str, float
  112. # right now
  113. __slots__ = ()
  114. _role_name = "SQL expression element"
  115. def label(self, name: Optional[str]) -> Label[_T]:
  116. raise NotImplementedError()
  117. class ConstExprRole(ExpressionElementRole[_T]):
  118. __slots__ = ()
  119. _role_name = "Constant True/False/None expression"
  120. class LabeledColumnExprRole(ExpressionElementRole[_T]):
  121. __slots__ = ()
  122. class BinaryElementRole(ExpressionElementRole[_T]):
  123. __slots__ = ()
  124. _role_name = "SQL expression element or literal value"
  125. class InElementRole(SQLRole):
  126. __slots__ = ()
  127. _role_name = (
  128. "IN expression list, SELECT construct, or bound parameter object"
  129. )
  130. class JoinTargetRole(AllowsLambdaRole, UsesInspection, StructuralRole):
  131. __slots__ = ()
  132. _role_name = (
  133. "Join target, typically a FROM expression, or ORM "
  134. "relationship attribute"
  135. )
  136. class FromClauseRole(ColumnsClauseRole, JoinTargetRole):
  137. __slots__ = ()
  138. _role_name = "FROM expression, such as a Table or alias() object"
  139. _is_subquery = False
  140. named_with_column: bool
  141. class StrictFromClauseRole(FromClauseRole):
  142. __slots__ = ()
  143. # does not allow text() or select() objects
  144. class AnonymizedFromClauseRole(StrictFromClauseRole):
  145. __slots__ = ()
  146. if TYPE_CHECKING:
  147. def _anonymous_fromclause(
  148. self, *, name: Optional[str] = None, flat: bool = False
  149. ) -> FromClause: ...
  150. class ReturnsRowsRole(SQLRole):
  151. __slots__ = ()
  152. _role_name = (
  153. "Row returning expression such as a SELECT, a FROM clause, or an "
  154. "INSERT/UPDATE/DELETE with RETURNING"
  155. )
  156. class StatementRole(SQLRole):
  157. __slots__ = ()
  158. _role_name = "Executable SQL or text() construct"
  159. if TYPE_CHECKING:
  160. @util.memoized_property
  161. def _propagate_attrs(self) -> _PropagateAttrsType: ...
  162. else:
  163. _propagate_attrs = util.EMPTY_DICT
  164. class SelectStatementRole(StatementRole, ReturnsRowsRole):
  165. __slots__ = ()
  166. _role_name = "SELECT construct or equivalent text() construct"
  167. def subquery(self) -> Subquery:
  168. raise NotImplementedError(
  169. "All SelectStatementRole objects should implement a "
  170. ".subquery() method."
  171. )
  172. class HasCTERole(ReturnsRowsRole):
  173. __slots__ = ()
  174. class IsCTERole(SQLRole):
  175. __slots__ = ()
  176. _role_name = "CTE object"
  177. class CompoundElementRole(AllowsLambdaRole, SQLRole):
  178. """SELECT statements inside a CompoundSelect, e.g. UNION, EXTRACT, etc."""
  179. __slots__ = ()
  180. _role_name = (
  181. "SELECT construct for inclusion in a UNION or other set construct"
  182. )
  183. # TODO: are we using this?
  184. class DMLRole(StatementRole):
  185. __slots__ = ()
  186. class DMLTableRole(FromClauseRole):
  187. __slots__ = ()
  188. _role_name = "subject table for an INSERT, UPDATE or DELETE"
  189. class DMLColumnRole(SQLRole):
  190. __slots__ = ()
  191. _role_name = "SET/VALUES column expression or string key"
  192. class DMLSelectRole(SQLRole):
  193. """A SELECT statement embedded in DML, typically INSERT from SELECT"""
  194. __slots__ = ()
  195. _role_name = "SELECT statement or equivalent textual object"
  196. class DDLRole(StatementRole):
  197. __slots__ = ()
  198. class DDLExpressionRole(StructuralRole):
  199. __slots__ = ()
  200. _role_name = "SQL expression element for DDL constraint"
  201. class DDLConstraintColumnRole(SQLRole):
  202. __slots__ = ()
  203. _role_name = "String column name or column expression for DDL constraint"
  204. class DDLReferredColumnRole(DDLConstraintColumnRole):
  205. __slots__ = ()
  206. _role_name = (
  207. "String column name or Column object for DDL foreign key constraint"
  208. )