functions.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. # sql/functions.py
  2. # Copyright (C) 2005-2024 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. """SQL function API, factories, and built-in functions.
  8. """
  9. from . import annotation
  10. from . import coercions
  11. from . import operators
  12. from . import roles
  13. from . import schema
  14. from . import sqltypes
  15. from . import util as sqlutil
  16. from .base import _entity_namespace
  17. from .base import ColumnCollection
  18. from .base import Executable
  19. from .base import Generative
  20. from .base import HasMemoized
  21. from .elements import _type_from_args
  22. from .elements import BinaryExpression
  23. from .elements import BindParameter
  24. from .elements import Cast
  25. from .elements import ClauseList
  26. from .elements import ColumnElement
  27. from .elements import Extract
  28. from .elements import FunctionFilter
  29. from .elements import Grouping
  30. from .elements import literal_column
  31. from .elements import NamedColumn
  32. from .elements import Over
  33. from .elements import WithinGroup
  34. from .selectable import FromClause
  35. from .selectable import Select
  36. from .selectable import TableValuedAlias
  37. from .visitors import InternalTraversal
  38. from .visitors import TraversibleType
  39. from .. import util
  40. _registry = util.defaultdict(dict)
  41. def register_function(identifier, fn, package="_default"):
  42. """Associate a callable with a particular func. name.
  43. This is normally called by _GenericMeta, but is also
  44. available by itself so that a non-Function construct
  45. can be associated with the :data:`.func` accessor (i.e.
  46. CAST, EXTRACT).
  47. """
  48. reg = _registry[package]
  49. identifier = util.text_type(identifier).lower()
  50. # Check if a function with the same identifier is registered.
  51. if identifier in reg:
  52. util.warn(
  53. "The GenericFunction '{}' is already registered and "
  54. "is going to be overridden.".format(identifier)
  55. )
  56. reg[identifier] = fn
  57. class FunctionElement(Executable, ColumnElement, FromClause, Generative):
  58. """Base for SQL function-oriented constructs.
  59. .. seealso::
  60. :ref:`tutorial_functions` - in the :ref:`unified_tutorial`
  61. :class:`.Function` - named SQL function.
  62. :data:`.func` - namespace which produces registered or ad-hoc
  63. :class:`.Function` instances.
  64. :class:`.GenericFunction` - allows creation of registered function
  65. types.
  66. """
  67. _traverse_internals = [
  68. ("clause_expr", InternalTraversal.dp_clauseelement),
  69. ("_with_ordinality", InternalTraversal.dp_boolean),
  70. ("_table_value_type", InternalTraversal.dp_has_cache_key),
  71. ]
  72. packagenames = ()
  73. _has_args = False
  74. _with_ordinality = False
  75. _table_value_type = None
  76. def __init__(self, *clauses, **kwargs):
  77. r"""Construct a :class:`.FunctionElement`.
  78. :param \*clauses: list of column expressions that form the arguments
  79. of the SQL function call.
  80. :param \**kwargs: additional kwargs are typically consumed by
  81. subclasses.
  82. .. seealso::
  83. :data:`.func`
  84. :class:`.Function`
  85. """
  86. args = [
  87. coercions.expect(
  88. roles.ExpressionElementRole,
  89. c,
  90. name=getattr(self, "name", None),
  91. apply_propagate_attrs=self,
  92. )
  93. for c in clauses
  94. ]
  95. self._has_args = self._has_args or bool(args)
  96. self.clause_expr = ClauseList(
  97. operator=operators.comma_op, group_contents=True, *args
  98. ).self_group()
  99. _non_anon_label = None
  100. @property
  101. def _proxy_key(self):
  102. return super(FunctionElement, self)._proxy_key or getattr(
  103. self, "name", None
  104. )
  105. def _execute_on_connection(
  106. self, connection, multiparams, params, execution_options
  107. ):
  108. return connection._execute_function(
  109. self, multiparams, params, execution_options
  110. )
  111. def scalar_table_valued(self, name, type_=None):
  112. """Return a column expression that's against this
  113. :class:`_functions.FunctionElement` as a scalar
  114. table-valued expression.
  115. The returned expression is similar to that returned by a single column
  116. accessed off of a :meth:`_functions.FunctionElement.table_valued`
  117. construct, except no FROM clause is generated; the function is rendered
  118. in the similar way as a scalar subquery.
  119. E.g.::
  120. >>> from sqlalchemy import func, select
  121. >>> fn = func.jsonb_each("{'k', 'v'}").scalar_table_valued("key")
  122. >>> print(select(fn))
  123. SELECT (jsonb_each(:jsonb_each_1)).key
  124. .. versionadded:: 1.4.0b2
  125. .. seealso::
  126. :meth:`_functions.FunctionElement.table_valued`
  127. :meth:`_functions.FunctionElement.alias`
  128. :meth:`_functions.FunctionElement.column_valued`
  129. """ # noqa: E501
  130. return ScalarFunctionColumn(self, name, type_)
  131. def table_valued(self, *expr, **kw):
  132. r"""Return a :class:`_sql.TableValuedAlias` representation of this
  133. :class:`_functions.FunctionElement` with table-valued expressions added.
  134. e.g.::
  135. >>> fn = (
  136. ... func.generate_series(1, 5).
  137. ... table_valued("value", "start", "stop", "step")
  138. ... )
  139. >>> print(select(fn))
  140. SELECT anon_1.value, anon_1.start, anon_1.stop, anon_1.step
  141. FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1
  142. >>> print(select(fn.c.value, fn.c.stop).where(fn.c.value > 2))
  143. SELECT anon_1.value, anon_1.stop
  144. FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1
  145. WHERE anon_1.value > :value_1
  146. A WITH ORDINALITY expression may be generated by passing the keyword
  147. argument "with_ordinality"::
  148. >>> fn = func.generate_series(4, 1, -1).table_valued("gen", with_ordinality="ordinality")
  149. >>> print(select(fn))
  150. SELECT anon_1.gen, anon_1.ordinality
  151. FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) WITH ORDINALITY AS anon_1
  152. :param \*expr: A series of string column names that will be added to the
  153. ``.c`` collection of the resulting :class:`_sql.TableValuedAlias`
  154. construct as columns. :func:`_sql.column` objects with or without
  155. datatypes may also be used.
  156. :param name: optional name to assign to the alias name that's generated.
  157. If omitted, a unique anonymizing name is used.
  158. :param with_ordinality: string name that when present results in the
  159. ``WITH ORDINALITY`` clause being added to the alias, and the given
  160. string name will be added as a column to the .c collection
  161. of the resulting :class:`_sql.TableValuedAlias`.
  162. :param joins_implicitly: when True, the table valued function may be
  163. used in the FROM clause without any explicit JOIN to other tables
  164. in the SQL query, and no "cartesian product" warning will be generated.
  165. May be useful for SQL functions such as ``func.json_each()``.
  166. .. versionadded:: 1.4.33
  167. .. versionadded:: 1.4.0b2
  168. .. seealso::
  169. :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial`
  170. :ref:`postgresql_table_valued` - in the :ref:`postgresql_toplevel` documentation
  171. :meth:`_functions.FunctionElement.scalar_table_valued` - variant of
  172. :meth:`_functions.FunctionElement.table_valued` which delivers the
  173. complete table valued expression as a scalar column expression
  174. :meth:`_functions.FunctionElement.column_valued`
  175. :meth:`_sql.TableValuedAlias.render_derived` - renders the alias
  176. using a derived column clause, e.g. ``AS name(col1, col2, ...)``
  177. """ # noqa: 501
  178. new_func = self._generate()
  179. with_ordinality = kw.pop("with_ordinality", None)
  180. joins_implicitly = kw.pop("joins_implicitly", None)
  181. name = kw.pop("name", None)
  182. if with_ordinality:
  183. expr += (with_ordinality,)
  184. new_func._with_ordinality = True
  185. new_func.type = new_func._table_value_type = sqltypes.TableValueType(
  186. *expr
  187. )
  188. return new_func.alias(name=name, joins_implicitly=joins_implicitly)
  189. def column_valued(self, name=None, joins_implicitly=False):
  190. """Return this :class:`_functions.FunctionElement` as a column expression that
  191. selects from itself as a FROM clause.
  192. E.g.::
  193. >>> from sqlalchemy import select, func
  194. >>> gs = func.generate_series(1, 5, -1).column_valued()
  195. >>> print(select(gs))
  196. SELECT anon_1
  197. FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) AS anon_1
  198. This is shorthand for::
  199. gs = func.generate_series(1, 5, -1).alias().column
  200. :param name: optional name to assign to the alias name that's generated.
  201. If omitted, a unique anonymizing name is used.
  202. :param joins_implicitly: when True, the "table" portion of the column
  203. valued function may be a member of the FROM clause without any
  204. explicit JOIN to other tables in the SQL query, and no "cartesian
  205. product" warning will be generated. May be useful for SQL functions
  206. such as ``func.json_array_elements()``.
  207. .. versionadded:: 1.4.46
  208. .. seealso::
  209. :ref:`tutorial_functions_column_valued` - in the :ref:`unified_tutorial`
  210. :ref:`postgresql_column_valued` - in the :ref:`postgresql_toplevel` documentation
  211. :meth:`_functions.FunctionElement.table_valued`
  212. """ # noqa: 501
  213. return self.alias(name=name, joins_implicitly=joins_implicitly).column
  214. @property
  215. def columns(self):
  216. r"""The set of columns exported by this :class:`.FunctionElement`.
  217. This is a placeholder collection that allows the function to be
  218. placed in the FROM clause of a statement::
  219. >>> from sqlalchemy import column, select, func
  220. >>> stmt = select(column('x'), column('y')).select_from(func.myfunction())
  221. >>> print(stmt)
  222. SELECT x, y FROM myfunction()
  223. The above form is a legacy feature that is now superseded by the
  224. fully capable :meth:`_functions.FunctionElement.table_valued`
  225. method; see that method for details.
  226. .. seealso::
  227. :meth:`_functions.FunctionElement.table_valued` - generates table-valued
  228. SQL function expressions.
  229. """ # noqa: E501
  230. return ColumnCollection(
  231. columns=[(col.key, col) for col in self._all_selected_columns]
  232. )
  233. @property
  234. def _all_selected_columns(self):
  235. if self.type._is_table_value:
  236. cols = self.type._elements
  237. else:
  238. cols = [self.label(None)]
  239. return cols
  240. @property
  241. def exported_columns(self):
  242. return self.columns
  243. @HasMemoized.memoized_attribute
  244. def clauses(self):
  245. """Return the underlying :class:`.ClauseList` which contains
  246. the arguments for this :class:`.FunctionElement`.
  247. """
  248. return self.clause_expr.element
  249. def over(self, partition_by=None, order_by=None, rows=None, range_=None):
  250. """Produce an OVER clause against this function.
  251. Used against aggregate or so-called "window" functions,
  252. for database backends that support window functions.
  253. The expression::
  254. func.row_number().over(order_by='x')
  255. is shorthand for::
  256. from sqlalchemy import over
  257. over(func.row_number(), order_by='x')
  258. See :func:`_expression.over` for a full description.
  259. .. seealso::
  260. :func:`_expression.over`
  261. :ref:`tutorial_window_functions` - in the :ref:`unified_tutorial`
  262. """
  263. return Over(
  264. self,
  265. partition_by=partition_by,
  266. order_by=order_by,
  267. rows=rows,
  268. range_=range_,
  269. )
  270. def within_group(self, *order_by):
  271. """Produce a WITHIN GROUP (ORDER BY expr) clause against this function.
  272. Used against so-called "ordered set aggregate" and "hypothetical
  273. set aggregate" functions, including :class:`.percentile_cont`,
  274. :class:`.rank`, :class:`.dense_rank`, etc.
  275. See :func:`_expression.within_group` for a full description.
  276. .. versionadded:: 1.1
  277. .. seealso::
  278. :ref:`tutorial_functions_within_group` -
  279. in the :ref:`unified_tutorial`
  280. """
  281. return WithinGroup(self, *order_by)
  282. def filter(self, *criterion):
  283. """Produce a FILTER clause against this function.
  284. Used against aggregate and window functions,
  285. for database backends that support the "FILTER" clause.
  286. The expression::
  287. func.count(1).filter(True)
  288. is shorthand for::
  289. from sqlalchemy import funcfilter
  290. funcfilter(func.count(1), True)
  291. .. versionadded:: 1.0.0
  292. .. seealso::
  293. :ref:`tutorial_functions_within_group` -
  294. in the :ref:`unified_tutorial`
  295. :class:`.FunctionFilter`
  296. :func:`.funcfilter`
  297. """
  298. if not criterion:
  299. return self
  300. return FunctionFilter(self, *criterion)
  301. def as_comparison(self, left_index, right_index):
  302. """Interpret this expression as a boolean comparison between two
  303. values.
  304. This method is used for an ORM use case described at
  305. :ref:`relationship_custom_operator_sql_function`.
  306. A hypothetical SQL function "is_equal()" which compares to values
  307. for equality would be written in the Core expression language as::
  308. expr = func.is_equal("a", "b")
  309. If "is_equal()" above is comparing "a" and "b" for equality, the
  310. :meth:`.FunctionElement.as_comparison` method would be invoked as::
  311. expr = func.is_equal("a", "b").as_comparison(1, 2)
  312. Where above, the integer value "1" refers to the first argument of the
  313. "is_equal()" function and the integer value "2" refers to the second.
  314. This would create a :class:`.BinaryExpression` that is equivalent to::
  315. BinaryExpression("a", "b", operator=op.eq)
  316. However, at the SQL level it would still render as
  317. "is_equal('a', 'b')".
  318. The ORM, when it loads a related object or collection, needs to be able
  319. to manipulate the "left" and "right" sides of the ON clause of a JOIN
  320. expression. The purpose of this method is to provide a SQL function
  321. construct that can also supply this information to the ORM, when used
  322. with the :paramref:`_orm.relationship.primaryjoin` parameter. The
  323. return value is a containment object called :class:`.FunctionAsBinary`.
  324. An ORM example is as follows::
  325. class Venue(Base):
  326. __tablename__ = 'venue'
  327. id = Column(Integer, primary_key=True)
  328. name = Column(String)
  329. descendants = relationship(
  330. "Venue",
  331. primaryjoin=func.instr(
  332. remote(foreign(name)), name + "/"
  333. ).as_comparison(1, 2) == 1,
  334. viewonly=True,
  335. order_by=name
  336. )
  337. Above, the "Venue" class can load descendant "Venue" objects by
  338. determining if the name of the parent Venue is contained within the
  339. start of the hypothetical descendant value's name, e.g. "parent1" would
  340. match up to "parent1/child1", but not to "parent2/child1".
  341. Possible use cases include the "materialized path" example given above,
  342. as well as making use of special SQL functions such as geometric
  343. functions to create join conditions.
  344. :param left_index: the integer 1-based index of the function argument
  345. that serves as the "left" side of the expression.
  346. :param right_index: the integer 1-based index of the function argument
  347. that serves as the "right" side of the expression.
  348. .. versionadded:: 1.3
  349. .. seealso::
  350. :ref:`relationship_custom_operator_sql_function` -
  351. example use within the ORM
  352. """
  353. return FunctionAsBinary(self, left_index, right_index)
  354. @property
  355. def _from_objects(self):
  356. return self.clauses._from_objects
  357. def within_group_type(self, within_group):
  358. """For types that define their return type as based on the criteria
  359. within a WITHIN GROUP (ORDER BY) expression, called by the
  360. :class:`.WithinGroup` construct.
  361. Returns None by default, in which case the function's normal ``.type``
  362. is used.
  363. """
  364. return None
  365. def alias(self, name=None, joins_implicitly=False):
  366. r"""Produce a :class:`_expression.Alias` construct against this
  367. :class:`.FunctionElement`.
  368. .. tip::
  369. The :meth:`_functions.FunctionElement.alias` method is part of the
  370. mechanism by which "table valued" SQL functions are created.
  371. However, most use cases are covered by higher level methods on
  372. :class:`_functions.FunctionElement` including
  373. :meth:`_functions.FunctionElement.table_valued`, and
  374. :meth:`_functions.FunctionElement.column_valued`.
  375. This construct wraps the function in a named alias which
  376. is suitable for the FROM clause, in the style accepted for example
  377. by PostgreSQL. A column expression is also provided using the
  378. special ``.column`` attribute, which may
  379. be used to refer to the output of the function as a scalar value
  380. in the columns or where clause, for a backend such as PostgreSQL.
  381. For a full table-valued expression, use the
  382. :meth:`_functions.FunctionElement.table_valued` method first to
  383. establish named columns.
  384. e.g.::
  385. >>> from sqlalchemy import func, select, column
  386. >>> data_view = func.unnest([1, 2, 3]).alias("data_view")
  387. >>> print(select(data_view.column))
  388. SELECT data_view
  389. FROM unnest(:unnest_1) AS data_view
  390. The :meth:`_functions.FunctionElement.column_valued` method provides
  391. a shortcut for the above pattern::
  392. >>> data_view = func.unnest([1, 2, 3]).column_valued("data_view")
  393. >>> print(select(data_view))
  394. SELECT data_view
  395. FROM unnest(:unnest_1) AS data_view
  396. .. versionadded:: 1.4.0b2 Added the ``.column`` accessor
  397. :param name: alias name, will be rendered as ``AS <name>`` in the
  398. FROM clause
  399. :param joins_implicitly: when True, the table valued function may be
  400. used in the FROM clause without any explicit JOIN to other tables
  401. in the SQL query, and no "cartesian product" warning will be
  402. generated. May be useful for SQL functions such as
  403. ``func.json_each()``.
  404. .. versionadded:: 1.4.33
  405. .. seealso::
  406. :ref:`tutorial_functions_table_valued` -
  407. in the :ref:`unified_tutorial`
  408. :meth:`_functions.FunctionElement.table_valued`
  409. :meth:`_functions.FunctionElement.scalar_table_valued`
  410. :meth:`_functions.FunctionElement.column_valued`
  411. """
  412. return TableValuedAlias._construct(
  413. self,
  414. name,
  415. table_value_type=self.type,
  416. joins_implicitly=joins_implicitly,
  417. )
  418. def select(self):
  419. """Produce a :func:`_expression.select` construct
  420. against this :class:`.FunctionElement`.
  421. This is shorthand for::
  422. s = select(function_element)
  423. """
  424. s = Select._create_select(self)
  425. if self._execution_options:
  426. s = s.execution_options(**self._execution_options)
  427. return s
  428. @util.deprecated_20(
  429. ":meth:`.FunctionElement.scalar`",
  430. alternative="Scalar execution in SQLAlchemy 2.0 is performed "
  431. "by the :meth:`_engine.Connection.scalar` method of "
  432. ":class:`_engine.Connection`, "
  433. "or in the ORM by the :meth:`.Session.scalar` method of "
  434. ":class:`.Session`.",
  435. )
  436. def scalar(self):
  437. """Execute this :class:`.FunctionElement` against an embedded
  438. 'bind' and return a scalar value.
  439. This first calls :meth:`~.FunctionElement.select` to
  440. produce a SELECT construct.
  441. Note that :class:`.FunctionElement` can be passed to
  442. the :meth:`.Connectable.scalar` method of :class:`_engine.Connection`
  443. or :class:`_engine.Engine`.
  444. """
  445. return self.select().execute().scalar()
  446. @util.deprecated_20(
  447. ":meth:`.FunctionElement.execute`",
  448. alternative="All statement execution in SQLAlchemy 2.0 is performed "
  449. "by the :meth:`_engine.Connection.execute` method of "
  450. ":class:`_engine.Connection`, "
  451. "or in the ORM by the :meth:`.Session.execute` method of "
  452. ":class:`.Session`.",
  453. )
  454. def execute(self):
  455. """Execute this :class:`.FunctionElement` against an embedded
  456. 'bind'.
  457. This first calls :meth:`~.FunctionElement.select` to
  458. produce a SELECT construct.
  459. Note that :class:`.FunctionElement` can be passed to
  460. the :meth:`.Connectable.execute` method of :class:`_engine.Connection`
  461. or :class:`_engine.Engine`.
  462. """
  463. return self.select().execute()
  464. def _bind_param(self, operator, obj, type_=None, **kw):
  465. return BindParameter(
  466. None,
  467. obj,
  468. _compared_to_operator=operator,
  469. _compared_to_type=self.type,
  470. unique=True,
  471. type_=type_,
  472. **kw
  473. )
  474. def self_group(self, against=None):
  475. # for the moment, we are parenthesizing all array-returning
  476. # expressions against getitem. This may need to be made
  477. # more portable if in the future we support other DBs
  478. # besides postgresql.
  479. if against is operators.getitem and isinstance(
  480. self.type, sqltypes.ARRAY
  481. ):
  482. return Grouping(self)
  483. else:
  484. return super(FunctionElement, self).self_group(against=against)
  485. @property
  486. def entity_namespace(self):
  487. """overrides FromClause.entity_namespace as functions are generally
  488. column expressions and not FromClauses.
  489. """
  490. # ideally functions would not be fromclauses but we failed to make
  491. # this adjustment in 1.4
  492. return _entity_namespace(self.clause_expr)
  493. class FunctionAsBinary(BinaryExpression):
  494. _traverse_internals = [
  495. ("sql_function", InternalTraversal.dp_clauseelement),
  496. ("left_index", InternalTraversal.dp_plain_obj),
  497. ("right_index", InternalTraversal.dp_plain_obj),
  498. ("modifiers", InternalTraversal.dp_plain_dict),
  499. ]
  500. def _gen_cache_key(self, anon_map, bindparams):
  501. return ColumnElement._gen_cache_key(self, anon_map, bindparams)
  502. def __init__(self, fn, left_index, right_index):
  503. self.sql_function = fn
  504. self.left_index = left_index
  505. self.right_index = right_index
  506. self.operator = operators.function_as_comparison_op
  507. self.type = sqltypes.BOOLEANTYPE
  508. self.negate = None
  509. self._is_implicitly_boolean = True
  510. self.modifiers = {}
  511. @property
  512. def left(self):
  513. return self.sql_function.clauses.clauses[self.left_index - 1]
  514. @left.setter
  515. def left(self, value):
  516. self.sql_function.clauses.clauses[self.left_index - 1] = value
  517. @property
  518. def right(self):
  519. return self.sql_function.clauses.clauses[self.right_index - 1]
  520. @right.setter
  521. def right(self, value):
  522. self.sql_function.clauses.clauses[self.right_index - 1] = value
  523. class ScalarFunctionColumn(NamedColumn):
  524. __visit_name__ = "scalar_function_column"
  525. _traverse_internals = [
  526. ("name", InternalTraversal.dp_anon_name),
  527. ("type", InternalTraversal.dp_type),
  528. ("fn", InternalTraversal.dp_clauseelement),
  529. ]
  530. is_literal = False
  531. table = None
  532. def __init__(self, fn, name, type_=None):
  533. self.fn = fn
  534. self.name = name
  535. self.type = sqltypes.to_instance(type_)
  536. class _FunctionGenerator(object):
  537. """Generate SQL function expressions.
  538. :data:`.func` is a special object instance which generates SQL
  539. functions based on name-based attributes, e.g.::
  540. >>> print(func.count(1))
  541. count(:param_1)
  542. The returned object is an instance of :class:`.Function`, and is a
  543. column-oriented SQL element like any other, and is used in that way::
  544. >>> print(select(func.count(table.c.id)))
  545. SELECT count(sometable.id) FROM sometable
  546. Any name can be given to :data:`.func`. If the function name is unknown to
  547. SQLAlchemy, it will be rendered exactly as is. For common SQL functions
  548. which SQLAlchemy is aware of, the name may be interpreted as a *generic
  549. function* which will be compiled appropriately to the target database::
  550. >>> print(func.current_timestamp())
  551. CURRENT_TIMESTAMP
  552. To call functions which are present in dot-separated packages,
  553. specify them in the same manner::
  554. >>> print(func.stats.yield_curve(5, 10))
  555. stats.yield_curve(:yield_curve_1, :yield_curve_2)
  556. SQLAlchemy can be made aware of the return type of functions to enable
  557. type-specific lexical and result-based behavior. For example, to ensure
  558. that a string-based function returns a Unicode value and is similarly
  559. treated as a string in expressions, specify
  560. :class:`~sqlalchemy.types.Unicode` as the type:
  561. >>> print(func.my_string(u'hi', type_=Unicode) + ' ' +
  562. ... func.my_string(u'there', type_=Unicode))
  563. my_string(:my_string_1) || :my_string_2 || my_string(:my_string_3)
  564. The object returned by a :data:`.func` call is usually an instance of
  565. :class:`.Function`.
  566. This object meets the "column" interface, including comparison and labeling
  567. functions. The object can also be passed the :meth:`~.Connectable.execute`
  568. method of a :class:`_engine.Connection` or :class:`_engine.Engine`,
  569. where it will be
  570. wrapped inside of a SELECT statement first::
  571. print(connection.execute(func.current_timestamp()).scalar())
  572. In a few exception cases, the :data:`.func` accessor
  573. will redirect a name to a built-in expression such as :func:`.cast`
  574. or :func:`.extract`, as these names have well-known meaning
  575. but are not exactly the same as "functions" from a SQLAlchemy
  576. perspective.
  577. Functions which are interpreted as "generic" functions know how to
  578. calculate their return type automatically. For a listing of known generic
  579. functions, see :ref:`generic_functions`.
  580. .. note::
  581. The :data:`.func` construct has only limited support for calling
  582. standalone "stored procedures", especially those with special
  583. parameterization concerns.
  584. See the section :ref:`stored_procedures` for details on how to use
  585. the DBAPI-level ``callproc()`` method for fully traditional stored
  586. procedures.
  587. .. seealso::
  588. :ref:`tutorial_functions` - in the :ref:`unified_tutorial`
  589. :class:`.Function`
  590. """
  591. def __init__(self, **opts):
  592. self.__names = []
  593. self.opts = opts
  594. def __getattr__(self, name):
  595. # passthru __ attributes; fixes pydoc
  596. if name.startswith("__"):
  597. try:
  598. return self.__dict__[name]
  599. except KeyError:
  600. raise AttributeError(name)
  601. elif name.endswith("_"):
  602. name = name[0:-1]
  603. f = _FunctionGenerator(**self.opts)
  604. f.__names = list(self.__names) + [name]
  605. return f
  606. def __call__(self, *c, **kwargs):
  607. o = self.opts.copy()
  608. o.update(kwargs)
  609. tokens = len(self.__names)
  610. if tokens == 2:
  611. package, fname = self.__names
  612. elif tokens == 1:
  613. package, fname = "_default", self.__names[0]
  614. else:
  615. package = None
  616. if package is not None:
  617. func = _registry[package].get(fname.lower())
  618. if func is not None:
  619. return func(*c, **o)
  620. return Function(
  621. self.__names[-1], packagenames=tuple(self.__names[0:-1]), *c, **o
  622. )
  623. func = _FunctionGenerator()
  624. func.__doc__ = _FunctionGenerator.__doc__
  625. modifier = _FunctionGenerator(group=False)
  626. class Function(FunctionElement):
  627. r"""Describe a named SQL function.
  628. The :class:`.Function` object is typically generated from the
  629. :data:`.func` generation object.
  630. :param \*clauses: list of column expressions that form the arguments
  631. of the SQL function call.
  632. :param type\_: optional :class:`.TypeEngine` datatype object that will be
  633. used as the return value of the column expression generated by this
  634. function call.
  635. :param packagenames: a string which indicates package prefix names
  636. to be prepended to the function name when the SQL is generated.
  637. The :data:`.func` generator creates these when it is called using
  638. dotted format, e.g.::
  639. func.mypackage.some_function(col1, col2)
  640. .. seealso::
  641. :ref:`tutorial_functions` - in the :ref:`unified_tutorial`
  642. :data:`.func` - namespace which produces registered or ad-hoc
  643. :class:`.Function` instances.
  644. :class:`.GenericFunction` - allows creation of registered function
  645. types.
  646. """
  647. __visit_name__ = "function"
  648. _traverse_internals = FunctionElement._traverse_internals + [
  649. ("packagenames", InternalTraversal.dp_plain_obj),
  650. ("name", InternalTraversal.dp_string),
  651. ("type", InternalTraversal.dp_type),
  652. ]
  653. type = sqltypes.NULLTYPE
  654. """A :class:`_types.TypeEngine` object which refers to the SQL return
  655. type represented by this SQL function.
  656. This datatype may be configured when generating a
  657. :class:`_functions.Function` object by passing the
  658. :paramref:`_functions.Function.type_` parameter, e.g.::
  659. >>> select(func.lower("some VALUE", type_=String))
  660. The small number of built-in classes of :class:`_functions.Function` come
  661. with a built-in datatype that's appropriate to the class of function and
  662. its arguments. For functions that aren't known, the type defaults to the
  663. "null type".
  664. """
  665. @util.deprecated_params(
  666. bind=(
  667. "2.0",
  668. "The :paramref:`_sql.text.bind` argument is deprecated and "
  669. "will be removed in SQLAlchemy 2.0.",
  670. ),
  671. )
  672. def __init__(self, name, *clauses, **kw):
  673. """Construct a :class:`.Function`.
  674. The :data:`.func` construct is normally used to construct
  675. new :class:`.Function` instances.
  676. """
  677. self.packagenames = kw.pop("packagenames", None) or ()
  678. self.name = name
  679. self._bind = self._get_bind(kw)
  680. self.type = sqltypes.to_instance(kw.get("type_", None))
  681. FunctionElement.__init__(self, *clauses, **kw)
  682. def _get_bind(self, kw):
  683. if "bind" in kw:
  684. util.warn_deprecated_20(
  685. "The Function.bind argument is deprecated and "
  686. "will be removed in SQLAlchemy 2.0.",
  687. )
  688. return kw["bind"]
  689. def _bind_param(self, operator, obj, type_=None, **kw):
  690. return BindParameter(
  691. self.name,
  692. obj,
  693. _compared_to_operator=operator,
  694. _compared_to_type=self.type,
  695. type_=type_,
  696. unique=True,
  697. **kw
  698. )
  699. class _GenericMeta(TraversibleType):
  700. def __init__(cls, clsname, bases, clsdict):
  701. if annotation.Annotated not in cls.__mro__:
  702. cls.name = name = clsdict.get("name", clsname)
  703. cls.identifier = identifier = clsdict.get("identifier", name)
  704. package = clsdict.pop("package", "_default")
  705. # legacy
  706. if "__return_type__" in clsdict:
  707. cls.type = clsdict["__return_type__"]
  708. # Check _register attribute status
  709. cls._register = getattr(cls, "_register", True)
  710. # Register the function if required
  711. if cls._register:
  712. register_function(identifier, cls, package)
  713. else:
  714. # Set _register to True to register child classes by default
  715. cls._register = True
  716. super(_GenericMeta, cls).__init__(clsname, bases, clsdict)
  717. class GenericFunction(util.with_metaclass(_GenericMeta, Function)):
  718. """Define a 'generic' function.
  719. A generic function is a pre-established :class:`.Function`
  720. class that is instantiated automatically when called
  721. by name from the :data:`.func` attribute. Note that
  722. calling any name from :data:`.func` has the effect that
  723. a new :class:`.Function` instance is created automatically,
  724. given that name. The primary use case for defining
  725. a :class:`.GenericFunction` class is so that a function
  726. of a particular name may be given a fixed return type.
  727. It can also include custom argument parsing schemes as well
  728. as additional methods.
  729. Subclasses of :class:`.GenericFunction` are automatically
  730. registered under the name of the class. For
  731. example, a user-defined function ``as_utc()`` would
  732. be available immediately::
  733. from sqlalchemy.sql.functions import GenericFunction
  734. from sqlalchemy.types import DateTime
  735. class as_utc(GenericFunction):
  736. type = DateTime
  737. inherit_cache = True
  738. print(select(func.as_utc()))
  739. User-defined generic functions can be organized into
  740. packages by specifying the "package" attribute when defining
  741. :class:`.GenericFunction`. Third party libraries
  742. containing many functions may want to use this in order
  743. to avoid name conflicts with other systems. For example,
  744. if our ``as_utc()`` function were part of a package
  745. "time"::
  746. class as_utc(GenericFunction):
  747. type = DateTime
  748. package = "time"
  749. inherit_cache = True
  750. The above function would be available from :data:`.func`
  751. using the package name ``time``::
  752. print(select(func.time.as_utc()))
  753. A final option is to allow the function to be accessed
  754. from one name in :data:`.func` but to render as a different name.
  755. The ``identifier`` attribute will override the name used to
  756. access the function as loaded from :data:`.func`, but will retain
  757. the usage of ``name`` as the rendered name::
  758. class GeoBuffer(GenericFunction):
  759. type = Geometry
  760. package = "geo"
  761. name = "ST_Buffer"
  762. identifier = "buffer"
  763. inherit_cache = True
  764. The above function will render as follows::
  765. >>> print(func.geo.buffer())
  766. ST_Buffer()
  767. The name will be rendered as is, however without quoting unless the name
  768. contains special characters that require quoting. To force quoting
  769. on or off for the name, use the :class:`.sqlalchemy.sql.quoted_name`
  770. construct::
  771. from sqlalchemy.sql import quoted_name
  772. class GeoBuffer(GenericFunction):
  773. type = Geometry
  774. package = "geo"
  775. name = quoted_name("ST_Buffer", True)
  776. identifier = "buffer"
  777. inherit_cache = True
  778. The above function will render as::
  779. >>> print(func.geo.buffer())
  780. "ST_Buffer"()
  781. .. versionadded:: 1.3.13 The :class:`.quoted_name` construct is now
  782. recognized for quoting when used with the "name" attribute of the
  783. object, so that quoting can be forced on or off for the function
  784. name.
  785. """
  786. coerce_arguments = True
  787. _register = False
  788. inherit_cache = True
  789. def __init__(self, *args, **kwargs):
  790. parsed_args = kwargs.pop("_parsed_args", None)
  791. if parsed_args is None:
  792. parsed_args = [
  793. coercions.expect(
  794. roles.ExpressionElementRole,
  795. c,
  796. name=self.name,
  797. apply_propagate_attrs=self,
  798. )
  799. for c in args
  800. ]
  801. self._has_args = self._has_args or bool(parsed_args)
  802. self.packagenames = ()
  803. self._bind = self._get_bind(kwargs)
  804. self.clause_expr = ClauseList(
  805. operator=operators.comma_op, group_contents=True, *parsed_args
  806. ).self_group()
  807. self.type = sqltypes.to_instance(
  808. kwargs.pop("type_", None) or getattr(self, "type", None)
  809. )
  810. register_function("cast", Cast)
  811. register_function("extract", Extract)
  812. class next_value(GenericFunction):
  813. """Represent the 'next value', given a :class:`.Sequence`
  814. as its single argument.
  815. Compiles into the appropriate function on each backend,
  816. or will raise NotImplementedError if used on a backend
  817. that does not provide support for sequences.
  818. """
  819. type = sqltypes.Integer()
  820. name = "next_value"
  821. _traverse_internals = [
  822. ("sequence", InternalTraversal.dp_named_ddl_element)
  823. ]
  824. def __init__(self, seq, **kw):
  825. assert isinstance(
  826. seq, schema.Sequence
  827. ), "next_value() accepts a Sequence object as input."
  828. self._bind = self._get_bind(kw)
  829. self.sequence = seq
  830. self.type = sqltypes.to_instance(
  831. seq.data_type or getattr(self, "type", None)
  832. )
  833. def compare(self, other, **kw):
  834. return (
  835. isinstance(other, next_value)
  836. and self.sequence.name == other.sequence.name
  837. )
  838. @property
  839. def _from_objects(self):
  840. return []
  841. class AnsiFunction(GenericFunction):
  842. """Define a function in "ansi" format, which doesn't render parenthesis."""
  843. inherit_cache = True
  844. def __init__(self, *args, **kwargs):
  845. GenericFunction.__init__(self, *args, **kwargs)
  846. class ReturnTypeFromArgs(GenericFunction):
  847. """Define a function whose return type is the same as its arguments."""
  848. inherit_cache = True
  849. def __init__(self, *args, **kwargs):
  850. args = [
  851. coercions.expect(
  852. roles.ExpressionElementRole,
  853. c,
  854. name=self.name,
  855. apply_propagate_attrs=self,
  856. )
  857. for c in args
  858. ]
  859. kwargs.setdefault("type_", _type_from_args(args))
  860. kwargs["_parsed_args"] = args
  861. super(ReturnTypeFromArgs, self).__init__(*args, **kwargs)
  862. class coalesce(ReturnTypeFromArgs):
  863. _has_args = True
  864. inherit_cache = True
  865. class max(ReturnTypeFromArgs): # noqa: A001
  866. """The SQL MAX() aggregate function."""
  867. inherit_cache = True
  868. class min(ReturnTypeFromArgs): # noqa: A001
  869. """The SQL MIN() aggregate function."""
  870. inherit_cache = True
  871. class sum(ReturnTypeFromArgs): # noqa: A001
  872. """The SQL SUM() aggregate function."""
  873. inherit_cache = True
  874. class now(GenericFunction):
  875. """The SQL now() datetime function.
  876. SQLAlchemy dialects will usually render this particular function
  877. in a backend-specific way, such as rendering it as ``CURRENT_TIMESTAMP``.
  878. """
  879. type = sqltypes.DateTime
  880. inherit_cache = True
  881. class concat(GenericFunction):
  882. """The SQL CONCAT() function, which concatenates strings.
  883. E.g.::
  884. >>> print(select(func.concat('a', 'b')))
  885. SELECT concat(:concat_2, :concat_3) AS concat_1
  886. String concatenation in SQLAlchemy is more commonly available using the
  887. Python ``+`` operator with string datatypes, which will render a
  888. backend-specific concatenation operator, such as ::
  889. >>> print(select(literal("a") + "b"))
  890. SELECT :param_1 || :param_2 AS anon_1
  891. """
  892. type = sqltypes.String
  893. inherit_cache = True
  894. class char_length(GenericFunction):
  895. """The CHAR_LENGTH() SQL function."""
  896. type = sqltypes.Integer
  897. inherit_cache = True
  898. def __init__(self, arg, **kwargs):
  899. GenericFunction.__init__(self, arg, **kwargs)
  900. class random(GenericFunction):
  901. """The RANDOM() SQL function."""
  902. _has_args = True
  903. inherit_cache = True
  904. class count(GenericFunction):
  905. r"""The ANSI COUNT aggregate function. With no arguments,
  906. emits COUNT \*.
  907. E.g.::
  908. from sqlalchemy import func
  909. from sqlalchemy import select
  910. from sqlalchemy import table, column
  911. my_table = table('some_table', column('id'))
  912. stmt = select(func.count()).select_from(my_table)
  913. Executing ``stmt`` would emit::
  914. SELECT count(*) AS count_1
  915. FROM some_table
  916. """
  917. type = sqltypes.Integer
  918. inherit_cache = True
  919. def __init__(self, expression=None, **kwargs):
  920. if expression is None:
  921. expression = literal_column("*")
  922. super(count, self).__init__(expression, **kwargs)
  923. class current_date(AnsiFunction):
  924. """The CURRENT_DATE() SQL function."""
  925. type = sqltypes.Date
  926. inherit_cache = True
  927. class current_time(AnsiFunction):
  928. """The CURRENT_TIME() SQL function."""
  929. type = sqltypes.Time
  930. inherit_cache = True
  931. class current_timestamp(AnsiFunction):
  932. """The CURRENT_TIMESTAMP() SQL function."""
  933. type = sqltypes.DateTime
  934. inherit_cache = True
  935. class current_user(AnsiFunction):
  936. """The CURRENT_USER() SQL function."""
  937. type = sqltypes.String
  938. inherit_cache = True
  939. class localtime(AnsiFunction):
  940. """The localtime() SQL function."""
  941. type = sqltypes.DateTime
  942. inherit_cache = True
  943. class localtimestamp(AnsiFunction):
  944. """The localtimestamp() SQL function."""
  945. type = sqltypes.DateTime
  946. inherit_cache = True
  947. class session_user(AnsiFunction):
  948. """The SESSION_USER() SQL function."""
  949. type = sqltypes.String
  950. inherit_cache = True
  951. class sysdate(AnsiFunction):
  952. """The SYSDATE() SQL function."""
  953. type = sqltypes.DateTime
  954. inherit_cache = True
  955. class user(AnsiFunction):
  956. """The USER() SQL function."""
  957. type = sqltypes.String
  958. inherit_cache = True
  959. class array_agg(GenericFunction):
  960. """Support for the ARRAY_AGG function.
  961. The ``func.array_agg(expr)`` construct returns an expression of
  962. type :class:`_types.ARRAY`.
  963. e.g.::
  964. stmt = select(func.array_agg(table.c.values)[2:5])
  965. .. versionadded:: 1.1
  966. .. seealso::
  967. :func:`_postgresql.array_agg` - PostgreSQL-specific version that
  968. returns :class:`_postgresql.ARRAY`, which has PG-specific operators
  969. added.
  970. """
  971. type = sqltypes.ARRAY
  972. inherit_cache = True
  973. def __init__(self, *args, **kwargs):
  974. args = [
  975. coercions.expect(
  976. roles.ExpressionElementRole, c, apply_propagate_attrs=self
  977. )
  978. for c in args
  979. ]
  980. default_array_type = kwargs.pop("_default_array_type", sqltypes.ARRAY)
  981. if "type_" not in kwargs:
  982. type_from_args = _type_from_args(args)
  983. if isinstance(type_from_args, sqltypes.ARRAY):
  984. kwargs["type_"] = type_from_args
  985. else:
  986. kwargs["type_"] = default_array_type(type_from_args)
  987. kwargs["_parsed_args"] = args
  988. super(array_agg, self).__init__(*args, **kwargs)
  989. class OrderedSetAgg(GenericFunction):
  990. """Define a function where the return type is based on the sort
  991. expression type as defined by the expression passed to the
  992. :meth:`.FunctionElement.within_group` method."""
  993. array_for_multi_clause = False
  994. inherit_cache = True
  995. def within_group_type(self, within_group):
  996. func_clauses = self.clause_expr.element
  997. order_by = sqlutil.unwrap_order_by(within_group.order_by)
  998. if self.array_for_multi_clause and len(func_clauses.clauses) > 1:
  999. return sqltypes.ARRAY(order_by[0].type)
  1000. else:
  1001. return order_by[0].type
  1002. class mode(OrderedSetAgg):
  1003. """Implement the ``mode`` ordered-set aggregate function.
  1004. This function must be used with the :meth:`.FunctionElement.within_group`
  1005. modifier to supply a sort expression to operate upon.
  1006. The return type of this function is the same as the sort expression.
  1007. .. versionadded:: 1.1
  1008. """
  1009. inherit_cache = True
  1010. class percentile_cont(OrderedSetAgg):
  1011. """Implement the ``percentile_cont`` ordered-set aggregate function.
  1012. This function must be used with the :meth:`.FunctionElement.within_group`
  1013. modifier to supply a sort expression to operate upon.
  1014. The return type of this function is the same as the sort expression,
  1015. or if the arguments are an array, an :class:`_types.ARRAY` of the sort
  1016. expression's type.
  1017. .. versionadded:: 1.1
  1018. """
  1019. array_for_multi_clause = True
  1020. inherit_cache = True
  1021. class percentile_disc(OrderedSetAgg):
  1022. """Implement the ``percentile_disc`` ordered-set aggregate function.
  1023. This function must be used with the :meth:`.FunctionElement.within_group`
  1024. modifier to supply a sort expression to operate upon.
  1025. The return type of this function is the same as the sort expression,
  1026. or if the arguments are an array, an :class:`_types.ARRAY` of the sort
  1027. expression's type.
  1028. .. versionadded:: 1.1
  1029. """
  1030. array_for_multi_clause = True
  1031. inherit_cache = True
  1032. class rank(GenericFunction):
  1033. """Implement the ``rank`` hypothetical-set aggregate function.
  1034. This function must be used with the :meth:`.FunctionElement.within_group`
  1035. modifier to supply a sort expression to operate upon.
  1036. The return type of this function is :class:`.Integer`.
  1037. .. versionadded:: 1.1
  1038. """
  1039. type = sqltypes.Integer()
  1040. inherit_cache = True
  1041. class dense_rank(GenericFunction):
  1042. """Implement the ``dense_rank`` hypothetical-set aggregate function.
  1043. This function must be used with the :meth:`.FunctionElement.within_group`
  1044. modifier to supply a sort expression to operate upon.
  1045. The return type of this function is :class:`.Integer`.
  1046. .. versionadded:: 1.1
  1047. """
  1048. type = sqltypes.Integer()
  1049. inherit_cache = True
  1050. class percent_rank(GenericFunction):
  1051. """Implement the ``percent_rank`` hypothetical-set aggregate function.
  1052. This function must be used with the :meth:`.FunctionElement.within_group`
  1053. modifier to supply a sort expression to operate upon.
  1054. The return type of this function is :class:`.Numeric`.
  1055. .. versionadded:: 1.1
  1056. """
  1057. type = sqltypes.Numeric()
  1058. inherit_cache = True
  1059. class cume_dist(GenericFunction):
  1060. """Implement the ``cume_dist`` hypothetical-set aggregate function.
  1061. This function must be used with the :meth:`.FunctionElement.within_group`
  1062. modifier to supply a sort expression to operate upon.
  1063. The return type of this function is :class:`.Numeric`.
  1064. .. versionadded:: 1.1
  1065. """
  1066. type = sqltypes.Numeric()
  1067. inherit_cache = True
  1068. class cube(GenericFunction):
  1069. r"""Implement the ``CUBE`` grouping operation.
  1070. This function is used as part of the GROUP BY of a statement,
  1071. e.g. :meth:`_expression.Select.group_by`::
  1072. stmt = select(
  1073. func.sum(table.c.value), table.c.col_1, table.c.col_2
  1074. ).group_by(func.cube(table.c.col_1, table.c.col_2))
  1075. .. versionadded:: 1.2
  1076. """
  1077. _has_args = True
  1078. inherit_cache = True
  1079. class rollup(GenericFunction):
  1080. r"""Implement the ``ROLLUP`` grouping operation.
  1081. This function is used as part of the GROUP BY of a statement,
  1082. e.g. :meth:`_expression.Select.group_by`::
  1083. stmt = select(
  1084. func.sum(table.c.value), table.c.col_1, table.c.col_2
  1085. ).group_by(func.rollup(table.c.col_1, table.c.col_2))
  1086. .. versionadded:: 1.2
  1087. """
  1088. _has_args = True
  1089. inherit_cache = True
  1090. class grouping_sets(GenericFunction):
  1091. r"""Implement the ``GROUPING SETS`` grouping operation.
  1092. This function is used as part of the GROUP BY of a statement,
  1093. e.g. :meth:`_expression.Select.group_by`::
  1094. stmt = select(
  1095. func.sum(table.c.value), table.c.col_1, table.c.col_2
  1096. ).group_by(func.grouping_sets(table.c.col_1, table.c.col_2))
  1097. In order to group by multiple sets, use the :func:`.tuple_` construct::
  1098. from sqlalchemy import tuple_
  1099. stmt = select(
  1100. func.sum(table.c.value),
  1101. table.c.col_1, table.c.col_2,
  1102. table.c.col_3
  1103. ).group_by(
  1104. func.grouping_sets(
  1105. tuple_(table.c.col_1, table.c.col_2),
  1106. tuple_(table.c.value, table.c.col_3),
  1107. )
  1108. )
  1109. .. versionadded:: 1.2
  1110. """
  1111. _has_args = True
  1112. inherit_cache = True