o znhe@sdZddlmZddlZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Z dd l mZdd l mZdd l mZdd l mZdd lmZddlmZddlmZddlmZddlmZddlmZddZddZddZdddZdddZddd Zd!d"Zej Gd#d$d$eZ!Gd%d&d&ej"e!Z#Gd'd(d(e#Z$Gd)d*d*e!Z%Gd+d,d,ee!Z&Gd-d.d.e#Z'Gd/d0d0e#Z(Gd1d2d2e#Z)Gd3d4d4e!Z*Gd5d6d6e*e#Z+e+j,Z,e+j-Z-Gd7d8d8e*e#Z.Gd9d:d:e#Z/dd;d<Z0Gd=d>d>e#Z1Gd?d@d@e#Z2GdAdBdBe#Z3GdCdDdDe#Z4GdEdFdFe#Z5GdGdHdHe#Z6GdIdJdJe6Z7GdKdLdLe6Z8GdMdNdNe#Z9GdOdPdPe#Z:GdQdRdRe9Z;GdSdTdTe#Ze=dVZ?GdWdXdXe#Z@GdYdZdZe#ZAGd[d\d\e#ZBGd]d^d^e#ZCGd_d`d`ee#ZDGdadbdbe#ZEGdcddddee!ZFGdedfdfeFZGGdgdhdheFZHGdidjdjeFZIGdkdldlejJejKZLGdmdndneLZMGdodpdpeMZNGdqdrdreMZOGdsdtdteOZPePduZQeMZRGdvdwdweMZSdxdyZTdzd{ZUd|d}ZVd~dZWddZXddZYeZdddZ[ddZ\ddZ]ddZ^ddZ_ddZ`ddZaddZbddZcdddZdddZeddZfejgdfddZhddZiddZjddZkddZldddZmendejoZpddZqddZrddZsdddZtGddde ZudS)zpCore SQL expression elements, including :class:`.ClauseElement`, :class:`.ColumnElement`, and derived classes. )unicode_literalsN) operators)type_api Annotated) _generative) Executable) Immutable)NO_ARG)PARSE_AUTOCOMMIT)cloned_traverse)traverse) Visitable)exc) inspection)utilcKs|SN_clone)elementkwrB/usr/local/lib/python3.10/dist-packages/sqlalchemy/sql/elements.pyr$rcCst|d||fS)Nz.. warning:: The %s argument to %s can be passed as a Python string argument, which will be treated as **trusted SQL text** and rendered as given. **DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER**.)radd_parameter_text) paramnamemeth_rst param_rstrrr_document_text_coercion(s r cCs t|}t|t|tj|jdS)aReturn the clause ``expression COLLATE collation``. e.g.:: collate(mycolumn, 'utf8_bin') produces:: mycolumn COLLATE utf8_bin The collation expression is also quoted if it is a case sensitive identifier, e.g. contains uppercase characters. .. versionchanged:: 1.2 quoting is automatically applied to COLLATE expressions if they are case sensitive. type_)_literal_as_bindsBinaryExpressionCollationClausercollatetype) expression collationexprrrrr&6sr&FcCst|}|j|||dS)aEProduce a ``BETWEEN`` predicate clause. E.g.:: from sqlalchemy import between stmt = select([users_table]).where(between(users_table.c.id, 5, 7)) Would produce SQL resembling:: SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2 The :func:`.between` function is a standalone version of the :meth:`.ColumnElement.between` method available on all SQL expressions, as in:: stmt = select([users_table]).where(users_table.c.id.between(5, 7)) All arguments passed to :func:`.between`, including the left side column expression, are coerced from Python scalar values if a the value is not a :class:`.ColumnElement` subclass. For example, three fixed values can be compared as in:: print(between(5, 3, 7)) Which would produce:: :param_1 BETWEEN :param_2 AND :param_3 :param expr: a column expression, typically a :class:`.ColumnElement` instance or alternatively a Python scalar expression to be coerced into a column expression, serving as the left side of the ``BETWEEN`` expression. :param lower_bound: a column or Python scalar expression serving as the lower bound of the right side of the ``BETWEEN`` expression. :param upper_bound: a column or Python scalar expression serving as the upper bound of the right side of the ``BETWEEN`` expression. :param symmetric: if True, will render " BETWEEN SYMMETRIC ". Note that not all databases support this syntax. .. versionadded:: 0.9.5 .. seealso:: :meth:`.ColumnElement.between` ) symmetric)r#between)r* lower_bound upper_boundr+rrrr,Os2r,cCstd||ddS)aReturn a literal clause, bound to a bind parameter. Literal clauses are created automatically when non- :class:`.ClauseElement` objects (such as strings, ints, dates, etc.) are used in a comparison operation with a :class:`.ColumnElement` subclass, such as a :class:`~sqlalchemy.schema.Column` object. Use this function to force the generation of a literal clause, which will be created as a :class:`BindParameter` with a bound value. :param value: the value to be bound. Can be any Python object supported by the underlying DB-API, or is translatable via the given type argument. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which will provide bind-parameter translation for this literal. NTr"unique BindParameter)valuer"rrrliteralsr4cCst|d|dddS)awCreate an 'OUT' parameter for usage in functions (stored procedures), for databases which support them. The ``outparam`` can be used like a regular function parameter. The "output" value will be available from the :class:`~sqlalchemy.engine.ResultProxy` object via its ``out_parameters`` attribute, which returns a dictionary containing the values. NFT)r"r0 isoutparamr1)keyr"rrroutparams r7cCstt|S)zReturn a negation of the given clause, i.e. ``NOT(clause)``. The ``~`` operator is also overloaded on all :class:`.ColumnElement` subclasses to produce the same result. )rinvr#clauserrrnot_r;c@s6eZdZdZdZiZdZgZdZdZ dZ dZ dZ dZ dZddZedd Zejd d Zd d ZddZddZd:ddZddZddZddZddZddZefddZd d!Zd;d"d#Z e!d$drHrrr _constructors zClauseElement._constructorcCs0t}|}|dur|||j}|dus |S)aReturn the set consisting all cloned ancestors of this ClauseElement. Includes this ClauseElement. This accessor tends to be used for FromClause objects to identify 'equivalent' FROM clauses, regardless of transformative operations. N)r column_setaddrF)rHsfrrrrBs  zClauseElement._cloned_setcCs|j}|dd|S)NrF)r@rApop)rHdrrr __getstate__s  zClauseElement.__getstate__cC t||S)zgreturn a copy of this ClauseElement with annotations updated by the given dictionary. rrHvaluesrrr _annotate zClauseElement._annotatecCrU)zhreturn a copy of this ClauseElement with annotations replaced by the given dictionary. rrVrrr_with_annotations rYzClauseElement._with_annotationscCs|r|S|S)zreturn a copy of this :class:`.ClauseElement` with annotations removed. :param values: optional tuple of individual values to remove. rrHrWclonerrr _deannotateszClauseElement._deannotatecCs|jr ||||St|r)supports_execution_execute_clauseelementrObjectNotExecutableError)rH connection multiparamsparamsrrr_execute_on_connection#s z$ClauseElement._execute_on_connectioncO|d||S)zReturn a copy with :func:`bindparam()` elements replaced. Same functionality as ``params()``, except adds `unique=True` to affected bind parameters so that multiple statements can be used. T_paramsrH optionaldictkwargsrrr unique_params)r<zClauseElement.unique_paramscOre)aReturn a copy with :func:`bindparam()` elements replaced. Returns a copy of this ClauseElement with :func:`bindparam()` elements replaced with values taken from the given dictionary:: >>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7} Frfrhrrrrc3s zClauseElement.paramscsPt|dkr|dn t|dkrtdfdd}t|id|iS)Nrrz9params() takes zero or one positional dictionary argumentcs0|jvr|j|_d|_r|dSdSNF)r6r3required_convert_to_uniquebindrjr0rrvisit_bindparamJs   z.ClauseElement._params..visit_bindparam bindparam)lenupdater ArgumentErrorr )rHr0rirjrrrrqrrgBs  zClauseElement._paramscKs||uS)aTCompare this ClauseElement to the given ClauseElement. Subclasses should override the default behavior, which is a straight identity comparison. \**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see :class:`.ColumnElement`) rrHotherrrrrcompareSs zClauseElement.comparecKdS)atReassign internal elements to be clones of themselves. Called during a copy-and-traverse operation on newly shallow-copied elements to create a deep copy. The given clone function should be used, which may be applying additional transformations to the element (i.e. replacement traversal, cloned traversal, annotations). NrrHr\rrrr_copy_internals`s zClauseElement._copy_internalscKsgS)aReturn immediate child elements of this :class:`.ClauseElement`. This is used for visit traversal. \**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level). rrHrjrrr get_childrenms zClauseElement.get_childrencC|S)aaApply a 'grouping' to this :class:`.ClauseElement`. This method is overridden by subclasses to return a "grouping" construct, i.e. parenthesis. In particular it's used by "binary" expressions to provide a grouping around themselves when placed into a larger expression, as well as by :func:`.select` constructs when placed into the FROM clause of another :func:`.select`. (Note that subqueries should be normally created using the :meth:`.Select.alias` method, as many platforms require nested SELECT statements to be named). As expressions are composed together, the application of :meth:`self_group` is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy's clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like ``x OR (y AND z)`` - AND takes precedence over OR. The base :meth:`self_group` method of :class:`.ClauseElement` just returns self. rrHagainstrrr self_group{szClauseElement.self_groupzsqlalchemy.engine.defaultcKsD|s|r|j}n|jr|jj}|j}n|}|j|fd|i|S)a Compile this SQL expression. The return value is a :class:`~.Compiled` object. Calling ``str()`` or ``unicode()`` on the returned value will yield a string representation of the result. The :class:`~.Compiled` object also can return a dictionary of bind parameter names and values using the ``params`` accessor. :param bind: An ``Engine`` or ``Connection`` from which a ``Compiled`` will be acquired. This argument takes precedence over this :class:`.ClauseElement`'s bound engine, if any. :param column_keys: Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If ``None``, all columns from the target table object are rendered. :param dialect: A ``Dialect`` instance from which a ``Compiled`` will be acquired. This argument takes precedence over the `bind` argument as well as this :class:`.ClauseElement`'s bound engine, if any. :param inline: Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement's VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key `Column`. :param compile_kwargs: optional dictionary of additional parameters that will be passed through to the compiler within all "visit" methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the ``literal_binds`` flag through:: from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True}) .. versionadded:: 0.9.0 .. seealso:: :ref:`faq_sql_expression_string` rp)dialectrpStrCompileDialect _compiler)rHdefaultrprrrrrcompiles7zClauseElement.compilecKs|j||fi|S)zNReturn a compiler appropriate for this ClauseElement, given a Dialect.)statement_compiler)rHrrrrrrszClauseElement._compilercCs&tjr t|St|ddSNasciibackslashreplace)rpy3kstrrunicodeencoderLrrr__str__s   zClauseElement.__str__0.9zThe :meth:`.ClauseElement.__and__` method is deprecated and will be removed in a future release. Conjunctions should only be used from a :class:`.ColumnElement` subclass, e.g. :meth:`.ColumnElement.__and__`.cCrU)z*'and' at the ClauseElement level. and_rHrxrrr__and__ zClauseElement.__and__zThe :meth:`.ClauseElement.__or__` method is deprecated and will be removed in a future release. Conjunctions should only be used from a :class:`.ColumnElement` subclass, e.g. :meth:`.ColumnElement.__or__`.cCrU)z)'or' at the ClauseElement level. )or_rrrr__or__rzClauseElement.__or__cCst|dr|jS|S)Nnegation_clause)hasattrr_negaterLrrr __invert__s zClauseElement.__invert__cCst|jtjdtjddS)Nr)operatornegate)UnaryExpressionrrr8rLrrrrs  zClauseElement._negatecCtd)N+Boolean value of this clause is not defined) TypeErrorrLrrr__bool__ rzClauseElement.__bool__cCs2|j}|dur t|Sd|j|jjt||fS)Nz<%s.%s at 0x%x; %s>) descriptionobject__repr__ __module__r>__name__id)rHfriendlyrrrrs zClauseElement.__repr__rlrNN)-rr __qualname____doc____visit_name__ _annotationsr^ _from_objectsrprF is_selectableis_clause_elementr_order_by_label_element_is_from_containerrpropertyrMrmemoized_propertyrBrTrXrZr]rdrkrcrgryr|r~r dependenciesrrr deprecatedrrrrr __nonzero__rrrrrr=sb       @   r=cs$eZdZdZdZdZgZdZdZ dZ dZ dZ dZ dZ dZdZd/ddZfd d Zejd d Zejd dZddZddZddZd/ddZeddZeddZejddZejddZdd Zd!d"Z d#d$Z! d0d%d&Z"d1d'd(Z#d)d*Z$d+d,Z%ejd-d.Z&Z'S)2rDa[Represent a column-oriented SQL expression suitable for usage in the "columns" clause, WHERE clause etc. of a statement. While the most familiar kind of :class:`.ColumnElement` is the :class:`.Column` object, :class:`.ColumnElement` serves as the basis for any unit that may be present in a SQL expression, including the expressions themselves, SQL functions, bound parameters, literal expressions, keywords such as ``NULL``, etc. :class:`.ColumnElement` is the ultimate base class for all such elements. A wide variety of SQLAlchemy Core functions work at the SQL expression level, and are intended to accept instances of :class:`.ColumnElement` as arguments. These functions will typically document that they accept a "SQL expression" as an argument. What this means in terms of SQLAlchemy usually refers to an input which is either already in the form of a :class:`.ColumnElement` object, or a value which can be **coerced** into one. The coercion rules followed by most, but not all, SQLAlchemy Core functions with regards to SQL expressions are as follows: * a literal Python value, such as a string, integer or floating point value, boolean, datetime, ``Decimal`` object, or virtually any other Python object, will be coerced into a "literal bound value". This generally means that a :func:`.bindparam` will be produced featuring the given value embedded into the construct; the resulting :class:`.BindParameter` object is an instance of :class:`.ColumnElement`. The Python value will ultimately be sent to the DBAPI at execution time as a parameterized argument to the ``execute()`` or ``executemany()`` methods, after SQLAlchemy type-specific converters (e.g. those provided by any associated :class:`.TypeEngine` objects) are applied to the value. * any special object value, typically ORM-level constructs, which feature a method called ``__clause_element__()``. The Core expression system looks for this method when an object of otherwise unknown type is passed to a function that is looking to coerce the argument into a :class:`.ColumnElement` expression. The ``__clause_element__()`` method, if present, should return a :class:`.ColumnElement` instance. The primary use of ``__clause_element__()`` within SQLAlchemy is that of class-bound attributes on ORM-mapped classes; a ``User`` class which contains a mapped attribute named ``.name`` will have a method ``User.name.__clause_element__()`` which when invoked returns the :class:`.Column` called ``name`` associated with the mapped table. * The Python ``None`` value is typically interpreted as ``NULL``, which in SQLAlchemy Core produces an instance of :func:`.null`. A :class:`.ColumnElement` provides the ability to generate new :class:`.ColumnElement` objects using Python expressions. This means that Python operators such as ``==``, ``!=`` and ``<`` are overloaded to mimic SQL operations, and allow the instantiation of further :class:`.ColumnElement` instances which are composed from other, more fundamental :class:`.ColumnElement` objects. For example, two :class:`.ColumnClause` objects can be added together with the addition operator ``+`` to produce a :class:`.BinaryExpression`. Both :class:`.ColumnClause` and :class:`.BinaryExpression` are subclasses of :class:`.ColumnElement`:: >>> from sqlalchemy.sql import column >>> column('a') + column('b') >>> print column('a') + column('b') a + b .. seealso:: :class:`.Column` :func:`.expression.column` column_elementFrNTcCsP|tjtjtjfvr|jjtjjurt|tj tj S|tj tj fvr&t |S|Sr)rrr_asboolr'_type_affinityr BOOLEANTYPE AsBooleanistrueisfalseany_opall_opGroupingrrrrrs zColumnElement.self_groupcs.|jjtjjurt|tjtjStt | Sr) r'rrrrrrrsuperrDrrLrKrrrszColumnElement._negatecCtjSrrNULLTYPErLrrrr'zColumnElement.typecCs0z |jj}W||Stytd|jw)NzOObject %r associated with '.type' attribute is not a TypeEngine class or object)r'comparator_factoryAttributeErrorr)rHrrrrrEs  zColumnElement.comparatorcCs>zt|j|WStytdt|jt|jj|fw)Nz3Neither %r object nor %r object has an attribute %r)getattrrErr'r)rHr6rrr __getattr__s zColumnElement.__getattr__cOs||jg|Ri|SrrErHoprxrjrrroperatezColumnElement.operatecKs|||jfi|Srrrrrrreverse_operatezColumnElement.reverse_operatecCstd||||jddS)NT)_compared_to_operatorr"_compared_to_typer0)r2r'rHrobjr"rrr _bind_paramszColumnElement._bind_paramcCr)z^Return a column expression. Part of the inspection interface; returns self. rrLrrrr(szColumnElement.expressioncC|fSrrrLrrr_select_iterablerzColumnElement._select_iterablecCstdd|jDS)Ncss|]}|js|VqdSr)_proxies.0rIrrr sz-ColumnElement.base_columns..)rrN proxy_setrLrrr base_columnsszColumnElement.base_columnscCs(t|g}|jD]}||jq |Sr)rrNrrurrHrPrIrrrrs  zColumnElement.proxy_setcCs*t|g}|jD] }||q |S)zAn 'uncached' version of proxy set. This is so that we can read annotations from the list of columns without breaking the caching of the above proxy_set. )rrNrru_uncached_proxy_setrrrrrs  z!ColumnElement._uncached_proxy_setcCst|j|jS)zoReturn True if the given :class:`.ColumnElement` has a common ancestor to this :class:`.ColumnElement`.)boolr intersection)rH othercolumnrrrshares_lineageszColumnElement.shares_lineagecCs t|dot|do|j|jkS)zhReturn True if the given column element compares to this one when targeting within a result row.name)rrrrrr_compare_name_for_results  z&ColumnElement._compare_name_for_resultcKs|dur"|j}|jr|j}nzt|}Wntjy!|j}Ynw|}t|r+t|n|t|dd|d}|g|_|j durF|j j ||_ ||j |<|S)zCreate a new :class:`.ColumnElement` representing this :class:`.ColumnElement` as it appears in the select list of a descending selectable. Nr')r" _selectable) anon_labelr6rrUnsupportedCompilationError ColumnClause _as_truncatedrrrFcolumnsget_columns)rH selectablername_is_truncatablerr6corrr _make_proxys(     zColumnElement._make_proxycKsX|f}|r||vr|||}|D]}|r||rdSt|t|kr)dSqdS)aCompare this ColumnElement to another. Special arguments understood: :param use_proxies: when True, consider two columns that share a common base column as equivalent (i.e. shares_lineage()) :param equivalents: a dictionary of columns as keys mapped to sets of columns. If the given "other" column is present in this dictionary, if any of the columns in the corresponding set() pass the comparison test, the result is True. This is used to expand the comparison to other columns that may be known to be equivalent to this one via foreign key or other criterion. TF)unionrhash)rHrx use_proxies equivalentsr to_compareothrrrry=s zColumnElement.comparecCrU)a?Produce a type cast, i.e. ``CAST( AS )``. This is a shortcut to the :func:`~.expression.cast` function. .. seealso:: :ref:`coretutorial_casts` :func:`~.expression.cast` :func:`~.expression.type_coerce` .. versionadded:: 1.0.7 )CastrHr"rrrcastYs zColumnElement.castcCst|||jS)zProduce a column label, i.e. `` AS ``. This is a shortcut to the :func:`~.expression.label` function. if 'name' is None, an anonymous label name will be generated. )Labelr')rHrrrrlabelkr<zColumnElement.labelcCs6|jdur |j}|jdustdt|t|ddfS)aprovides a constant 'anonymous label' for this ColumnElement. This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time. the compiler uses this function automatically at compile time for expressions that are known to be 'unnamed' like binary expressions and function calls. N %%(%d %s)sranon)rF_anonymous_labelrrrLrrrrus  zColumnElement.anon_labelrrl)FN)(rrrrr primary_key foreign_keysr_labelr6 _key_label_render_label_in_columns_clause_resolve_label_allow_label_resolve_is_implicitly_boolean _alt_namesrrrrr'rErrrrrr(rrrrrrrryrrr __classcell__rrrKrrDs`I                  rDc @seZdZdZdZdZdZeddeddddddf ddZdd Z d d Z e d d Z ddZ ddZddZddZddZddZdS)r2aRepresent a "bound expression". :class:`.BindParameter` is invoked explicitly using the :func:`.bindparam` function, as in:: from sqlalchemy import bindparam stmt = select([users_table]).\ where(users_table.c.name == bindparam('username')) Detailed discussion of how :class:`.BindParameter` is used is at :func:`.bindparam`. .. seealso:: :func:`.bindparam` rsFrNc Cs"t|tr |j}|j}|tur|tuo|du}|turd}|dur&t||}|rBtdt||dur;t dd| dndf|_n |pKtdt||_|j|_ |pTd|_ ||_ ||_||_| |_||_||_|dur| dury| | ||_dSt||_dSt|tr||_dS||_dS)a<$Produce a "bound expression". The return value is an instance of :class:`.BindParameter`; this is a :class:`.ColumnElement` subclass which represents a so-called "placeholder" value in a SQL expression, the value of which is supplied at the point at which the statement in executed against a database connection. In SQLAlchemy, the :func:`.bindparam` construct has the ability to carry along the actual value that will be ultimately used at expression time. In this way, it serves not just as a "placeholder" for eventual population, but also as a means of representing so-called "unsafe" values which should not be rendered directly in a SQL statement, but rather should be passed along to the :term:`DBAPI` as values which need to be correctly escaped and potentially handled for type-safety. When using :func:`.bindparam` explicitly, the use case is typically one of traditional deferment of parameters; the :func:`.bindparam` construct accepts a name which can then be referred to at execution time:: from sqlalchemy import bindparam stmt = select([users_table]).\ where(users_table.c.name == bindparam('username')) The above statement, when rendered, will produce SQL similar to:: SELECT id, name FROM user WHERE name = :username In order to populate the value of ``:username`` above, the value would typically be applied at execution time to a method like :meth:`.Connection.execute`:: result = connection.execute(stmt, username='wendy') Explicit use of :func:`.bindparam` is also common when producing UPDATE or DELETE statements that are to be invoked multiple times, where the WHERE criterion of the statement is to change on each invocation, such as:: stmt = (users_table.update(). where(user_table.c.name == bindparam('username')). values(fullname=bindparam('fullname')) ) connection.execute( stmt, [{"username": "wendy", "fullname": "Wendy Smith"}, {"username": "jack", "fullname": "Jack Jones"}, ] ) SQLAlchemy's Core expression system makes wide use of :func:`.bindparam` in an implicit sense. It is typical that Python literal values passed to virtually all SQL expression functions are coerced into fixed :func:`.bindparam` constructs. For example, given a comparison operation such as:: expr = users_table.c.name == 'Wendy' The above expression will produce a :class:`.BinaryExpression` construct, where the left side is the :class:`.Column` object representing the ``name`` column, and the right side is a :class:`.BindParameter` representing the literal value:: print(repr(expr.right)) BindParameter('%(4327771088 name)s', 'Wendy', type_=String()) The expression above will render SQL such as:: user.name = :name_1 Where the ``:name_1`` parameter name is an anonymous name. The actual string ``Wendy`` is not in the rendered string, but is carried along where it is later used within statement execution. If we invoke a statement like the following:: stmt = select([users_table]).where(users_table.c.name == 'Wendy') result = connection.execute(stmt) We would see SQL logging output as:: SELECT "user".id, "user".name FROM "user" WHERE "user".name = %(name_1)s {'name_1': 'Wendy'} Above, we see that ``Wendy`` is passed as a parameter to the database, while the placeholder ``:name_1`` is rendered in the appropriate form for the target database, in this case the PostgreSQL database. Similarly, :func:`.bindparam` is invoked automatically when working with :term:`CRUD` statements as far as the "VALUES" portion is concerned. The :func:`.insert` construct produces an ``INSERT`` expression which will, at statement execution time, generate bound placeholders based on the arguments passed, as in:: stmt = users_table.insert() result = connection.execute(stmt, name='Wendy') The above will produce SQL output as:: INSERT INTO "user" (name) VALUES (%(name)s) {'name': 'Wendy'} The :class:`.Insert` construct, at compilation/execution time, rendered a single :func:`.bindparam` mirroring the column name ``name`` as a result of the single ``name`` parameter we passed to the :meth:`.Connection.execute` method. :param key: the key (e.g. the name) for this bind param. Will be used in the generated SQL statement for dialects that use named parameters. This value may be modified when part of a compilation operation, if other :class:`BindParameter` objects exist with the same key, or if its length is too long and truncation is required. :param value: Initial value for this bind param. Will be used at statement execution time as the value for this parameter passed to the DBAPI, if no other value is indicated to the statement execution method for this particular parameter name. Defaults to ``None``. :param callable\_: A callable function that takes the place of "value". The function will be called at statement execution time to determine the ultimate value. Used for scenarios where the actual bind value cannot be determined at the point at which the clause construct is created, but embedded bind values are still desirable. :param type\_: A :class:`.TypeEngine` class or instance representing an optional datatype for this :func:`.bindparam`. If not passed, a type may be determined automatically for the bind, based on the given value; for example, trivial Python types such as ``str``, ``int``, ``bool`` may result in the :class:`.String`, :class:`.Integer` or :class:`.Boolean` types being automatically selected. The type of a :func:`.bindparam` is significant especially in that the type will apply pre-processing to the value before it is passed to the database. For example, a :func:`.bindparam` which refers to a datetime value, and is specified as holding the :class:`.DateTime` type, may apply conversion needed to the value (such as stringification on SQLite) before passing the value to the database. :param unique: if True, the key name of this :class:`.BindParameter` will be modified if another :class:`.BindParameter` of the same name already has been located within the containing expression. This flag is used generally by the internals when producing so-called "anonymous" bound expressions, it isn't generally applicable to explicitly-named :func:`.bindparam` constructs. :param required: If ``True``, a value is required at execution time. If not passed, it defaults to ``True`` if neither :paramref:`.bindparam.value` or :paramref:`.bindparam.callable` were passed. If either of these parameters are present, then :paramref:`.bindparam.required` defaults to ``False``. :param quote: True if this parameter name requires quoting and is not currently known as a SQLAlchemy reserved word; this currently only applies to the Oracle backend, where bound names must sometimes be quoted. :param isoutparam: if True, the parameter should be treated like a stored procedure "OUT" parameter. This applies to backends such as Oracle which support OUT parameters. :param expanding: if True, this parameter will be treated as an "expanding" parameter at execution time; the parameter value is expected to be a sequence, rather than a scalar value, and the string SQL statement will be transformed on a per-execution basis to accommodate the sequence with a variable number of parameter slots passed to the DBAPI. This is to allow statement caching to be used in conjunction with an IN clause. .. seealso:: :meth:`.ColumnOperators.in_` :ref:`baked_in` - with baked queries .. note:: The "expanding" feature does not support "executemany"- style parameter sets. .. versionadded:: 1.2 .. versionchanged:: 1.3 the "expanding" bound parameter feature now supports empty lists. .. seealso:: :ref:`coretutorial_bind_param` :ref:`coretutorial_insert_expressions` :func:`.outparam` Nrz [%\(\) \$]+_paramz %%(%d param)s) isinstancerr'r6r quoted_namerrresubstrip_identifying_key _orig_keyr0r3callabler5rm expandingcoerce_compared_valuer_resolve_value_to_type) rHr6r3r"r0rmquote callable_rr5rrrrr__init__sL a       zBindParameter.__init__cCs|}||_|S)zrReturn a copy of this :class:`.BindParameter` in the context of an expanding IN against a tuple. )r_expanding_in_types)rHtypesclonedrrr_with_expanding_in_typessz&BindParameter._with_expanding_in_typescCs6|}||_d|_d|_|jtjurt||_|S)zXReturn a copy of this :class:`.BindParameter` with the given value set. NF)rr3rrmr'rrr)rHr3r rrr _with_values  zBindParameter._with_valuecCs|jr|S|jS)zReturn the value of this bound parameter, taking into account if the ``callable`` parameter was set. The ``callable`` value will be evaluated and returned if present, else ``value``. )rr3rLrrreffective_values zBindParameter.effective_valuecCs0t|}|jrtdt||jpdf|_|S)Nrr)r=rr0rrrr6rGrrrrs zBindParameter._clonecCs0|jsd|_tdt||jpdf|_dSdS)NTrr)r0rrrr6rLrrrrns  z BindParameter._convert_to_uniquecKs0t|to|j|jo|j|jko|j|jkS)z@Compare this :class:`BindParameter` to the given clause.)rr2r'_compare_type_affinityr3rrwrrrrys    zBindParameter.comparecCs2|j}|j}|jr|}d|d<||d<|S)z4execute a deferred value for serialization purposes.Nrr3)r@rAr3r)rHrSvrrrrTs zBindParameter.__getstate__cCs<|ddrtdt||ddf|d<|j|dS)Nr0Frrrr6)rrrr@rurHstaterrr __setstate__s zBindParameter.__setstate__cCsd|j|j|jfS)NzBindParameter(%r, %r, type_=%r))r6r3r'rLrrrrs zBindParameter.__repr__)rrrrr_is_crudrr rr!r"rr#rrnryrTr(rrrrrr2s8     r2c@seZdZdZdZddZdS) TypeClausezTHandle a type keyword in a SQL statement. Used by the ``Case`` statement. typeclausecC ||_dSrr'rrrrr zTypeClause.__init__N)rrrrrrrrrrr*s r*c@seZdZdZdZedejZe j de iZ dZ ddZedd Zed d ZgZd ZZZdZd)d dZeejddddeddd d*ddZeddZedddZ eddZ!edd Z"d)d!d"Z#e$fd#d$Z%d%d&Z&d'd(Z'd S)+ TextClauseaURepresent a literal SQL text fragment. E.g.:: from sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t) The :class:`.Text` construct is produced using the :func:`.text` function; see that function for full documentation. .. seealso:: :func:`.text` textclausez(?.repl)_bindr4_bind_params_regexrtext)rHr9rpr6rrLrrOs zTextClause.__init__)z0.6zThe :paramref:`.text.autocommit` parameter is deprecated and will be removed in a future release. Please use the :paramref:`.Connection.execution_options.autocommit` parameter in conjunction with the :meth:`.Executable.execution_options` method.)rzThe :paramref:`.text.bindparams` parameter is deprecated and will be removed in a future release. Please refer to the :meth:`.TextClause.bindparams` method.)rzThe :paramref:`.text.typemap` parameter is deprecated and will be removed in a future release. Please refer to the :meth:`.TextClause.columns` method.)r1 bindparamstypemapr9z :func:`.text`z:paramref:`.text.text`cCsFt||d}|r |j|}|r|jdi|}|dur!|j|d}|S)aDConstruct a new :class:`.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:`.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("SELECT * FROM users WHERE name='\:username'") The :class:`.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:`.TextClause.bindparams` method is used to provide bound parameter detail, and :meth:`.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:`.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:`.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 it supports the :meth:`Executable.execution_options` method. For example, a :func:`.text` construct that should be subject to "autocommit" can be set explicitly so using the :paramref:`.Connection.execution_options.autocommit` option:: t = text("EXEC my_procedural_thing()").\ execution_options(autocommit=True) Note that SQLAlchemy's usual "autocommit" behavior applies to :func:`.text` constructs implicitly - that is, statements which begin with a phrase such as ``INSERT``, ``UPDATE``, ``DELETE``, or a variety of other phrases specific to certain backends, will be eligible for autocommit if no transaction is in progress. :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. :param autocommit: whether or not to set the "autocommit" execution option for this :class:`.TextClause` object. :param bind: an optional connection or engine to be used for this text query. :param bindparams: A list of :func:`.bindparam` instances used to provide information about parameters embedded in the statement. E.g.:: stmt = text("SELECT * FROM table WHERE id=:id", bindparams=[bindparam('id', value=5, type_=Integer)]) :param typemap: A dictionary mapping the names of columns represented in the columns clause of a ``SELECT`` statement to type objects. E.g.:: stmt = text("SELECT * FROM table", typemap={'id': Integer, 'name': String}, ) .. seealso:: :ref:`sqlexpression_text` - in the Core tutorial :ref:`orm_tutorial_literal_sql` - in the ORM tutorial roN)r1r)r/r:rexecution_options)rHr9rpr:r;r1stmtrrr _create_text[s   zTextClause._create_textc Os|j|_}|D]}z||j}Wnty"td|jw|||j<q |D] \}}z||}WntyEtd|w||||<q-dS)aiEstablish the values and/or types of bound parameters within this :class:`.TextClause` construct. Given a text construct such as:: from sqlalchemy import text stmt = text("SELECT id, name FROM user WHERE name=:name " "AND timestamp=:timestamp") the :meth:`.TextClause.bindparams` method can be used to establish the initial value of ``:name`` and ``:timestamp``, using simple keyword arguments:: stmt = stmt.bindparams(name='jack', timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)) Where above, new :class:`.BindParameter` objects will be generated with the names ``name`` and ``timestamp``, and values of ``jack`` and ``datetime.datetime(2012, 10, 8, 15, 12, 5)``, respectively. The types will be inferred from the values given, in this case :class:`.String` and :class:`.DateTime`. When specific typing behavior is needed, the positional ``*binds`` argument can be used in which to specify :func:`.bindparam` constructs directly. These constructs must include at least the ``key`` argument, then an optional value and type:: from sqlalchemy import bindparam stmt = stmt.bindparams( bindparam('name', value='jack', type_=String), bindparam('timestamp', type_=DateTime) ) Above, we specified the type of :class:`.DateTime` for the ``timestamp`` bind, and the type of :class:`.String` for the ``name`` bind. In the case of ``name`` we also set the default value of ``"jack"``. Additional bound parameters can be supplied at statement execution time, e.g.:: result = connection.execute(stmt, timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)) The :meth:`.TextClause.bindparams` method can be called repeatedly, where it will re-use existing :class:`.BindParameter` objects to add new information. For example, we can call :meth:`.TextClause.bindparams` first with typing information, and a second time with value information, and it will be combined:: stmt = text("SELECT id, name FROM user WHERE name=:name " "AND timestamp=:timestamp") stmt = stmt.bindparams( bindparam('name', type_=String), bindparam('timestamp', type_=DateTime) ) stmt = stmt.bindparams( name='jack', timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5) ) The :meth:`.TextClause.bindparams` method also supports the concept of **unique** bound parameters. These are parameters that are "uniquified" on name at statement compilation time, so that multiple :func:`.text` constructs may be combined together without the names conflicting. To use this feature, specify the :paramref:`.BindParameter.unique` flag on each :func:`.bindparam` object:: stmt1 = text("select id from table where name=:name").bindparams( bindparam("name", value='name1', unique=True) ) stmt2 = text("select id from table where name=:name").bindparams( bindparam("name", value='name2', unique=True) ) union = union_all( stmt1.columns(column("id")), stmt2.columns(column("id")) ) The above statement will render as:: select id from table where name=:name_1 UNION ALL select id from table where name=:name_2 .. versionadded:: 1.3.11 Added support for the :paramref:`.BindParameter.unique` flag to work with :func:`.text` constructs. z?This text() construct doesn't define a bound parameter named %rN)r4rArKeyErrorrrvitemsr")rHbindsnames_to_values new_paramsrpexistingr6r3rrrr:s0^    zTextClause.bindparamszsqlalchemy.sql.selectablecsBfdd|D}ddD}|j|||t|o| dS)aTurn this :class:`.TextClause` object into a :class:`.TextAsFrom` object that can be embedded into another statement. This function essentially bridges the gap between an entirely textual SELECT statement and the SQL expression language concept of a "selectable":: from sqlalchemy.sql import column, text stmt = text("SELECT id, name FROM some_table") stmt = stmt.columns(column('id'), column('name')).alias('st') stmt = select([mytable]). select_from( mytable.join(stmt, mytable.c.name == stmt.c.name) ).where(stmt.c.id > 5) Above, we pass a series of :func:`.column` elements to the :meth:`.TextClause.columns` method positionally. These :func:`.column` elements now become first class elements upon the :attr:`.TextAsFrom.c` column collection, just like any other selectable. The column expressions we pass to :meth:`.TextClause.columns` may also be typed; when we do so, these :class:`.TypeEngine` objects become the effective return type of the column, so that SQLAlchemy's result-set-processing systems may be used on the return values. This is often needed for types such as date or boolean types, as well as for unicode processing on some dialect configurations:: stmt = text("SELECT id, name, timestamp FROM some_table") stmt = stmt.columns( column('id', Integer), column('name', Unicode), column('timestamp', DateTime) ) for id, name, timestamp in connection.execute(stmt): print(id, name, timestamp) As a shortcut to the above syntax, keyword arguments referring to types alone may be used, if only type conversion is needed:: stmt = text("SELECT id, name, timestamp FROM some_table") stmt = stmt.columns( id=Integer, name=Unicode, timestamp=DateTime ) for id, name, timestamp in connection.execute(stmt): print(id, name, timestamp) The positional form of :meth:`.TextClause.columns` also provides the unique feature of **positional column targeting**, which is particularly useful when using the ORM with complex textual queries. If we specify the columns from our model to :meth:`.TextClause.columns`, the result set will match to those columns positionally, meaning the name or origin of the column in the textual SQL doesn't matter:: stmt = text("SELECT users.id, addresses.id, users.id, " "users.name, addresses.email_address AS email " "FROM users JOIN addresses ON users.id=addresses.user_id " "WHERE users.id = 1").columns( User.id, Address.id, Address.user_id, User.name, Address.email_address ) query = session.query(User).from_statement(stmt).options( contains_eager(User.addresses)) .. versionadded:: 1.1 the :meth:`.TextClause.columns` method now offers positional column targeting in the result set when the column expressions are passed purely positionally. The :meth:`.TextClause.columns` method provides a direct route to calling :meth:`.FromClause.alias` as well as :meth:`.SelectBase.cte` against a textual SELECT statement:: stmt = stmt.columns(id=Integer, name=String).cte('st') stmt = select([sometable]).where(sometable.c.id == stmt.c.id) .. versionadded:: 0.9.0 :func:`.text` can now be converted into a fully featured "selectable" construct using the :meth:`.TextClause.columns` method. cs.g|]}|jvrt|j|jn|qSr)r6rrR)rcolrrr s  z&TextClause.columns..cSsg|] \}}t||qSrr)rr6r"rrrrGs) positional)r@ TextAsFromr)rHrcolsrpositional_input_colskeyed_input_colsrrFrrds ^ zTextClause.columnscCrrrrLrrrr'rzTextClause.typecCs |j|Sr)r'rrLrrrrE zTextClause.comparatorcCs|tjur t|S|Sr)rin_oprrrrrr zTextClause.self_groupc s$tfdd|jD|_dS)Nc3s&|]}|j|fifVqdSr)r6)rbr\rrrrs z-TextClause._copy_internals..)dictr4rWr{rrRrr|szTextClause._copy_internalscKst|jSr)listr4rWr}rrrr~zTextClause.get_childrencCst|to |j|jkSr)rr/r9rrrrryzTextClause.comparerNNNN)(rrrrrrrUNICODEr8r _execution_optionsrr r rrrr _hide_fromsr6rr r r classmethodrdeprecated_paramsr r>rr:rrr'rErrr|r~ryrrrrr/sL      x x m     r/c@s6eZdZdZdZejddZeddZ ddZ d S) NullzRepresent the NULL keyword in a SQL statement. :class:`.Null` is accessed as a constant via the :func:`.null` function. nullcCrrrrLrrrr'rz Null.typecCtS)z+Return a constant :class:`.Null` construct.)r]clsrrr _instanceszNull._instancecC t|tSr)rr]rrrrryr.z Null.compareN) rrrrrrrr'r[rbryrrrrr]s   r]c@s>eZdZdZdZejddZddZe ddZ d d Z d S) False_zRepresent the ``false`` keyword, or equivalent, in a SQL statement. :class:`.False_` is accessed as a constant via the :func:`.false` function. falsecCrrrrrLrrrr'rz False_.typecCr_rTrue_rLrrrrzFalse_._negatecCr_)aReturn a :class:`.False_` construct. E.g.:: >>> from sqlalchemy import false >>> print select([t.c.x]).where(false()) SELECT x FROM t WHERE false A backend which does not support true/false constants will render as an expression against 1 or 0:: >>> print select([t.c.x]).where(false()) 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:: >>> print select([t.c.x]).where(or_(t.c.x > 5, true())) SELECT x FROM t WHERE true >>> print select([t.c.x]).where(and_(t.c.x > 5, false())) SELECT x FROM t WHERE false .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature better integrated behavior within conjunctions and on dialects that don't support true/false constants. .. seealso:: :func:`.true` rdr`rrrrb$zFalse_._instancecCrcr)rrdrrrrry;r.zFalse_.compareN) rrrrrrrr'rr[rbryrrrrrds   %rdc@sJeZdZdZdZejddZddZe ddZ e d d Z d d Z d S)rhzRepresent the ``true`` keyword, or equivalent, in a SQL statement. :class:`.True_` is accessed as a constant via the :func:`.true` function. truecCrrrfrLrrrr'Irz True_.typecCr_rrjrLrrrrMriz True_._negatecCs|dur|S|Sr)rb)rarxrrr_ifnonePsz True_._ifnonecCr_)aReturn a constant :class:`.True_` construct. E.g.:: >>> from sqlalchemy import true >>> print select([t.c.x]).where(true()) SELECT x FROM t WHERE true A backend which does not support true/false constants will render as an expression against 1 or 0:: >>> print select([t.c.x]).where(true()) 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:: >>> print select([t.c.x]).where(or_(t.c.x > 5, true())) SELECT x FROM t WHERE true >>> print select([t.c.x]).where(and_(t.c.x > 5, false())) SELECT x FROM t WHERE false .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature better integrated behavior within conjunctions and on dialects that don't support true/false constants. .. seealso:: :func:`.false` rgr`rrrrbWrkzTrue_._instancecCrcr)rrhrrrrry}r.z True_.compareN) rrrrrrrr'rr[rmrbryrrrrrh?s    %rhc@sreZdZdZdZddZddZddZed d Z d d Z e fd dZ ddZ eddZdddZddZdS) ClauseListzzDescribe a list of clauses, separated by an operator. By default, is comma-separated, such as a column listing. clauselistcs|dtj_|dd_|dd_|dd_|dtjr2fdd |D_n fd d |D_t j_ dS) Nrr3Tgroup_contents _tuple_valuesF_literal_as_textcsg|] }|jjdqSr)rrrr:rHtext_converterrrrGsz'ClauseList.__init__..csg|]}|qSrrrt)rvrrrG) rRrcomma_oprr3rprq_expression_literal_as_textclauses is_booleanr )rHrzrjrrurrs  zClauseList.__init__cC t|jSr)iterrzrLrrr__iter__r.zClauseList.__iter__cCr|r)rtrzrLrrr__len__r.zClauseList.__len__cCt|Sr)r}rLrrrrzClauseList._select_iterablecCs8|jr|jt|j|jddS|jt|dSNr)rprzappendrrrr)rHr:rrrrs zClauseList.appendc sfdd|jD|_dS)Ncsg|] }|fiqSrrrtrRrrrGsz.ClauseList._copy_internals..rzr{rrRrr|szClauseList._copy_internalscKrJrrr}rrrr~rizClauseList.get_childrencCsttjdd|jDS)NcSg|]}|jqSrrrrrrrGz,ClauseList._from_objects..)rT itertoolschainrzrLrrrrszClauseList._from_objectsNcCs |jrt|j|rt|S|Sr)r3r is_precedentrrrrrrrzClauseList.self_groupcKst|tst|jdkr|jdj|fi|St|trt|jt|jkr|j|jur|jtjtjfvrct }|jD]}t |j |D]}|j|fi|rX| |nqFq.rrrcsg|]}|jdqSrs)rrrrrrGs T)rcoerce_generator_argrrrrrrtr?rzr3rrprrr'r ) rar continue_onskip_onrzrconvert_clausesr:rHrrr _constructs2      zBooleanClauseList._constructcG|jtjttg|RS)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:`.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) .. seealso:: :func:`.or_` )rrrrhrdrarzrrrr s'zBooleanClauseList.and_cGr)adProduce 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') ) .. seealso:: :func:`.and_` )rrrrdrhrrrrr4szBooleanClauseList.or_cCrrrrLrrrrTrz"BooleanClauseList._select_iterableNcs|js|Stt|j|dSr)rzrrrrrKrrrXszBooleanClauseList.self_groupcCs t|Sr)rnrrLrrrr^r.zBooleanClauseList._negater)rrrrrqrr[rrrrrrrr rrrKrrs " (  rcs6eZdZdZfddZeddZd ddZZS) TuplezRepresent a SQL tuple.csXdd|D}dd|D|_|d|jr|jdntj|_tt|j|i|dS)aReturn 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. cSrr)r#rrrrrGrwz"Tuple.__init__..cSrrr-)rrrrrrGrr"rN) _type_tuplerRrrr'rrr)rHrzrrKrrriszTuple.__init__cCrrrrLrrrrrzTuple._select_iterableNcs$tfddt||jDS)Nc s$g|]\}}td||ddqS)NT)rrr0r"r1)rocompared_to_typerr"rrrGs z%Tuple._bind_param..)rziprrrrrrrs   zTuple._bind_paramr) rrrrrrrrr rrrKrrfs  ! rc@s>eZdZdZdZd ddZefddZdd Ze d d Z dS) CaseaRepresent a ``CASE`` expression. :class:`.Case` is produced using the :func:`.case` factory function, as in:: from sqlalchemy import case stmt = select([users_table]). where( case( [ (users_table.c.name == 'wendy', 'W'), (users_table.c.name == 'jack', 'J') ], else_='E' ) ) Details on :class:`.Case` usage is at :func:`.case`. .. seealso:: :func:`.case` caseNcCszt|}Wn tyYnw|durdd|D}ndd|D}|r0t|ddj}nd}|dur:d|_nt||_||_||_|durPt||_dSd|_dS)aProduce a ``CASE`` expression. The ``CASE`` construct in SQL is a conditional object that acts somewhat analogously to an "if/then" construct in other languages. It returns an instance of :class:`.Case`. :func:`.case` in its usual form is passed a list of "when" constructs, that is, a list of conditions and results as tuples:: from sqlalchemy import case stmt = select([users_table]).\ where( case( [ (users_table.c.name == 'wendy', 'W'), (users_table.c.name == 'jack', 'J') ], else_='E' ) ) The above statement will produce SQL resembling:: SELECT id, name FROM user WHERE CASE WHEN (name = :name_1) THEN :param_1 WHEN (name = :name_2) THEN :param_2 ELSE :param_3 END When simple equality expressions of several values against a single parent column are needed, :func:`.case` also has a "shorthand" format used via the :paramref:`.case.value` parameter, which is passed a column expression to be compared. In this form, the :paramref:`.case.whens` parameter is passed as a dictionary containing expressions to be compared against keyed to result expressions. The statement below is equivalent to the preceding statement:: stmt = select([users_table]).\ where( case( {"wendy": "W", "jack": "J"}, value=users_table.c.name, else_='E' ) ) The values which are accepted as result values in :paramref:`.case.whens` as well as with :paramref:`.case.else_` are coerced from Python literals into :func:`.bindparam` constructs. SQL expressions, e.g. :class:`.ColumnElement` constructs, are accepted as well. To coerce a literal string expression into a constant expression rendered inline, use the :func:`.literal_column` construct, as in:: from sqlalchemy import case, literal_column case( [ ( orderline.c.qty > 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. In the first form, it accepts a list of 2-tuples; 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. NcSs$g|]\}}t|t|fqSr)r#rrrIrrrrrG: z!Case.__init__..cSs$g|]\}}t|t|fqSr) _no_literalsrr#rrrrrG? r) rdictlike_iteritemsrrTr'r3r#whenselse_)rHrr3rwhenlistr"rrrrs.y   z Case.__init__c s\|jdur|jfi|_fdd|jD|_|jdur,|jfi|_dSdS)Ncs0g|]\}}|fi|fifqSrr)rxyrRrrrGX s0z(Case._copy_internals..r3rrr{rrRrr|U s  zCase._copy_internalscksJ|jdur |jV|jD] \}}|V|Vq |jdur#|jVdSdSrr)rHrjrrrrrr~\ s   zCase.get_childrencCsttjdd|DS)NcSrrrrrrrrrGh rz&Case._from_objects..)rTrrr~rLrrrre szCase._from_objectsr rrrrrrrr|r~rrrrrrrs   rcCst||ddS)a3Produce a :class:`.ColumnClause` object that has the :paramref:`.column.is_literal` flag set to True. :func:`.literal_column` is similar to :func:`.column`, except that it is more often used as a "standalone" column expression that renders exactly as stated; while :func:`.column` stores a string name that will be assumed to be part of a table and may be quoted as such, :func:`.literal_column` can be that, or any other arbitrary column-oriented expression. :param text: the text of the expression; can be any SQL expression. Quoting rules will not be applied. To specify a column-name expression which should be subject to quoting rules, use the :func:`column` function. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` object which will provide result-set translation and additional expression semantics for this column. If left as None the type will be NullType. .. seealso:: :func:`.column` :func:`.text` :ref:`sqlexpression_literal_column` T)r" is_literalrH)r9r"rrrliteral_columnl src@<eZdZdZdZddZefddZddZe d d Z d S) ra`Represent a ``CAST`` expression. :class:`.Cast` is produced using the :func:`.cast` factory function, as in:: from sqlalchemy import cast, Numeric stmt = select([ cast(product_table.c.unit_price, Numeric(10, 4)) ]) Details on :class:`.Cast` usage is at :func:`.cast`. .. seealso:: :ref:`coretutorial_casts` :func:`.cast` :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. rcCs,t||_t||jd|_t|j|_dS)aProduce 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. .. versionchanged:: 0.9.0 :func:`.cast` now applies the given type to the expression such that it takes effect on the bound-value, e.g. the Python-to-database direction, in addition to the result handling, e.g. database-to-Python, direction. 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:`.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:`coretutorial_casts` :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. r!N)r to_instancer'r#r:r*r+rHr(r"rrrr s 5z Cast.__init__cK,||jfi||_||jfi||_dSrr:r+r{rrrr| zCast._copy_internalscK |j|jfSrrr}rrrr~  zCast.get_childrencC|jjSrr:rrLrrrr rzCast._from_objectsNrrrrrr s 9rc@sJeZdZdZdZddZefddZddZe d d Z e j d d Z d S) TypeCoerceaRepresent a Python-side type-coercion wrapper. :class:`.TypeCoerce` supplies the :func:`.expression.type_coerce` function; see that function for usage details. .. versionchanged:: 1.1 The :func:`.type_coerce` function now produces a persistent :class:`.TypeCoerce` wrapper object rather than translating the given object in place. .. seealso:: :func:`.expression.type_coerce` :func:`.cast` type_coercecCs t||_t||jd|_dS)aL 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 renders SQL that labels the expression, but otherwise does not modify its value on the SQL side:: SELECT date_string AS anon_1 FROM log When result rows are fetched, the ``StringDateTime`` type will be applied to result rows on behalf of the ``date_string`` column. The rationale for the "anon_1" label is so that the type-coerced column remains separate in the list of result columns vs. other type-coerced or direct values of the target column. In order to provide a named label for the expression, use :meth:`.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)]) :func:`.type_coerce` is similar to the :func:`.cast` function, except that it does not render the ``CAST`` expression in the resulting statement. :param expression: A SQL expression, such as a :class:`.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:`coretutorial_casts` :func:`.cast` r!N)rrr'r#r:rrrrr s ?zTypeCoerce.__init__cKs&||jfi||_|jdddS)Ntyped_expression)r:r@rRr{rrrr|D szTypeCoerce._copy_internalscK|jfSrr9r}rrrr~H rzTypeCoerce.get_childrencCrrrrLrrrrK rzTypeCoerce._from_objectscCs(t|jtr|j}|j|_|S|jSr)rr:r2rr')rHbprrrrO s  zTypeCoerce.typed_expressionN)rrrrrrrr|r~rrrrrrrrrr s B rc@r) Extractz=Represent a SQL EXTRACT clause, ``extract(field FROM expr)``.extractcKstj|_||_t|d|_dS)zReturn a :class:`.Extract` construct. This is typically available as :func:`.extract` as well as ``func.extract`` from the :data:`.func` namespace. N)r INTEGERTYPEr'fieldr#r*)rHrr*rjrrrr^ szExtract.__init__cK||jfi||_dSrr*r{rrrr|j rzExtract._copy_internalscKrrrr}rrrr~m rzExtract.get_childrencCrr)r*rrLrrrrp rzExtract._from_objectsNrrrrrrY s rc@s4eZdZdZdZddZefddZeddZ d S) _label_referenceaWrap a column expression as it appears in a 'reference' context. This expression is any that includes an _order_by_label_element, which is a Label, or a DESC / ASC construct wrapping a Label. The production of _label_reference() should occur when an expression is added to this context; this includes the ORDER BY or GROUP BY of a SELECT statement, as well as a few other places, such as the ORDER BY within an OVER clause. label_referencecCr,rrrHrrrrr r.z_label_reference.__init__cKrrrr{rrrr| rz _label_reference._copy_internalscCrz)NrrrLrrrr z_label_reference._from_objectsN) rrrrrrrr|rrrrrrru s  rc@s&eZdZdZddZejddZdS)_textual_label_referencetextual_label_referencecCr,rrrrrrr r.z!_textual_label_reference.__init__cC t|jSr)r/r>rrLrrr _text_clause rNz%_textual_label_reference._text_clauseN)rrrrrrrrrrrrr s rc@seZdZdZdZ     dddZeddZed d Zed d Z ed dZ eddZ e ddZ e ddZefddZddZddZddZd ddZdS)!raDefine a 'unary' expression. A unary expression has a single column expression and an operator. The operator can be placed on the left (where it is called the 'operator') or right (where it is called the 'modifier') of the column expression. :class:`.UnaryExpression` is the basis for several unary operators including those used by :func:`.desc`, :func:`.asc`, :func:`.distinct`, :func:`.nullsfirst` and :func:`.nullslast`. unaryNFcCs>||_||_|j|jp |jd|_t||_||_||_dSr) rmodifierrrrrr'rwraps_column_expression)rHrrrr"rrrrrr s    zUnaryExpression.__init__cCtt|tjddS)aZProduce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression. :func:`.nullsfirst` 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, nullsfirst stmt = select([users_table]). order_by(nullsfirst(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:`.nullsfirst` is typically invoked from the column expression itself using :meth:`.ColumnElement.nullsfirst`, rather than as its standalone function version, as in:: stmt = (select([users_table]). order_by(users_table.c.name.desc().nullsfirst()) ) .. seealso:: :func:`.asc` :func:`.desc` :func:`.nullslast` :meth:`.Select.order_by` Frr)r_literal_as_label_referencer nullsfirst_opracolumnrrr_create_nullsfirst s &z"UnaryExpression._create_nullsfirstcCr)a?Produce the ``NULLS LAST`` modifier for an ``ORDER BY`` expression. :func:`.nullslast` 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, nullslast stmt = select([users_table]). order_by(nullslast(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:`.nullslast` is typically invoked from the column expression itself using :meth:`.ColumnElement.nullslast`, rather than as its standalone function version, as in:: stmt = select([users_table]). order_by(users_table.c.name.desc().nullslast()) .. seealso:: :func:`.asc` :func:`.desc` :func:`.nullsfirst` :meth:`.Select.order_by` Fr)rrr nullslast_oprrrr_create_nullslast s %z!UnaryExpression._create_nullslastcCr)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:`.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:`.ColumnElement` (e.g. scalar SQL expression) with which to apply the :func:`.desc` operation. .. seealso:: :func:`.asc` :func:`.nullsfirst` :func:`.nullslast` :meth:`.Select.order_by` Fr)rrrdesc_oprrrr _create_desc s #zUnaryExpression._create_desccCr)a!Produce an ascending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import asc stmt = select([users_table]).order_by(asc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name ASC The :func:`.asc` function is a standalone version of the :meth:`.ColumnElement.asc` method available on all SQL expressions, e.g.:: stmt = select([users_table]).order_by(users_table.c.name.asc()) :param column: A :class:`.ColumnElement` (e.g. scalar SQL expression) with which to apply the :func:`.asc` operation. .. seealso:: :func:`.desc` :func:`.nullsfirst` :func:`.nullslast` :meth:`.Select.order_by` Fr)rrrasc_oprrrr _create_asc< s "zUnaryExpression._create_asccCst|}t|tj|jddS)asProduce an column-expression-level unary ``DISTINCT`` clause. This applies the ``DISTINCT`` keyword to an individual column expression, and is typically contained within an aggregate function, as in:: from sqlalchemy import distinct, func stmt = select([func.count(distinct(users_table.c.name))]) The above would produce an expression resembling:: SELECT COUNT(DISTINCT name) FROM user The :func:`.distinct` function is also available as a column-level method, e.g. :meth:`.ColumnElement.distinct`, as in:: stmt = select([func.count(users_table.c.name.distinct())]) The :func:`.distinct` operator is different from the :meth:`.Select.distinct` method of :class:`.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:`.ColumnElement.distinct` :meth:`.Select.distinct` :data:`.func` Frr"r)r#rr distinct_opr'rar*rrr_create_distinctd s$z UnaryExpression._create_distinctcCs|jtjtjfvr |jjSdSr)rrrrrrrLrrrr sz'UnaryExpression._order_by_label_elementcCrrrrrLrrrr rzUnaryExpression._from_objectscKrrrr{rrrr| rzUnaryExpression._copy_internalscKrrrr}rrrr~ rzUnaryExpression.get_childrencKs8t|to|j|jko|j|jko|jj|jfi|S)zXCompare this :class:`UnaryExpression` against the given :class:`.ClauseElement`.)rrrrrryrwrrrry s   zUnaryExpression.comparecCsf|jdurt|j|j|j|j|j|jdS|jjtj jur.t|j t j dt j tj |jddSt |S)N)rrrr"rr)rr"rr)rrrrrr'rrrrrrr8r=rrLrrrr s$   zUnaryExpression._negatecCs |jrt|j|rt|S|Sr)rrrrrrrrr rzUnaryExpression.self_group)NNNNFr)rrrrrrr[rrrrrrrrrr|r~ryrrrrrrr s8   + * ( ' +    rc@s8eZdZdZeddZeddZddZdd Zd S) CollectionAggregatea Forms the basis for right-hand collection operator modifiers ANY and ALL. The ANY and ALL keywords are available in different ways on different backends. On PostgreSQL, they only work for an ARRAY type. On MySQL, they only work for subqueries. cC<t|}|jrt|dr|}|}t|tjtj ddS)aProduce an ANY expression. This may apply to an array type for some dialects (e.g. postgresql), or to a subquery for others (e.g. mysql). e.g.:: # postgresql '5 = ANY (somearray)' expr = 5 == any_(mytable.c.somearray) # mysql '5 = ANY (SELECT value FROM table)' expr = 5 == any_(select([table.c.value])) .. versionadded:: 1.1 .. seealso:: :func:`.expression.all_` as_scalarFr) r#rrrrrrrrrrrrr _create_any szCollectionAggregate._create_anycCr)aProduce an ALL expression. This may apply to an array type for some dialects (e.g. postgresql), or to a subquery for others (e.g. mysql). e.g.:: # postgresql '5 = ALL (somearray)' expr = 5 == all_(mytable.c.somearray) # mysql '5 = ALL (SELECT value FROM table)' expr = 5 == all_(select([table.c.value])) .. versionadded:: 1.1 .. seealso:: :func:`.expression.any_` rFr) r#rrrrrrrrrrrrr _create_all szCollectionAggregate._create_allcOs<t|s tdd|d<|jjt|g|Ri|S)N2Only comparison operators may be used with ANY/ALLTreverse)r is_comparisonrrvrErmirrorrrrrr s  zCollectionAggregate.operatecKst|rJtd)Nr)rrrrvrrrrr sz#CollectionAggregate.reverse_operateN) rrrrr[rrrrrrrrr s  " rc@s&eZdZddZdddZddZdS) rcCs2||_tj|_||_||_d|_d|_|j|_dS)NT) rrrr'rrrrr )rHrrrrrrr' s zAsBoolean.__init__NcCrrrrrrrr0 zAsBoolean.self_groupcCs,t|jttfr |jSt|j|j|jSr)rrrhrdrrrrrLrrrr3 s zAsBoolean._negater)rrrrrrrrrrr& s rcseZdZdZdZdZ dddZddZeZe d d Z e d d Z e fd dZ ddZddZdddZfddZZS)r$aRepresent an expression that is ``LEFT RIGHT``. A :class:`.BinaryExpression` is generated automatically whenever two column expressions are used in a Python binary expression:: >>> from sqlalchemy.sql import column >>> column('a') + column('b') >>> print column('a') + column('b') a + b binaryTNcCs|t|tjr t|}||f|_|j|d|_|j|d|_||_ t ||_ ||_ t||_|dur9i|_dS||_dSr)rr string_typesr custom_op_origrleftrightrrrr'rr{r  modifiers)rHrrrr"rrrrrrP s       zBinaryExpression.__init__cCs:|jtjtjfvr|t|jdt|jdStd)Nrrr)reqnerrrrLrrrrd s zBinaryExpression.__bool__cCrr)rrrrLrrrrl rNzBinaryExpression.is_comparisoncCs|jj|jjSr)rrrrLrrrrp zBinaryExpression._from_objectscKrrrrr{rrrr|t rz BinaryExpression._copy_internalscKrrrr}rrrr~x rzBinaryExpression.get_childrencKszt|to<|j|jko<|jj|jfi|r!|jj|jfi|p.rrrr}rrrr~ szOver.get_childrencKsX||jfi||_|jdur||jfi||_|jdur*||jfi||_dSdSrrr{rrrr| s   zOver._copy_internalscCs$ttjdd|j|j|jfDS)NcSg|] }|dur|jqSrrrrrrrG z&Over._from_objects..)rTrrrrrrLrrrr szOver._from_objectsrW)rrrrrrrrrrrrrrrr'r~rr|rrrrrr s,  m    rc@sXeZdZdZdZdZddZdddZej dd Z d d Z e fd d Z eddZdS) WithinGroupaRepresent a WITHIN GROUP (ORDER BY) clause. This is a special operator against so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including ``percentile_cont()``, ``rank()``, ``dense_rank()``, etc. It's supported only by certain database backends, such as PostgreSQL, Oracle and MS SQL Server. The :class:`.WithinGroup` construct extracts its type from the method :meth:`.FunctionElement.within_group_type`. If this returns ``None``, the function's ``.type`` is used. withingroupNcGs,||_|durtt|dti|_dSdS)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. .. versionadded:: 1.1 .. seealso:: :data:`.expression.func` :func:`.expression.over` Nrr)rrnrrrr)rHrrrrrr s$ zWithinGroup.__init__cCt|||||dS)zProduce an OVER clause against this :class:`.WithinGroup` construct. This function has the same signature as that of :meth:`.FunctionElement.over`. rrrrrrHrrrrrrrrszWithinGroup.overcCs |j|}|dur |S|jjSr)rwithin_group_typer')rHwgtrrrr's zWithinGroup.typecKdd|j|jfDS)NcSrrrrrrrrGz,WithinGroup.get_children..rrr}rrrr~rVzWithinGroup.get_childrencK:||jfi||_|jdur||jfi||_dSdSrr+r{rrrr| zWithinGroup._copy_internalscC ttjdd|j|jfDS)NcSrrrrrrrrG&r z-WithinGroup._from_objects..)rTrrrrrLrrrr" zWithinGroup._from_objectsrW)rrrrrrrrrrr'r~rr|rrrrrrr! s +  r!c@sjeZdZdZdZdZddZddZddd Zdd d Z e j d d Z ddZ efddZeddZdS)FunctionFilteraRepresent a function FILTER clause. This is a special operator against aggregate and window functions, which controls which rows are passed to it. It's supported only by certain database backends. Invocation of :class:`.FunctionFilter` is via :meth:`.FunctionElement.filter`:: func.count(1).filter(True) .. versionadded:: 1.0.0 .. seealso:: :meth:`.FunctionElement.filter` funcfilterNcGs||_|j|dS)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. .. versionadded:: 1.0.0 .. seealso:: :meth:`.FunctionElement.filter` N)rfilter)rHr criterionrrrrGszFunctionFilter.__init__cGs8t|D]}t|}|jdur|j|@|_q||_q|S)a Produce an additional FILTER against the function. This method adds additional criteria to the initial criteria set up by :meth:`.FunctionElement.filter`. Multiple criteria are joined together at SQL render time via ``AND``. N)rTryr3)rHr3rrrr2bs  zFunctionFilter.filtercCr#)aProduce an OVER clause against this filtered function. Used against aggregate or so-called "window" functions, for database backends that support window functions. The expression:: func.rank().filter(MyClass.y > 5).over(order_by='x') is shorthand for:: from sqlalchemy import over, funcfilter over(funcfilter(func.rank(), MyClass.y > 5), order_by='x') See :func:`~.expression.over` for a full description. r$r%r&rrrrxszFunctionFilter.overcCsttj|r t|S|Sr)rr filter_oprrrrrrrzFunctionFilter.self_groupcCrr)rr'rLrrrr'rzFunctionFilter.typecKr))NcSrrrrrrrrGr*z/FunctionFilter.get_children..rr3r}rrrr~rVzFunctionFilter.get_childrencKr,rr5r{rrrr|r-zFunctionFilter._copy_internalscCr.)NcSrrrrrrrrGr z0FunctionFilter._from_objects..)rTrrrr3rLrrrrr/zFunctionFilter._from_objectsrWr)rrrrrr3rr2rrrrr'r~rr|rrrrrrr0/s    r0c@seZdZdZdZd%ddZddZejdd Z ejd d Z e d d Z ejddZ ejddZd%ddZddZddZe ddZe ddZddZedfdd Ze d!d"Zd%d#d$ZdS)&rzRepresents a column label (AS). Represent a label, as typically applied to any column-level element using the ``AS`` sql keyword. rNcCst|tr |j|_t|tr|j}t|ts|r ||_|j|_ntdt|t|ddf|_|j|_ |_|_ ||_ ||_ |g|_ dS)aReturn a :class:`Label` object for the given :class:`.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:`.ColumnElement.label` method on :class:`.ColumnElement`. :param name: label name :param obj: a :class:`.ColumnElement`. rrrN)rrrr rrrrrr6r_element_typer)rHrrr"rrrrs     zLabel.__init__cCs|j|j|j|jffSr)r>rr6r7rLrrr __reduce__rVzLabel.__reduce__cCrrr rLrrrr rzLabel._is_implicitly_booleancCrr)rr rLrrrr rzLabel._allow_label_resolvecCrrrrLrrrrrzLabel._order_by_label_elementcCst|jp t|jddSr )rrr7rr6rLrrrr'sz Label.typecCs|jjtjdSr)r6rras_rLrrrrrz Label.elementcCs|j|jj|dSr)_apply_to_innerr6rrrrrrzLabel.self_groupcCs||jjSr)r:r6rrLrrrrrUz Label._negatecOs.||i|}||jurt|j||jdS|S)Nr!)r6rrr7)rHfnrr sub_elementrrrr:s zLabel._apply_to_innercCrr)rrrLrrrrrzLabel.primary_keycCrr)rrrLrrrrrzLabel.foreign_keyscKrrrr}rrrr~ rzLabel.get_childrenFcKsv||jfi||_|jdd|jdd|r9tdt|t|jddf|_|_|j|_ |_ |_ dSdS)Nrr rrr) r6r@rRrrrrrr r6rr)rHr\anonymize_labelsrrrrr|s zLabel._copy_internalscCrrrrLrrrrrzLabel._from_objectscKs>|jj||r|n|jdd}|j||jdur|j|_|S)NT)rdisallow_is_literal)rrrrrr7r')rHrrrerrrrs   zLabel._make_proxyr)rrrrrrr8rrr r rrr'rrrr:rrr~rr|rrrrrrrs6 #         rc@seZdZdZdZdZZZZdZ e Z d ddZ ddZd d Zd d ZeeeZe d dZe jddZe ddZe ddZe ddZeddZd!ddZd"ddZ    d#ddZdS)$raRepresents a column expression from any textual string. The :class:`.ColumnClause`, a lightweight analogue to the :class:`.Column` class, is typically invoked using the :func:`.column` function, 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 :class:`.ColumnClause` is the immediate superclass of the schema-specific :class:`.Column` object. While the :class:`.Column` class has all the same capabilities as :class:`.ColumnClause`, the :class:`.ColumnClause` class is usable by itself in those cases where behavioral requirements are limited to simple SQL expression generation. The object has none of the associations with schema-level metadata or with execution-time behavior that :class:`.Column` does, so in that sense is a "lightweight" version of :class:`.Column`. Full details on :class:`.ColumnClause` usage is at :func:`.column`. .. seealso:: :func:`.column` :class:`.Column` rNFcCs(||_|_||_t||_||_dS)aC Produce a :class:`.ColumnClause` object. The :class:`.ColumnClause` is a lightweight analogue to the :class:`.Column` class. The :func:`.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:`.column` may be used like any other SQL expression element such as within :func:`.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:`.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:`.literal_column` instead, or pass ``True`` as the value of :paramref:`.column.is_literal`. Additionally, full SQL statements are best handled using the :func:`.text` construct. :func:`.column` can be used in a table-like fashion by combining it with the :func:`.table` function (which is the lightweight analogue to :class:`.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:`.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:`.Table` counterpart. .. versionchanged:: 1.0.0 :func:`.expression.column` can now be imported from the plain ``sqlalchemy`` namespace like any other SQL element. :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:`.literal_column()` function essentially invokes :func:`.column` while passing ``is_literal=True``. .. seealso:: :class:`.Column` :func:`.literal_column` :func:`.table` :func:`.text` :ref:`sqlexpression_literal_column` N)r6rtablerrr'r)rHr9r"rrrrrrUs S  zColumnClause.__init__cCs~|js"|jdus"|jjs"t|dr"t|tr8|js"|jdus"|jjr8t|dr-|j|jkp7t|do7|j|jkS|j |jS)Nrrr) rrA_textualrrrrrrrrrrrrs$  z%ColumnClause._compare_name_for_resultcCs |jdSNrA)r@rLrrr _get_tabler.zColumnClause._get_tablecCs|j|||jd<dSrC)_memoized_propertyexpire_instancer@)rHrArrr _set_tables zColumnClause._set_tablecCs|j}|dur |gSgSrrA)rHtrrrrszColumnClause._from_objectscCstjr|jS|jddSr)rrrrrLrrrrszColumnClause.descriptioncCs|j|jkr ||jS|jSr)r6r _gen_labelrrLrrrrs  zColumnClause._key_labelcCs ||jSrrJrrLrrrrrNzColumnClause._labelcCs |jduSrrHrLrrrrr2z,ColumnClause._render_label_in_columns_clausecCs|j|jddS)NF) dedupe_on_keyrKrLrrr _ddl_labelrzColumnClause._ddl_labelTcCs |j}|jrdS|dur|jrt|ddr&|jddd|jd|}n|jd|}t|dddurFt|tr?|j |_ nt||j }nt|jdddur]t|trVJt||jj }|r||j vr|}d}||j vr~|dt |}|d7}||j vsm|}t |S|S)Nschema.rrr) rArnamed_with_columnrrNreplacerrrrrIrr)rHrrLrIrrcounterrrrrJs2 "     zColumnClause._gen_labelcCst|j|||j|ddS)NT)rrr"r0)r2r6r'rrrrrszColumnClause._bind_paramc Ks| o|jo|dup||jk}|j|rt|p|jn|p|j|j||d}|dur-|j|_|g|_|jdur?|jj |j|_|rG||j |j<|S)N)r"rr) rrrMrr'r6rrFrrr) rHrrattachrr?rrrIrrrr%s,   zColumnClause._make_proxy)NFN)Tr)NTFF)rrrrronupdaterserver_defaultserver_onupdate_is_multiparam_columnr!group_expirable_memoized_propertyrErrrDrGrrArrrrrrrMrJrrrrrrr*s<" X         . rc@seZdZdZddZdS)r%r)cCr,r)r))rHr)rrrrTr.zCollationClause.__init__N)rrrrrrrrrr%Qs r%c@s(eZdZdZejddiZddZdS)_IdentifiedClause identifiedr1FcCr,r)ident)rHr[rrrr_r.z_IdentifiedClause.__init__N)rrrrr rYrrrrrrrYXs  rYc@r)SavepointClause savepointNrrrrrrrrr\cr\c@r)RollbackToSavepointClauserollback_to_savepointNr^rrrrr`gr_r`c@r)ReleaseSavepointClauserelease_savepointNr^rrrrrbkr_rbcsDeZdZdZdZfddZddZddZd d Zd d Z Z S) raRepresent a SQL identifier combined with quoting preferences. :class:`.quoted_name` is a Python unicode/str subclass which represents a particular identifier name along with a ``quote`` flag. This ``quote`` flag, when set to ``True`` or ``False``, overrides automatic quoting behavior for this identifier in order to either unconditionally quote or to not quote the name. If left at its default of ``None``, quoting behavior is applied to the identifier on a per-backend basis based on an examination of the token itself. A :class:`.quoted_name` object with ``quote=True`` is also prevented from being modified in the case of a so-called "name normalize" option. Certain database backends, such as Oracle, Firebird, and DB2 "normalize" case-insensitive names as uppercase. The SQLAlchemy dialects for these backends convert from SQLAlchemy's lower-case-means-insensitive convention to the upper-case-means-insensitive conventions of those backends. The ``quote=True`` flag here will prevent this conversion from occurring to support an identifier that's quoted as all lower case against such a backend. The :class:`.quoted_name` object is normally created automatically when specifying the name for key schema constructs such as :class:`.Table`, :class:`.Column`, and others. The class can also be passed explicitly as the name to any function that receives a name which can be quoted. Such as to use the :meth:`.Engine.has_table` method with an unconditionally quoted name:: from sqlalchemy import create_engine from sqlalchemy.sql import quoted_name engine = create_engine("oracle+cx_oracle://some_dsn") engine.has_table(quoted_name("some_table", True)) The above logic will run the "has table" logic against the Oracle backend, passing the name exactly as ``"some_table"`` without converting to upper case. .. versionadded:: 0.9.0 .. versionchanged:: 1.2 The :class:`.quoted_name` construct is now importable from ``sqlalchemy.sql``, in addition to the previous location of ``sqlalchemy.sql.elements``. )rrrcsH|durdSt||r|dus|j|kr|Stt|||}||_|Sr)rrrrr?)rar3rrHrKrrr?s zquoted_name.__new__cCstt||jffSr)rr text_typerrLrrrr8rzquoted_name.__reduce__cC|jr|St|Sr)rrrdrrLrrr_memoized_method_lowerz"quoted_name._memoized_method_lowercCrer)rrrdrrLrrr_memoized_method_upperrgz"quoted_name._memoized_method_uppercCs4tjr|dd}tjs|d}d|St|S)Nrrz'%s')rpy2krdecoderr)rH backslashedrrrrs    zquoted_name.__repr__) rrrr __slots__r?r8rfrhrr rrrKrros/ rcs6eZdZdZdZd fdd ZddZdd ZZS) _truncated_labelzVA unicode subclass used to identify symbolic " "names that may require truncation.rNcs t|d|}tt||||S)Nr)rrrmr?)rar3rrKrrr?s z_truncated_label.__new__cCs|jt||jffSr)r>rrdrrLrrrr8rVz_truncated_label.__reduce__cCrrrrHmap_rrr apply_maprz_truncated_label.apply_mapr) rrrrrlr?r8rpr rrrKrrms rmc@eZdZdZdZdS)convaMark a string indicating that a name has already been converted by a naming convention. This is a string subclass that indicates a name that should not be subject to any further naming conventions. E.g. when we create a :class:`.Constraint` using a naming convention as follows:: m = MetaData(naming_convention={ "ck": "ck_%(table_name)s_%(constraint_name)s" }) t = Table('t', m, Column('x', Integer), CheckConstraint('x > 5', name='x5')) The name of the above constraint will be rendered as ``"ck_t_x5"``. That is, the existing name ``x5`` is used in the naming convention as the ``constraint_name`` token. In some situations, such as in migration scripts, we may be rendering the above :class:`.CheckConstraint` with a name that's already been converted. In order to make sure the name isn't double-modified, the new name is applied using the :func:`.schema.conv` marker. We can use this explicitly as follows:: m = MetaData(naming_convention={ "ck": "ck_%(table_name)s_%(constraint_name)s" }) t = Table('t', m, Column('x', Integer), CheckConstraint('x > 5', name=conv('ck_t_x5'))) Where above, the :func:`.schema.conv` marker indicates that the constraint name here is final, and the name will render as ``"ck_t_x5"`` and not ``"ck_t_ck_t_x5"`` .. versionadded:: 0.9.4 .. seealso:: :ref:`constraint_naming_conventions` rNrrrrrlrrrrrrs,rrcs,eZdZdZdZfddZddZZS) _defer_namezRmark a name as 'deferred' for the purposes of automated name generation. rcs,|durtSt|tr |Stt|||Sr) _NONE_NAMErrrrrtr?)rar3rKrrr?s  z_defer_name.__new__cCs|jt|ffSr)r>rrdrLrrrr8r;z_defer_name.__reduce__)rrrrrlr?r8r rrrKrrt s  rtc@rq)_defer_none_namez>indicate a 'deferred' name that was ultimately the value None.rNrsrrrrrv!srv _unnamed_c@s,eZdZdZdZddZddZddZd S) rzDA unicode subclass used to identify anonymously generated names.rcCs tttj|t||jSrrrrrd__add__rrrrrry6 z_anonymous_label.__add__cCs tttjt|||jSrrxrrrr__radd__=rzz_anonymous_label.__radd__cCs"|jdur t|||jS||Sr)rrrnrrrrpDs z_anonymous_label.apply_mapN)rrrrrlryr{rprrrrr0s  rcCst|tr|St|S)zcoerce the given value to :class:`._truncated_label`. Existing :class:`._truncated_label` and :class:`._anonymous_label` objects are passed unchanged. )rrm)r3rrrrMs rcCs6t|tjr|Szt|WStyd|YSw)Nzunprintable element %r)rrrr Exceptionrrrr_string_or_unprintable[s    r}cCtjdd|DS)z\expand the given set of ClauseElements to be the set of all 'cloned' predecessors. cSrr)rBrrrrrGjrz"_expand_cloned..rrelementsrrr_expand_clonedercCr~)zXexpand tables into individual columns in the given list of column expressions. cSrr)rrrrrrGrrz%_select_iterables..rrrrr_select_iterablesmrrc,tt|t|tfdd|DS)zreturn the intersection of sets a and b, counting any overlap between 'cloned' predecessors. The returned set is in terms of the entities present within 'a'. c3s |] }|jr|VqdSrrrBrelem all_overlaprrr}   z'_cloned_intersection..rrrarQrrr_cloned_intersectionus rcr)Nc3s |] }|js|VqdSrrrrrrrrz%_cloned_difference..rrrrr_cloned_differences rzsqlalchemy.sql.functionscCs$t|dr t||jr|dS|S)Nr)rrFunctionElementr) functionsrrrr_labeleds  rcC t|tS)z:True if ``col`` is an instance of :class:`.ColumnElement`.)rrD)rErrr _is_columns rcCst}t|id|ji|S)z2locate Column objects within the given expression.r)rrNrrO)r:rKrrr _find_columnssrcCs@t|tjr|St|dr|}z|jWStyYdSwN__clause_element__)rrrrrr6rrrrr_column_as_keys   rcCst|dr |S|Sr)rrrrrr_clause_element_as_exprrPrcCs.t|tjr t|St|dr|}t|Sr)rrrrrrrrrrrrrs  rcCsJt|tjr t|St|dr|}t|tr!|jdur!t|St |Sr) rrrrrrrDrrrrrrrr&_literal_and_labels_as_label_references   rcCrr)rrrrrrryrrycCs^t|tr|St|dr|St|tjr||St|tjtfr&t|St dt |)Nrz=SQL expression object expected, got object of type %r instead) rrrrrrNoneTyper _const_exprrrvr')r text_fallbackrrr _literal_ass   rcCs|rt|tSt|tSr)rr/_no_text_coercion)rallow_coercion_to_textrrrrrs  rrcCrr)rrrrrr_literal_as_columnr.rcCs6t|}t| }tdt||rdndd)NzTextual column expression %(column)r should be explicitly declared with text(%(column)r), or use %(literal_column)s(%(column)r) for more specificityrr)rr)r_guess_straight_columnmatchrrvrellipses_string)rguess_is_literalrrr_no_column_coercions rcCs$|dt||r d|ndd)NzX%(extra)sTextual SQL expression %(expr)r should be explicitly declared as text(%(expr)r)z%s )r*extra)rr)rexc_clsrrrrrsrcCs0t|dr |St|tstd|f|S)NrzAmbiguous literal: %r. Use the 'text()' function to indicate a SQL expression literal, or 'literal()' to indicate a bound value.)rrrrrrvrrrrrs  rcCst|t o t|d Sr)rrrrrrr _is_literal!srcCs|durdSt||Sr)_only_column_elementsrrrrr_only_column_elements_or_none's rcCs8t|dr |}t|tstd||t|f|S)NrzMColumn-based expression object expected for argument '%s'; got: '%s', type %s)rrrrDrrvr'rrrrr.s   rcCs>t|dr |St|ts|durtSt|||ddS|S)NrTr/)rrrrr]r2)rrr"rrrr#9s  r#z^\w\S*$cCst|tr|St|dr|Stj|dd}|dur(t|tjtfr't |Snt|dr0|j S|dkr7d}nt|t j rEt t|ddSt|t ||dS)NrF)raiseerrr*T)r)rrrrrinspectrrrrrnumbersNumberrrr)rinsprrrr_interpret_as_column_or_fromHs"     rcCsHt|tttfr |S|durtS|durtS|durtStd)NFTzExpected None, False, or True)rr]rdrhrrvrrrrr`s rcCs"|D] }|jjs |jSqtjSr)r'_isnullrr)argsrrrr_type_from_argsms  rcCs8|j||d}|durtd|t|dd|jf|S)N)require_embeddedzbGiven column '%s', attached to table '%s', failed to locate a corresponding column from table '%s'rA)corresponding_columnrInvalidRequestErrorrr) fromclauserrrIrrr_corresponding_column_or_errorusrcsjeZdZddZfddZejddZejddZejd d Z ejd d Z ejd dZ Z S)AnnotatedColumnElementcCsFt|||tj|dD]}|j|ddur |j|qdS)N)rr6rAF)rrrDrErCr@rrR)rHrrWr rrrrs  zAnnotatedColumnElement.__init__cs tt||}tj||Sr)rrrZrDrErCr[rKrrrZs z(AnnotatedColumnElement._with_annotationscCr)z'pull 'name' from parent, if not present)_Annotated__elementrrLrrrrzAnnotatedColumnElement.namecCr)z(pull 'table' from parent, if not present)rrArLrrrrArzAnnotatedColumnElement.tablecCr)z&pull 'key' from parent, if not present)rr6rLrrrr6rzAnnotatedColumnElement.keycCrr)rinforLrrrrrzAnnotatedColumnElement.infocCrr)rrrLrrrrrz!AnnotatedColumnElement.anon_label) rrrrrZrrrrAr6rrr rrrKrrs     r)Frr)vr __future__rrrrrrrr annotationrbaserr r r r visitorsr rrrrrrr r&r,r4r7r;_self_inspectsr=ColumnOperatorsrDr2r*r/r]rdrhrnrrrrrrrrrrrrrrr$rrrsymbolr rrr!r0rrr%rYr\r`rb MemoizedSlotsrdrrmrrrtrvru_generated_labelrrr}rrrrrrrrrrrrryrrrrrrvrrrrrr#rIrrrrrrrrrrs                 6   kr R;B]8 O!ak 0^g 2 Pmy) \0