o znh@sldZddlZddlZddlZddlmZddlmZddlmZddlm Z ddl m Z dd l m Z dd l mZdd l mZdd l mZdd l mZddl mZddl mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$dd lm%Z%dd!lm&Z&dd"lm'Z'dd#lm(Z(dd$lm)Z)d%d&lm*Z*d%d'lm+Z+d%d(lm,Z,d)d*Z-d+d,Z.Gd-d.d.e#Z/d_d/d0Z0d1d2Z1d3d4Z2Gd5d6d6e$Z3Gd7d8d8e4Z5Gd9d:d:e4Z6Gd;d<dd>e7Z8Gd?d@d@e7Z9GdAdBdBe9Z:GdCdDdDe9Z;GdEdFdFee5e6e9ZGdKdLdLee7Z?GdMdNdNe$Z@GdOdPdPe=ee7ZAGdQdRdReAZBGdSdTdTeBZCGdUdVdVe5e6eBZDGdWdXdXee&ZEGdYdZdZe)ZFGd[d\d\eAZGGd]d^d^e ZHdS)`ziThe :class:`.FromClause` class of SQL expression elements, representing SQL tables and derived rowsets. N) attrgetter) Visitable) operators)type_api) Annotated) _from_objects) _generative)ColumnCollection) ColumnSet) Executable) Generative) Immutable)_anonymous_label)_clause_element_as_expr)_clone)_cloned_difference_cloned_intersection)_document_text_coercion)_expand_cloned_interpret_as_column_or_from)&_literal_and_labels_as_label_reference_literal_as_label_reference_literal_as_text)_no_text_coercion)_select_iterables)and_) BindParameter) ClauseElement) ClauseList)Grouping)literal_column)True_)UnaryExpression)exc) inspection)utilcCsLtj|dd}|durt|tjrt|z|jWSty%t dw)NF)raiseerrzFROM expression expected) r*inspect isinstancer+ string_typesr selectableAttributeErrorr) ArgumentError)elementinspr5D/usr/local/lib/python3.10/dist-packages/sqlalchemy/sql/selectable.py_interpret_as_from7s   r7cCs.t|}t|tr |j}t|ts|}|SN)r7r.Aliasoriginal SelectBaseselectr3r5r5r6_interpret_as_selectBs   r>c@seZdZeddZdS)_OffsetLimitParamcCs|jSr8)effective_valueselfr5r5r6_limit_offset_valueLz%_OffsetLimitParam._limit_offset_valueN)__name__ __module__ __qualname__propertyrCr5r5r5r6r?Ksr?cCsF|durdSt|dr|St|tr|St|}t|||ddS)zConvert the given value to an "offset or limit" clause. This handles incoming integers and converts to an expression; if an expression is already given, it is passed through. N__clause_element__T)type_unique)hasattrrIr.rr+asintr?)r3namerJvaluer5r5r6_offset_or_limit_clauseQs   rPcCs>|durdSz|j}Wntytd|wt|S)zConvert the "offset or limit" clause of a select construct to an integer. This is only possible if the value is stored as a simple bound parameter. Otherwise, a compilation error is raised. Nz@This SELECT structure does not use a simple integer value for %s)rCr1r) CompileErrorr+rM)clauseattrnamerOr5r5r6_offset_or_limit_clause_asintcs   rTcOst|i||S)zReturn an :class:`.Alias` object derived from a :class:`.Select`. name alias name \*args, \**kwargs all other arguments are delivered to the :func:`select` function. )Selectalias)rVargskwargsr5r5r6subqueryx rYc@s$eZdZdZdZdZeddZdS) Selectablez mark a class as being selectabler0TcC|Sr8r5rAr5r5r6r0szSelectable.selectableN)rErFrG__doc____visit_name__ is_selectablerHr0r5r5r5r6r[s r[c@2eZdZdZeedddddZd dd ZdS) HasPrefixesr5exprz :meth:`.HasPrefixes.prefix_with`z*:paramref:`.HasPrefixes.prefix_with.*expr`cO4|dd}|rtdd||||dS)aAdd one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative. This is used to support backend-specific prefix keywords such as those provided by MySQL. E.g.:: stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql") # MySQL 5.7 optimizer hints stmt = select([table]).prefix_with( "/*+ BKA(t1) */", dialect="mysql") Multiple prefixes can be specified by multiple calls to :meth:`.prefix_with`. :param \*expr: textual or :class:`.ClauseElement` construct which will be rendered following the INSERT, UPDATE, or DELETE keyword. :param \**kw: A single keyword 'dialect' is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect. dialectNUnsupported argument(s): %s,)popr)r2join_setup_prefixesrBrbkwrdr5r5r6 prefix_withs  zHasPrefixes.prefix_withNc"|jtfdd|D|_dS)Ncg|] }t|ddfqST)allow_coercion_to_textr.0prdr5r6 z/HasPrefixes._setup_prefixes..) _prefixestuple)rBprefixesrdr5rtr6ri   zHasPrefixes._setup_prefixesr8)rErFrGrwr rrlrir5r5r5r6ras !rac@r`) HasSuffixesr5rbz :meth:`.HasSuffixes.suffix_with`z*:paramref:`.HasSuffixes.suffix_with.*expr`cOrc)aAdd one or more expressions following the statement as a whole. This is used to support backend-specific suffix keywords on certain constructs. E.g.:: stmt = select([col1, col2]).cte().suffix_with( "cycle empno set y_cycle to 1 default 0", dialect="oracle") Multiple suffixes can be specified by multiple calls to :meth:`.suffix_with`. :param \*expr: textual or :class:`.ClauseElement` construct which will be rendered following the target clause. :param \**kw: A single keyword 'dialect' is accepted. This is an optional string dialect name which will limit rendering of this suffix to only that dialect. rdNrerf)rgr)r2rh_setup_suffixesrjr5r5r6 suffix_withs  zHasSuffixes.suffix_withNcrm)Ncrnrorrqrtr5r6rurvz/HasSuffixes._setup_suffixes..) _suffixesrx)rBsuffixesrdr5rtr6r|rzzHasSuffixes._setup_suffixesr8)rErFrGr~r rr}r|r5r5r5r6r{s r{c@sVeZdZdZdZdZgZdZdZdZ dZ dZ dZ ddZ edgZejdd d ed d:d d Zd:ddZd;ddZdd#d$Zed%d&Z d'd(Z!ed)d*Z"ed+d,Z#ed-d.Z$ee%d/d0d1Z&ee%d/Z'd2d3Z(ed4d5Z)d6d7Z*d8d9Z+dS)? FromClauseaRepresent an element that can be used within the ``FROM`` clause of a ``SELECT`` statement. The most common forms of :class:`.FromClause` are the :class:`.Table` and the :func:`.select` constructs. Key features common to all :class:`.FromClause` objects include: * a :attr:`.c` collection, which provides per-name access to a collection of :class:`.ColumnElement` objects. * a :attr:`.primary_key` attribute, which is a collection of all those :class:`.ColumnElement` objects that indicate the ``primary_key`` flag. * Methods to generate various derivations of a "from" clause, including :meth:`.FromClause.alias`, :meth:`.FromClause.join`, :meth:`.FromClause.select`. fromclauseFNcCs|Sr8r5)rBeffective_schemamap_r5r5r6_translate_schemazFromClause._translate_schema_columnsz1.1zThe :meth:`.FromClause.count` method is deprecated, and will be removed in a future release. Please use the :class:`.functions.count` function available from the :attr:`.func` namespace.messagesqlalchemy.sql.functionscKsL|jr t|jd}nt|jd}t|j|dg|fd|gi|S)zreturn a SELECT COUNT generated against this :class:`.FromClause`. .. seealso:: :class:`.functions.count` r tbl_row_countfrom_obj) primary_keylistcolumnsrUfunccountlabel)rB functions whereclauseparamscolr5r5r6r$szFromClause.countcKt|g|fi|S)zreturn a SELECT of this :class:`.FromClause`. .. seealso:: :func:`~.sql.expression.select` - general purpose method which allows for arbitrary column lists. rUrBrrr5r5r6r<As zFromClause.selectcCst|||||S)a Return a :class:`.Join` from this :class:`.FromClause` to another :class:`FromClause`. E.g.:: from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j) would emit SQL along the lines of:: SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id :param right: the right side of the join; this is any :class:`.FromClause` object such as a :class:`.Table` object, and may also be a selectable-compatible object such as an ORM-mapped class. :param onclause: a SQL expression representing the ON clause of the join. If left at ``None``, :meth:`.FromClause.join` will attempt to join the two tables based on a foreign key relationship. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN. :param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies :paramref:`.FromClause.join.isouter`. .. versionadded:: 1.1 .. seealso:: :func:`.join` - standalone function :class:`.Join` - the type of object produced Join)rBrightonclauseisouterfullr5r5r6rhM)zFromClause.joincCst|||d|S)aReturn a :class:`.Join` from this :class:`.FromClause` to another :class:`FromClause`, with the "isouter" flag set to True. E.g.:: from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id) The above is equivalent to:: j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True) :param right: the right side of the join; this is any :class:`.FromClause` object such as a :class:`.Table` object, and may also be a selectable-compatible object such as an ORM-mapped class. :param onclause: a SQL expression representing the ON clause of the join. If left at ``None``, :meth:`.FromClause.join` will attempt to join the two tables based on a foreign key relationship. :param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. .. versionadded:: 1.1 .. seealso:: :meth:`.FromClause.join` :class:`.Join` Tr)rBrrrr5r5r6 outerjoinxrzFromClause.outerjoincC t||S)aVreturn an alias of this :class:`.FromClause`. E.g.:: a2 = some_table.alias('a2') The above code creates an :class:`.Alias` object which can be used as a FROM clause in any SELECT statement. .. seealso:: :ref:`core_tutorial_aliases` :func:`~.expression.alias` )r9 _constructrBrNflatr5r5r6rVs zFromClause.aliascCr)a8Return a LATERAL alias of this :class:`.FromClause`. The return value is the :class:`.Lateral` construct also provided by the top-level :func:`~.expression.lateral` function. .. versionadded:: 1.1 .. seealso:: :ref:`lateral_selects` - overview of usage. )LateralrrBrNr5r5r6laterals zFromClause.lateralcCst||||S)aZReturn a TABLESAMPLE alias of this :class:`.FromClause`. The return value is the :class:`.TableSample` construct also provided by the top-level :func:`~.expression.tablesample` function. .. versionadded:: 1.1 .. seealso:: :func:`~.expression.tablesample` - usage guidelines and parameters ) TableSampler)rBsamplingrNseedr5r5r6 tablesamples zFromClause.tablesamplecCs ||jvS)zReturn True if this FromClause is 'derived' from the given FromClause. An example would be an Alias of a Table is derived from that Table. ) _cloned_setrBrr5r5r6is_derived_froms zFromClause.is_derived_fromcCs|j|jS)zReturn True if this FromClause and the other represent the same lexical identity. This tests if either one is a copy of the other, or if they are the same via annotation identity. )r intersectionrBotherr5r5r6_is_lexical_equivalentsz!FromClause._is_lexical_equivalentsqlalchemy.sql.utilcCs|||S)zreplace all occurrences of FromClause 'old' with the given Alias object, returning a copy of this :class:`.FromClause`. ) ClauseAdaptertraverse)rBsqlutiloldrVr5r5r6replace_selectableszFromClause.replace_selectablecCsJ|j|dd}|dur#||vr#||D]}|j|dd}|r"|Sq|S)zzReturn corresponding_column for the given column, or if None search for a match in the given dictionary. T)require_embeddedN)corresponding_column)rBcolumn equivalentsrequivncr5r5r6correspond_on_equivalentss z$FromClause.correspond_on_equivalentsc sdd}|jr Sd\}}j}|jj}|D]\}tt|j} || } | ru|r0|| |ru|dur:|| }}qt| t|krH|| }}q| |krut t j fdd| D} t t j fdd| D} | | kru|| }}q|S)aGiven a :class:`.ColumnElement`, return the exported :class:`.ColumnElement` object from this :class:`.Selectable` which corresponds to that original :class:`~sqlalchemy.schema.Column` via a common ancestor column. :param column: the target :class:`.ColumnElement` to be matched :param require_embedded: only return corresponding columns for the given :class:`.ColumnElement`, if the given :class:`.ColumnElement` is actually present within a sub-element of this :class:`.FromClause`. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this :class:`.FromClause`. cSs.||D]}tt|g|sdSqdS)NFT) differencesetrr)expanded_proxy_set target_settr5r5r6embeddedsz1FromClause.corresponding_column..embeddedNNNc$g|]}|r|jddqSweightrshares_lineage _annotationsgetrrscrr5r6ruC  z3FromClause.corresponding_column..crrrrrr5r6ruKr) ccontains_column proxy_set _all_columnsrrrlenr+reduceoperatoradd_uncached_proxy_set) rBrrrr intersectrcolsrri col_distance c_distancer5rr6rsF        zFromClause.corresponding_columncCst|d|jjdS)zga brief description of this FromClause. Used primarily for error message formatting. rNz object)getattr __class__rErAr5r5r6 descriptionUszFromClause.descriptioncCs|j|dS)z8delete memoized collections when a FromClause is cloned.N)_memoized_propertyexpire_instancerAr5r5r6_reset_exported^szFromClause._reset_exportedcCs$d|jvr |||jS)akA named-based collection of :class:`.ColumnElement` objects maintained by this :class:`.FromClause`. The :attr:`.columns`, or :attr:`.c` collection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:: select([mytable]).where(mytable.c.somecolumn == 5) r)__dict___init_collections_populate_column_collectionr as_immutablerAr5r5r6rcs  zFromClause.columnscC|||jS)zbReturn the collection of Column objects which comprise the primary key of this FromClause.)rrrrAr5r5r6ruzFromClause.primary_keycCr)zUReturn the collection of ForeignKey objects which this FromClause references.)rr foreign_keysrAr5r5r6r~rzFromClause.foreign_keysrz,An alias for the :attr:`.columns` attribute.)doccCsFd|jvsJd|jvsJd|jvsJt|_t|_t|_dS)Nrrr)rr rr rrrrAr5r5r6rs  zFromClause._init_collectionscCs d|jvS)Nr)rrAr5r5r6_cols_populateds zFromClause._cols_populatedcCsdS)zCalled on subclasses to establish the .c collection. Each implementation has a different way of establishing this collection. Nr5rAr5r5r6rsz&FromClause._populate_column_collectioncCs.|jsdS|j|jvr|j|j|ur|SdS)aMGiven a column added to the .c collection of an underlying selectable, produce the local version of that column, assuming this selectable ultimately should proxy this column. this is used to "ping" a derived selectable to add a new column to its .c. collection when a Column has been added to one of the Table objects it ultimtely derives from. If the given selectable hasn't populated its .c. collection yet, it should at least pass on the message to the contained selectables, but it will return None. This method is currently used by Declarative to allow Table columns to be added to a partially constructed inheritance mapping that may have already produced joins. The method isn't public right now, as the full span of implications and/or caveats aren't yet clear. It's also possible that this functionality could be invoked by default via an event, which would require that selectables maintain a weak referencing collection of all derivations. N)rkeyrrBrr5r5r6_refresh_for_new_columns z"FromClause._refresh_for_new_columnr8NFFNFrF),rErFrGr]r^named_with_column _hide_froms_is_join _is_select_is_from_container _is_lateral_textualschemarr+!group_expirable_memoized_propertyr deprecated dependenciesrr<rhrrVrrrrrrrrHrrrrrrr_select_iterablerrrrr5r5r5r6rsh   + +     T       rc@seZdZdZdZdZd1ddZed2dd Ze d1d d Z e d d Z ddZ d3ddZ edddZddZefddZddZddZeejdd   d4dd Zed3d!d"Zed#d$Zed%d&Zd3d'd(Ze d)d*Zedd2d+d,Ze d-d.Ze d/d0ZdS)5rawrepresent a ``JOIN`` construct between two :class:`.FromClause` elements. The public constructor function for :class:`.Join` is the module-level :func:`.join()` function, as well as the :meth:`.FromClause.join` method of any :class:`.FromClause` (e.g. such as :class:`.Table`). .. seealso:: :func:`.join` :meth:`.FromClause.join` rhTNFcCsJt||_t||_|dur||j|j|_n||_||_||_dS)zConstruct a new :class:`.Join`. The usual entrypoint here is the :func:`~.expression.join` function or the :meth:`.FromClause.join` method of any :class:`.FromClause` object. N)r7left self_groupr_match_primariesrrr)rBrrrrrr5r5r6__init__s  z Join.__init__cCs||||d|dS)aReturn an ``OUTER JOIN`` clause element. The returned object is an instance of :class:`.Join`. Similar functionality is also available via the :meth:`~.FromClause.outerjoin()` method on any :class:`.FromClause`. :param left: The left side of the join. :param right: The right side of the join. :param onclause: Optional criterion for the ``ON`` clause, is derived from foreign key relationships established between left and right otherwise. To chain joins together, use the :meth:`.FromClause.join` or :meth:`.FromClause.outerjoin` methods on the resulting :class:`.Join` object. Trrr5)clsrrrrr5r5r6_create_outerjoinszJoin._create_outerjoincCs||||||S)aProduce a :class:`.Join` object, given two :class:`.FromClause` expressions. E.g.:: j = join(user_table, address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j) would emit SQL along the lines of:: SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id Similar functionality is available given any :class:`.FromClause` object (e.g. such as a :class:`.Table`) using the :meth:`.FromClause.join` method. :param left: The left side of the join. :param right: the right side of the join; this is any :class:`.FromClause` object such as a :class:`.Table` object, and may also be a selectable-compatible object such as an ORM-mapped class. :param onclause: a SQL expression representing the ON clause of the join. If left at ``None``, :meth:`.FromClause.join` will attempt to join the two tables based on a foreign key relationship. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN. :param full: if True, render a FULL OUTER JOIN, instead of JOIN. .. versionadded:: 1.1 .. seealso:: :meth:`.FromClause.join` - method form, based on a given left side :class:`.Join` - the type of object produced r5)rrrrrrr5r5r6 _create_joins/zJoin._create_joincCs$d|jjt|j|jjt|jfS)Nz Join object on %s(%d) and %s(%d))rridrrAr5r5r6r4s zJoin.descriptioncCs ||up|j|p|j|Sr8)rrrrr5r5r6r=s   zJoin.is_derived_fromcCt|Sr8 FromGroupingrBagainstr5r5r6rDzJoin.self_grouprcCszdd|jjDdd|jjD}|j|dd|D|j|jdd|D|j t j dd|DdS)NcSg|]}|qSr5r5rrrr5r5r6ruIz4Join._populate_column_collection..css|]}|jr|VqdSr8)rrr5r5r6 Oz3Join._populate_column_collection..cs|]}|j|fVqdSr8)_labelrrrr5r5r6rRrcSsg|]}|jqSr5)rrr5r5r6ruTs) rrrrextendreduce_columnsrrupdater itertoolschain)rBrrr5r5r6rGsz Join._populate_column_collectioncCsb|j|}|dur|j|}|dur/|jr/||j|j<|j|j|jr-|j ||SdSr8) rrrrrrrrrrrBrrr5r5r6rWs    zJoin._refresh_for_new_columncKsH|||jfi||_||jfi||_||jfi||_dSr8)rrrrrBclonerkr5r5r6_copy_internalsdszJoin._copy_internalscKs|j|j|jfSr8)rrrrBrXr5r5r6 get_childrenjszJoin.get_childrencCs&t|tr |j}nd}|j|||dS)N)a_subset)r.rr_join_condition)rBrr left_rightr5r5r6rms zJoin._match_primaries)0.9zThe :paramref:`.join_condition.ignore_nonexistent_tables` parameter is deprecated and will be removed in a future release. Tables outside of the two tables being handled are no longer considered.)ignore_nonexistent_tablesc Cs|||||}t|dkr|||||t|dkr2t|tr$d}nd}td|j|j|fddt| dD}t|dkrI|dSt |S)acreate a join condition between two tables or selectables. e.g.:: join_condition(tablea, tableb) would produce an expression along the lines of:: tablea.c.id==tableb.c.tablea_id The join is determined based on the foreign key relationships between the two selectables. If there are multiple ways to join, or no way to join, an error is raised. :param ignore_nonexistent_tables: unused - tables outside of the two tables being handled are not considered. :param a_subset: An optional expression that is a sub-component of ``a``. An attempt will be made to join to just this sub-component first before looking at the full ``a`` construct, and if found will be successful even if there are other ways to join to ``a``. This allows the "right side" of a join to be passed thereby providing a "natural join". rrzI Perhaps you meant to convert the right side to a subquery using alias()?zACan't find any foreign key relationships between '%s' and '%s'.%scSsg|]\}}||kqSr5r5)rrxyr5r5r6ruz(Join._join_condition..) _joincond_scan_left_rightr_joincond_trim_constraintsr.r r)NoForeignKeysErrorrrvaluesr ) rabr'r#consider_as_foreign_keys constraintshintcritr5r5r6r$ts*+     zJoin._join_conditioncCs0t|tr |j}nd}|j||||d}t|S)N)r0r1r#r2)r.rrr,bool)rrrr2r%r3r5r5r6 _can_joins zJoin._can_joinc CsTtt}||fD]}|durq t|jdddD]=}|dur%|j|vr%qz||}WntjyF} z | j |j kr<WYd} ~ qd} ~ ww|durV||j  ||jfq||urt|jdddD]=}|durp|j|vrpqdz||}Wntjy} z | j |j krWYd} ~ qdd} ~ ww|dur||j  ||jfqd|r|Sq |S)NcS|jjSr8parent_creation_orderfkr5r5r6z0Join._joincond_scan_left_right..rcSr8r8r9r<r5r5r6r>r?) collections defaultdictrsortedrr: get_referentr)NoReferenceError table_namerN constraintappend) rr0r#r1r2r3rr=rnrter5r5r6r,sX            zJoin._joincond_scan_left_rightcCs|rt|D]}tdd|jDt|kr||=qt|dkr=tdd|D}t|dkr=t|d}|||i}t|dkrNtd|j|jfdS)Ncss|]}|jVqdSr8)r:rrfr5r5r6rsz2Join._joincond_trim_constraints..rcs|]}t|VqdSr8)rx)rrr5r5r5r6rsrzCan't determine join between '%s' and '%s'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.)rrelementsrr/r)AmbiguousForeignKeysErrorr)rr0r1r3r2constdeduperr5r5r6r-s&       zJoin._joincond_trim_constraintscKs$|j|jg}t||fd|gi|S)a"Create a :class:`.Select` from this :class:`.Join`. The equivalent long-hand form, given a :class:`.Join` object ``j``, is:: from sqlalchemy import select j = select([j.left, j.right], **kw).\ where(whereclause).\ select_from(j) :param whereclause: the WHERE criterion that will be sent to the :func:`select()` function :param \**kwargs: all other kwargs are sent to the underlying :func:`select()` function. r)rrrU)rBrrXcollistr5r5r6r<s z Join.selectcCs|jjp|jjSr8)rbindrrAr5r5r6rR3z Join.bindcCsz|r3|dus Jd|jjdd|jjdd}}||||}|j|||j|j|j dS|j ddd|S)abreturn an alias of this :class:`.Join`. The default behavior here is to first produce a SELECT construct from this :class:`.Join`, then to produce an :class:`.Alias` from that. So given a join of the form:: j = table_a.join(table_b, table_a.c.id == table_b.c.a_id) The JOIN by itself would look like:: table_a JOIN table_b ON table_a.id = table_b.a_id Whereas the alias of the above, ``j.alias()``, would in a SELECT context look like:: (SELECT table_a.id AS table_a_id, table_b.id AS table_b_id, table_b.a_id AS table_b_a_id FROM table_a JOIN table_b ON table_a.id = table_b.a_id) AS anon_1 The equivalent long-hand form, given a :class:`.Join` object ``j``, is:: from sqlalchemy import select, alias j = alias( select([j.left, j.right]).\ select_from(j).\ with_labels(True).\ correlate(False), name=name ) The selectable produced by :meth:`.Join.alias` features the same columns as that of the two individual selectables presented under a single name - the individual columns are "auto-labeled", meaning the ``.c.`` collection of the resulting :class:`.Alias` represents the names of the individual columns using a ``_`` scheme:: j.c.table_a_id j.c.table_b_a_id :meth:`.Join.alias` also features an alternate option for aliasing joins which produces no enclosing SELECT and does not normally apply labels to the column names. The ``flat=True`` option will call :meth:`.FromClause.alias` against the left and right sides individually. Using this option, no new ``SELECT`` is produced; we instead, from a construct as below:: j = table_a.join(table_b, table_a.c.id == table_b.c.a_id) j = j.alias(flat=True) we get a result like this:: table_a AS table_a_1 JOIN table_b AS table_b_1 ON table_a_1.id = table_b_1.a_id The ``flat=True`` argument is also propagated to the contained selectables, so that a composite join such as:: j = table_a.join( table_b.join(table_c, table_b.c.id == table_c.c.b_id), table_b.c.a_id == table_a.c.id ).alias(flat=True) Will produce an expression like:: table_a AS table_a_1 JOIN ( table_b AS table_b_1 JOIN table_c AS table_c_1 ON table_b_1.id = table_c_1.b_id ) ON table_a_1.id = table_b_1.a_id The standalone :func:`~.expression.alias` function as well as the base :meth:`.FromClause.alias` method also support the ``flat=True`` argument as a no-op, so that the argument can be passed to the ``alias()`` method of any selectable. .. versionadded:: 0.9.0 Added the ``flat=True`` option to create "aliases" of joins without enclosing inside of a SELECT subquery. :param name: name given to the alias. :param flat: if True, produce an alias of the left and right sides of this :class:`.Join` and return the join of those two selectables. This produces join expression that does not include an enclosing SELECT. .. versionadded:: 0.9.0 .. seealso:: :ref:`core_tutorial_aliases` :func:`~.expression.alias` Nz"Can't send name argument with flatT)rrF) use_labels correlate) rrVrrrrhrrrrr<)rBrrNrleft_aright_aadapterr5r5r6rV7se    z Join.aliascCstjdd|jDS)NcSsg|] }t|j|jqSr5)rrrrrr)r5r5r6rusz$Join._hide_froms..)rrrrAr5r5r6rszJoin._hide_fromscCs|g|jj|jj|jjSr8)rrrrrAr5r5r6rszJoin._from_objectsrrr8)FNN) rErFrGr]r^rr classmethodrrrHrrrr+rrrrr r"rdeprecated_paramsr$r7r,r-r<rRrVrrr5r5r5r6rsV   0     >  1    w rcseZdZdZdZdZdZddZeddZ ed"d d Z d#d d Z d#fdd Z e ddZddZddZddZddZefddZd$ddZe ddZe d d!ZZS)%r9aRepresents an table or selectable alias (AS). Represents an alias, as typically applied to any table or sub-select within a SQL statement using the ``AS`` keyword (or without the keyword on certain databases such as Oracle). This object is constructed from the :func:`~.expression.alias` module level function as well as the :meth:`.FromClause.alias` method available on all :class:`.FromClause` subclasses. rVTcOs&td|jj|jj|jjf)NzThe %s class is not intended to be constructed directly. Please use the %s() standalone function or the %s() method available from appropriate selectable objects.)NotImplementedErrorrrElower)rBargrkr5r5r6rs  zAlias.__init__cOs||}|j|i||Sr8)__new___init)rr^rkobjr5r5r6rs zAlias._constructNFcCt|j||dS)aMReturn an :class:`.Alias` object. An :class:`.Alias` represents any :class:`.FromClause` with an alternate name assigned within SQL, typically using the ``AS`` clause when generated, e.g. ``SELECT * FROM table AS aliasname``. Similar functionality is available via the :meth:`~.FromClause.alias` method available on all :class:`.FromClause` subclasses. In terms of a SELECT object as generated from the :func:`.select` function, the :meth:`.SelectBase.alias` method returns an :class:`.Alias` or similar object which represents a named, parenthesized subquery. When an :class:`.Alias` is created from a :class:`.Table` object, this has the effect of the table being rendered as ``tablename AS aliasname`` in a SELECT statement. For :func:`.select` objects, the effect is that of creating a named subquery, i.e. ``(select ...) AS aliasname``. The ``name`` parameter is optional, and provides the name to use in the rendered SQL. If blank, an "anonymous" name will be deterministically generated at compile time. Deterministic means the name is guaranteed to be unique against other constructs used in the same statement, and will also be the same name for each successive compilation of the same statement object. :param selectable: any :class:`.FromClause` subclass, such as a table, select statement, etc. :param name: string name to be assigned as the alias. If ``None``, a name will be deterministically generated at compile time. :param flat: Will be passed through to if the given selectable is an instance of :class:`.Join` - see :meth:`.Join.alias` for details. .. versionadded:: 0.9.0 )rNr)r7rV)rr0rNrr5r5r6_factorys,zAlias._factorycCs|}t|tr|j}t|ts||_|j|_|jr|j|_||_|dur;|jjr/t|jdd}tdt ||p7df}||_ dS)NrNz %%(%d %s)sanon) r.r9r3r:supports_execution_execution_optionsrrrr rN)rBr0rNbaseselectabler5r5r6r`s   z Alias._initcs:t|trt|jtr|jrt|Stt|j|dS)Nr) r.CompoundSelectr:rU_needs_parens_for_groupingr superr9rr rr5r6r!s zAlias.self_groupcCtjr|jS|jddSNasciibackslashreplacer+py3krNencoderAr5r5r6r+zAlias.descriptioncCs*z|jWStytd|jw)Nz)Element %s does not support 'as_scalar()')r3 as_scalarr1rAr5r5r6ru2s  zAlias.as_scalarcCs||jvrdS|j|S)NT)rr3rrr5r5r6r:s  zAlias.is_derived_fromcCs|jjjD]}||qdSr8)r3rr _make_proxy)rBrr5r5r6r?s z!Alias._populate_column_collectioncCs,|j|}|dur|jsdS||SdSr8)r3rrrvrr5r5r6rCs  zAlias._refresh_for_new_columncKsVt|jtrdS|||jfi||_|j}t|tr&|j}t|ts||_dSr8)r.r3 TableClauserr9r:)rBrrkrgr5r5r6r Ms   zAlias._copy_internalscks$|r |jD]}|Vq|jVdSr8)rr3)rBcolumn_collectionsrkrr5r5r6r"Zs   zAlias.get_childrencC|gSr8r5rAr5r5r6r`rDzAlias._from_objectscCr8r8)r3rRrAr5r5r6rRdz Alias.bindrr8T)rErFrGr]r^rrrrZrrcr`rrHrrurrrrr r"rrR __classcell__r5r5rlr6r9s0    -   r9c@s&eZdZdZdZdZedddZdS)raRepresent a LATERAL subquery. This object is constructed from the :func:`~.expression.lateral` module level function as well as the :meth:`.FromClause.lateral` method available on all :class:`.FromClause` subclasses. While LATERAL is part of the SQL standard, currently only more recent PostgreSQL versions provide support for this keyword. .. versionadded:: 1.1 .. seealso:: :ref:`lateral_selects` - overview of usage. rTNcCst|j|dS)afReturn a :class:`.Lateral` object. :class:`.Lateral` is an :class:`.Alias` subclass that represents a subquery with the LATERAL keyword applied to it. The special behavior of a LATERAL subquery is that it appears in the FROM clause of an enclosing SELECT, but may correlate to other FROM clauses of that SELECT. It is a special case of subquery only supported by a small number of backends, currently more recent PostgreSQL versions. .. versionadded:: 1.1 .. seealso:: :ref:`lateral_selects` - overview of usage. rN)r7r)rr0rNr5r5r6rc~szLateral._factoryr8)rErFrGr]r^rrZrcr5r5r5r6ris rcsFeZdZdZdZed ddZd fdd Ze dd d Z Z S) raLRepresent a TABLESAMPLE clause. This object is constructed from the :func:`~.expression.tablesample` module level function as well as the :meth:`.FromClause.tablesample` method available on all :class:`.FromClause` subclasses. .. versionadded:: 1.1 .. seealso:: :func:`~.expression.tablesample` rNcCst|j|||dS)aeReturn a :class:`.TableSample` object. :class:`.TableSample` is an :class:`.Alias` subclass that represents a table with the TABLESAMPLE clause applied to it. :func:`~.expression.tablesample` is also available from the :class:`.FromClause` class via the :meth:`.FromClause.tablesample` method. The TABLESAMPLE clause allows selecting a randomly selected approximate percentage of rows from a table. It supports multiple sampling methods, most commonly BERNOULLI and SYSTEM. e.g.:: from sqlalchemy import func selectable = people.tablesample( func.bernoulli(1), name='alias', seed=func.random()) stmt = select([selectable.c.people_id]) Assuming ``people`` with a column ``people_id``, the above statement would render as:: SELECT alias.people_id FROM people AS alias TABLESAMPLE bernoulli(:bernoulli_1) REPEATABLE (random()) .. versionadded:: 1.1 :param sampling: a ``float`` percentage between 0 and 100 or :class:`.functions.Function`. :param name: optional alias name :param seed: any real-valued SQL expression. When specified, the REPEATABLE sub-clause is also rendered. )rNr)r7r)rr0rrNrr5r5r6rcs*zTableSample._factorycs$||_||_tt|j||ddSNr})rrrkrr`)rBr0rrNrrlr5r6r`szTableSample._initrcCs"t|j|jr |jS|j|jSr8)r.rFunctionrsystem)rBrr5r5r6 _get_methodszTableSample._get_methodr) rErFrGr]r^rZrcr`r+rrr|r5r5rlr6rs -rcs~eZdZdZdZedddZdddeddffdd Ze ffd d Z e d d d Z dddZddZddZZS)CTEzRepresent a Common Table Expression. The :class:`.CTE` object is obtained using the :meth:`.SelectBase.cte` method from any selectable. See that method for complete examples. cteNFcCrb)zReturn a new :class:`.CTE`, or Common Table Expression instance. Please see :meth:`.HasCte.cte` for detail on CTE usage. rN recursive)r7r)rr0rNrr5r5r6rcsz CTE._factorycs>||_||_||_|r||_|r||_tt|j||ddSr~)r _cte_alias _restatesrwr~rkrr`)rBr0rNrrrrwr~rlr5r6r`s z CTE._initc sVtt|jfi|jdur|jfi|_tfdd|jD|_dS)Ncg|] }|fiqSr5r5rrelemrrkr5r6ruz'CTE._copy_internals..)rkrr r frozensetrrrlrr6r  s   zCTE._copy_internalssqlalchemy.sql.dmlcCsHt|j|jr|jjD]}||q dS|jjjD]}||qdSr8)r.r3 UpdateBase _returningrvrr)rBdmlrr5r5r6rs   zCTE._populate_column_collectioncCstj|j||j||j|jdS)a Return an :class:`.Alias` of this :class:`.CTE`. This method is a CTE-specific specialization of the :class:`.FromClause.alias` method. .. seealso:: :ref:`core_tutorial_aliases` :func:`~.expression.alias` )rNrrrwr~)rrr:rrwr~rr5r5r6rVs z CTE.aliascCs0tj|j||j|j|j|g|j|jdSN)rNrrrwr~) rrr:unionrNrrrwr~rr5r5r6r1  z CTE.unioncCs0tj|j||j|j|j|g|j|j dSr) rrr: union_allrNrrrrwr~rr5r5r6r;rz CTE.union_allr)rErFrGr]r^rZrcrr`rr r+rrrVrrr|r5r5rlr6rs$     rc@seZdZdZdddZdS)HasCTEzTMixin that declares a class to include CTE support. .. versionadded:: 1.1 NFcCstj|||dS)aReturn a new :class:`.CTE`, or Common Table Expression instance. Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called "WITH". Special semantics regarding UNION can also be employed to allow "recursive" queries, where a SELECT statement can draw upon the set of rows that have previously been selected. CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows. .. versionchanged:: 1.1 Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE. SQLAlchemy detects :class:`.CTE` objects, which are treated similarly to :class:`.Alias` objects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement. For special prefixes such as PostgreSQL "MATERIALIZED" and "NOT MATERIALIZED", the :meth:`.CTE.prefix_with` method may be used to establish these. .. versionchanged:: 1.3.13 Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED. :param name: name given to the common table expression. Like :meth:`._FromClause.alias`, the name can be left as ``None`` in which case an anonymous symbol will be used at query compile time. :param recursive: if ``True``, will render ``WITH RECURSIVE``. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected. The following examples include two from PostgreSQL's documentation at http://www.postgresql.org/docs/current/static/queries-with.html, as well as additional examples. Example 1, non recursive:: from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() orders = Table('orders', metadata, Column('region', String), Column('amount', Integer), Column('product', String), Column('quantity', Integer) ) regional_sales = select([ orders.c.region, func.sum(orders.c.amount).label('total_sales') ]).group_by(orders.c.region).cte("regional_sales") top_regions = select([regional_sales.c.region]).\ where( regional_sales.c.total_sales > select([ func.sum(regional_sales.c.total_sales)/10 ]) ).cte("top_regions") statement = select([ orders.c.region, orders.c.product, func.sum(orders.c.quantity).label("product_units"), func.sum(orders.c.amount).label("product_sales") ]).where(orders.c.region.in_( select([top_regions.c.region]) )).group_by(orders.c.region, orders.c.product) result = conn.execute(statement).fetchall() Example 2, WITH RECURSIVE:: from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() parts = Table('parts', metadata, Column('part', String), Column('sub_part', String), Column('quantity', Integer), ) included_parts = select([ parts.c.sub_part, parts.c.part, parts.c.quantity]).\ where(parts.c.part=='our part').\ cte(recursive=True) incl_alias = included_parts.alias() parts_alias = parts.alias() included_parts = included_parts.union_all( select([ parts_alias.c.sub_part, parts_alias.c.part, parts_alias.c.quantity ]). where(parts_alias.c.part==incl_alias.c.sub_part) ) statement = select([ included_parts.c.sub_part, func.sum(included_parts.c.quantity). label('total_quantity') ]).\ group_by(included_parts.c.sub_part) result = conn.execute(statement).fetchall() Example 3, an upsert using UPDATE and INSERT with CTEs:: from datetime import date from sqlalchemy import (MetaData, Table, Column, Integer, Date, select, literal, and_, exists) metadata = MetaData() visitors = Table('visitors', metadata, Column('product_id', Integer, primary_key=True), Column('date', Date, primary_key=True), Column('count', Integer), ) # add 5 visitors for the product_id == 1 product_id = 1 day = date.today() count = 5 update_cte = ( visitors.update() .where(and_(visitors.c.product_id == product_id, visitors.c.date == day)) .values(count=visitors.c.count + count) .returning(literal(1)) .cte('update_cte') ) upsert = visitors.insert().from_select( [visitors.c.product_id, visitors.c.date, visitors.c.count], select([literal(product_id), literal(day), literal(count)]) .where(~exists(update_cte.select())) ) connection.execute(upsert) .. seealso:: :meth:`.orm.query.Query.cte` - ORM version of :meth:`.HasCTE.cte`. r)rr)rBrNrr5r5r6rMs&z HasCTE.cter)rErFrGr]rr5r5r5r6rFsrc@seZdZdZdZddZddZeddZed d Z ed d Z d dZ ddZ eddZ ddZefddZeddZddZddZddZdS) r z%Represent a grouping of a FROM clausegroupingcC ||_dSr8r=rBr3r5r5r6r zFromGrouping.__init__cCdSr8r5rAr5r5r6rrzFromGrouping._init_collectionscCr8r8)r3rrAr5r5r6rrzzFromGrouping.columnscCr8r8)r3rrAr5r5r6rrzzFromGrouping.primary_keycCr8r8)r3rrAr5r5r6rrzzFromGrouping.foreign_keyscCs |j|Sr8)r3rrr5r5r6r  zFromGrouping.is_derived_fromcKst|jjdi|S)Nr5)r r3rV)rBrkr5r5r6rVszFromGrouping.aliascCr8r8)r3rrAr5r5r6rrzzFromGrouping._hide_fromscKs|jfSr8r=r!r5r5r6r"rzFromGrouping.get_childrencKs||jfi||_dSr8r=rr5r5r6r szFromGrouping._copy_internalscCr8r8)r3rrAr5r5r6rrzzFromGrouping._from_objectscCs t|j|Sr8)rr3)rBattrr5r5r6 __getattr__ rzFromGrouping.__getattr__cCs d|jiSNr3r=rAr5r5r6 __getstate__#rzFromGrouping.__getstate__cCs|d|_dSrr=)rBstater5r5r6 __setstate__&zFromGrouping.__setstate__N)rErFrGr]r^rrrHrrrrrVrr"rr rrrrr5r5r5r6r s,       r cseZdZdZdZdZdZ dZ fddZdd Z e j d d Z d d Z dddZe ddddZe d dddZe ddddZeddZZS)rwaRepresents a minimal "table" construct. This is a lightweight table object that has only a name and a collection of columns, which are typically produced by the :func:`.expression.column` function:: from sqlalchemy import table, column user = table("user", column("id"), column("name"), column("description"), ) The :class:`.TableClause` construct serves as the base for the more commonly used :class:`~.schema.Table` object, providing the usual set of :class:`~.expression.FromClause` services including the ``.c.`` collection and statement generation methods. It does **not** provide all the additional schema-level services of :class:`~.schema.Table`, including constraints, references to other tables, or support for :class:`.MetaData`-level services. It's useful on its own as an ad-hoc construct used to generate quick SQL statements when a more fully fledged :class:`~.schema.Table` is not on hand. tableTFNcsJtt|||_|_t|_t|_t |_ |D]}| |qdS)aIProduce a new :class:`.TableClause`. The object returned is an instance of :class:`.TableClause`, which represents the "syntactical" portion of the schema-level :class:`~.schema.Table` object. It may be used to construct lightweight table constructs. .. versionchanged:: 1.0.0 :func:`.expression.table` can now be imported from the plain ``sqlalchemy`` namespace like any other SQL element. :param name: Name of the table. :param columns: A collection of :func:`.expression.column` constructs. N) rkrwrrNfullnamer rr rrr append_column)rBrNrrrlr5r6rRs  zTableClause.__init__cCrr8r5rAr5r5r6rlrzTableClause._init_collectionscCrmrnrqrAr5r5r6rortzTableClause.descriptioncCs||j|j<||_dSr8)rrrrBrr5r5r6rvs  zTableClause.append_columncKs|r dd|jDSgS)NcSrr5r5rr5r5r6ru|rz,TableClause.get_children..)rrBrxrXr5r5r6r"zszTableClause.get_childrenrcKs|j|f||d|S)zGenerate an :func:`.insert` construct against this :class:`.TableClause`. E.g.:: table.insert().values(name='foo') See :func:`.insert` for argument and usage information. )r/inline)Insert)rBrr/rrXr5r5r6inserts zTableClause.insertcKs|j|f|||d|S)zGenerate an :func:`.update` construct against this :class:`.TableClause`. E.g.:: table.update().where(table.c.id==7).values(name='foo') See :func:`.update` for argument and usage information. )rr/r)Update)rBrrr/rrXr5r5r6rszTableClause.updatecKs|j||fi|S)zGenerate a :func:`.delete` construct against this :class:`.TableClause`. E.g.:: table.delete().where(table.c.id==7) See :func:`.delete` for argument and usage information. )Delete)rBrrrXr5r5r6deleterZzTableClause.deletecCryr8r5rAr5r5r6rrDzTableClause._from_objectsr{r)NNFr8)rErFrGr]r^rimplicit_returning_autoincrement_columnrrr+memoized_propertyrrr"rrrrrHrr|r5r5rlr6rw*s.      rwc@sTeZdZeddZeddZddZddZe fd d Z dd dZ d S) ForUpdateArgcCsd|dvrdSd}}|dkrd}n|dkrd}n|dkr!d}}n |dur,td|t||d S) aParse the for_update argument of :func:`.select`. :param mode: Defines the lockmode to use. ``None`` - translates to no lockmode ``'update'`` - translates to ``FOR UPDATE`` (standard SQL, supported by most dialects) ``'nowait'`` - translates to ``FOR UPDATE NOWAIT`` (supported by Oracle, PostgreSQL 8.1 upwards) ``'read'`` - translates to ``LOCK IN SHARE MODE`` (for MySQL), and ``FOR SHARE`` (for PostgreSQL) ``'read_nowait'`` - translates to ``FOR SHARE NOWAIT`` (supported by PostgreSQL). ``FOR SHARE`` and ``FOR SHARE NOWAIT`` (PostgreSQL). rNFnowaitTread read_nowaitzUnknown for_update argument: %rrr)r)r2r)rBr^rrr5r5r6parse_legacy_selects  z ForUpdateArg.parse_legacy_selectcCs.|jr|jsdS|jr|jrdS|jrdSdS)NrrrTrrAr5r5r6legacy_for_update_values  z$ForUpdateArg.legacy_for_update_valuecCsFt|to"|j|jko"|j|jko"|j|jko"|j|jko"|j|juSr8)r.rrr skip_locked key_shareofrr5r5r6__eq__s      zForUpdateArg.__eq__cCr r8)r rAr5r5r6__hash__rzForUpdateArg.__hash__c s*|jdurfdd|jD|_dSdS)Ncrr5r5rrr5r6rurz0ForUpdateArg._copy_internals..)rrr5rr6r s zForUpdateArg._copy_internalsFNcCsD||_||_||_||_|durddt|D|_dSd|_dS)zhRepresents arguments specified to :meth:`.Select.for_update`. .. versionadded:: 0.9.0 NcSg|]}t|qSr5rrr5r5r6rusz)ForUpdateArg.__init__..)rrrrr+to_listrrBrrrrrr5r5r6rs zForUpdateArg.__init__FFNFF) rErFrGrZrrHrrrrr rr5r5r5r6rs $   rc@sNeZdZdZddZddZeejdddd d Z d d Z e d dZ dS)r;zBase class for SELECT statements. This includes :class:`.Select`, :class:`.CompoundSelect` and :class:`.TextAsFrom`. cCr )aLreturn a 'scalar' representation of this selectable, which can be used as a column expression. Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression. The returned object is an instance of :class:`ScalarSelect`. ) ScalarSelectrAr5r5r6ru s zSelectBase.as_scalarcCs||S)zreturn a 'scalar' representation of this selectable, embedded as a subquery with a label. .. seealso:: :meth:`~.SelectBase.as_scalar`. )rurrr5r5r6r-s zSelectBase.label0.6zThe :meth:`.SelectBase.autocommit` method is deprecated, and will be removed in a future release. Please use the the :paramref:`.Connection.execution_options.autocommit` parameter in conjunction with the :meth:`.Executable.execution_options` method.rcCs|jddi|_dS)zPreturn a new selectable with the 'autocommit' flag set to True. autocommitTN)rfrrAr5r5r6r8s zSelectBase.autocommitcCs&|j|j}|j|_||S)zWOverride the default _generate() method to also clear out exported collections.)rr_rcopyr)rBsr5r5r6 _generateJs zSelectBase._generatecCryr8r5rAr5r5r6rSrDzSelectBase._from_objectsN) rErFrGr]rurr r+rrrrHrr5r5r5r6r;s      r;c@seZdZdZeZeZdZdZdZ        d%ddZ e ddZ e j ddZ e     d&d d Zed d Ze d dZe ddZe ddZe ddZeddZeddZeddZeddZddZdd Ze d!d"Zefd#d$ZdS)'GenerativeSelectaBase class for SELECT statements where additional elements can be added. This serves as the base for :class:`.Select` and :class:`.CompoundSelect` where elements such as ORDER BY, GROUP BY can be added and column rendering can be controlled. Compare to :class:`.TextAsFrom`, which, while it subclasses :class:`.SelectBase` and is also a SELECT construct, represents a fixed textual string which cannot be altered at this level, only wrapped as a subquery. .. versionadded:: 0.9.0 :class:`.GenerativeSelect` was added to provide functionality specific to :class:`.Select` and :class:`.CompoundSelect` while allowing :class:`.SelectBase` to be used for other SELECT-like objects, e.g. :class:`.TextAsFrom`. NFc Cs||_|dur t||_|durtd|jd|i|_|dur(t||_ |dur1t||_ ||_ |durCt t |dti|_|durTt t |dti|_dSdS)NFzThe select.autocommit parameter is deprecated and will be removed in a future release. Please refer to the Select.execution_options.autocommit` parameter.rr)rTrr_for_update_argr+warn_deprecatedrfrrP _limit_clause_offset_clause_bindr#rr_order_by_clauser_group_by_clause) rBrT for_updatelimitoffsetorder_bygroup_byrRrr5r5r6rps8     zGenerativeSelect.__init__cCs|jdur |jjSdS)zIProvide legacy dialect support for the ``for_update`` attribute. N)rrrAr5r5r6rs zGenerativeSelect.for_updatecCst||_dSr8)rrr)rBrOr5r5r6rrScCst|||||d|_dS)aSpecify a ``FOR UPDATE`` clause for this :class:`.GenerativeSelect`. E.g.:: stmt = select([table]).with_for_update(nowait=True) On a database like PostgreSQL or Oracle, the above would render a statement like:: SELECT table.a, table.b FROM table FOR UPDATE NOWAIT on other backends, the ``nowait`` option is ignored and instead would produce:: SELECT table.a, table.b FROM table FOR UPDATE When called with no arguments, the statement will render with the suffix ``FOR UPDATE``. Additional arguments can then be provided which allow for common database-specific variants. :param nowait: boolean; will render ``FOR UPDATE NOWAIT`` on Oracle and PostgreSQL dialects. :param read: boolean; will render ``LOCK IN SHARE MODE`` on MySQL, ``FOR SHARE`` on PostgreSQL. On PostgreSQL, when combined with ``nowait``, will render ``FOR SHARE NOWAIT``. :param of: SQL expression or list of SQL expression elements (typically :class:`.Column` objects or a compatible expression) which will render into a ``FOR UPDATE OF`` clause; supported by PostgreSQL and Oracle. May render as a table or as a column depending on backend. :param skip_locked: boolean, will render ``FOR UPDATE SKIP LOCKED`` on Oracle and PostgreSQL dialects or ``FOR SHARE SKIP LOCKED`` if ``read=True`` is also specified. .. versionadded:: 1.1.0 :param key_share: boolean, will render ``FOR NO KEY UPDATE``, or if combined with ``read=True`` will render ``FOR KEY SHARE``, on the PostgreSQL dialect. .. versionadded:: 1.1.0 )rrrrrN)rrrr5r5r6with_for_updates8 z GenerativeSelect.with_for_updatecCs d|_dS)areturn a new selectable with the 'use_labels' flag set to True. This will result in column expressions being generated using labels against their table name, such as "SELECT somecolumn AS tablename_somecolumn". This allows selectables which contain multiple FROM clauses to produce a unique set of column names regardless of name conflicts among the individual FROM clauses. TN)rTrAr5r5r6 apply_labelss zGenerativeSelect.apply_labelscC t|jdS)zGet an integer value for the limit. This should only be used by code that cannot support a limit as a BindParameter or other custom clause as it will throw an exception if the limit isn't currently set to an integer. r)rTrrAr5r5r6_limit zGenerativeSelect._limitcC t|jtS)zqTrue if the LIMIT clause is a simple integer, False if it is not present or is a SQL expression. )r.rr?rAr5r5r6_simple_int_limit z"GenerativeSelect._simple_int_limitcCr)zrTrue if the OFFSET clause is a simple integer, False if it is not present or is a SQL expression. )r.rr?rAr5r5r6_simple_int_offset rz#GenerativeSelect._simple_int_offsetcCr)zGet an integer value for the offset. This should only be used by code that cannot support an offset as a BindParameter or other custom clause as it will throw an exception if the offset isn't currently set to an integer. r)rTrrAr5r5r6_offset rzGenerativeSelect._offsetcCt||_dS)a&return a new selectable with the given LIMIT criterion applied. This is a numerical value which usually renders as a ``LIMIT`` expression in the resulting select. Backends that don't support ``LIMIT`` will attempt to provide similar functionality. .. versionchanged:: 1.0.0 - :meth:`.Select.limit` can now accept arbitrary SQL expressions as well as integer values. :param limit: an integer LIMIT parameter, or a SQL expression that provides an integer result. N)rPr)rBrr5r5r6r zGenerativeSelect.limitcCr)a-return a new selectable with the given OFFSET criterion applied. This is a numeric value which usually renders as an ``OFFSET`` expression in the resulting select. Backends that don't support ``OFFSET`` will attempt to provide similar functionality. .. versionchanged:: 1.0.0 - :meth:`.Select.offset` can now accept arbitrary SQL expressions as well as integer values. :param offset: an integer OFFSET parameter, or a SQL expression that provides an integer result. N)rPr)rBrr5r5r6r* szGenerativeSelect.offsetcG|j|dS)a{return a new selectable with the given list of ORDER BY criterion applied. e.g.:: stmt = select([table]).order_by(table.c.id, table.c.name) :param \*order_by: a series of :class:`.ColumnElement` constructs which will be used to generate an ORDER BY clause. .. seealso:: :ref:`core_tutorial_ordering` N)append_order_byrBclausesr5r5r6r@ rzGenerativeSelect.order_bycGr)areturn a new selectable with the given list of GROUP BY criterion applied. e.g.:: stmt = select([table.c.name, func.max(table.c.stat)]).\ group_by(table.c.name) :param \*group_by: a series of :class:`.ColumnElement` constructs which will be used to generate an GROUP BY clause. .. seealso:: :ref:`core_tutorial_ordering` N)append_group_byrr5r5r6rT szGenerativeSelect.group_bycGZt|dkr|ddurt|_dSt|dddur#t|jt|}t|dti|_dS)aAppend the given ORDER BY criterion applied to this selectable. The criterion will be appended to any pre-existing ORDER BY criterion. This is an **in-place** mutation method; the :meth:`~.GenerativeSelect.order_by` method is preferred, as it provides standard :term:`method chaining`. .. seealso:: :meth:`.GenerativeSelect.order_by` rrNrr)rr#rrrrrr5r5r6ri s  z GenerativeSelect.append_order_bycGr)aAppend the given GROUP BY criterion applied to this selectable. The criterion will be appended to any pre-existing GROUP BY criterion. This is an **in-place** mutation method; the :meth:`~.GenerativeSelect.group_by` method is preferred, as it provides standard :term:`method chaining`. .. seealso:: :meth:`.GenerativeSelect.group_by` rrNrr)rr#rrrrrr5r5r6r s  z GenerativeSelect.append_group_bycCstr8)r\rAr5r5r6_label_resolve_dict rDz$GenerativeSelect._label_resolve_dictcKsD|jdur||jfi||_|jdur ||jfi||_dSdSr8)rrrr5r5r6r  s  z GenerativeSelect._copy_internals)FFNNNNNNr)rErFrGr]r#rrrrrrrHrsetterr rrrrrrrrrrrrrrr r5r5r5r6rXsd *   ?          rcseZdZdZdZedZedZedZ edZ edZ edZ d Z d d Zed d ZeddZeddZeddZeddZeddZeddZddZd-ddZdd Zd!d"Zd#d$Zeffd%d& Zd.d'd(Zd)d*Z d+d,Z!ee e!Z Z"S)/riaForms the basis of ``UNION``, ``UNION ALL``, and other SELECT-based set operations. .. seealso:: :func:`.union` :func:`.union_all` :func:`.intersect` :func:`.intersect_all` :func:`.except` :func:`.except_all` compound_selectUNIONz UNION ALLEXCEPTz EXCEPT ALL INTERSECTz INTERSECT ALLTc Os|dd|_||_g|_d}t|D];\}}t|}|s$t|jj}n t|jj|krDt ddt|jdjj|dt|jjf|j |j |dqt j|fi|dS)NrUFz}All selectables passed to CompoundSelect must have identical numbers of columns; select #%d has %d columns, select #%d has %drrrh)rg_auto_correlatekeywordselects enumeraterrrrr)r2rHrrr)rBrrrXnumcolsnrr5r5r6r s(  zCompoundSelect.__init__cCstdd|jD}|||fS)Ncsrr8r@rr5r5r6r rz5CompoundSelect._label_resolve_dict..)dictr)rBdr5r5r6r s z"CompoundSelect._label_resolve_dictcOttjg|Ri|S)aReturn a ``UNION`` of multiple selectables. The returned object is an instance of :class:`.CompoundSelect`. A similar :func:`union()` method is available on all :class:`.FromClause` subclasses. \*selects a list of :class:`.Select` instances. \**kwargs available keyword arguments are the same as those of :func:`select`. )rirrrrXr5r5r6 _create_union zCompoundSelect._create_unioncOr)aReturn a ``UNION ALL`` of multiple selectables. The returned object is an instance of :class:`.CompoundSelect`. A similar :func:`union_all()` method is available on all :class:`.FromClause` subclasses. \*selects a list of :class:`.Select` instances. \**kwargs available keyword arguments are the same as those of :func:`select`. )ri UNION_ALLrr5r5r6_create_union_all rz CompoundSelect._create_union_allcOr)a7Return an ``EXCEPT`` of multiple selectables. The returned object is an instance of :class:`.CompoundSelect`. \*selects a list of :class:`.Select` instances. \**kwargs available keyword arguments are the same as those of :func:`select`. )rirrr5r5r6_create_except zCompoundSelect._create_exceptcOr)a;Return an ``EXCEPT ALL`` of multiple selectables. The returned object is an instance of :class:`.CompoundSelect`. \*selects a list of :class:`.Select` instances. \**kwargs available keyword arguments are the same as those of :func:`select`. )ri EXCEPT_ALLrr5r5r6_create_except_all rz!CompoundSelect._create_except_allcOr)a:Return an ``INTERSECT`` of multiple selectables. The returned object is an instance of :class:`.CompoundSelect`. \*selects a list of :class:`.Select` instances. \**kwargs available keyword arguments are the same as those of :func:`select`. )rirrr5r5r6_create_intersect1 rz CompoundSelect._create_intersectcOr)a>Return an ``INTERSECT ALL`` of multiple selectables. The returned object is an instance of :class:`.CompoundSelect`. \*selects a list of :class:`.Select` instances. \**kwargs available keyword arguments are the same as those of :func:`select`. )ri INTERSECT_ALLrr5r5r6_create_intersect_allB rz$CompoundSelect._create_intersect_allcCs|jdSNr)r _scalar_typerAr5r5r6rS rzCompoundSelect._scalar_typeNcCr r8r r r5r5r6rV rzCompoundSelect.self_groupcCs |jD] }||r dSqdSNTF)rr)rBrrr5r5r6rY s  zCompoundSelect.is_derived_fromcCsftdd|jDD]&}|dj||jr|djnd|jr"|djndd}ddt|D|_q dS)NcSsg|]}|jjqSr5)rrrrrr5r5r6ru` z>CompoundSelect._populate_column_collection..r)rNrcSs"g|] \}}|d|diqSr) _annotate)rrrrr5r5r6ruw s)ziprrvrTr _key_labelr_proxies)rBrproxyr5r5r6r_ s   z*CompoundSelect._populate_column_collectioncCs(|jD]}||q|jsdStd)NzUCompoundSelect constructs don't support addition of columns to underlying selectables)rrrr\)rBrrr5r5r6r{ s  z&CompoundSelect._refresh_for_new_columnc stt|jfi|fdd|jD|_t|dr#|`dD]}t||dur=t||t||fiq%dS)Ncrr5r5rrr5r6ru rz2CompoundSelect._copy_internals.._col_map)rrr) rkrir rrrLr rsetattrrBrrkrrlrr6r  s zCompoundSelect._copy_internalscKs(|rt|jpg|j|jgt|jSr8)rrrrrrr5r5r6r" s  zCompoundSelect.get_childrencCs.|jr|jS|jD] }|j}|r|Sq dSr8)rrrR)rBrer5r5r6rR s zCompoundSelect.bindcCrr8rrBrRr5r5r6 _set_bind rzCompoundSelect._set_bindr8r{)#rErFrGr]r^r+symbolrrrrrrrrrHrrZrrrrrrrrrrrrr r"rRrr|r5r5rlr6ri sF                rics"eZdZdZdZdZdZeZ dZ dZ dZ dZ dZejZdZejddd         d`d d Zed d Z daddZddZeddZdbddZedbddZeddZejddZeddZedd Z d!d"Z!e"ffd#d$ Z#dcd%d&Z$ed'd(Z%e&d)dcd*d+Z'ed,d-Z(ed.d/Z)ed0d1Z*ed2d3Z+ed4d5Z,ed6d7Z-ed8d9Z.d:d;Z/dd?Z1d@dAZ2dBdCZ3dDdEZ4edFdGZ5dHdIZ6dJdKZ7dLdMZ8dddNdOZ9dPdQZ:dRdSZ;dTdUZdZd[Z?d\d]Z@d^d_ZAee@eAZ@ZBS)erUz(Represents a ``SELECT`` statement. r<r5FNT)ra<The :paramref:`.select.autocommit` parameter is deprecated and will be removed in a future release. Please refer to the :paramref:`.Connection.execution_options.autocommit` parameter in conjunction with the the :meth:`.Executable.execution_options` method in order to affect the autocommit behavior for a statement.)r&zThe :paramref:`.select.for_update` parameter is deprecated and will be removed in a future release. Please refer to the :meth:`.Select.with_for_update` to specify the structure of the ``FOR UPDATE`` clause.)rrc KsL||_|dur|durd|_n ddt|D|_|dur-tddt|D|_nt|_zt|} Wn tyDt dw| rfg|_ |D]} t | } t | t r^| jtjd } |j | qLng|_ |durxt|jtjd |_nd|_|durt|jtjd |_nd|_|r|||r||tj|fi| dS) aConstruct a new :class:`.Select`. Similar functionality is also available via the :meth:`.FromClause.select` method on any :class:`.FromClause`. All arguments which accept :class:`.ClauseElement` arguments also accept string arguments, which will be converted as appropriate into either :func:`text()` or :func:`literal_column()` constructs. .. seealso:: :ref:`coretutorial_selecting` - Core Tutorial description of :func:`.select`. :param columns: A list of :class:`.ColumnElement` or :class:`.FromClause` objects which will form the columns clause of the resulting statement. For those objects that are instances of :class:`.FromClause` (typically :class:`.Table` or :class:`.Alias` objects), the :attr:`.FromClause.c` collection is extracted to form a collection of :class:`.ColumnElement` objects. This parameter will also accept :class:`.Text` constructs as given, as well as ORM-mapped classes. .. note:: The :paramref:`.select.columns` parameter is not available in the method form of :func:`.select`, e.g. :meth:`.FromClause.select`. .. seealso:: :meth:`.Select.column` :meth:`.Select.with_only_columns` :param whereclause: A :class:`.ClauseElement` expression which will be used to form the ``WHERE`` clause. It is typically preferable to add WHERE criterion to an existing :class:`.Select` using method chaining with :meth:`.Select.where`. .. seealso:: :meth:`.Select.where` :param from_obj: A list of :class:`.ClauseElement` objects which will be added to the ``FROM`` clause of the resulting statement. This is equivalent to calling :meth:`.Select.select_from` using method chaining on an existing :class:`.Select` object. .. seealso:: :meth:`.Select.select_from` - full description of explicit FROM clause specification. :param autocommit: legacy autocommit parameter. :param bind=None: an :class:`~.Engine` or :class:`~.Connection` instance to which the resulting :class:`.Select` object will be bound. The :class:`.Select` object will otherwise automatically bind to whatever :class:`~.base.Connectable` instances can be located within its contained :class:`.ClauseElement` members. :param correlate=True: indicates that this :class:`.Select` object should have its contained :class:`.FromClause` elements "correlated" to an enclosing :class:`.Select` object. It is typically preferable to specify correlations on an existing :class:`.Select` construct using :meth:`.Select.correlate`. .. seealso:: :meth:`.Select.correlate` - full description of correlation. :param distinct=False: when ``True``, applies a ``DISTINCT`` qualifier to the columns clause of the resulting statement. The boolean argument may also be a column expression or list of column expressions - this is a special calling form which is understood by the PostgreSQL dialect to render the ``DISTINCT ON ()`` syntax. ``distinct`` is also available on an existing :class:`.Select` object via the :meth:`~.Select.distinct` method. .. seealso:: :meth:`.Select.distinct` :param for_update=False: when ``True``, applies ``FOR UPDATE`` to the end of the resulting statement. ``for_update`` accepts various string values interpreted by specific backends, including: * ``"read"`` - on MySQL, translates to ``LOCK IN SHARE MODE``; on PostgreSQL, translates to ``FOR SHARE``. * ``"nowait"`` - on PostgreSQL and Oracle, translates to ``FOR UPDATE NOWAIT``. * ``"read_nowait"`` - on PostgreSQL, translates to ``FOR SHARE NOWAIT``. .. seealso:: :meth:`.Select.with_for_update` - improved API for specifying the ``FOR UPDATE`` clause. :param group_by: a list of :class:`.ClauseElement` objects which will comprise the ``GROUP BY`` clause of the resulting select. This parameter is typically specified more naturally using the :meth:`.Select.group_by` method on an existing :class:`.Select`. .. seealso:: :meth:`.Select.group_by` :param having: a :class:`.ClauseElement` that will comprise the ``HAVING`` clause of the resulting select when ``GROUP BY`` is used. This parameter is typically specified more naturally using the :meth:`.Select.having` method on an existing :class:`.Select`. .. seealso:: :meth:`.Select.having` :param limit=None: a numerical value which usually renders as a ``LIMIT`` expression in the resulting select. Backends that don't support ``LIMIT`` will attempt to provide similar functionality. This parameter is typically specified more naturally using the :meth:`.Select.limit` method on an existing :class:`.Select`. .. seealso:: :meth:`.Select.limit` :param offset=None: a numeric value which usually renders as an ``OFFSET`` expression in the resulting select. Backends that don't support ``OFFSET`` will attempt to provide similar functionality. This parameter is typically specified more naturally using the :meth:`.Select.offset` method on an existing :class:`.Select`. .. seealso:: :meth:`.Select.offset` :param order_by: a scalar or list of :class:`.ClauseElement` objects which will comprise the ``ORDER BY`` clause of the resulting select. This parameter is typically specified more naturally using the :meth:`.Select.order_by` method on an existing :class:`.Select`. .. seealso:: :meth:`.Select.order_by` :param use_labels=False: when ``True``, the statement will be generated using labels for each column in the columns clause, which qualify each column with its parent table's (or aliases) name so that name conflicts between columns in different tables don't occur. The format of the label is _. The "c" collection of the resulting :class:`.Select` object will use these names as well for targeting column members. This parameter can also be specified on an existing :class:`.Select` object using the :meth:`.Select.apply_labels` method. .. seealso:: :meth:`.Select.apply_labels` FTcSrr5rrrrr5r5r6ru z#Select.__init__..NcsrLr8r7rJr5r5r6r  z"Select.__init__..zDcolumns argument to select() must be a Python list or other iterablerh)r _distinctr+r OrderedSet _from_objr6 TypeErrorr)r2 _raw_columnsrr.rrrcomma_oprHr_asbool _whereclause_havingrir|rr) rBrrrdistincthavingrUryrrX cols_presentrr5r5r6r sXY         zSelect.__init__cCsg}t}|j}tt|j|jdurt|jnd|jD]&}||ur(t d|r2||vr2||}| |j s=| || |j q|S)Nr5z-select() construct refers to itself as a FROM)r _from_clonedrrrrrrr)InvalidRequestErrorrrrHr)rBfromsseen translateitemr5r5r6_froms s(     z Select._fromscsjttjddDr-jr$fddjDfddDjr@jr@fddDjdurPfddDj rprpt d krpfd dDt spt d S) aReturn the full list of 'from' clauses to be displayed. Takes into account a set of existing froms which may be rendered in the FROM clause of enclosing selects; this Select may want to leave those absent if it is automatically correlating. cSsg|]}t|jqSr5)rrrJr5r5r6ru sz-Select._get_display_froms..c3s*|]}j||rj|VqdSr8)r$rrJrAr5r6r s z,Select._get_display_froms..csg|]}|vr|qSr5r5rJ)toremover5r6ru r+cs(g|]}|ttp dvr|qSr5rrJ)explicit_correlate_fromsr& to_correlater5r6ru sNcs*g|]}|ttp djvr|qSr,)rr_correlate_exceptrJ)r-r&rBr5r6ru srcsg|] }|tvr|qSr5rrJ)r&implicit_correlate_fromsr5r6ru. szSelect statement '%s' returned no FROM clauses due to auto-correlation; specify correlate() to control correlation manually.) r*rrrr$rr _correlater/rrr)r%)rBr-r0r5)r-r&r0rBr.r+r6_get_display_froms sF       zSelect._get_display_fromscCs|jd}t|j}|djSr)rrrtype)rBrrr5r5r6rA s   zSelect._scalar_typecCs|S)z1Return the displayed list of FromClause elements.)r2rAr5r5r6r&F sz Select.froms*cCs|d||S)aadd a statement hint to this :class:`.Select`. This method is similar to :meth:`.Select.with_hint` except that it does not require an individual table, and instead applies to the statement as a whole. Hints here are specific to the backend database and may include directives such as isolation levels, file directives, fetch directives, etc. .. versionadded:: 1.0.0 .. seealso:: :meth:`.Select.with_hint` :meth:.`.Select.prefix_with` - generic SELECT prefixing which also can suit some database-specific HINT syntaxes such as MySQL optimizer hints N) with_hint)rBtext dialect_namer5r5r6with_statement_hintL szSelect.with_statement_hintcCs:|dur|j||ff7_dS|j||f|i|_dS)aAdd an indexing or other executional context hint for the given selectable to this :class:`.Select`. The text of the hint is rendered in the appropriate location for the database backend in use, relative to the given :class:`.Table` or :class:`.Alias` passed as the ``selectable`` argument. The dialect implementation typically uses Python string substitution syntax with the token ``%(name)s`` to render the name of the table or alias. E.g. when using Oracle, the following:: select([mytable]).\ with_hint(mytable, "index(%(name)s ix_mytable)") Would render SQL as:: select /*+ index(mytable ix_mytable) */ ... from mytable The ``dialect_name`` option will limit the rendering of a particular hint to a particular backend. Such as, to add hints for both Oracle and Sybase simultaneously:: select([mytable]).\ with_hint(mytable, "index(%(name)s ix_mytable)", 'oracle').\ with_hint(mytable, "WITH INDEX ix_mytable", 'sybase') .. seealso:: :meth:`.Select.with_statement_hint` N)_statement_hints_hintsr)rBr0r6r7r5r5r6r5d s"zSelect.with_hintcC td)NzvSelect objects don't have a type. Call as_scalar() on this Select object to return a 'scalar' version of this Select.r)r%rAr5r5r6r3 z Select.typecCs|j}|tt|S)zreturn a Set of all FromClause elements referenced by this Select. This set is a superset of that returned by the ``froms`` property, which is specifically for those FromClause elements that would actually be rendered. )r*rr)rBr&r5r5r6locate_all_froms s zSelect.locate_all_fromscCs t|jS)zan iterator of all ColumnElement expressions which would be rendered into the columns clause of the resulting SELECT statement. )rrrAr5r5r6 inner_columns s zSelect.inner_columnscCs`tddt|jD}tddt|jD}|}|D] \}}|||q |||fS)Ncss,|]}|jr|jp|jp|j|fVqdSr8)_allow_label_resolve_resolve_labelrrrr5r5r6r s z-Select._label_resolve_dict..css |] }|jr|j|fVqdSr8)r@rrr5r5r6r s )rrrr&ritems setdefault)rB with_cols only_froms only_colsrrOr5r5r6r s zSelect._label_resolve_dictcCs0||jvrdS|D] }||rdSq dSr)rr>r)rBrrKr5r5r6r s   zSelect.is_derived_fromc stt|jfitfdd|j|jD|_t fdd|jD|_t fdd|j D|j |_ |j rUt fdd|j D|j |_ fdd|j D|_ dD]}t||dur{t||t||fiqc|dS) Nc3s$|] }||fifVqdSr8r5rJrr5r6r s z)Select._copy_internals..c3s|]}|VqdSr8r5rJ) from_clonedr5r6r rc3 |] }|fiVqdSr8r5rJrr5r6r sc3rHr8r5rJrr5r6r s crr5r5rrr5r6ru rz*Select._copy_internals..)rr rrr)rkrUr rrrr*r$r+rrr1r/rrr rrrl)rrGrkr6r  s,     zSelect._copy_internalscKs@|rt|jpg|jt|jdd|j|j|j|jfDS)z=return child elements as per the ClauseElement specification.cSsg|]}|dur|qSr8r5rYr5r5r6ru s z'Select.get_children..)rrrr*rr rrrr5r5r6r" szSelect.get_childrencC||dS)axreturn a new select() construct with the given column expression added to its columns clause. E.g.:: my_select = my_select.column(table.c.new_column) See the documentation for :meth:`.Select.with_only_columns` for guidelines on adding /replacing the columns of a :class:`.Select` object. N)rrr5r5r6r sz Select.columnrcCs.||j|jg|jft|jRd|iS)aReturn a new :func`.select` construct with redundantly named, equivalently-valued columns removed from the columns clause. "Redundant" here means two columns where one refers to the other either based on foreign key, or via a simple equality comparison in the WHERE clause of the statement. The primary purpose of this method is to automatically construct a select statement with all uniquely-named columns, without the need to use table-qualified labels as :meth:`.apply_labels` does. When columns are omitted based on foreign key, the referred-to column is the one that's kept. When columns are omitted based on WHERE equivalence, the first column in the columns clause is the one that's kept. :param only_synonyms: when True, limit the removal of columns to those which have the same name as the equivalent. Otherwise, all columns that are equivalent to another are removed. only_synonyms)with_only_columnsrr?rrxr)rBrrJr5r5r6r" szSelect.reduce_columnscCsJ|g}|D]}t|}t|tr|jtjd}||q||_dS)a Return a new :func:`.select` construct with its columns clause replaced with the given columns. This method is exactly equivalent to as if the original :func:`.select` had been called with the given columns clause. I.e. a statement:: s = select([table1.c.a, table1.c.b]) s = s.with_only_columns([table1.c.b]) should be exactly equivalent to:: s = select([table1.c.b]) This means that FROM clauses which are only derived from the column list will be discarded if the new column list no longer contains that FROM:: >>> table1 = table('t1', column('a'), column('b')) >>> table2 = table('t2', column('a'), column('b')) >>> s1 = select([table1.c.a, table2.c.b]) >>> print s1 SELECT t1.a, t2.b FROM t1, t2 >>> s2 = s1.with_only_columns([table2.c.b]) >>> print s2 SELECT t2.b FROM t1 The preferred way to maintain a specific FROM clause in the construct, assuming it won't be represented anywhere else (i.e. not in the WHERE clause, etc.) is to set it using :meth:`.Select.select_from`:: >>> s1 = select([table1.c.a, table2.c.b]).\ ... select_from(table1.join(table2, ... table1.c.a==table2.c.a)) >>> s2 = s1.with_only_columns([table2.c.b]) >>> print s2 SELECT t2.b FROM t1 JOIN t2 ON t1.a=t2.a Care should also be taken to use the correct set of column objects passed to :meth:`.Select.with_only_columns`. Since the method is essentially equivalent to calling the :func:`.select` construct in the first place with the given columns, the columns passed to :meth:`.Select.with_only_columns` should usually be a subset of those which were passed to the :func:`.select` construct, not those which are available from the ``.c`` collection of that :func:`.select`. That is:: s = select([table1.c.a, table1.c.b]).select_from(table1) s = s.with_only_columns([table1.c.b]) and **not**:: # usually incorrect s = s.with_only_columns([s.c.b]) The latter would produce the SQL:: SELECT b FROM (SELECT t1.a AS a, t1.b AS b FROM t1), t1 Since the :func:`.select` construct is essentially being asked to select both from ``table1`` as well as itself. rhN) rrr.rrrrrHr)rBrrcrr5r5r6rK@ sE   zSelect.with_only_columnscCrI)zreturn a new select() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any. N)append_whereclauserBrr5r5r6where sz Select.wherecCrI)zreturn a new select() construct with the given expression added to its HAVING clause, joined to the existing clause via AND, if any. N) append_havingrBr"r5r5r6r" sz Select.havingcGsB|rdd|D}t|jtr|j||_dS||_dSd|_dS)a Return a new select() construct which will apply DISTINCT to its columns clause. :param \*expr: optional column expressions. When present, the PostgreSQL dialect will render a ``DISTINCT ON (>)`` construct. cSrr5rrr5r5r6ru rz#Select.distinct..TN)r.rr)rBrbr5r5r6r! s     zSelect.distinctcCrI)areturn a new :func:`.select` construct with the given FROM expression merged into its list of FROM objects. E.g.:: table1 = table('t1', column('a')) table2 = table('t2', column('b')) s = select([table1.c.a]).\ select_from( table1.join(table2, table1.c.a==table2.c.b) ) The "from" list is a unique set on the identity of each element, so adding an already present :class:`.Table` or other selectable will have no effect. Passing a :class:`.Join` that refers to an already present :class:`.Table` or other selectable will have the effect of concealing the presence of that selectable as an individual element in the rendered FROM list, instead rendering it into a JOIN clause. While the typical purpose of :meth:`.Select.select_from` is to replace the default, derived FROM clause with a join, it can also be called with individual table elements, multiple times if desired, in the case that the FROM clause cannot be fully derived from the columns clause:: select([func.count('*')]).select_from(table1) N) append_fromrr5r5r6 select_from s zSelect.select_fromcGs@d|_|r|ddurd|_dSt|jdd|D|_dS)adreturn a new :class:`.Select` which will correlate the given FROM clauses to that of an enclosing :class:`.Select`. Calling this method turns off the :class:`.Select` object's default behavior of "auto-correlation". Normally, FROM elements which appear in a :class:`.Select` that encloses this one via its :term:`WHERE clause`, ORDER BY, HAVING or :term:`columns clause` will be omitted from this :class:`.Select` object's :term:`FROM clause`. Setting an explicit correlation collection using the :meth:`.Select.correlate` method provides a fixed list of FROM objects that can potentially take place in this process. When :meth:`.Select.correlate` is used to apply specific FROM clauses for correlation, the FROM elements become candidates for correlation regardless of how deeply nested this :class:`.Select` object is, relative to an enclosing :class:`.Select` which refers to the same FROM object. This is in contrast to the behavior of "auto-correlation" which only correlates to an immediate enclosing :class:`.Select`. Multi-level correlation ensures that the link between enclosed and enclosing :class:`.Select` is always via at least one WHERE/ORDER BY/HAVING/columns clause in order for correlation to take place. If ``None`` is passed, the :class:`.Select` object will correlate none of its FROM entries, and all will render unconditionally in the local FROM clause. :param \*fromclauses: a list of one or more :class:`.FromClause` constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate collection. .. seealso:: :meth:`.Select.correlate_except` :ref:`correlated_subqueries` FrNr5csrLr8rrJr5r5r6rrz#Select.correlate..)rr1rrrB fromclausesr5r5r6rU s ) zSelect.correlatecGsDd|_|r|ddurd|_dSt|jpddd|D|_dS)areturn a new :class:`.Select` which will omit the given FROM clauses from the auto-correlation process. Calling :meth:`.Select.correlate_except` turns off the :class:`.Select` object's default behavior of "auto-correlation" for the given FROM elements. An element specified here will unconditionally appear in the FROM list, while all other FROM elements remain subject to normal auto-correlation behaviors. If ``None`` is passed, the :class:`.Select` object will correlate all of its FROM entries. :param \*fromclauses: a list of one or more :class:`.FromClause` constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate-exception collection. .. seealso:: :meth:`.Select.correlate` :ref:`correlated_subqueries` FrNr5csrLr8rrJr5r5r6r$rz*Select.correlate_except..)rr/rrrTr5r5r6correlate_excepts  zSelect.correlate_exceptcCs&d|_t|jdd|D|_dS)zappend the given correlation expression to this select() construct. This is an **in-place** mutation method; the :meth:`~.Select.correlate` method is preferred, as it provides standard :term:`method chaining`. FcsrLr8rrJr5r5r6r3rz,Select.append_correlation..N)rrr1rrr5r5r6append_correlation(s zSelect.append_correlationcCs:|t|}t|tr|jtjd}|j|g|_dS)aappend the given column expression to the columns clause of this select() construct. E.g.:: my_select.append_column(some_table.c.new_column) This is an **in-place** mutation method; the :meth:`~.Select.column` method is preferred, as it provides standard :term:`method chaining`. See the documentation for :meth:`.Select.with_only_columns` for guidelines on adding /replacing the columns of a :class:`.Select` object. rhN)rrr.rrrrrrr5r5r6r7s  zSelect.append_columncCst|}|j|f|_dS)aappend the given columns clause prefix expression to this select() construct. This is an **in-place** mutation method; the :meth:`~.Select.prefix_with` method is preferred, as it provides standard :term:`method chaining`. N)rrw)rBrRr5r5r6 append_prefixPs zSelect.append_prefixcC |tt|j||_dS)aJappend the given expression to this select() construct's WHERE criterion. The expression will be joined to existing WHERE criterion via AND. This is an **in-place** mutation method; the :meth:`~.Select.where` method is preferred, as it provides standard :term:`method chaining`. N)rr r&_ifnonerrNr5r5r6rM\s zSelect.append_whereclausecCrY)aMappend the given expression to this select() construct's HAVING criterion. The expression will be joined to existing HAVING criterion via AND. This is an **in-place** mutation method; the :meth:`~.Select.having` method is preferred, as it provides standard :term:`method chaining`. N)rr r&rZr rQr5r5r6rPks zSelect.append_havingcCs$|t|}|j|g|_dS)a append the given FromClause expression to this select() construct's FROM clause. This is an **in-place** mutation method; the :meth:`~.Select.select_from` method is preferred, as it provides standard :term:`method chaining`. N)rr7rrrr5r5r6rRys zSelect.append_fromcsP|jrtfddfddtt|jDSddtt|jDS)NcsF|jdus|js d|fS|j}|vr|j}||fS|||fSr8)r_render_label_in_columns_clause anon_labelr)rrN)namesr5r6 name_for_cols z0Select._columns_plus_names..name_for_colcsg|]}|qSr5r5r)r^r5r6rurz.Select._columns_plus_names..cSsg|]}d|fqSr8r5rr5r5r6rur)rTrr+ unique_listrrrAr5)r^r]r6_columns_plus_namess  zSelect._columns_plus_namescCsj|jD]/\}}t|ds q|durd}n|jr'|j}|dur&||jvr&|j}nd}|j|||ddqdS)NrvT)rrNname_is_truncatable)r`rLrTr rr\rv)rBrNrrr5r5r6rs z"Select._populate_column_collectioncCs|jD];}||}|dur>||jvr;|jr;|jr|jn|j}||jvr;|j||jr-|j nd|jr4|jndddSdSqdS)NT)rNrra) r*rr?rrTr rrrvr)rBrrr our_labelr5r5r6rs     zSelect._refresh_for_new_columncCs |jdup|jdupt|jjSr8)rrr6rrrAr5r5r6rjs  z!Select._needs_parens_for_groupingcCst|tr |s |St|S)a+return a 'grouping' construct as per the ClauseElement specification. This produces an element that can be embedded in an expression. Note that this method is called automatically as needed when constructing expressions and should not require explicit use. )r.rirjr r r5r5r6rs  zSelect.self_groupcKtj||fi|S)zSreturn a SQL UNION of this select() construct against the given selectable.)rirrBrrXr5r5r6rz Select.unioncKrc)zareturn a SQL UNION ALL of this select() construct against the given selectable. )rirrdr5r5r6rzSelect.union_allcKrc)zTreturn a SQL EXCEPT of this select() construct against the given selectable.)rirrdr5r5r6except_rezSelect.except_cKrc)zbreturn a SQL EXCEPT ALL of this select() construct against the given selectable. )rirrdr5r5r6 except_allrfzSelect.except_allcKrc)zareturn a SQL INTERSECT of this select() construct against the given selectable. )rirrdr5r5r6rrfzSelect.intersectcKrc)zereturn a SQL INTERSECT ALL of this select() construct against the given selectable. )rirrdr5r5r6 intersect_allrfzSelect.intersect_allcCs^|jr|jS|j}|s|jD]}|j}|r||_|SqdSt|dj}|r-||_|SdSr)rr*rrRr)rBr&rrr5r5r6rRs   z Select.bindcCrr8rrr5r5r6rrzSelect._set_bind)NNNFNTNNr)r4r{r8)CrErFrGr]r^rwr~r+ immutabledictr:r9rr$r1r/r;rrr[rrHr*r2rr&r8r r5r3methodr>r?rrrr r"rrrrKrOr"r!rSrUrVrWrrXrMrPrRr`rrrjrrrrgrhrrirRrr|r5r5rlr6rU s    T   &     <   M    ! 0 "   rUc@sDeZdZgZdZdZddZeddZeZ e ddZ d d Z d S) rTFcCs||_||_dSr8)r3rr3rr5r5r6rszScalarSelect.__init__cCr;)NzcScalar Select expression has no columns; use this object directly within a column-level expression.r<rAr5r5r6rr=zScalarSelect.columnscCs|j||_dS)zjApply a WHERE clause to the SELECT statement referred to by this :class:`.ScalarSelect`. N)r3rO)rBr5r5r5r6rO(szScalarSelect.wherecKr\r8r5r!r5r5r6r0rzScalarSelect.self_groupN) rErFrGrr_is_implicitly_booleanrrHrrr rOrr5r5r5r6rs   rc@sLeZdZdZejZgZddZdddZddZ d d Z d d Z d dZ dS)Existsz%Represent an ``EXISTS`` clause. cOsb|rt|dttfr|d}n|stdgf}t|i|}tj||t j t j dddS)aConstruct a new :class:`.Exists` against an existing :class:`.Select` object. Calling styles are of the following forms:: # use on an existing select() s = select([table.c.col1]).where(table.c.col2==5) s = exists(s) # construct a select() at once exists(['*'], **select_arguments).where(criterion) # columns argument is optional, generates "EXISTS (SELECT *)" # by default. exists().where(table.c.col2==5) rr4T)rrJwraps_column_expressionN) r.r;rr%rUrurr'rrexistsr BOOLEANTYPE)rBrWrXrr5r5r6r<s   zExists.__init__NcKrr8rrr5r5r6r<]sz Exists.selectcG|}|jj||_|Sr8)rr3rUrrBrrr5r5r6rU`zExists.correlatecGrqr8)rr3rVrrrr5r5r6rVerszExists.correlate_exceptcC|}|j||_|S)zreturn a new :class:`.Exists` construct, applying the given expression to the :meth:`.Select.select_from` method of the select statement contained. )rr3rSrrBrRrr5r5r6rSjszExists.select_fromcCrt)zreturn a new exists() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any. )rr3rOrrur5r5r6rOtsz Exists.wherer8) rErFrGr]r'r^rrr<rUrVrSrOr5r5r5r6rm4s ! rmc@sVeZdZdZdZdZdddZeddZe d d Z d d Z e fd dZ ddZdS) TextAsFromaWrap a :class:`.TextClause` construct within a :class:`.SelectBase` interface. This allows the :class:`.TextClause` object to gain a ``.c`` collection and other FROM-like capabilities such as :meth:`.FromClause.alias`, :meth:`.SelectBase.cte`, etc. The :class:`.TextAsFrom` construct is produced via the :meth:`.TextClause.columns` method - see that method for details. .. versionadded:: 0.9.0 .. seealso:: :func:`.text` :meth:`.TextClause.columns` text_as_fromTFcCs||_||_||_dSr8)r3 column_args positional)rBr6rryr5r5r6rs zTextAsFrom.__init__cCr8r8)r3rrAr5r5r6rrzzTextAsFrom._bindcOs|jj|i||_dSr8)r3 bindparams)rBbindsbind_as_valuesr5r5r6rzszTextAsFrom.bindparamscCs|jD]}||qdSr8)rxrvrr5r5r6rs  z&TextAsFrom._populate_column_collectioncKs |||jfi||_dSr8)rr3rr5r5r6r szTextAsFrom._copy_internalscCs |jdjSr)rxr3rAr5r5r6rrzTextAsFrom._scalar_typeNr)rErFrGr]r^rrrHrr rzrrr rr5r5r5r6rv~s     rvc@seZdZddZdS)AnnotatedFromClausecCs|jt|||dSr8)rrr)rBr3r/r5r5r6rszAnnotatedFromClause.__init__N)rErFrGrr5r5r5r6r}s r}r)Ir]rArrrsqlalchemy.sql.visitorsrr(rr annotationrbaserr r r r r rrMrrrrrrrrrrrrrr r!r"r#r$r%r&r'r)r*r+r7r>r?rPrTrYr[objectrar{rrr9rrrrr rwrr;rrirUrrmrvr}r5r5r5r6s                                       3.Q+,Le05\BM pJ2