U kf@sUdZddlmZddlZddlZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$dd l%m&Z&dd!l%m'Z'dd"l%m(Z(dd#l%m)Z)dd$l%m*Z*dd%l%m+Z+dd&l%m,Z,dd'l%m-Z-dd(l%m.Z.dd)l%m/Z/dd*l%m0Z0dd+l%m1Z1dd,l%m2Z2dd-l3m4Z4dd.l3m5Z5dd/l3m6Z6dd0lm7Z7dd1lm8Z8dd2l9m:Z:d3dlmZerdd4lm;Z;dd5lmZ>dd8lm?Z?dd9lm@Z@dd:lmAZAdd;l%mBZBddlmEZEd3d?lFmGZGd3d@lHmIZId3dAlJmKZKd3dBlJmLZLd3dClMmNZNedDedEZOedFedEZPeQeRZSdGeTdH<ddJdKdJdLdMdNdOZUGdPdQdQe"e+eOe4e#ZVGdRdSdSe'eZWGdTdUdUe0eOZXGdVdWdWZYeYZZeYjeZ_eYdXdYZ[GdZd[d[eVeOZ\Gd\d]d]e\eOZ]eUd^e)eUd_e,Gd`dadae]e^Z_Gdbdcdce]eOZ`Gdddedee]eOZaGdfdgdgeaeOZbGdhdidieaeOZcGdjdkdkeaeOZdGdldmdmeaeOZeGdndodoe]ejZfGdpdqdqe]egZhGdrdsdse]e^ZiGdtdudue]ejZkGdvdwdwe]e^ZlGdxdydye`ejmZnGdzd{d{e`ejoZpGd|d}d}e`ejZqGd~dde`egZrGddde`ejZsGddde`ejZtGddde`egZuGddde`ejZvGddde`egZwGddde]eOZxGddde]eOZyGdddeyeOZzGdddeyeOZ{GdddeyeOZ|Gddde]e^Z}Gddde]e^Z~Gddde]ejZGddde]ejZGddde]eOZGddde]eOZGddde]eOZGddde]egZdS)z6SQL function API, factories, and built-in functions. ) annotationsN)Any)cast)Dict)List)Mapping)Optional)overload)Sequence)Tuple)Type) TYPE_CHECKING)TypeVar)Union) annotation) coercions) operators)roles)schema)sqltypes)type_api)util)is_table_value_type)_entity_namespace)ColumnCollection) Executable) Generative) HasMemoized)_type_from_args)BinaryExpression) BindParameter)Cast) ClauseList) ColumnElement)ExtractFunctionFilter)Grouping)literal_column) NamedColumnOver WithinGroup) FromClause)Select)TableValuedAlias)TableValueType) TypeEngine)InternalTraversal) _ByArgument)_ColumnExpressionArgument)"_ColumnExpressionOrLiteralArgument)#_ColumnExpressionOrStrLabelArgument) _StarOrOne)_TypeEngineArgument)_EntityNamespace) ClauseElement)KeyedColumnElement)TableValuedColumn) OperatorType) Connection) CursorResult)_CoreMultiExecuteParams)CoreExecuteOptionsParameter)Self_T)bound_Sz5util.defaultdict[str, Dict[str, Type[Function[Any]]]] _registry_defaultstrzType[Function[Any]]None) identifierfnpackagereturncCs8t|}t|}||kr,td||||<dS)zAssociate a callable with a particular func. name. This is normally called by GenericFunction, but is also available by itself so that a non-Function construct can be associated with the :data:`.func` accessor (i.e. CAST, EXTRACT). zMThe GenericFunction '{}' is already registered and is going to be overridden.N)rIrKlowerrwarnformat)rMrNrOregrUH/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/sql/functions.pyregister_function]s  rWcsBeZdZUdZdejfdejfdejfgZdZ de d<dZ dZ d Z d e d<d e d <d e d <de d<ddddZd Zed dfdd ZdddddddZdpdddd d!d"Zd#d d$d%d&d'Zdqd(d)d*d+d,d-Zejd.dd/d0Zejd.dd1d2Zed3dd4d5Zed.dd6d7Zejd8dd9d:Zd d d d d;dd?d@dAZ dBdCdDdEdFZ!e"dGddHdIZ#e"dJdJdKdLdMdIZ#dJdNdOdPdIZ#dQdQdRdSdTdUZ$ed ddVdWZ%dXdYdZd[d\Z&drd(d)d$d+d]d^Z'd_dd`daZ(dsdbd dcd)d dddedfdgZ)dtdhdidjfdkdl Z*edmddndoZ+Z,S)uFunctionElementaBase for SQL function-oriented constructs. This is a `generic type `_, meaning that type checkers and IDEs can be instructed on the types to expect in a :class:`_engine.Result` for this function. See :class:`.GenericFunction` for an example of how this is done. .. seealso:: :ref:`tutorial_functions` - in the :ref:`unified_tutorial` :class:`.Function` - named SQL function. :data:`.func` - namespace which produces registered or ad-hoc :class:`.Function` instances. :class:`.GenericFunction` - allows creation of registered function types. clause_expr_with_ordinality_table_value_typerUzTuple[str, ...] packagenamesFNzOptional[TableValueType]rZ primary_keyZ _is_clone_ofz Grouping[Any]'_ColumnExpressionOrLiteralArgument[Any])clausescs>fdd|D}jpt|_tt|tjdd_dS)aOConstruct a :class:`.FunctionElement`. :param \*clauses: list of column expressions that form the arguments of the SQL function call. :param \**kwargs: additional kwargs are typically consumed by subclasses. .. seealso:: :data:`.func` :class:`.Function` c s(g|] }tjtj|tdddqS)nameNr_apply_propagate_attrs)rexpectrExpressionElementRolegetattr.0cselfrUrV s z,FunctionElement.__init__..ToperatorZgroup_contentsN) _has_argsboolr(r#rcomma_oprY)rir^argsrUrhrV__init__s  zFunctionElement.__init__rPcstjpt|ddS)Nr_)super _proxy_keyrdrh __class__rUrVrtszFunctionElement._proxy_keyrArCrDzCursorResult[Any]) connectiondistilled_paramsexecution_optionsrPcCs||||SN)Z_execute_function)rirwrxryrUrUrV_execute_on_connections z&FunctionElement._execute_on_connectionrK!Optional[_TypeEngineArgument[_T]]zScalarFunctionColumn[_T])r_type_rPcCs t|||S)aReturn a column expression that's against this :class:`_functions.FunctionElement` as a scalar table-valued expression. The returned expression is similar to that returned by a single column accessed off of a :meth:`_functions.FunctionElement.table_valued` construct, except no FROM clause is generated; the function is rendered in the similar way as a scalar subquery. E.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import func, select >>> fn = func.jsonb_each("{'k', 'v'}").scalar_table_valued("key") >>> print(select(fn)) {printsql}SELECT (jsonb_each(:jsonb_each_1)).key .. versionadded:: 1.4.0b2 .. seealso:: :meth:`_functions.FunctionElement.table_valued` :meth:`_functions.FunctionElement.alias` :meth:`_functions.FunctionElement.column_valued` )ScalarFunctionColumn)rir_r}rUrUrVscalar_table_valueds!z#FunctionElement.scalar_table_valuedz(_ColumnExpressionOrStrLabelArgument[Any]r1)exprkwrPcOs^|}|dd}|dd}|dd}|r@||f7}d|_t||_|_|j||dS)a Return a :class:`_sql.TableValuedAlias` representation of this :class:`_functions.FunctionElement` with table-valued expressions added. e.g.: .. sourcecode:: pycon+sql >>> fn = ( ... func.generate_series(1, 5). ... table_valued("value", "start", "stop", "step") ... ) >>> print(select(fn)) {printsql}SELECT anon_1.value, anon_1.start, anon_1.stop, anon_1.step FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1{stop} >>> print(select(fn.c.value, fn.c.stop).where(fn.c.value > 2)) {printsql}SELECT anon_1.value, anon_1.stop FROM generate_series(:generate_series_1, :generate_series_2) AS anon_1 WHERE anon_1.value > :value_1{stop} A WITH ORDINALITY expression may be generated by passing the keyword argument "with_ordinality": .. sourcecode:: pycon+sql >>> fn = func.generate_series(4, 1, -1).table_valued("gen", with_ordinality="ordinality") >>> print(select(fn)) {printsql}SELECT anon_1.gen, anon_1.ordinality FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) WITH ORDINALITY AS anon_1 :param \*expr: A series of string column names that will be added to the ``.c`` collection of the resulting :class:`_sql.TableValuedAlias` construct as columns. :func:`_sql.column` objects with or without datatypes may also be used. :param name: optional name to assign to the alias name that's generated. If omitted, a unique anonymizing name is used. :param with_ordinality: string name that when present results in the ``WITH ORDINALITY`` clause being added to the alias, and the given string name will be added as a column to the .c collection of the resulting :class:`_sql.TableValuedAlias`. :param joins_implicitly: when True, the table valued function may be used in the FROM clause without any explicit JOIN to other tables in the SQL query, and no "cartesian product" warning will be generated. May be useful for SQL functions such as ``func.json_each()``. .. versionadded:: 1.4.33 .. versionadded:: 1.4.0b2 .. seealso:: :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial` :ref:`postgresql_table_valued` - in the :ref:`postgresql_toplevel` documentation :meth:`_functions.FunctionElement.scalar_table_valued` - variant of :meth:`_functions.FunctionElement.table_valued` which delivers the complete table valued expression as a scalar column expression :meth:`_functions.FunctionElement.column_valued` :meth:`_sql.TableValuedAlias.render_derived` - renders the alias using a derived column clause, e.g. ``AS name(col1, col2, ...)`` with_ordinalityNjoins_implicitlyr_Tr_r)Z _generatepoprZr2typer[alias)rirrnew_funcrrr_rUrUrV table_valuedsJ    zFunctionElement.table_valuedz Optional[str]rnzTableValuedColumn[_T])r_rrPcCs|j||djS)aQReturn this :class:`_functions.FunctionElement` as a column expression that selects from itself as a FROM clause. E.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, func >>> gs = func.generate_series(1, 5, -1).column_valued() >>> print(select(gs)) {printsql}SELECT anon_1 FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) AS anon_1 This is shorthand for:: gs = func.generate_series(1, 5, -1).alias().column :param name: optional name to assign to the alias name that's generated. If omitted, a unique anonymizing name is used. :param joins_implicitly: when True, the "table" portion of the column valued function may be a member of the FROM clause without any explicit JOIN to other tables in the SQL query, and no "cartesian product" warning will be generated. May be useful for SQL functions such as ``func.json_array_elements()``. .. versionadded:: 1.4.46 .. seealso:: :ref:`tutorial_functions_column_valued` - in the :ref:`unified_tutorial` :ref:`postgresql_column_valued` - in the :ref:`postgresql_toplevel` documentation :meth:`_functions.FunctionElement.table_valued` r)rcolumnrir_rrUrUrV column_valuedGs)zFunctionElement.column_valuedz.ColumnCollection[str, KeyedColumnElement[Any]]cCs|jS)aThe set of columns exported by this :class:`.FunctionElement`. This is a placeholder collection that allows the function to be placed in the FROM clause of a statement: .. sourcecode:: pycon+sql >>> from sqlalchemy import column, select, func >>> stmt = select(column('x'), column('y')).select_from(func.myfunction()) >>> print(stmt) {printsql}SELECT x, y FROM myfunction() The above form is a legacy feature that is now superseded by the fully capable :meth:`_functions.FunctionElement.table_valued` method; see that method for details. .. seealso:: :meth:`_functions.FunctionElement.table_valued` - generates table-valued SQL function expressions. )rgrhrUrUrVcolumnsrszFunctionElement.columnscCstdd|jDdS)z-synonym for :attr:`.FunctionElement.columns`.cSsg|]}|j|fqSrU)key)rfcolrUrUrVrjsz%FunctionElement.c..r)r_all_selected_columnsrhrUrUrVrgszFunctionElement.c!Sequence[KeyedColumnElement[Any]]cCs*t|jrtd|jj}n |dg}|S)Nr)rrrZ _elementslabel)ricolsrUrUrVrs  z%FunctionElement._all_selected_columnscCs|jSrzrrhrUrUrVexported_columnssz FunctionElement.exported_columnsr#cCstt|jjS)z}Return the underlying :class:`.ClauseList` which contains the arguments for this :class:`.FunctionElement`. )rr#rYelementrhrUrUrVr^szFunctionElement.clauses partition_byorder_byrowsrange_zOptional[_ByArgument]z-Optional[Tuple[Optional[int], Optional[int]]]zOver[_T])rrrrrPcCst|||||dS)aAProduce an OVER clause against this function. Used against aggregate or so-called "window" functions, for database backends that support window functions. The expression:: func.row_number().over(order_by='x') is shorthand for:: from sqlalchemy import over over(func.row_number(), order_by='x') See :func:`_expression.over` for a full description. .. seealso:: :func:`_expression.over` :ref:`tutorial_window_functions` - in the :ref:`unified_tutorial` rr+)rirrrrrUrUrVoverszFunctionElement.over_ColumnExpressionArgument[Any]zWithinGroup[_T])rrPcGst|f|S)aProduce a WITHIN GROUP (ORDER BY expr) clause against this function. Used against so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including :class:`.percentile_cont`, :class:`.rank`, :class:`.dense_rank`, etc. See :func:`_expression.within_group` for a full description. .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial` r-)rirrUrUrV within_groupszFunctionElement.within_grouprEcCsdSrzrUrhrUrUrVfilterszFunctionElement.filterz_ColumnExpressionArgument[bool]zFunctionFilter[_T])_FunctionElement__criterion0 criterionrPcGsdSrzrU)rirrrUrUrVrszUnion[Self, FunctionFilter[_T]])rrPcGs|s|St|f|S)a&Produce a FILTER clause against this function. Used against aggregate and window functions, for database backends that support the "FILTER" clause. The expression:: func.count(1).filter(True) is shorthand for:: from sqlalchemy import funcfilter funcfilter(func.count(1), True) .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial` :class:`.FunctionFilter` :func:`.funcfilter` r&)rirrUrUrVrsintFunctionAsBinary) left_index right_indexrPcCs t|||S)a^ Interpret this expression as a boolean comparison between two values. This method is used for an ORM use case described at :ref:`relationship_custom_operator_sql_function`. A hypothetical SQL function "is_equal()" which compares to values for equality would be written in the Core expression language as:: expr = func.is_equal("a", "b") If "is_equal()" above is comparing "a" and "b" for equality, the :meth:`.FunctionElement.as_comparison` method would be invoked as:: expr = func.is_equal("a", "b").as_comparison(1, 2) Where above, the integer value "1" refers to the first argument of the "is_equal()" function and the integer value "2" refers to the second. This would create a :class:`.BinaryExpression` that is equivalent to:: BinaryExpression("a", "b", operator=op.eq) However, at the SQL level it would still render as "is_equal('a', 'b')". The ORM, when it loads a related object or collection, needs to be able to manipulate the "left" and "right" sides of the ON clause of a JOIN expression. The purpose of this method is to provide a SQL function construct that can also supply this information to the ORM, when used with the :paramref:`_orm.relationship.primaryjoin` parameter. The return value is a containment object called :class:`.FunctionAsBinary`. An ORM example is as follows:: class Venue(Base): __tablename__ = 'venue' id = Column(Integer, primary_key=True) name = Column(String) descendants = relationship( "Venue", primaryjoin=func.instr( remote(foreign(name)), name + "/" ).as_comparison(1, 2) == 1, viewonly=True, order_by=name ) Above, the "Venue" class can load descendant "Venue" objects by determining if the name of the parent Venue is contained within the start of the hypothetical descendant value's name, e.g. "parent1" would match up to "parent1/child1", but not to "parent2/child1". Possible use cases include the "materialized path" example given above, as well as making use of special SQL functions such as geometric functions to create join conditions. :param left_index: the integer 1-based index of the function argument that serves as the "left" side of the expression. :param right_index: the integer 1-based index of the function argument that serves as the "right" side of the expression. .. versionadded:: 1.3 .. seealso:: :ref:`relationship_custom_operator_sql_function` - example use within the ORM )r)rirrrUrUrV as_comparisonsJzFunctionElement.as_comparisoncCs|jjSrz)r^ _from_objectsrhrUrUrVr_szFunctionElement._from_objectszWithinGroup[_S]zOptional[TypeEngine[_S]]rrPcCsdS)aFor types that define their return type as based on the criteria within a WITHIN GROUP (ORDER BY) expression, called by the :class:`.WithinGroup` construct. Returns None by default, in which case the function's normal ``.type`` is used. NrU)rirrUrUrVwithin_group_typecs z!FunctionElement.within_group_typecCstj|||j|dS)a+ Produce a :class:`_expression.Alias` construct against this :class:`.FunctionElement`. .. tip:: The :meth:`_functions.FunctionElement.alias` method is part of the mechanism by which "table valued" SQL functions are created. However, most use cases are covered by higher level methods on :class:`_functions.FunctionElement` including :meth:`_functions.FunctionElement.table_valued`, and :meth:`_functions.FunctionElement.column_valued`. This construct wraps the function in a named alias which is suitable for the FROM clause, in the style accepted for example by PostgreSQL. A column expression is also provided using the special ``.column`` attribute, which may be used to refer to the output of the function as a scalar value in the columns or where clause, for a backend such as PostgreSQL. For a full table-valued expression, use the :meth:`_functions.FunctionElement.table_valued` method first to establish named columns. e.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import func, select, column >>> data_view = func.unnest([1, 2, 3]).alias("data_view") >>> print(select(data_view.column)) {printsql}SELECT data_view FROM unnest(:unnest_1) AS data_view The :meth:`_functions.FunctionElement.column_valued` method provides a shortcut for the above pattern: .. sourcecode:: pycon+sql >>> data_view = func.unnest([1, 2, 3]).column_valued("data_view") >>> print(select(data_view)) {printsql}SELECT data_view FROM unnest(:unnest_1) AS data_view .. versionadded:: 1.4.0b2 Added the ``.column`` accessor :param name: alias name, will be rendered as ``AS `` in the FROM clause :param joins_implicitly: when True, the table valued function may be used in the FROM clause without any explicit JOIN to other tables in the SQL query, and no "cartesian product" warning will be generated. May be useful for SQL functions such as ``func.json_each()``. .. versionadded:: 1.4.33 .. seealso:: :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial` :meth:`_functions.FunctionElement.table_valued` :meth:`_functions.FunctionElement.scalar_table_valued` :meth:`_functions.FunctionElement.column_valued` )r_Ztable_value_typer)r1Z _constructrrrUrUrVrqs IzFunctionElement.aliaszSelect[Tuple[_T]]cCs t|}|jr|jf|j}|S)zProduce a :func:`_expression.select` construct against this :class:`.FunctionElement`. This is shorthand for:: s = select(function_element) )r0Z_execution_optionsry)risrUrUrVselects zFunctionElement.selectr@Optional[TypeEngine[_T]]BindParameter[_T]rlobjr} expandingrrPcKs td|f||jd||d|S)NT)_compared_to_operator_compared_to_typeuniquer}r)r!rrirlrr}rrrUrUrV _bind_paramszFunctionElement._bind_paramzOptional[OperatorType]r=)againstrPcs2|tjkr t|jtjr t|Stj|dSdS)N)r) rgetitem isinstancerrARRAYr(rs self_group)rirrurUrVrs  zFunctionElement.self_groupr<cCs t|jS)zzoverrides FromClause.entity_namespace as functions are generally column expressions and not FromClauses. )rrYrhrUrUrVentity_namespacesz FunctionElement.entity_namespace)N)NF)NF)NF)N)-__name__ __module__ __qualname____doc__r4dp_clauseelementZ dp_booleanZdp_has_cache_key_traverse_internalsr\__annotations__rmrZr[rqZ_non_anon_labelpropertyrtr{rrrrZro_non_memoized_propertyrZro_memoized_propertyrgrrrZmemoized_attributer^rrr rrrrrrrrr __classcell__rUrUrurVrXust    #Y+  ' LP rXc@seZdZUdejfdejfdejfdejfgZded<ded<ded<ddddd d Z dddd d d Z e ddddZ e j dddddZ e ddddZej dddddZese ZeZdS)r sql_functionrr modifierszFunctionElement[Any]rr)anon_map bindparamsrPcCst|||Srz)r$_gen_cache_key)rirrrUrUrVrszFunctionAsBinary._gen_cache_key)rNrrcCs8||_||_||_tj|_tj|_d|_ d|_ i|_ dS)NT) rrrrZfunction_as_comparison_oprlrZ BOOLEANTYPErnegateZ_is_implicitly_booleanr)rirNrrrUrUrVrqszFunctionAsBinary.__init__zColumnElement[Any]rrcCs|jjj|jdSNrrr^rrhrUrUrV left_exprszFunctionAsBinary.left_exprrL)valuerPcCs||jjj|jd<dSrrrirrUrUrVrscCs|jjj|jdSrrr^rrhrUrUrV right_exprszFunctionAsBinary.right_exprcCs||jjj|jd<dSrrrrUrUrVr!sN)rrrr4r dp_plain_objZ dp_plain_dictrrrrqrrsetterrr leftrightrUrUrUrVrs*  rc@sHeZdZdZdejfdejfdejfgZdZ dZ d ddd d d d Z dS)r~Zscalar_function_columnr_rrNFNzFunctionElement[_T]rKr|)rNr_r}cCs||_||_t||_dSrz)rNr_r to_instancer)rirNr_r}rUrUrVrq9szScalarFunctionColumn.__init__)N) rrr__visit_name__r4Z dp_anon_namedp_typerrZ is_literaltablerqrUrUrUrVr~-sr~c@seZdZdZddddZddddd Zedd dd d d dZeddddddZddddddZere ddddZ e ddddZ e ddddZ e ddddZ e d dd!d"Zed#d$dd%d&d'd(Zed)d$dd%d&d*d(Zed+d$dd%d&d,d(Zd+d$dd%d&d-d(Ze d.dd/d0Ze d1dd2d3Ze d4dd5d6Ze d7dd8d9Ze d:dd;d<Ze d=dd>d?Ze d@ddAdBZe dCddDdEZe dFddGdHZe dIddJdKZe dLddMdNZe dOddPdQZe dRddSdTZed#d$ddUd&dVdWZed)d$ddUd&dXdWZed+d$ddUd&dYdWZd+d$ddUd&dZdWZed#d$dd[d&d\d]Zed)d$dd[d&d^d]Zed+d$dd[d&d_d]Zd+d$dd[d&d`d]Ze daddbdcZe ddddedfZ e dgddhdiZ!e djddkdlZ"e dmddndoZ#e dpddqdrZ$e dsddtduZ%e dvddwdxZ&e dyddzd{Z'e d|dd}d~Z(e ddddZ)ed#d$ddd&ddZ*ed)d$ddd&ddZ*ed+d$ddd&ddZ*d+d$ddd&ddZ*e ddddZ+e ddddZ,dS)_FunctionGeneratora Generate SQL function expressions. :data:`.func` is a special object instance which generates SQL functions based on name-based attributes, e.g.: .. sourcecode:: pycon+sql >>> print(func.count(1)) {printsql}count(:param_1) The returned object is an instance of :class:`.Function`, and is a column-oriented SQL element like any other, and is used in that way: .. sourcecode:: pycon+sql >>> print(select(func.count(table.c.id))) {printsql}SELECT count(sometable.id) FROM sometable Any name can be given to :data:`.func`. If the function name is unknown to SQLAlchemy, it will be rendered exactly as is. For common SQL functions which SQLAlchemy is aware of, the name may be interpreted as a *generic function* which will be compiled appropriately to the target database: .. sourcecode:: pycon+sql >>> print(func.current_timestamp()) {printsql}CURRENT_TIMESTAMP To call functions which are present in dot-separated packages, specify them in the same manner: .. sourcecode:: pycon+sql >>> print(func.stats.yield_curve(5, 10)) {printsql}stats.yield_curve(:yield_curve_1, :yield_curve_2) SQLAlchemy can be made aware of the return type of functions to enable type-specific lexical and result-based behavior. For example, to ensure that a string-based function returns a Unicode value and is similarly treated as a string in expressions, specify :class:`~sqlalchemy.types.Unicode` as the type: .. sourcecode:: pycon+sql >>> print(func.my_string(u'hi', type_=Unicode) + ' ' + ... func.my_string(u'there', type_=Unicode)) {printsql}my_string(:my_string_1) || :my_string_2 || my_string(:my_string_3) The object returned by a :data:`.func` call is usually an instance of :class:`.Function`. This object meets the "column" interface, including comparison and labeling functions. The object can also be passed the :meth:`~.Connectable.execute` method of a :class:`_engine.Connection` or :class:`_engine.Engine`, where it will be wrapped inside of a SELECT statement first:: print(connection.execute(func.current_timestamp()).scalar()) In a few exception cases, the :data:`.func` accessor will redirect a name to a built-in expression such as :func:`.cast` or :func:`.extract`, as these names have well-known meaning but are not exactly the same as "functions" from a SQLAlchemy perspective. Functions which are interpreted as "generic" functions know how to calculate their return type automatically. For a listing of known generic functions, see :ref:`generic_functions`. .. note:: The :data:`.func` construct has only limited support for calling standalone "stored procedures", especially those with special parameterization concerns. See the section :ref:`stored_procedures` for details on how to use the DBAPI-level ``callproc()`` method for fully traditional stored procedures. .. seealso:: :ref:`tutorial_functions` - in the :ref:`unified_tutorial` :class:`.Function` r)optscKsg|_||_dSrz)_FunctionGenerator__namesr)rirrUrUrVrqsz_FunctionGenerator.__init__rK)r_rPcCsn|dr6z |j|WStk r2t|YqLXn|drL|dd}tf|j}t|j|g|_|S)N___r) startswith__dict__KeyErrorAttributeErrorendswithrrlistr)rir_frUrUrV __getattr__s     z_FunctionGenerator.__getattr___TypeEngineArgument[_T]z Function[_T])rgr}kwargsrPcOsdSrzrU)rir}rgrrUrUrV__call__sz_FunctionGenerator.__call__z Function[Any])rgrrPcOsdSrzrU)rirgrrUrUrVrscOs|j}||t|j}|dkr2|j\}}n|dkrLd|jd}}nd}|dk r|t||}|dk r||||St|jdf|dt |jddi|S)Nr5rrJrrr\) rcopyupdatelenrrIgetrQFunctiontuple)rirgrotokensrOfnamefuncrUrUrVrs*     zType[aggregate_strings]rrcCsdSrzrUrhrUrUrVaggregate_stringssz$_FunctionGenerator.aggregate_stringszType[AnsiFunction[Any]]cCsdSrzrUrhrUrUrV ansifunctionsz_FunctionGenerator.ansifunctionzType[array_agg[Any]]cCsdSrzrUrhrUrUrV array_aggsz_FunctionGenerator.array_aggzType[Cast[Any]]cCsdSrzrUrhrUrUrVrsz_FunctionGenerator.castzType[char_length]cCsdSrzrUrhrUrUrV char_lengthsz_FunctionGenerator.char_lengthColumnElement[_T]r]z coalesce[_T])rrprrPcOsdSrzrUrirrprrUrUrVcoalescesz_FunctionGenerator.coalesce_ColumnExpressionArgument[_T]cOsdSrzrUrrUrUrVrs&_ColumnExpressionOrLiteralArgument[_T]cOsdSrzrUrrUrUrVrscOsdSrzrUrrUrUrVrsz Type[concat]cCsdSrzrUrhrUrUrVconcatsz_FunctionGenerator.concatz Type[count]cCsdSrzrUrhrUrUrVcount sz_FunctionGenerator.countzType[cube[Any]]cCsdSrzrUrhrUrUrVcube sz_FunctionGenerator.cubezType[cume_dist]cCsdSrzrUrhrUrUrV cume_distsz_FunctionGenerator.cume_distzType[current_date]cCsdSrzrUrhrUrUrV current_datesz_FunctionGenerator.current_datezType[current_time]cCsdSrzrUrhrUrUrV current_timesz_FunctionGenerator.current_timezType[current_timestamp]cCsdSrzrUrhrUrUrVcurrent_timestampsz$_FunctionGenerator.current_timestampzType[current_user]cCsdSrzrUrhrUrUrV current_usersz_FunctionGenerator.current_userzType[dense_rank]cCsdSrzrUrhrUrUrV dense_ranksz_FunctionGenerator.dense_rankz Type[Extract]cCsdSrzrUrhrUrUrVextract"sz_FunctionGenerator.extractzType[grouping_sets[Any]]cCsdSrzrUrhrUrUrV grouping_sets%sz _FunctionGenerator.grouping_setszType[localtime]cCsdSrzrUrhrUrUrV localtime(sz_FunctionGenerator.localtimezType[localtimestamp]cCsdSrzrUrhrUrUrVlocaltimestamp+sz!_FunctionGenerator.localtimestampzmax[_T]cOsdSrzrUrrUrUrVmax3sz_FunctionGenerator.maxcOsdSrzrUrrUrUrVr ;scOsdSrzrUrrUrUrVr CscOsdSrzrUrrUrUrVr Kszmin[_T]cOsdSrzrUrrUrUrVminWsz_FunctionGenerator.mincOsdSrzrUrrUrUrVr _scOsdSrzrUrrUrUrVr gscOsdSrzrUrrUrUrVr oszType[mode[Any]]cCsdSrzrUrhrUrUrVmodevsz_FunctionGenerator.modezType[next_value]cCsdSrzrUrhrUrUrV next_valueysz_FunctionGenerator.next_valuez Type[now]cCsdSrzrUrhrUrUrVnow|sz_FunctionGenerator.nowzType[OrderedSetAgg[Any]]cCsdSrzrUrhrUrUrV orderedsetaggsz _FunctionGenerator.orderedsetaggzType[percent_rank]cCsdSrzrUrhrUrUrV percent_ranksz_FunctionGenerator.percent_rankzType[percentile_cont[Any]]cCsdSrzrUrhrUrUrVpercentile_contsz"_FunctionGenerator.percentile_contzType[percentile_disc[Any]]cCsdSrzrUrhrUrUrVpercentile_discsz"_FunctionGenerator.percentile_discz Type[random]cCsdSrzrUrhrUrUrVrandomsz_FunctionGenerator.randomz Type[rank]cCsdSrzrUrhrUrUrVranksz_FunctionGenerator.rankzType[rollup[Any]]cCsdSrzrUrhrUrUrVrollupsz_FunctionGenerator.rollupzType[session_user]cCsdSrzrUrhrUrUrV session_usersz_FunctionGenerator.session_userzsum[_T]cOsdSrzrUrrUrUrVsumsz_FunctionGenerator.sumcOsdSrzrUrrUrUrVrscOsdSrzrUrrUrUrVrscOsdSrzrUrrUrUrVrsz Type[sysdate]cCsdSrzrUrhrUrUrVsysdatesz_FunctionGenerator.sysdatez Type[user]cCsdSrzrUrhrUrUrVusersz_FunctionGenerator.userN)-rrrrrqrr rr rrrrrrrrrrrrrrrrrrr r r r r rrrrrrrrrrrrrrUrUrUrVrGsV rF)groupc@seZdZUdZdZejdejfdej fdej fgZde d<de d<de d<e d d d dd d d dddZ e d d d dddd dddZ ddd dddd dddZ d dddddddddZdS)!raDescribe a named SQL function. The :class:`.Function` object is typically generated from the :data:`.func` generation object. :param \*clauses: list of column expressions that form the arguments of the SQL function call. :param type\_: optional :class:`.TypeEngine` datatype object that will be used as the return value of the column expression generated by this function call. :param packagenames: a string which indicates package prefix names to be prepended to the function name when the SQL is generated. The :data:`.func` generator creates these when it is called using dotted format, e.g.:: func.mypackage.some_function(col1, col2) .. seealso:: :ref:`tutorial_functions` - in the :ref:`unified_tutorial` :data:`.func` - namespace which produces registered or ad-hoc :class:`.Function` instances. :class:`.GenericFunction` - allows creation of registered function types. functionr\r_rrKrMzTypeEngine[_T].)r}r\rrLzOptional[Tuple[str, ...]])r_r^r}r\cGsdSrzrUrir_r}r\r^rUrUrVrqszFunction.__init__r]rcGsdSrzrUrrUrUrVrqsNr|cGs0|pd|_||_t||_tj|f|dS)zConstruct a :class:`.Function`. The :data:`.func` construct is normally used to construct new :class:`.Function` instances. rUN)r\r_rrrrXrqrrUrUrVrqs  Fr@rrrnrrcKs"t|j|f||j|d|d|S)NT)rrr}rr)r!r_rrrUrUrVr0szFunction._bind_param)NF)rrrrrrXrr4rZ dp_stringrrr rqrrUrUrUrVrs0   rcsbeZdZUdZdZdZded<dZddfdd Ze d d dd d d Z dddddZ Z S)GenericFunctionaqDefine a 'generic' function. A generic function is a pre-established :class:`.Function` class that is instantiated automatically when called by name from the :data:`.func` attribute. Note that calling any name from :data:`.func` has the effect that a new :class:`.Function` instance is created automatically, given that name. The primary use case for defining a :class:`.GenericFunction` class is so that a function of a particular name may be given a fixed return type. It can also include custom argument parsing schemes as well as additional methods. Subclasses of :class:`.GenericFunction` are automatically registered under the name of the class. For example, a user-defined function ``as_utc()`` would be available immediately:: from sqlalchemy.sql.functions import GenericFunction from sqlalchemy.types import DateTime class as_utc(GenericFunction): type = DateTime() inherit_cache = True print(select(func.as_utc())) User-defined generic functions can be organized into packages by specifying the "package" attribute when defining :class:`.GenericFunction`. Third party libraries containing many functions may want to use this in order to avoid name conflicts with other systems. For example, if our ``as_utc()`` function were part of a package "time":: class as_utc(GenericFunction): type = DateTime() package = "time" inherit_cache = True The above function would be available from :data:`.func` using the package name ``time``:: print(select(func.time.as_utc())) A final option is to allow the function to be accessed from one name in :data:`.func` but to render as a different name. The ``identifier`` attribute will override the name used to access the function as loaded from :data:`.func`, but will retain the usage of ``name`` as the rendered name:: class GeoBuffer(GenericFunction): type = Geometry() package = "geo" name = "ST_Buffer" identifier = "buffer" inherit_cache = True The above function will render as follows: .. sourcecode:: pycon+sql >>> print(func.geo.buffer()) {printsql}ST_Buffer() The name will be rendered as is, however without quoting unless the name contains special characters that require quoting. To force quoting on or off for the name, use the :class:`.sqlalchemy.sql.quoted_name` construct:: from sqlalchemy.sql import quoted_name class GeoBuffer(GenericFunction): type = Geometry() package = "geo" name = quoted_name("ST_Buffer", True) identifier = "buffer" inherit_cache = True The above function will render as: .. sourcecode:: pycon+sql >>> print(func.geo.buffer()) {printsql}"ST_Buffer"() Type parameters for this class as a `generic type `_ can be passed and should match the type seen in a :class:`_engine.Result`. For example:: class as_utc(GenericFunction[datetime.datetime]): type = DateTime() inherit_cache = True The above indicates that the following expression returns a ``datetime`` object:: connection.scalar(select(func.as_utc())) .. versionadded:: 1.3.13 The :class:`.quoted_name` construct is now recognized for quoting when used with the "name" attribute of the object, so that quoting can be forced on or off for the function name. Trn _registerrLrrcs*tj|jkr||j|jtdSrz)r Annotated__mro___register_generic_functionrrrs__init_subclass__)clsrurUrVr#s z!GenericFunction.__init_subclass__rKzMapping[str, Any])clsnameclsdictrPcCsn|d||_}|d||_}|dd}d|krB|d|_t|dd|_|jrdt|||nd|_dS)Nr_rMrOrJZ__return_type__rT)rr_rMrrdrrW)r$r%r&r_rMrOrUrUrVr"s  z*GenericFunction._register_generic_functionr]rrprcsx|dd}|dkr&fdd|D}jp2t|_d_tt|tjdd_t |ddpnt dd_ dS) N _parsed_argscs"g|]}tjtj|jdqSr`rrbrrcr_rerhrUrVrjsz,GenericFunction.__init__..rUTrkr}r) rrmrnr\r(r#rrorYrrrdr)rirprZ parsed_argsrUrhrVrqs"   zGenericFunction.__init__) rrrrZcoerce_arguments inherit_cacherr_r# classmethodr"rqrrUrUrurVrDs krrrc@s\eZdZdZeZdZdej fgZ dddddZ dddd d d Z e dd d dZdS)raRepresent the 'next value', given a :class:`.Sequence` as its single argument. Compiles into the appropriate function on each backend, or will raise NotImplementedError if used on a backend that does not provide support for sequences. sequencezschema.Sequencer)seqrcKs8t|tjstd||_t|jp.t|dd|_ dS)Nz0next_value() accepts a Sequence object as input.r) rrr AssertionErrorr-rrZ data_typerdr)rir.rrUrUrVrqsznext_value.__init__rn)otherrrPcKst|to|jj|jjkSrz)rrr-r_)rir0rrUrUrVcompare s znext_value.comparerrcCsgSrzrUrhrUrUrVrsznext_value._from_objectsN)rrrrrIntegerrr_r4Zdp_named_ddl_elementrrqr1rrrUrUrUrVrs  rc@s$eZdZdZdZdddddZdS) AnsiFunctionzEDefine a function in "ansi" format, which doesn't render parenthesis.Trrr'cOstj|f||dSrz)rrq)rirprrUrUrVrqszAnsiFunction.__init__N)rrrrr+rqrUrUrUrVr3sr3csneZdZdZdZeddddddZed dddd dZed dddd dZddd fdd ZZS)ReturnTypeFromArgszADefine a function whose return type is the same as its arguments.Trr]r)rrprcOsdSrzrUrrUrUrVrq)szReturnTypeFromArgs.__init__rcOsdSrzrUrrUrUrVrq1srcOsdSrzrUrrUrUrVrq9sr'cs<fdd|D}|dt|||d<tj||dS)Ncs"g|]}tjtj|jdqSr)r*rerhrUrVrjDsz/ReturnTypeFromArgs.__init__..r}r() setdefaultrrsrq)rirprfn_argsrurhrVrqAs   )rrrrr+r rqrrUrUrurVr4sr4c@seZdZdZdZdS)rTN)rrrrmr+rUrUrUrVrRsrc@seZdZdZdZdS)r z!The SQL MAX() aggregate function.TNrrrrr+rUrUrUrVr Wsr c@seZdZdZdZdS)r z!The SQL MIN() aggregate function.TNr7rUrUrUrVr ]sr c@seZdZdZdZdS)rz!The SQL SUM() aggregate function.TNr7rUrUrUrVrcsrc@seZdZdZeZdZdS)rzThe SQL now() datetime function. SQLAlchemy dialects will usually render this particular function in a backend-specific way, such as rendering it as ``CURRENT_TIMESTAMP``. TNrrrrrDateTimerr+rUrUrUrVrisrc@seZdZdZeZdZdS)ra*The SQL CONCAT() function, which concatenates strings. E.g.: .. sourcecode:: pycon+sql >>> print(select(func.concat('a', 'b'))) {printsql}SELECT concat(:concat_2, :concat_3) AS concat_1 String concatenation in SQLAlchemy is more commonly available using the Python ``+`` operator with string datatypes, which will render a backend-specific concatenation operator, such as : .. sourcecode:: pycon+sql >>> print(select(literal("a") + "b")) {printsql}SELECT :param_1 || :param_2 AS anon_1 TNrrrrrStringrr+rUrUrUrVrusrcs4eZdZdZeZdZdddfdd ZZ S)rzThe CHAR_LENGTH() SQL function.Tz_ColumnExpressionArgument[str]r)argrc stj|f|dSrzrsrq)rir<rrurUrVrqszchar_length.__init__ rrrrrr2rr+rqrrUrUrurVrsrc@seZdZdZdZdZdS)rzThe RANDOM() SQL function.TNrrrrrmr+rUrUrUrVrsrcs6eZdZdZeZdZd dddfdd ZZ S) raThe ANSI COUNT aggregate function. With no arguments, emits COUNT \*. E.g.:: from sqlalchemy import func from sqlalchemy import select from sqlalchemy import table, column my_table = table('some_table', column('id')) stmt = select(func.count()).select_from(my_table) Executing ``stmt`` would emit:: SELECT count(*) AS count_1 FROM some_table TNz7Union[_ColumnExpressionArgument[Any], _StarOrOne, None]r) expressionrc s$|dkrtd}tj|f|dS)N*)r)rsrq)rir@rrurUrVrqszcount.__init__)Nr>rUrUrurVrs rc@seZdZdZeZdZdS)rz The CURRENT_DATE() SQL function.TN)rrrrrDaterr+rUrUrUrVrsrc@seZdZdZeZdZdS)rz The CURRENT_TIME() SQL function.TN)rrrrrZTimerr+rUrUrUrVrsrc@seZdZdZeZdZdS)rz%The CURRENT_TIMESTAMP() SQL function.TNr8rUrUrUrVrsrc@seZdZdZeZdZdS)rz The CURRENT_USER() SQL function.TNr:rUrUrUrVrsrc@seZdZdZeZdZdS)r zThe localtime() SQL function.TNr8rUrUrUrVr sr c@seZdZdZeZdZdS)r z"The localtimestamp() SQL function.TNr8rUrUrUrVr sr c@seZdZdZeZdZdS)rz The SESSION_USER() SQL function.TNr:rUrUrUrVrsrc@seZdZdZeZdZdS)rzThe SYSDATE() SQL function.TNr8rUrUrUrVrsrc@seZdZdZeZdZdS)rzThe USER() SQL function.TNr:rUrUrUrVrsrcs,eZdZdZdZdddfdd ZZS)raSupport for the ARRAY_AGG function. The ``func.array_agg(expr)`` construct returns an expression of type :class:`_types.ARRAY`. e.g.:: stmt = select(func.array_agg(table.c.values)[2:5]) .. seealso:: :func:`_postgresql.array_agg` - PostgreSQL-specific version that returns :class:`_postgresql.ARRAY`, which has PG-specific operators added. Trrr'cspfdd|D}|dtj}d|krVt|}t|tjrF||d<n||dd|d<||d<tj||dS)Ncsg|]}tjtj|dqS))ra)rrbrrcrerhrUrVrjs z&array_agg.__init__..Z_default_array_typer}r) dimensionsr()rrrrrrsrq)rirprr6Zdefault_array_typeZtype_from_argsrurhrVrqs    zarray_agg.__init__)rrrrr+rqrrUrUrurVrsrc@s(eZdZdZdZdZdddddZd S) OrderedSetAggzDefine a function where the return type is based on the sort expression type as defined by the expression passed to the :meth:`.FunctionElement.within_group` method.FTzWithinGroup[Any]zTypeEngine[Any]rcCsLtt|jj}t|j}|jr>t|j dkr>t |dj S|dj SdS)Nrr) rr#rYrsqlutilZunwrap_order_byrarray_for_multi_clauserr^rrr)rirZ func_clausesrrUrUrVr7szOrderedSetAgg.within_group_typeN)rrrrrFr+rrUrUrUrVrD/srDc@seZdZdZdZdS)r aImplement the ``mode`` ordered-set aggregate function. This function must be used with the :meth:`.FunctionElement.within_group` modifier to supply a sort expression to operate upon. The return type of this function is the same as the sort expression. TNr7rUrUrUrVr Ds r c@seZdZdZdZdZdS)ra|Implement the ``percentile_cont`` ordered-set aggregate function. This function must be used with the :meth:`.FunctionElement.within_group` modifier to supply a sort expression to operate upon. The return type of this function is the same as the sort expression, or if the arguments are an array, an :class:`_types.ARRAY` of the sort expression's type. TNrrrrrFr+rUrUrUrVrQs rc@seZdZdZdZdZdS)ra|Implement the ``percentile_disc`` ordered-set aggregate function. This function must be used with the :meth:`.FunctionElement.within_group` modifier to supply a sort expression to operate upon. The return type of this function is the same as the sort expression, or if the arguments are an array, an :class:`_types.ARRAY` of the sort expression's type. TNrGrUrUrUrVras rc@seZdZdZeZdZdS)raImplement the ``rank`` hypothetical-set aggregate function. This function must be used with the :meth:`.FunctionElement.within_group` modifier to supply a sort expression to operate upon. The return type of this function is :class:`.Integer`. TNrrrrrr2rr+rUrUrUrVrqs rc@seZdZdZeZdZdS)ra Implement the ``dense_rank`` hypothetical-set aggregate function. This function must be used with the :meth:`.FunctionElement.within_group` modifier to supply a sort expression to operate upon. The return type of this function is :class:`.Integer`. TNrHrUrUrUrVrs rc@s&eZdZUdZeZded<dZdS)raImplement the ``percent_rank`` hypothetical-set aggregate function. This function must be used with the :meth:`.FunctionElement.within_group` modifier to supply a sort expression to operate upon. The return type of this function is :class:`.Numeric`. !sqltypes.Numeric[decimal.Decimal]rTN rrrrrZNumericrrr+rUrUrUrVrs  rc@s&eZdZUdZeZded<dZdS)ra Implement the ``cume_dist`` hypothetical-set aggregate function. This function must be used with the :meth:`.FunctionElement.within_group` modifier to supply a sort expression to operate upon. The return type of this function is :class:`.Numeric`. rIrTNrJrUrUrUrVrs  rc@seZdZdZdZdZdS)raSImplement the ``CUBE`` grouping operation. This function is used as part of the GROUP BY of a statement, e.g. :meth:`_expression.Select.group_by`:: stmt = select( func.sum(table.c.value), table.c.col_1, table.c.col_2 ).group_by(func.cube(table.c.col_1, table.c.col_2)) .. versionadded:: 1.2 TNr?rUrUrUrVrs rc@seZdZdZdZdZdS)raWImplement the ``ROLLUP`` grouping operation. This function is used as part of the GROUP BY of a statement, e.g. :meth:`_expression.Select.group_by`:: stmt = select( func.sum(table.c.value), table.c.col_1, table.c.col_2 ).group_by(func.rollup(table.c.col_1, table.c.col_2)) .. versionadded:: 1.2 TNr?rUrUrUrVrs rc@seZdZdZdZdZdS)raImplement the ``GROUPING SETS`` grouping operation. This function is used as part of the GROUP BY of a statement, e.g. :meth:`_expression.Select.group_by`:: stmt = select( func.sum(table.c.value), table.c.col_1, table.c.col_2 ).group_by(func.grouping_sets(table.c.col_1, table.c.col_2)) In order to group by multiple sets, use the :func:`.tuple_` construct:: from sqlalchemy import tuple_ stmt = select( func.sum(table.c.value), table.c.col_1, table.c.col_2, table.c.col_3 ).group_by( func.grouping_sets( tuple_(table.c.col_1, table.c.col_2), tuple_(table.c.value, table.c.col_3), ) ) .. versionadded:: 1.2 TNr?rUrUrUrVrsrcs8eZdZdZeZdZdZdddfdd Z Z S)raImplement a generic string aggregation function. This function will concatenate non-null values into a string and separate the values by a delimiter. This function is compiled on a per-backend basis, into functions such as ``group_concat()``, ``string_agg()``, or ``LISTAGG()``. e.g. Example usage with delimiter '.':: stmt = select(func.aggregate_strings(table.c.str_col, ".")) The return type of this function is :class:`.String`. .. versionadded: 2.0.21 TrrK)clause separatorcst||dSrzr=)rirKrLrurUrVrqszaggregate_strings.__init__) rrrrrr;rrmr+rqrrUrUrurVrs r)rJ)r __future__rdatetimedecimaltypingrrrrrrr r r r r rrrrrrrrrrrEZ_typingrbaserrrrrelementsrr r!r"r#r$r%r'r(r)r*r,r.Z selectabler/r0r1r2r3Zvisitorsr4r6r7r8r9r:r;r<r=r>r?r@Z engine.baserAZ engine.cursorrBZengine.interfacesrCrDZ util.typingrErFrH defaultdictdictrIrrWrXrr~rrmodifierrrrrr3r4rr r rrrKrrfloatrrdatertimerrrr r rrrrrDr rrrrDecimalrrrrrrrUrUrUrV s                                                                    4 z*  % 3  %) "