U a0@sJdZddlmZddlmZddlmZddlmZddlmZddlmZddlmZ dd l m Z dd l m Z dd l m Z dd l mZdd l mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddl"m#Z#ddl"m$Z$d dlmZe%e&Z'dyd"d#Z(Gd$d%d%e eeeZ)Gd&d'd'eZ*Gd(d)d)eZ+Gd*d+d+e,Z-e-Z.e-je._e-d,d-Z/Gd.d/d/e)Z0Gd0d1d1e$Z1Gd2d3d3e2e1e0Z3e(d4ee(d5eGd6d7d7e3Z4Gd8d9d9e3Z5Gd:d;d;e3Z6Gdd?d?e6Z8Gd@dAdAe6Z9GdBdCdCe6Z:GdDdEdEe3Z;GdFdGdGe3ZGdLdMdMe3Z?GdNdOdOe5Z@GdPdQdQe5ZAGdRdSdSe5ZBGdTdUdUe5ZCGdVdWdWe5ZDGdXdYdYe5ZEGdZd[d[e5ZFGd\d]d]e5ZGGd^d_d_e5ZHGd`dadae3ZIGdbdcdce3ZJGdddedeeJZKGdfdgdgeJZLGdhdidieJZMGdjdkdke3ZNGdldmdme3ZOGdndodoe3ZPGdpdqdqe3ZQGdrdsdse3ZRGdtdudue3ZSGdvdwdwe3ZTdxS)zz6SQL function API, factories, and built-in functions. ) annotation) coercions) operators)roles)schema)sqltypes)util)_entity_namespace)ColumnCollection) Executable) Generative) HasMemoized)_type_from_args)BinaryExpression) BindParameter)Cast) ClauseList) ColumnElement)ExtractFunctionFilter)Grouping)literal_column) NamedColumnOver WithinGroup) FromClause)Select)TableValuedAlias)InternalTraversal)TraversibleType_defaultcCs:t|}t|}||kr.td||||<dS)zAssociate a callable with a particular func. name. This is normally called by _GenericMeta, 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) _registryr text_typelowerwarnformat) identifierfnpackageregr.YC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\sql\functions.pyregister_function/s r0cs2eZdZdZdejfdejfdejfgZdZ dZ dZ dZ dd Z dZefd d Zd d Zd7ddZddZd8ddZeddZejddZd9ddZddZddZddZed d!Zd"d#Zd:d$d%Zd&d'Z e!j"d(d)d*d+d,Z#e!j"d-d.d*d/d0Z$d;d1d2Z%d<fd3d4 Z&ed5d6Z'Z(S)=FunctionElementazBase for SQL function-oriented constructs. .. seealso:: :ref:`coretutorial_functions` - in the Core 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_typer.FNcs>fdd|D}jpt|_t|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)nameNr5apply_propagate_attrs)rexpectrExpressionElementRolegetattr.0cselfr.r/ rs z,FunctionElement.__init__..ToperatorZgroup_contentsN) _has_argsboolrrcomma_op self_groupr2)r?clauseskwargsargsr.r>r/__init__bs  zFunctionElement.__init__cstt|jpt|ddS)Nr5)superr1 _proxy_keyr:r> __class__r.r/rLs zFunctionElement._proxy_keycCs|||||SN)Z_execute_function)r? connectionZ multiparamsparamsexecution_optionsr.r.r/_execute_on_connections z&FunctionElement._execute_on_connectioncCs t|||S)a~Return 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.:: >>> from sqlalchemy import func, select >>> fn = func.jsonb_each("{'k', 'v'}").scalar_table_valued("key") >>> print(select(fn)) 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)r?r5type_r.r.r/scalar_table_valuedsz#FunctionElement.scalar_table_valuedcOsR|}|dd}|dd}|r4||f7}d|_tj||_|_|j|dS)a Return a :class:`_sql.TableValuedAlias` representation of this :class:`_functions.FunctionElement` with table-valued expressions added. e.g.:: >>> fn = ( ... func.generate_series(1, 5). ... table_valued("value", "start", "stop", "step") ... ) >>> print(select(fn)) 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 >>> print(select(fn.c.value, fn.c.stop).where(fn.c.value > 2)) 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 A WITH ORDINALITY expression may be generated by passing the keyword argument "with_ordinality":: >>> fn = func.generate_series(4, 1, -1).table_valued("gen", with_ordinality="ordinality") >>> print(select(fn)) 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`. .. 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_ordinalityNr5Tr5)Z _generatepopr3rZTableValueTypetyper4alias)r?exprkwnew_funcrWr5r.r.r/ table_valueds<    zFunctionElement.table_valuedcCs|j|djS)aReturn this :class:`_functions.FunctionElement` as a column expression that selects from itself as a FROM clause. E.g.:: >>> from sqlalchemy import select, func >>> gs = func.generate_series(1, 5, -1).column_valued() >>> print(select(gs)) 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 .. 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` rX)r[columnr?r5r.r.r/ column_valuedszFunctionElement.column_valuedcCs2|jjr|jj}n |dg}tdd|DdS)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:: >>> from sqlalchemy import column, select, func >>> stmt = select(column('x'), column('y')).select_from(func.myfunction()) >>> print(stmt) 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. NcSsg|]}|j|fqSr.)key)r<colr.r.r/r@1sz+FunctionElement.columns..)columns)rZZ_is_table_valueZ _elementslabelr )r?colsr.r.r/res  zFunctionElement.columnscCs|jjS)z}Return the underlying :class:`.ClauseList` which contains the arguments for this :class:`.FunctionElement`. )r2elementr>r.r.r/rG3szFunctionElement.clausescCst|||||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` ) partition_byorder_byrowsrange_r)r?rirjrkrlr.r.r/over;szFunctionElement.overcGst|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. .. versionadded:: 1.1 .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial` r)r?rjr.r.r/ within_group[szFunctionElement.within_groupcGs|s|St|f|S)aGProduce 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) .. versionadded:: 1.0.0 .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial` :class:`.FunctionFilter` :func:`.funcfilter` r)r?Z criterionr.r.r/filterpszFunctionElement.filtercCs t|||S)aV 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 )FunctionAsBinary)r? left_index right_indexr.r.r/ as_comparisonsGzFunctionElement.as_comparisoncCs|jjSrO)rG _from_objectsr>r.r.r/rtszFunctionElement._from_objectscCsdS)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. Nr.)r?rnr.r.r/within_group_types z!FunctionElement.within_group_typecCstj|||jdS)aProduce 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:`_function.FunctionElement.table_valued` method first to establish named columns. e.g.:: >>> from sqlalchemy import func, select, column >>> data_view = func.unnest([1, 2, 3]).alias("data_view") >>> print(select(data_view.column)) SELECT data_view FROM unnest(:unnest_1) AS data_view The :meth:`_functions.FunctionElement.column_valued` method provides a shortcut for the above pattern:: >>> data_view = func.unnest([1, 2, 3]).column_valued("data_view") >>> print(select(data_view)) SELECT data_view FROM unnest(:unnest_1) AS data_view .. versionadded:: 1.4.0b2 Added the ``.column`` accessor .. 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` )Ztable_value_type)r Z _constructrZrar.r.r/r[s 8zFunctionElement.aliascCs"t|}|jr|jf|j}|S)zProduce a :func:`_expression.select` construct against this :class:`.FunctionElement`. This is shorthand for:: s = select(function_element) )rZ_create_selectZ_execution_optionsrR)r?sr.r.r/select%s zFunctionElement.selectz:meth:`.FunctionElement.scalar`zScalar execution in SQLAlchemy 2.0 is performed by the :meth:`_engine.Connection.scalar` method of :class:`_engine.Connection`, or in the ORM by the :meth:`.Session.scalar` method of :class:`.Session`.) alternativecCs|S)aExecute this :class:`.FunctionElement` against an embedded 'bind' and return a scalar value. This first calls :meth:`~.FunctionElement.select` to produce a SELECT construct. Note that :class:`.FunctionElement` can be passed to the :meth:`.Connectable.scalar` method of :class:`_engine.Connection` or :class:`_engine.Engine`. )rwexecutescalarr>r.r.r/rz3szFunctionElement.scalarz :meth:`.FunctionElement.execute`zAll statement execution in SQLAlchemy 2.0 is performed by the :meth:`_engine.Connection.execute` method of :class:`_engine.Connection`, or in the ORM by the :meth:`.Session.execute` method of :class:`.Session`.cCs |S)agExecute this :class:`.FunctionElement` against an embedded 'bind'. This first calls :meth:`~.FunctionElement.select` to produce a SELECT construct. Note that :class:`.FunctionElement` can be passed to the :meth:`.Connectable.execute` method of :class:`_engine.Connection` or :class:`_engine.Engine`. )rwryr>r.r.r/ryIszFunctionElement.executecKstd|f||jd|d|S)NT)_compared_to_operator_compared_to_typeuniquerU)rrZr?rBobjrUr]r.r.r/ _bind_param_szFunctionElement._bind_paramcs6|tjkr t|jtjr t|Stt|j |dSdS)N)against) rgetitem isinstancerZrARRAYrrKr1rF)r?rrMr.r/rFjs  zFunctionElement.self_groupcCs t|jS)zzoverrides FromClause.entity_namespace as functions are generally column expressions and not FromClauses. )r r2r>r.r.r/entity_namespacevsz FunctionElement.entity_namespace)N)N)NNNN)N)N)N))__name__ __module__ __qualname____doc__r!dp_clauseelementZ dp_booleanZdp_has_cache_key_traverse_internals packagenamesrCr3r4rJZ_non_anon_labelpropertyrLrSrVr_rbrer Zmemoized_attributerGrmrnrorsrtrur[rwrZ deprecated_20rzryrrFr __classcell__r.r.rMr/r1EsX K     I  <    r1c@steZdZdejfdejfdejfdejfgZddZddZ e d d Z e j d d Z e d d Z e j dd Z dS)rp sql_functionrqrr modifierscCst|||SrO)r_gen_cache_key)r?Zanon_mapZ bindparamsr.r.r/rszFunctionAsBinary._gen_cache_keycCs8||_||_||_tj|_tj|_d|_ d|_ i|_ dS)NT) rrqrrrZfunction_as_comparison_oprBrZ BOOLEANTYPErZnegateZ_is_implicitly_booleanr)r?r+rqrrr.r.r/rJszFunctionAsBinary.__init__cCs|jjj|jdSNrrrGrqr>r.r.r/leftszFunctionAsBinary.leftcCs||jjj|jd<dSrrr?valuer.r.r/rscCs|jjj|jdSrrrGrrr>r.r.r/rightszFunctionAsBinary.rightcCs||jjj|jd<dSrrrr.r.r/rsN)rrrr!r dp_plain_objZ dp_plain_dictrrrJrrsetterrr.r.r.r/rps    rpc@s>eZdZdZdejfdejfdejfgZdZ dZ d ddZ dS) rTZscalar_function_columnr5rZr+FNcCs||_||_t||_dSrO)r+r5r to_instancerZ)r?r+r5rUr.r.r/rJszScalarFunctionColumn.__init__)N) rrr__visit_name__r!Z dp_anon_namedp_typerrZ is_literaltablerJr.r.r.r/rTsrTc@s(eZdZdZddZddZddZdS) _FunctionGeneratora Generate SQL function expressions. :data:`.func` is a special object instance which generates SQL functions based on name-based attributes, e.g.:: >>> print(func.count(1)) 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:: >>> print(select(func.count(table.c.id))) 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:: >>> print(func.current_timestamp()) CURRENT_TIMESTAMP To call functions which are present in dot-separated packages, specify them in the same manner:: >>> print(func.stats.yield_curve(5, 10)) 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: >>> print(func.my_string(u'hi', type_=Unicode) + ' ' + ... func.my_string(u'there', type_=Unicode)) 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:`coretutorial_functions` - in the Core Tutorial :class:`.Function` cKsg|_||_dSrO)_FunctionGenerator__namesopts)r?rr.r.r/rJsz_FunctionGenerator.__init__cCsn|dr6z |j|WStk r2t|YqLXn|drL|dd}tf|j}t|j|g|_|S)N___) startswith__dict__KeyErrorAttributeErrorendswithrrlistr)r?r5fr.r.r/ __getattr__ s     z_FunctionGenerator.__getattr__cOs|j}||t|j}|dkr2|j\}}n|dkrLd|jd}}nd}|dk r|t||}|dk r||||St|jdf|dt |jddi|S)Nr#rr$rrr) rcopyupdatelenrr%getr'Functiontuple)r?r=rHotokensr,fnamefuncr.r.r/__call__s*     z_FunctionGenerator.__call__N)rrrrrJrrr.r.r.r/rsLrF)groupc@sbeZdZdZdZejdejfdej fdej fgZe j Z ejdddd Zd d Zdd dZd S)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. functionrr5rZ)z2.0z\The :paramref:`_sql.text.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.)bindcOsN|ddpd|_||_|||_t|dd|_t j |f||dS)zConstruct a :class:`.Function`. The :data:`.func` construct is normally used to construct new :class:`.Function` instances. rNr.rU) rYrr5 _get_bind_bindrrrrZr1rJ)r?r5rGr]r.r.r/rJps  zFunction.__init__cCsd|krtd|dSdS)NrzOThe Function.bind argument is deprecated and will be removed in SQLAlchemy 2.0.)rZwarn_deprecated_20)r?r]r.r.r/rs zFunction._get_bindNcKs t|j|f||j|dd|S)NT)r{r|rUr})rr5rZr~r.r.r/rszFunction._bind_param)N)rrrrrr1rr!rZ dp_stringrrZNULLTYPErZrZdeprecated_paramsrJrrr.r.r.r/r6s  rcseZdZfddZZS) _GenericMetacstj|jkrv|d||_}|d||_}|dd}d|krN|d|_t|dd|_ |j rpt |||nd|_ t t | |||dS)Nr5r*r,r$Z__return_type__ _registerT)rZ Annotated__mro__rr5r*rYrZr:rr0rKrrJ)clsZclsnamebasesZclsdictr5r*r,rMr.r/rJs   z_GenericMeta.__init__)rrrrJrr.r.rMr/rsrc@s$eZdZdZdZdZdZddZdS)GenericFunctiona Define 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 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" 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" The above function will render as follows:: >>> print(func.geo.buffer()) 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" The above function will render as:: >>> print(func.geo.buffer()) "ST_Buffer"() .. 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. TFcs|dd}|dkr&fdd|D}jp2t|_d_|_t|tjdd _ t |ddpzt dd_dS) N _parsed_argscs"g|]}tjtj|jdqSr6rr8rr9r5r;r>r.r/r@sz,GenericFunction.__init__..r.TrArUrZ)rYrCrDrrrrrrErFr2rrr:rZ)r?rIrHZ parsed_argsr.r>r/rJ s     zGenericFunction.__init__N)rrrrZcoerce_argumentsr inherit_cacherJr.r.r.r/rs Vrcastextractc@sDeZdZdZeZdZdej fgZ ddZ ddZ e ddZd S) next_valueaRepresent 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. sequencecKsDt|tjstd|||_||_t|j p:t |dd|_ dS)Nz0next_value() accepts a Sequence object as input.rZ) rrSequenceAssertionErrorrrrrrZ data_typer:rZ)r?seqr]r.r.r/rJ8s znext_value.__init__cKst|to|jj|jjkSrO)rrrr5)r?otherr]r.r.r/compareBs znext_value.comparecCsgSrOr.r>r.r.r/rtHsznext_value._from_objectsN)rrrrrIntegerrZr5r!Zdp_named_ddl_elementrrJrrrtr.r.r.r/r's  rc@seZdZdZdZddZdS) AnsiFunctionzEDefine a function in "ansi" format, which doesn't render parenthesis.TcOstj|f||dSrOrrJr?rIrHr.r.r/rJRszAnsiFunction.__init__N)rrrrrrJr.r.r.r/rMsrcs$eZdZdZdZfddZZS)ReturnTypeFromArgszADefine a function whose return type is the same as its arguments.Tcs@fdd|D}|dt|||d<ttj||dS)Ncs"g|]}tjtj|jdqSrrr;r>r.r/r@\sz/ReturnTypeFromArgs.__init__..rUr) setdefaultrrKrrJrrMr>r/rJ[s   zReturnTypeFromArgs.__init__)rrrrrrJrr.r.rMr/rVsrc@seZdZdZdZdS)coalesceTN)rrrrCrr.r.r.r/rjsrc@seZdZdZdZdS)maxz!The SQL MAX() aggregate function.TNrrrrrr.r.r.r/rosrc@seZdZdZdZdS)minz!The SQL MIN() aggregate function.TNrr.r.r.r/rusrc@seZdZdZdZdS)sumz!The SQL SUM() aggregate function.TNrr.r.r.r/r{src@seZdZdZejZdZdS)nowzThe SQL now() datetime function. SQLAlchemy dialects will usually render this particular function in a backend-specific way, such as rendering it as ``CURRENT_TIMESTAMP``. TNrrrrrDateTimerZrr.r.r.r/rsrc@seZdZdZejZdZdS)concataThe SQL CONCAT() function, which concatenates strings. E.g.:: >>> print(select(func.concat('a', 'b'))) 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 :: >>> print(select(literal("a") + "b")) SELECT :param_1 || :param_2 AS anon_1 TNrrrrrStringrZrr.r.r.r/rsrc@s"eZdZdZejZdZddZdS) char_lengthzThe CHAR_LENGTH() SQL function.TcKstj||f|dSrOr)r?argrHr.r.r/rJszchar_length.__init__N) rrrrrrrZrrJr.r.r.r/rsrc@seZdZdZdZdZdS)randomzThe RANDOM() SQL function.TNrrrrrCrr.r.r.r/rsrcs,eZdZdZejZdZdfdd ZZ S)countaThe 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 TNc s(|dkrtd}tt|j|f|dS)N*)rrKrrJ)r?Z expressionrHrMr.r/rJszcount.__init__)N) rrrrrrrZrrJrr.r.rMr/rsrc@seZdZdZejZdZdS) current_datez The CURRENT_DATE() SQL function.TN)rrrrrDaterZrr.r.r.r/rsrc@seZdZdZejZdZdS) current_timez The CURRENT_TIME() SQL function.TN)rrrrrZTimerZrr.r.r.r/rsrc@seZdZdZejZdZdS)current_timestampz%The CURRENT_TIMESTAMP() SQL function.TNrr.r.r.r/rsrc@seZdZdZejZdZdS) current_userz The CURRENT_USER() SQL function.TNrr.r.r.r/rsrc@seZdZdZejZdZdS) localtimezThe localtime() SQL function.TNrr.r.r.r/rsrc@seZdZdZejZdZdS)localtimestampz"The localtimestamp() SQL function.TNrr.r.r.r/rsrc@seZdZdZejZdZdS) session_userz The SESSION_USER() SQL function.TNrr.r.r.r/rsrc@seZdZdZejZdZdS)sysdatezThe SYSDATE() SQL function.TNrr.r.r.r/rsrc@seZdZdZejZdZdS)userzThe USER() SQL function.TNrr.r.r.r/r srcs*eZdZdZejZdZfddZZ S) array_aggaSupport 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]) .. versionadded:: 1.1 .. seealso:: :func:`_postgresql.array_agg` - PostgreSQL-specific version that returns :class:`_postgresql.ARRAY`, which has PG-specific operators added. Tcspfdd|D}|dtj}d|krRt|}t|tjrF||d<n |||d<||d<ttj||dS)Ncsg|]}tjtj|dqS))r7)rr8rr9r;r>r.r/r@)s z&array_agg.__init__..Z_default_array_typerUr)rYrrrrrKrrJ)r?rIrHZdefault_array_typeZtype_from_argsrMr>r/rJ(s    zarray_agg.__init__) rrrrrrrZrrJrr.r.rMr/rsrc@s eZdZdZdZdZddZdS) 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.FTcCsF|jj}t|j}|jr8t|jdkr8t |dj S|dj SdS)Nrr) r2rhsqlutilZunwrap_order_byrjarray_for_multi_clauserrGrrrZ)r?rnZ func_clausesrjr.r.r/ruDs  zOrderedSetAgg.within_group_typeN)rrrrrrrur.r.r.r/r<src@seZdZdZdZdS)modea*Implement 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. .. versionadded:: 1.1 TNrr.r.r.r/rMs rc@seZdZdZdZdZdS)percentile_contaImplement 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. .. versionadded:: 1.1 TNrrrrrrr.r.r.r/r\s rc@seZdZdZdZdZdS)percentile_discaImplement 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. .. versionadded:: 1.1 TNrr.r.r.r/rns rc@seZdZdZeZdZdS)ranka!Implement 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`. .. versionadded:: 1.1 TNrrrrrrrZrr.r.r.r/rs rc@seZdZdZeZdZdS) dense_ranka'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`. .. versionadded:: 1.1 TNrr.r.r.r/rs rc@seZdZdZeZdZdS) percent_ranka)Implement 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`. .. versionadded:: 1.1 TNrrrrrZNumericrZrr.r.r.r/rs rc@seZdZdZeZdZdS) cume_dista&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`. .. versionadded:: 1.1 TNrr.r.r.r/rs rc@seZdZdZdZdZdS)cubeaSImplement 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 TNrr.r.r.r/rs rc@seZdZdZdZdZdS)rollupaWImplement 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 TNrr.r.r.r/rs rc@seZdZdZdZdZdS) grouping_setsaImplement 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 TNrr.r.r.r/rsrN)r$)Urrrrrrrrrbaser r r r r elementsrrrrrrrrrrrrrZ selectablerrr Zvisitorsr!r" defaultdictdictr%r0r1rprTobjectrrmodifierrrwith_metaclassrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr.r.r.r/s                                 @'v dr  &   +