U kfH @sddlmZddlZddlmZddlmZddlmZddlmZddlmZddlmZdd lm Z dd lm Z dd lm Z dd lm Z d dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlm Z d dlm!Z!d dlm"Z"d d lm#Z#d d!lm$Z$d d"lm%Z%d d lm Z d d#lm&Z&d d$lm'Z'd d%lm(Z(d d&l)m*Z*d'd(l+m,Z,ej r8d d)l-m.Z.d d*l-m/Z/d d+l-m0Z0d d,l-m1Z1d d-l-m2Z2d d.lm3Z3d d/l4m5Z5d d0l6m7Z7e d1Z8d2d3d4d5d6Z9d7d8d9d:d;d<Z:e spd=d<Z:d2d3d4d>d?Z;d@dAdBdCdDZddFdSdTdUdVdWZ?edXdXdYdZd[Z@ed2d\dYd]d[Z@d2d\dYd^d[Z@ejAddKejAdddKdKdKf d_dMd`dNdadbdcdNdNdNdTdd dedfZBdddgdhdididjdkdldmZCdndodpdqdrdsZDdndodtdqdudvZEddFd`dNdwdxdydzd{ZFd@dAdBd|d}ZGd2dAd4d~dZHd2dAd4ddZIdFdddddZJddddZKdd8ddddZLddFd2d`ddddZMddddZNd2dAdBddZOd2dAdBddZPdd8d9d:ddZQe s^ddZQddddddddddZReddddFddddZSddddZTddddddddZUdndoddqddZVddddddZWdS)) annotationsN)Any)Callable)Mapping)Optional)overload)SequenceTuple) TYPE_CHECKING)TypeVar)Union) coercions)roles)_NoArg)_document_text_coercion BindParameter)BooleanClauseListCaseCast)CollationClause)CollectionAggregate ColumnClause) ColumnElementExtract)False_FunctionFilterLabel)NullOver TextClause)True_TryCast TypeCoerce)UnaryExpression WithinGroup)FunctionElement)Literal) _ByArgument)_ColumnExpressionArgument)"_ColumnExpressionOrLiteralArgument)#_ColumnExpressionOrStrLabelArgument)_TypeEngineArgument)BinaryExpression) FromClause) TypeEngine_Tz_ColumnExpressionArgument[_T]zCollectionAggregate[bool])exprreturncCs t|S)akProduce an ALL expression. For dialects such as that of PostgreSQL, this operator applies to usage of the :class:`_types.ARRAY` datatype, for that of MySQL, it may apply to a subquery. e.g.:: # renders on PostgreSQL: # '5 = ALL (somearray)' expr = 5 == all_(mytable.c.somearray) # renders on MySQL: # '5 = ALL (SELECT value FROM table)' expr = 5 == all_(select(table.c.value)) Comparison to NULL may work using ``None``:: None == all_(mytable.c.somearray) The any_() / all_() operators also feature a special "operand flipping" behavior such that if any_() / all_() are used on the left side of a comparison using a standalone operator such as ``==``, ``!=``, etc. (not including operator methods such as :meth:`_sql.ColumnOperators.is_`) the rendered expression is flipped:: # would render '5 = ALL (column)` all_(mytable.c.column) == 5 Or with ``None``, which note will not perform the usual step of rendering "IS" as is normally the case for NULL:: # would render 'NULL = ALL(somearray)' all_(mytable.c.somearray) == None .. versionchanged:: 1.4.26 repaired the use of any_() / all_() comparing to NULL on the right side to be flipped to the left. The column-level :meth:`_sql.ColumnElement.all_` method (not to be confused with :class:`_types.ARRAY` level :meth:`_types.ARRAY.Comparator.all`) is shorthand for ``all_(col)``:: 5 == mytable.c.somearray.all_() .. seealso:: :meth:`_sql.ColumnOperators.all_` :func:`_expression.any_` )rZ _create_allr?rBU/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/sql/_elements_constructors.pyall_?s3rDz5Union[Literal[True], _ColumnExpressionArgument[bool]]z_ColumnExpressionArgument[bool]zColumnElement[bool])initial_clauseclausesr@cGsdS)aProduce a conjunction of expressions joined by ``AND``. E.g.:: from sqlalchemy import and_ stmt = select(users_table).where( and_( users_table.c.name == 'wendy', users_table.c.enrolled == True ) ) The :func:`.and_` conjunction is also available using the Python ``&`` operator (though note that compound expressions need to be parenthesized in order to function with Python operator precedence behavior):: stmt = select(users_table).where( (users_table.c.name == 'wendy') & (users_table.c.enrolled == True) ) The :func:`.and_` operation is also implicit in some cases; the :meth:`_expression.Select.where` method for example can be invoked multiple times against a statement, which will have the effect of each clause being combined using :func:`.and_`:: stmt = select(users_table).\ where(users_table.c.name == 'wendy').\ where(users_table.c.enrolled == True) The :func:`.and_` construct must be given at least one positional argument in order to be valid; a :func:`.and_` construct with no arguments is ambiguous. To produce an "empty" or dynamically generated :func:`.and_` expression, from a given list of expressions, a "default" element of :func:`_sql.true` (or just ``True``) should be specified:: from sqlalchemy import true criteria = and_(true(), *expressions) The above expression will compile to SQL as the expression ``true`` or ``1 = 1``, depending on backend, if no other expressions are present. If expressions are present, then the :func:`_sql.true` value is ignored as it does not affect the outcome of an AND expression that has other elements. .. deprecated:: 1.4 The :func:`.and_` element now requires that at least one argument is passed; creating the :func:`.and_` construct with no arguments is deprecated, and will emit a deprecation warning while continuing to produce a blank SQL string. .. seealso:: :func:`.or_` NrBrErFrBrBrCand_us?rHcGs tj|S)a~ Produce a conjunction of expressions joined by ``AND``. E.g.:: from sqlalchemy import and_ stmt = select(users_table).where( and_( users_table.c.name == 'wendy', users_table.c.enrolled == True ) ) The :func:`.and_` conjunction is also available using the Python ``&`` operator (though note that compound expressions need to be parenthesized in order to function with Python operator precedence behavior):: stmt = select(users_table).where( (users_table.c.name == 'wendy') & (users_table.c.enrolled == True) ) The :func:`.and_` operation is also implicit in some cases; the :meth:`_expression.Select.where` method for example can be invoked multiple times against a statement, which will have the effect of each clause being combined using :func:`.and_`:: stmt = select(users_table).\ where(users_table.c.name == 'wendy').\ where(users_table.c.enrolled == True) The :func:`.and_` construct must be given at least one positional argument in order to be valid; a :func:`.and_` construct with no arguments is ambiguous. To produce an "empty" or dynamically generated :func:`.and_` expression, from a given list of expressions, a "default" element of :func:`_sql.true` (or just ``True``) should be specified:: from sqlalchemy import true criteria = and_(true(), *expressions) The above expression will compile to SQL as the expression ``true`` or ``1 = 1``, depending on backend, if no other expressions are present. If expressions are present, then the :func:`_sql.true` value is ignored as it does not affect the outcome of an AND expression that has other elements. .. deprecated:: 1.4 The :func:`.and_` element now requires that at least one argument is passed; creating the :func:`.and_` construct with no arguments is deprecated, and will emit a deprecation warning while continuing to produce a blank SQL string. .. seealso:: :func:`.or_` )rrHrFrBrBrCrHs 100, literal_column("'greaterthan100'") ), ( orderline.c.qty > 10, literal_column("'greaterthan10'") ), else_=literal_column("'lessthan10'") ) The above will render the given constants without using bound parameters for the result values (but still for the comparison values), as in:: CASE WHEN (orderline.qty > :qty_1) THEN 'greaterthan100' WHEN (orderline.qty > :qty_2) THEN 'greaterthan10' ELSE 'lessthan10' END :param \*whens: The criteria to be compared against, :paramref:`.case.whens` accepts two different forms, based on whether or not :paramref:`.case.value` is used. .. versionchanged:: 1.4 the :func:`_sql.case` function now accepts the series of WHEN conditions positionally In the first form, it accepts multiple 2-tuples passed as positional arguments; each 2-tuple consists of ``(, )``, where the SQL expression is a boolean expression and "value" is a resulting value, e.g.:: case( (users_table.c.name == 'wendy', 'W'), (users_table.c.name == 'jack', 'J') ) In the second form, it accepts a Python dictionary of comparison values mapped to a resulting value; this form requires :paramref:`.case.value` to be present, and values will be compared using the ``==`` operator, e.g.:: case( {"wendy": "W", "jack": "J"}, value=users_table.c.name ) :param value: An optional SQL expression which will be used as a fixed "comparison point" for candidate values within a dictionary passed to :paramref:`.case.whens`. :param else\_: An optional SQL expression which will be the evaluated result of the ``CASE`` construct if all expressions within :paramref:`.case.whens` evaluate to false. When omitted, most databases will produce a result of NULL if none of the "when" expressions evaluate to true. rjr)rcrkrlrBrBrCcasesrmz'_ColumnExpressionOrLiteralArgument[Any]z_TypeEngineArgument[_T]zCast[_T])rOrZr@cCs t||S)a Produce a ``CAST`` expression. :func:`.cast` returns an instance of :class:`.Cast`. E.g.:: from sqlalchemy import cast, Numeric stmt = select(cast(product_table.c.unit_price, Numeric(10, 4))) The above statement will produce SQL resembling:: SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product The :func:`.cast` function performs two distinct functions when used. The first is that it renders the ``CAST`` expression within the resulting SQL string. The second is that it associates the given type (e.g. :class:`.TypeEngine` class or instance) with the column expression on the Python side, which means the expression will take on the expression operator behavior associated with that type, as well as the bound-value handling and result-row-handling behavior of the type. An alternative to :func:`.cast` is the :func:`.type_coerce` function. This function performs the second task of associating an expression with a specific type, but does not render the ``CAST`` expression in SQL. :param expression: A SQL expression, such as a :class:`_expression.ColumnElement` expression or a Python string which will be coerced into a bound literal value. :param type\_: A :class:`.TypeEngine` class or instance indicating the type to which the ``CAST`` should apply. .. seealso:: :ref:`tutorial_casts` :func:`.try_cast` - an alternative to CAST that results in NULLs when the cast fails, instead of raising an error. Only supported by some dialects. :func:`.type_coerce` - an alternative to CAST that coerces the type on the Python side only, which is often sufficient to generate the correct SQL and data coercion. rrOrZrBrBrCcastUs6roz TryCast[_T]cCs t||S)aProduce a ``TRY_CAST`` expression for backends which support it; this is a ``CAST`` which returns NULL for un-castable conversions. In SQLAlchemy, this construct is supported **only** by the SQL Server dialect, and will raise a :class:`.CompileError` if used on other included backends. However, third party backends may also support this construct. .. tip:: As :func:`_sql.try_cast` originates from the SQL Server dialect, it's importable both from ``sqlalchemy.`` as well as from ``sqlalchemy.dialects.mssql``. :func:`_sql.try_cast` returns an instance of :class:`.TryCast` and generally behaves similarly to the :class:`.Cast` construct; at the SQL level, the difference between ``CAST`` and ``TRY_CAST`` is that ``TRY_CAST`` returns NULL for an un-castable expression, such as attempting to cast a string ``"hi"`` to an integer value. E.g.:: from sqlalchemy import select, try_cast, Numeric stmt = select( try_cast(product_table.c.unit_price, Numeric(10, 4)) ) The above would render on Microsoft SQL Server as:: SELECT TRY_CAST (product_table.unit_price AS NUMERIC(10, 4)) FROM product_table .. versionadded:: 2.0.14 :func:`.try_cast` has been generalized from the SQL Server dialect into a general use construct that may be supported by additional dialects. r,rnrBrBrCtry_casts(rpzOptional[FromClause]zColumnClause[_T])textrZ is_literal _selectabler@cCst||||S)a Produce a :class:`.ColumnClause` object. The :class:`.ColumnClause` is a lightweight analogue to the :class:`_schema.Column` class. The :func:`_expression.column` function can be invoked with just a name alone, as in:: from sqlalchemy import column id, name = column("id"), column("name") stmt = select(id, name).select_from("user") The above statement would produce SQL like:: SELECT id, name FROM user Once constructed, :func:`_expression.column` may be used like any other SQL expression element such as within :func:`_expression.select` constructs:: from sqlalchemy.sql import column id, name = column("id"), column("name") stmt = select(id, name).select_from("user") The text handled by :func:`_expression.column` is assumed to be handled like the name of a database column; if the string contains mixed case, special characters, or matches a known reserved word on the target backend, the column expression will render using the quoting behavior determined by the backend. To produce a textual SQL expression that is rendered exactly without any quoting, use :func:`_expression.literal_column` instead, or pass ``True`` as the value of :paramref:`_expression.column.is_literal`. Additionally, full SQL statements are best handled using the :func:`_expression.text` construct. :func:`_expression.column` can be used in a table-like fashion by combining it with the :func:`.table` function (which is the lightweight analogue to :class:`_schema.Table` ) to produce a working table construct with minimal boilerplate:: from sqlalchemy import table, column, select user = table("user", column("id"), column("name"), column("description"), ) stmt = select(user.c.description).where(user.c.name == 'wendy') A :func:`_expression.column` / :func:`.table` construct like that illustrated above can be created in an ad-hoc fashion and is not associated with any :class:`_schema.MetaData`, DDL, or events, unlike its :class:`_schema.Table` counterpart. :param text: the text of the element. :param type: :class:`_types.TypeEngine` object which can associate this :class:`.ColumnClause` with a type. :param is_literal: if True, the :class:`.ColumnClause` is assumed to be an exact expression that will be delivered to the output with no quoting rules applied regardless of case sensitive settings. the :func:`_expression.literal_column()` function essentially invokes :func:`_expression.column` while passing ``is_literal=True``. .. seealso:: :class:`_schema.Column` :func:`_expression.literal_column` :func:`.table` :func:`_expression.text` :ref:`tutorial_select_arbitrary_text` r)rqrZrrrsrBrBrCrKs]rKcCs t|S)a Produce a descending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import desc stmt = select(users_table).order_by(desc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name DESC The :func:`.desc` function is a standalone version of the :meth:`_expression.ColumnElement.desc` method available on all SQL expressions, e.g.:: stmt = select(users_table).order_by(users_table.c.name.desc()) :param column: A :class:`_expression.ColumnElement` (e.g. scalar SQL expression) with which to apply the :func:`.desc` operation. .. seealso:: :func:`.asc` :func:`.nulls_first` :func:`.nulls_last` :meth:`_expression.Select.order_by` )r0Z _create_descrLrBrBrCdescs&rtcCs t|S)aProduce an column-expression-level unary ``DISTINCT`` clause. This applies the ``DISTINCT`` keyword to an **individual column expression** (e.g. not the whole statement), and renders **specifically in that column position**; this is used for containment within an aggregate function, as in:: from sqlalchemy import distinct, func stmt = select(users_table.c.id, func.count(distinct(users_table.c.name))) The above would produce an statement resembling:: SELECT user.id, count(DISTINCT user.name) FROM user .. tip:: The :func:`_sql.distinct` function does **not** apply DISTINCT to the full SELECT statement, instead applying a DISTINCT modifier to **individual column expressions**. For general ``SELECT DISTINCT`` support, use the :meth:`_sql.Select.distinct` method on :class:`_sql.Select`. The :func:`.distinct` function is also available as a column-level method, e.g. :meth:`_expression.ColumnElement.distinct`, as in:: stmt = select(func.count(users_table.c.name.distinct())) The :func:`.distinct` operator is different from the :meth:`_expression.Select.distinct` method of :class:`_expression.Select`, which produces a ``SELECT`` statement with ``DISTINCT`` applied to the result set as a whole, e.g. a ``SELECT DISTINCT`` expression. See that method for further information. .. seealso:: :meth:`_expression.ColumnElement.distinct` :meth:`_expression.Select.distinct` :data:`.func` )r0Z_create_distinctrArBrBrCdistinctBs+rucCs t|S)zProduce a unary bitwise NOT clause, typically via the ``~`` operator. Not to be confused with boolean negation :func:`_sql.not_`. .. versionadded:: 2.0.2 .. seealso:: :ref:`operators_bitwise` )r0Z_create_bitwise_notrArBrBrC bitwise_notpsrvz_ColumnExpressionArgument[Any]r )fieldr?r@cCs t||S)acReturn a :class:`.Extract` construct. This is typically available as :func:`.extract` as well as ``func.extract`` from the :data:`.func` namespace. :param field: The field to extract. :param expr: A column or Python scalar expression serving as the right side of the ``EXTRACT`` expression. E.g.:: from sqlalchemy import extract from sqlalchemy import table, column logged_table = table("user", column("id"), column("date_created"), ) stmt = select(logged_table.c.id).where( extract("YEAR", logged_table.c.date_created) == 2021 ) In the above example, the statement is used to select ids from the database where the ``YEAR`` component matches a specific value. Similarly, one can also select an extracted component:: stmt = select( extract("YEAR", logged_table.c.date_created) ).where(logged_table.c.id == 1) The implementation of ``EXTRACT`` may vary across database backends. Users are reminded to consult their database documentation. r)rwr?rBrBrCextracts&rxr!)r@cCstS)aReturn a :class:`.False_` construct. E.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import false >>> print(select(t.c.x).where(false())) {printsql}SELECT x FROM t WHERE false A backend which does not support true/false constants will render as an expression against 1 or 0: .. sourcecode:: pycon+sql >>> print(select(t.c.x).where(false())) {printsql}SELECT x FROM t WHERE 0 = 1 The :func:`.true` and :func:`.false` constants also feature "short circuit" operation within an :func:`.and_` or :func:`.or_` conjunction: .. sourcecode:: pycon+sql >>> print(select(t.c.x).where(or_(t.c.x > 5, true()))) {printsql}SELECT x FROM t WHERE true{stop} >>> print(select(t.c.x).where(and_(t.c.x > 5, false()))) {printsql}SELECT x FROM t WHERE false{stop} .. seealso:: :func:`.true` )r! _instancerBrBrBrCfalses%rzzFunctionElement[_T]zFunctionFilter[_T])func criterionr@cGst|f|S)aProduce a :class:`.FunctionFilter` object against a function. Used against aggregate and window functions, for database backends that support the "FILTER" clause. E.g.:: from sqlalchemy import funcfilter funcfilter(func.count(1), MyClass.name == 'some name') Would produce "COUNT(1) FILTER (WHERE myclass.name = 'some name')". This function is also available from the :data:`~.expression.func` construct itself via the :meth:`.FunctionElement.filter` method. .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial` :meth:`.FunctionElement.filter` r")r{r|rBrBrC funcfiltersr}z Label[_T])nameelementrZr@cCs t|||S)aReturn a :class:`Label` object for the given :class:`_expression.ColumnElement`. A label changes the name of an element in the columns clause of a ``SELECT`` statement, typically via the ``AS`` SQL keyword. This functionality is more conveniently available via the :meth:`_expression.ColumnElement.label` method on :class:`_expression.ColumnElement`. :param name: label name :param obj: a :class:`_expression.ColumnElement`. r$)r~rrZrBrBrClabelsrr&cCstS)z+Return a constant :class:`.Null` construct.)r&ryrBrBrBrCnullsrcCs t|S)aProduce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression. :func:`.nulls_first` is intended to modify the expression produced by :func:`.asc` or :func:`.desc`, and indicates how NULL values should be handled when they are encountered during ordering:: from sqlalchemy import desc, nulls_first stmt = select(users_table).order_by( nulls_first(desc(users_table.c.name))) The SQL expression from the above would resemble:: SELECT id, name FROM user ORDER BY name DESC NULLS FIRST Like :func:`.asc` and :func:`.desc`, :func:`.nulls_first` is typically invoked from the column expression itself using :meth:`_expression.ColumnElement.nulls_first`, rather than as its standalone function version, as in:: stmt = select(users_table).order_by( users_table.c.name.desc().nulls_first()) .. versionchanged:: 1.4 :func:`.nulls_first` is renamed from :func:`.nullsfirst` in previous releases. The previous name remains available for backwards compatibility. .. seealso:: :func:`.asc` :func:`.desc` :func:`.nulls_last` :meth:`_expression.Select.order_by` )r0Z_create_nulls_firstrLrBrBrC nulls_first s)rcCs t|S)aProduce the ``NULLS LAST`` modifier for an ``ORDER BY`` expression. :func:`.nulls_last` is intended to modify the expression produced by :func:`.asc` or :func:`.desc`, and indicates how NULL values should be handled when they are encountered during ordering:: from sqlalchemy import desc, nulls_last stmt = select(users_table).order_by( nulls_last(desc(users_table.c.name))) The SQL expression from the above would resemble:: SELECT id, name FROM user ORDER BY name DESC NULLS LAST Like :func:`.asc` and :func:`.desc`, :func:`.nulls_last` is typically invoked from the column expression itself using :meth:`_expression.ColumnElement.nulls_last`, rather than as its standalone function version, as in:: stmt = select(users_table).order_by( users_table.c.name.desc().nulls_last()) .. versionchanged:: 1.4 :func:`.nulls_last` is renamed from :func:`.nullslast` in previous releases. The previous name remains available for backwards compatibility. .. seealso:: :func:`.asc` :func:`.desc` :func:`.nulls_first` :meth:`_expression.Select.order_by` )r0Z_create_nulls_lastrLrBrBrC nulls_last8s)rz6Union[Literal[False], _ColumnExpressionArgument[bool]]cGsdS)a/Produce a conjunction of expressions joined by ``OR``. E.g.:: from sqlalchemy import or_ stmt = select(users_table).where( or_( users_table.c.name == 'wendy', users_table.c.name == 'jack' ) ) The :func:`.or_` conjunction is also available using the Python ``|`` operator (though note that compound expressions need to be parenthesized in order to function with Python operator precedence behavior):: stmt = select(users_table).where( (users_table.c.name == 'wendy') | (users_table.c.name == 'jack') ) The :func:`.or_` construct must be given at least one positional argument in order to be valid; a :func:`.or_` construct with no arguments is ambiguous. To produce an "empty" or dynamically generated :func:`.or_` expression, from a given list of expressions, a "default" element of :func:`_sql.false` (or just ``False``) should be specified:: from sqlalchemy import false or_criteria = or_(false(), *expressions) The above expression will compile to SQL as the expression ``false`` or ``0 = 1``, depending on backend, if no other expressions are present. If expressions are present, then the :func:`_sql.false` value is ignored as it does not affect the outcome of an OR expression which has other elements. .. deprecated:: 1.4 The :func:`.or_` element now requires that at least one argument is passed; creating the :func:`.or_` construct with no arguments is deprecated, and will emit a deprecation warning while continuing to produce a blank SQL string. .. seealso:: :func:`.and_` NrBrGrBrBrCor_ds5rcGs tj|S)aProduce a conjunction of expressions joined by ``OR``. E.g.:: from sqlalchemy import or_ stmt = select(users_table).where( or_( users_table.c.name == 'wendy', users_table.c.name == 'jack' ) ) The :func:`.or_` conjunction is also available using the Python ``|`` operator (though note that compound expressions need to be parenthesized in order to function with Python operator precedence behavior):: stmt = select(users_table).where( (users_table.c.name == 'wendy') | (users_table.c.name == 'jack') ) The :func:`.or_` construct must be given at least one positional argument in order to be valid; a :func:`.or_` construct with no arguments is ambiguous. To produce an "empty" or dynamically generated :func:`.or_` expression, from a given list of expressions, a "default" element of :func:`_sql.false` (or just ``False``) should be specified:: from sqlalchemy import false or_criteria = or_(false(), *expressions) The above expression will compile to SQL as the expression ``false`` or ``0 = 1``, depending on backend, if no other expressions are present. If expressions are present, then the :func:`_sql.false` value is ignored as it does not affect the outcome of an OR expression which has other elements. .. deprecated:: 1.4 The :func:`.or_` element now requires that at least one argument is passed; creating the :func:`.or_` construct with no arguments is deprecated, and will emit a deprecation warning while continuing to produce a blank SQL string. .. seealso:: :func:`.and_` )rrrIrBrBrCrs2zOptional[_ByArgument]z4Optional[typing_Tuple[Optional[int], Optional[int]]]zOver[_T])r partition_byorder_byrange_rowsr@cCst|||||S)aO Produce an :class:`.Over` object against a function. Used against aggregate or so-called "window" functions, for database backends that support window functions. :func:`_expression.over` is usually called using the :meth:`.FunctionElement.over` method, e.g.:: func.row_number().over(order_by=mytable.c.some_column) Would produce:: ROW_NUMBER() OVER(ORDER BY some_column) Ranges are also possible using the :paramref:`.expression.over.range_` and :paramref:`.expression.over.rows` parameters. These mutually-exclusive parameters each accept a 2-tuple, which contains a combination of integers and None:: func.row_number().over( order_by=my_table.c.some_column, range_=(None, 0)) The above would produce:: ROW_NUMBER() OVER(ORDER BY some_column RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) A value of ``None`` indicates "unbounded", a value of zero indicates "current row", and negative / positive integers indicate "preceding" and "following": * RANGE BETWEEN 5 PRECEDING AND 10 FOLLOWING:: func.row_number().over(order_by='x', range_=(-5, 10)) * ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW:: func.row_number().over(order_by='x', rows=(None, 0)) * RANGE BETWEEN 2 PRECEDING AND UNBOUNDED FOLLOWING:: func.row_number().over(order_by='x', range_=(-2, None)) * RANGE BETWEEN 1 FOLLOWING AND 3 FOLLOWING:: func.row_number().over(order_by='x', range_=(1, 3)) :param element: a :class:`.FunctionElement`, :class:`.WithinGroup`, or other compatible construct. :param partition_by: a column element or string, or a list of such, that will be used as the PARTITION BY clause of the OVER construct. :param order_by: a column element or string, or a list of such, that will be used as the ORDER BY clause of the OVER construct. :param range\_: optional range clause for the window. This is a tuple value which can contain integer values or ``None``, and will render a RANGE BETWEEN PRECEDING / FOLLOWING clause. :param rows: optional rows clause for the window. This is a tuple value which can contain integer values or None, and will render a ROWS BETWEEN PRECEDING / FOLLOWING clause. This function is also available from the :data:`~.expression.func` construct itself via the :meth:`.FunctionElement.over` method. .. seealso:: :ref:`tutorial_window_functions` - in the :ref:`unified_tutorial` :data:`.expression.func` :func:`_expression.within_group` r')rrrrrrBrBrCoversRrrqz :func:`.text`z:paramref:`.text.text`r*)rqr@cCst|S)a Construct a new :class:`_expression.TextClause` clause, representing a textual SQL string directly. E.g.:: from sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t) The advantages :func:`_expression.text` provides over a plain string are backend-neutral support for bind parameters, per-statement execution options, as well as bind parameter and result-column typing behavior, allowing SQLAlchemy type constructs to play a role when executing a statement that is specified literally. The construct can also be provided with a ``.c`` collection of column elements, allowing it to be embedded in other SQL expression constructs as a subquery. Bind parameters are specified by name, using the format ``:name``. E.g.:: t = text("SELECT * FROM users WHERE id=:user_id") result = connection.execute(t, {"user_id": 12}) For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape:: t = text(r"SELECT * FROM users WHERE name='\:username'") The :class:`_expression.TextClause` construct includes methods which can provide information about the bound parameters as well as the column values which would be returned from the textual statement, assuming it's an executable SELECT type of statement. The :meth:`_expression.TextClause.bindparams` method is used to provide bound parameter detail, and :meth:`_expression.TextClause.columns` method allows specification of return columns including names and types:: t = text("SELECT * FROM users WHERE id=:user_id").\ bindparams(user_id=7).\ columns(id=Integer, name=String) for id, name in connection.execute(t): print(id, name) The :func:`_expression.text` construct is used in cases when a literal string SQL fragment is specified as part of a larger query, such as for the WHERE clause of a SELECT statement:: s = select(users.c.id, users.c.name).where(text("id=:user_id")) result = connection.execute(s, {"user_id": 12}) :func:`_expression.text` is also used for the construction of a full, standalone statement using plain text. As such, SQLAlchemy refers to it as an :class:`.Executable` object and may be used like any other statement passed to an ``.execute()`` method. :param text: the text of the SQL statement to be created. Use ``:`` to specify bind parameters; they will be compiled to their engine-specific format. .. seealso:: :ref:`tutorial_select_arbitrary_text` r))rqrBrBrCrq(sKr+cCstS)aReturn a constant :class:`.True_` construct. E.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import true >>> print(select(t.c.x).where(true())) {printsql}SELECT x FROM t WHERE true A backend which does not support true/false constants will render as an expression against 1 or 0: .. sourcecode:: pycon+sql >>> print(select(t.c.x).where(true())) {printsql}SELECT x FROM t WHERE 1 = 1 The :func:`.true` and :func:`.false` constants also feature "short circuit" operation within an :func:`.and_` or :func:`.or_` conjunction: .. sourcecode:: pycon+sql >>> print(select(t.c.x).where(or_(t.c.x > 5, true()))) {printsql}SELECT x FROM t WHERE true{stop} >>> print(select(t.c.x).where(and_(t.c.x > 5, false()))) {printsql}SELECT x FROM t WHERE false{stop} .. seealso:: :func:`.false` )r+ryrBrBrBrCtruevs%r)typesz,Optional[Sequence[_TypeEngineArgument[Any]]]r )rFrr@cGst|d|iS)a|Return a :class:`.Tuple`. Main usage is to produce a composite IN construct using :meth:`.ColumnOperators.in_` :: from sqlalchemy import tuple_ tuple_(table.c.col1, table.c.col2).in_( [(1, 2), (5, 12), (10, 19)] ) .. versionchanged:: 1.3.6 Added support for SQLite IN tuples. .. warning:: The composite IN construct is not supported by all backends, and is currently known to work on PostgreSQL, MySQL, and SQLite. Unsupported backends will raise a subclass of :class:`~sqlalchemy.exc.DBAPIError` when such an expression is invoked. rr )rrFrBrBrCtuple_srzTypeCoerce[_T]cCs t||S)ag Associate a SQL expression with a particular type, without rendering ``CAST``. E.g.:: from sqlalchemy import type_coerce stmt = select(type_coerce(log_table.date_string, StringDateTime())) The above construct will produce a :class:`.TypeCoerce` object, which does not modify the rendering in any way on the SQL side, with the possible exception of a generated label if used in a columns clause context: .. sourcecode:: sql SELECT date_string AS date_string FROM log When result rows are fetched, the ``StringDateTime`` type processor will be applied to result rows on behalf of the ``date_string`` column. .. note:: the :func:`.type_coerce` construct does not render any SQL syntax of its own, including that it does not imply parenthesization. Please use :meth:`.TypeCoerce.self_group` if explicit parenthesization is required. In order to provide a named label for the expression, use :meth:`_expression.ColumnElement.label`:: stmt = select( type_coerce(log_table.date_string, StringDateTime()).label('date') ) A type that features bound-value handling will also have that behavior take effect when literal values or :func:`.bindparam` constructs are passed to :func:`.type_coerce` as targets. For example, if a type implements the :meth:`.TypeEngine.bind_expression` method or :meth:`.TypeEngine.bind_processor` method or equivalent, these functions will take effect at statement compilation/execution time when a literal value is passed, as in:: # bound-value handling of MyStringType will be applied to the # literal value "some string" stmt = select(type_coerce("some string", MyStringType)) When using :func:`.type_coerce` with composed expressions, note that **parenthesis are not applied**. If :func:`.type_coerce` is being used in an operator context where the parenthesis normally present from CAST are necessary, use the :meth:`.TypeCoerce.self_group` method: .. sourcecode:: pycon+sql >>> some_integer = column("someint", Integer) >>> some_string = column("somestr", String) >>> expr = type_coerce(some_integer + 5, String) + some_string >>> print(expr) {printsql}someint + :someint_1 || somestr{stop} >>> expr = type_coerce(some_integer + 5, String).self_group() + some_string >>> print(expr) {printsql}(someint + :someint_1) || somestr{stop} :param expression: A SQL expression, such as a :class:`_expression.ColumnElement` expression or a Python string which will be coerced into a bound literal value. :param type\_: A :class:`.TypeEngine` class or instance indicating the type to which the expression is coerced. .. seealso:: :ref:`tutorial_casts` :func:`.cast` r.rnrBrBrC type_coercesRrzWithinGroup[_T])rrr@cGst|f|S)aProduce a :class:`.WithinGroup` object against a function. Used against so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including :class:`.percentile_cont`, :class:`.rank`, :class:`.dense_rank`, etc. :func:`_expression.within_group` is usually called using the :meth:`.FunctionElement.within_group` method, e.g.:: from sqlalchemy import within_group stmt = select( department.c.id, func.percentile_cont(0.5).within_group( department.c.salary.desc() ) ) The above statement would produce SQL similar to ``SELECT department.id, percentile_cont(0.5) WITHIN GROUP (ORDER BY department.salary DESC)``. :param element: a :class:`.FunctionElement` construct, typically generated by :data:`~.expression.func`. :param \*order_by: one or more column elements that will be used as the ORDER BY clause of the WITHIN GROUP construct. .. seealso:: :ref:`tutorial_functions_within_group` - in the :ref:`unified_tutorial` :data:`.expression.func` :func:`_expression.over` r1)rrrBrBrC within_groups'r)F)N)NFN)N)NNNN)X __future__rtypingrrrrrrr Z typing_Tupler r r rrbaserrelementsrrrrrrrrr r!r#r%r&r(r*r+r-r/r0r2Z functionsr3Z util.typingr5Z_typingr6r7r8r9r:r;Z selectabler<Ztype_apir=r>rDrHrJrMrQrXr]raZNO_ARGrirmrorprKrtrurvrxrzr}rrrrrrrqrrrrrBrBrBrCs                                              6B?6(<$9-`).)( ,,87U M*U