U kf6 @sj dZddlmZddlZddlmZddlZddlmZddlm Z ddlm Z ddlm Z ddlm Z dd lm Z dd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#dd lm$Z$dd!l%m&Z&dd"l%m'Z'dd#l%m(Z(dd$l%m)Z)dd%l%m*Z*dd&l%m+Z+dd'l%m,Z,dd(l%m-Z-dd)l.m/Z/dd*l.m0Z0dd+l1m2Z2dd,l1m3Z3dd-l1m4Z4dd.l1m5Z5dd/l1m6Z6dd0l1m7Z7dd1l1m8Z8dd2l1m9Z9dd3l1m:Z:dd4l1m;Z;dd5l1mZ>dd8l1m?Z?dd9l1m@Z@dd:l1mAZAdd;l1mBZBddl1mEZEdd?l1mFZFdd@lmGZGddAlHmIZIddBlHmJZJddClHmKZKddDlHmLZLddElHmMZMddFlHmNZNddGlHmOZOddHlHmPZPddIlHmQZQddJlHmRZRddKlHmSZSddLlHmTZTddMl mUZUddNlVmWZWddOl$mXZXddPl$mYZYddQl$mZZZdRdSlm[Z[dRdTlm\Z\dRdUl\m]Z]dRdVl^m_Z_dRdWl^m`Z`dRdXl^maZaeKjbZbedYe dZZcerdd[l%mdZddd\l%meZedd]l%mfZfdd^l%mgZgdd_l%mhZhdd`l%miZiddal%mjZjddbl%mkZkddcl%mlZldddl%mmZmddel%mnZnddfl%moZoddgl%mpZpddhl%mqZqddil%mrZrddjl%msZsddkl%mtZtddll%muZuddml%mvZwddnl%mxZxddol1myZyddpl1mzZzddql1m{Z{ddrlm|Z|ddsl}m~Z~ddtlmZddulmZddvlHmZddwlHmZddxlHmZddylHmZddzlHmZdd{lmZdd|lmZdd}lmZdd~lVmZddl#mZddl$mZedeOe dfZe edgeefZGddde`ZedefZedefZeededfZeeeeede ee ffZeedZGdddeJeZGddde!jePZGdddeBeZGdddeee(ZGdddeZGdddZGdddZGdddZGddde!jeZGdddeZGdddeZee\ZZZZeZGddde!jeZGdddZGdddeZGdddeeZGdddeZGddde!jeZGdddeeZGdddeeZGdddeZGddde!je!jeCeeeZGdddeZGdddeZGdddeZGddde!jeZGdddeZGdddeQeZGdddeeZGddde!jeFeZeddee ee ffZGdd„deLZGddńde!jeCeZGddDŽde!jeQeOe ZGddɄde!je!je!je!jee0e ZededZZGdd̄deQeeeZGdd΄deeCZe@ddСGdd҄de@ZGddԄdeZGddքdeDeeZeD]Zeeeje҃ qe@ddסGddلde\je@ZGddۄdۃZGdd݄deje"je$jڃZGdd߄deeeeDeeee( ZGddde!jeCeQeOecZGdddeTeZGdddeeeCZeZGddde/ZdS)ztThe :class:`_expression.FromClause` class of SQL expression elements, representing SQL tables and derived rowsets. ) annotationsN)Enum) AbstractSet)Any)Callable)cast)Dict)Generic)Iterable)Iterator)List) NamedTuple)NoReturn)Optional)overload)Sequence)Set)Tuple)Type) TYPE_CHECKING)TypeVar)Union) cache_key) coercions) operators)roles) traversals)type_api)visitors)_ColumnsClauseArgument)_no_kw)_TPis_column_element)is_select_statement) is_subquery)is_table)is_text_clause) Annotated)SupportsCloneAnnotations)_clone)_cloned_difference_cloned_intersection_entity_namespace_key)_EntityNamespace)_expand_cloned _from_objects) _generative_never_select_column)_NoArg)_select_iterables)CacheableOptions)ColumnCollection) ColumnSet) CompileState)DedupeColumnCollection) Executable) Generative)HasCompileState) HasMemoized) Immutable)_document_text_coercion)_anonymous_label) BindParameter)BooleanClauseList) ClauseElement) ClauseList) ColumnClause) ColumnElement)DQLDMLClauseElement)GroupedElement)literal_column)TableValuedColumn)UnaryExpression) OperatorType)NULLTYPE)_TraverseInternalsType)InternalTraversal)prefix_anon_map)exc)util)!HasMemoized_ro_memoized_attribute)Literal)Protocol)Self_T)bound)_ColumnExpressionArgument)#_ColumnExpressionOrStrLabelArgument)_FromClauseArgument)_JoinTargetArgument)_LimitOffsetType) _MAYBE_ENTITY) _NOT_ENTITY)_OnClauseArgument)#_SelectStatementForCompoundArgument)_T0)_T1)_T2)_T3)_T4)_T5)_T6)_T7)_TextCoercedExpressionArgument)_TypedColumnClauseArgument)_TypeEngineArgument)_AmbiguousTableNameMap)ExecutableOption)ReadOnlyColumnCollection)_CacheKeyTraversalType) SQLCompiler)Delete)Update)BinaryExpression)KeyedColumnElement)Label) NamedColumn) TextClause)Function) ForeignKey)ForeignKeyConstraint)TableValueType) TypeEngine)_CloneCallableType FromClauser~)ColumnElement[Any]r~c@s4eZdZejddddZejddddZdS) _JoinTargetProtocolList[FromClause]returncCsdSNselfrrI/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/sql/selectable.pyr4sz!_JoinTargetProtocol._from_objectsr1cCsdSrrrrrrentity_namespacesz$_JoinTargetProtocol.entity_namespaceN)__name__ __module__ __qualname__rXro_non_memoized_propertyr4rrrrrrsrColumnElement[bool])_ColumnExpressionArgument[Any]rarc@s"eZdZdZeddddZdS)_OffsetLimitParamT Optional[int]rcCs|jSr)Zeffective_valuerrrr_limit_offset_valuesz%_OffsetLimitParam._limit_offset_valueN)rrr inherit_cachepropertyrrrrrrsrc@seZdZdZdZdZdZdZdZe ddddZ e j dddd Z d d d d dZddd ddZdddddZe ddddZdS) ReturnsRowsaThe base-most class for Core constructs that have some concept of columns that can represent rows. While the SELECT statement and TABLE are the primary things we think of in this category, DML like INSERT, UPDATE and DELETE can also specify RETURNING which means they can be used in CTEs and other forms, and PostgreSQL has functions that return rows also. .. versionadded:: 1.4 TFrcCs|Srrrrrr selectableszReturnsRows.selectable_SelectIterablecCs tdS)aEA sequence of column expression objects that represents the "selected" columns of this :class:`_expression.ReturnsRows`. This is typically equivalent to .exported_columns except it is delivered in the form of a straight sequence and not keyed :class:`_expression.ColumnCollection`. NNotImplementedErrorrrrr_all_selected_columnss z!ReturnsRows._all_selected_columnsOptional[FromClause]bool fromclausercCs tdS)zReturn ``True`` if this :class:`.ReturnsRows` is 'derived' from the given :class:`.FromClause`. An example would be an Alias of a Table is derived from that Table. Nrrrrrris_derived_fromszReturnsRows.is_derived_fromrNonecCs tdS)z=Populate columns into an :class:`.AliasedReturnsRows` object.Nrrrrr#_generate_fromclause_column_proxiessz/ReturnsRows._generate_fromclause_column_proxiesrcolumnrcCs tdS)z>reset internal collections for an incoming column being added.Nrrrrrr_refresh_for_new_columnsz#ReturnsRows._refresh_for_new_columnz"ReadOnlyColumnCollection[Any, Any]cCs tdS)aA :class:`_expression.ColumnCollection` that represents the "exported" columns of this :class:`_expression.ReturnsRows`. The "exported" columns represent the collection of :class:`_expression.ColumnElement` expressions that are rendered by this SQL construct. There are primary varieties which are the "FROM clause columns" of a FROM clause, such as a table, join, or subquery, the "SELECTed columns", which are the columns in the "columns clause" of a SELECT statement, and the RETURNING columns in a DML statement.. .. versionadded:: 1.4 .. seealso:: :attr:`_expression.FromClause.exported_columns` :attr:`_expression.SelectBase.exported_columns` Nrrrrrexported_columnsszReturnsRows.exported_columnsN)rrr__doc__Z_is_returns_rows_is_from_clause_is_select_base_is_select_statement _is_lateralrrrXrrrrrrrrrrrs   rc@seZdZdZdS)ExecutableReturnsRows0base for executable statements that return rows.Nrrrrrrrrrsrc@seZdZdZdS)TypedReturnsRowsrNrrrrrrsrc@sxeZdZdZdZdZdddddZd d d d d dZej ddde dddddddZ d!ddddddZ d S)" Selectablez!Mark a class as being selectable.rTrrrcCs tdSrrrrrrr'sz"Selectable._refresh_for_new_columnN Optional[str]LateralFromClausenamercCstj||dS);Return a LATERAL alias of this :class:`_expression.Selectable`. The return value is the :class:`_expression.Lateral` construct also provided by the top-level :func:`_expression.lateral` function. .. seealso:: :ref:`tutorial_lateral_correlation` - overview of usage. r)Lateral _constructrrrrrlateral*s zSelectable.lateral1.4zThe :meth:`.Selectable.replace_selectable` method is deprecated, and will be removed in a future release. Similar functionality is available via the sqlalchemy.sql.visitors module.)messagesqlalchemy.sql.utilrAliasr\)oldaliasrcCstjj||S)zReplace all occurrences of :class:`_expression.FromClause` 'old' with the given :class:`_expression.Alias` object, returning a copy of this :class:`_expression.FromClause`. )rX preloadedsql_util ClauseAdaptertraverse)rrrrrrreplace_selectable7s zSelectable.replace_selectableFzKeyedColumnElement[Any]rz!Optional[KeyedColumnElement[Any]])rrequire_embeddedrcCs|j||S)aGiven a :class:`_expression.ColumnElement`, return the exported :class:`_expression.ColumnElement` object from the :attr:`_expression.Selectable.exported_columns` collection of this :class:`_expression.Selectable` which corresponds to that original :class:`_expression.ColumnElement` via a common ancestor column. :param column: the target :class:`_expression.ColumnElement` to be matched. :param require_embedded: only return corresponding columns for the given :class:`_expression.ColumnElement`, if the given :class:`_expression.ColumnElement` is actually present within a sub-element of this :class:`_expression.Selectable`. Normally the column will match if it merely shares a common ancestor with one of the exported columns of this :class:`_expression.Selectable`. .. seealso:: :attr:`_expression.Selectable.exported_columns` - the :class:`_expression.ColumnCollection` that is used for the operation. :meth:`_expression.ColumnCollection.corresponding_column` - implementation method. )rcorresponding_column)rrrrrrrFs#zSelectable.corresponding_column)N)F) rrrr__visit_name__ is_selectablerrrX deprecatedpreload_modulerrrrrrr s  rc@sVeZdZUdZded<dejfgZded<ee dddd d d d d dddZ dS) HasPrefixesr+Tuple[Tuple[DQLDMLClauseElement, str], ...] _prefixesrS _has_prefixes_traverse_internalsprefixesz+:meth:`_expression.HasPrefixes.prefix_with`z.:paramref:`.HasPrefixes.prefix_with.*prefixes`*dialect#_TextCoercedExpressionArgument[Any]strr\)rrrcs"|jtfdd|D|_|S)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:`_expression.HasPrefixes.prefix_with`. :param \*prefixes: textual or :class:`_expression.ClauseElement` construct which will be rendered following the INSERT, UPDATE, or DELETE keyword. :param dialect: optional string dialect name which will limit rendering of this prefix to only that dialect. csg|]}ttj|fqSrrexpectrZStatementOptionRole.0prrr sz+HasPrefixes.prefix_with..)rtuple)rrrrrr prefix_withus $ zHasPrefixes.prefix_withN) rrrr__annotations__rTdp_prefix_sequencerr5rDrrrrrrns   rc@sVeZdZUdZded<dejfgZded<ee dddd d d d d dddZ dS) HasSuffixesrr _suffixesrS _has_suffixes_traverse_internalssuffixesz+:meth:`_expression.HasSuffixes.suffix_with`z.:paramref:`.HasSuffixes.suffix_with.*suffixes`rrrrr\)rrrcs"|jtfdd|D|_|S)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:`_expression.HasSuffixes.suffix_with`. :param \*suffixes: textual or :class:`_expression.ClauseElement` construct which will be rendered following the target clause. :param dialect: Optional string dialect name which will limit rendering of this suffix to only that dialect. csg|]}ttj|fqSrrrrrrrsz+HasSuffixes.suffix_with..)rr)rrrrrr suffix_withs  zHasSuffixes.suffix_withN) rrrrrrTrrr5rDrrrrrrs   rc@seZdZUeZded<dZded<dej fdej fgZ ded<dd d d d d d Z e ddd d d dddZdd d d dddZdS)HasHintsz/util.immutabledict[Tuple[FromClause, str], str]_hintsrzTuple[Tuple[str, str], ...]_statement_hintsrS_has_hints_traverse_internalsrrr\)text dialect_namercCs|d||S)aAdd a statement hint to this :class:`_expression.Select` or other selectable object. This method is similar to :meth:`_expression.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. .. seealso:: :meth:`_expression.Select.with_hint` :meth:`_expression.Select.prefix_with` - generic SELECT prefixing which also can suit some database-specific HINT syntaxes such as MySQL optimizer hints N _with_hint)rrrrrrwith_statement_hintszHasHints.with_statement_hintra)rrrrcCs||||S)aAdd an indexing or other executional context hint for the given selectable to this :class:`_expression.Select` or other selectable object. The text of the hint is rendered in the appropriate location for the database backend in use, relative to the given :class:`_schema.Table` or :class:`_expression.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", 'mssql') .. seealso:: :meth:`_expression.Select.with_statement_hint` rrrrrrrr with_hints*zHasHints.with_hintzOptional[_FromClauseArgument]cCsB|dkr|j||ff7_n |jttj||f|i|_|Sr)rrunionrrrFromClauseRolerrrrr s zHasHints._with_hintN)r)r)rrrrXZ immutabledictrrrrTZdp_statement_hint_listZdp_table_hint_listrrr5rrrrrrrs    +rc@seZdZUdZdZdZejddddZde d <d e d <d Z d e d<dZ dZ dZ dZddddZdZddddddddZd[dddddddZd\d ddddd Zd]d!d d"d#d$d%d&Zddd'd(d)Zddd*d+d,Zejd-dd.d/Zdd0d'd1d2Zejd3dd4d5Zejd3dd6d7Zejd3dd8d9Zejd:dd;d<Zejd=dd>d?Zejd@ddAdBZd0ddCdDZejdEddFdGZ d0ddHdIZ!e"dddJdKZ#d0ddLdMZ$dNd0dOdPdQZ%d ddRd ddddSdTZ&e'r d^dUdVdWdXdYZ(d S)_raERepresent an element that can be used within the ``FROM`` clause of a ``SELECT`` statement. The most common forms of :class:`_expression.FromClause` are the :class:`_schema.Table` and the :func:`_expression.select` constructs. Key features common to all :class:`_expression.FromClause` objects include: * a :attr:`.c` collection, which provides per-name access to a collection of :class:`_expression.ColumnElement` objects. * a :attr:`.primary_key` attribute, which is a collection of all those :class:`_expression.ColumnElement` objects that indicate the ``primary_key`` flag. * Methods to generate various derivations of a "from" clause, including :meth:`_expression.FromClause.alias`, :meth:`_expression.FromClause.join`, :meth:`_expression.FromClause.select`. rFIterable[FromClause]rcCsdSNrrrrrr _hide_fromsLszFromClause._hide_fromsr _is_clone_ofzColumnCollection[Any, Any]_columnsNrschemaT Select[Any]cCst|S)a#Return a SELECT of this :class:`_expression.FromClause`. e.g.:: stmt = some_table.select().where(some_table.c.id == 5) .. seealso:: :func:`_expression.select` - general purpose method which allows for arbitrary column lists. SelectrrrrselectcszFromClause.selectraz)Optional[_ColumnExpressionArgument[bool]]rJoin)rightonclauseisouterfullrcCst|||||S)aaReturn a :class:`_expression.Join` from this :class:`_expression.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:`_expression.FromClause` object such as a :class:`_schema.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:`_expression.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`. .. seealso:: :func:`_expression.join` - standalone function :class:`_expression.Join` - the type of object produced r)rrrrrrrrjoinss0zFromClause.join)rrrrcCst|||d|S)aReturn a :class:`_expression.Join` from this :class:`_expression.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:`_expression.FromClause` object such as a :class:`_schema.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:`_expression.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. .. seealso:: :meth:`_expression.FromClause.join` :class:`_expression.Join` Tr )rrrrrrr outerjoins/zFromClause.outerjoinNamedFromClauserflatrcCstj||dS)atReturn an alias of this :class:`_expression.FromClause`. E.g.:: a2 = some_table.alias('a2') The above code creates an :class:`_expression.Alias` object which can be used as a FROM clause in any SELECT statement. .. seealso:: :ref:`tutorial_using_aliases` :func:`_expression.alias` r)rrrrrrrrrszFromClause.aliasUnion[float, Function[Any]]*Optional[roles.ExpressionElementRole[Any]] TableSample)samplingrseedrcCstj||||dS)aWReturn a TABLESAMPLE alias of this :class:`_expression.FromClause`. The return value is the :class:`_expression.TableSample` construct also provided by the top-level :func:`_expression.tablesample` function. .. seealso:: :func:`_expression.tablesample` - usage guidelines and parameters )rrr)rr)rrrrrrr tablesamples zFromClause.tablesamplercCs ||jkS)zReturn ``True`` if this :class:`_expression.FromClause` is 'derived' from the given ``FromClause``. An example would be an Alias of a Table is derived from that Table. ) _cloned_setrrrrrs zFromClause.is_derived_fromotherrcCst|j|jS)zReturn ``True`` if this :class:`_expression.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. )rr intersectionrrrrr_is_lexical_equivalentsz!FromClause._is_lexical_equivalentrcCst|d|jjdS)z|A brief description of this :class:`_expression.FromClause`. Used primarily for error message formatting. rz object)getattr __class__rrrrr descriptionszFromClause.descriptionrcs jfdd|jDdS)Nc3s|]}|VqdSr _make_proxyrcolrrr $szAFromClause._generate_fromclause_column_proxies..)r_populate_separate_keyscrrr#rr!sz.FromClause._generate_fromclause_column_proxies6ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]cCs|jS)aA :class:`_expression.ColumnCollection` that represents the "exported" columns of this :class:`_expression.Selectable`. The "exported" columns for a :class:`_expression.FromClause` object are synonymous with the :attr:`_expression.FromClause.columns` collection. .. versionadded:: 1.4 .. seealso:: :attr:`_expression.Selectable.exported_columns` :attr:`_expression.SelectBase.exported_columns` r&rrrrr(szFromClause.exported_columnscCs|jS)aA named-based collection of :class:`_expression.ColumnElement` objects maintained by this :class:`_expression.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) :return: a :class:`.ColumnCollection` object. r(rrrrcolumns@szFromClause.columnscCs$d|jkr|||jS)zk A synonym for :attr:`.FromClause.columns` :return: a :class:`.ColumnCollection` r)__dict___init_collections_populate_column_collectionr as_readonlyrrrrr&Rs z FromClause.cr1cCs|jS)aReturn a namespace used for name-based access in SQL expressions. This is the namespace that is used to resolve "filter_by()" type expressions, such as:: stmt.filter_by(address='some address') It defaults to the ``.c`` collection, however internally it can be overridden using the "entity_namespace" annotation to deliver alternative results. r(rrrrr_szFromClause.entity_namespaceIterable[NamedColumn[Any]]cCs|||jS)apReturn the iterable collection of :class:`_schema.Column` objects which comprise the primary key of this :class:`_selectable.FromClause`. For a :class:`_schema.Table` object, this collection is represented by the :class:`_schema.PrimaryKeyConstraint` which itself is an iterable collection of :class:`_schema.Column` objects. )r+r, primary_keyrrrrr/os zFromClause.primary_keyIterable[ForeignKey]cCs|||jS)aVReturn the collection of :class:`_schema.ForeignKey` marker objects which this FromClause references. Each :class:`_schema.ForeignKey` is a member of a :class:`_schema.Table`-wide :class:`_schema.ForeignKeyConstraint`. .. seealso:: :attr:`_schema.Table.foreign_key_constraints` )r+r, foreign_keysrrrrr1}szFromClause.foreign_keyscCsdD]}|j|dqdS)aReset the attributes linked to the ``FromClause.c`` attribute. This collection is separate from all the other memoized things as it has shown to be sensitive to being cleared out in situations where enclosing code, typically in a replacement traversal scenario, has already established strong relationships with the exported columns. The collection is cleared for the case where a table is having a column added to it as well as within a Join during copy internals. )rr)r&r/r1N)r*pop)rkeyrrr_reset_column_collectionsz#FromClause._reset_column_collectionrcCsdd|jDS)Ncss|]}t|s|VqdSrr6rr&rrrr$sz.FromClause._select_iterable..r(rrrr_select_iterableszFromClause._select_iterablecCsFd|jkstd|jkstd|jks*tt|_t|_t|_dS)Nrr/r1)r*AssertionErrorr;rr<r/setr1rrrrr+s zFromClause._init_collectionscCs d|jkS)Nr)r*rrrr_cols_populatedszFromClause._cols_populatedcCsdS)zCalled on subclasses to establish the .c collection. Each implementation has a different way of establishing this collection. Nrrrrrr,sz&FromClause._populate_column_collectionrrcCs |dS)aNGiven 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 ultimately 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)r4rrrrrsz"FromClause._refresh_for_new_columnrrcCs |j|dSNr)rrrrr_anonymous_fromclausesz FromClause._anonymous_fromclauseOptional[OperatorType]zUnion[FromGrouping, Self]againstrcCsdSrrrr?rrr self_groupszFromClause.self_group)NFF)NF)NF)NN)N))rrrrrnamed_with_columnrXrrrrrr_is_joinZ_use_schema_maprr r rrrrrrrr)ro_memoized_propertyr&rr/r1r4r6r+rr9r,rr<rrArrrrr4sr  52     c@s6eZdZUdZdZded<eddddd Zd S) r zA :class:`.FromClause` that has a name. Examples include tables, subqueries, CTEs, aliased tables. .. versionadded:: 2.0 Trrzsqlalchemy.sql.sqltypesTableValuedColumn[Any]rcCs t|tjS)apReturn a :class:`_sql.TableValuedColumn` object for this :class:`_expression.FromClause`. A :class:`_sql.TableValuedColumn` is a :class:`_sql.ColumnElement` that represents a complete row in a table. Support for this construct is backend dependent, and is supported in various forms by backends such as PostgreSQL, Oracle and SQL Server. E.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, column, func, table >>> a = table("a", column("id"), column("x"), column("y")) >>> stmt = select(func.row_to_json(a.table_valued())) >>> print(stmt) {printsql}SELECT row_to_json(a) AS row_to_json_1 FROM a .. versionadded:: 1.4.0b2 .. seealso:: :ref:`tutorial_functions` - in the :ref:`unified_tutorial` )rOr TABLEVALUErrrr table_valuedszNamedFromClause.table_valuedN) rrrrrBrrXrrGrrrrr s r c@s$eZdZdZdZdZdZeZdZdS)SelectLabelStylezTLabel style constants that may be passed to :meth:`_sql.Select.set_label_style`.rrrVN) rrrrLABEL_STYLE_NONELABEL_STYLE_TABLENAME_PLUS_COLLABEL_STYLE_DISAMBIGUATE_ONLYLABEL_STYLE_DEFAULTZLABEL_STYLE_LEGACY_ORMrrrrrH s rHcseZdZUdZdZdejfdejfdejfdejfdejfgZde d <d Z d e d<d e d<d e d<d e d<d e d<dSdddd d dddZ e j ddddZdd dddZdTdddd d!Ze d"d#dd$d%Zefd&d'd#d(fd)d* Zd+d#d,fd-d. Zd d d/d0d1d2Zeddd3d d dd4d/d5d6d7Zedd8d d d4d d9d:d;Zee d"d dd d4dd?Zed d d@dAd#dBdCdDZdEddFdGZe d"dUdHd dIdJdKdLZe j dMddNdOZe j dPddQdRZZ S)VraRepresent a ``JOIN`` construct between two :class:`_expression.FromClause` elements. The public constructor function for :class:`_expression.Join` is the module-level :func:`_expression.join()` function, as well as the :meth:`_expression.FromClause.join` method of any :class:`_expression.FromClause` (e.g. such as :class:`_schema.Table`). .. seealso:: :func:`_expression.join` :meth:`_expression.FromClause.join` r leftrrrrrS_traverse_internalsTrzOptional[ColumnElement[bool]]rNFraOptional[_OnClauseArgument])rNrrrrcCsjttj||_ttj||_|dkr@||j|j|_nttj |jt j d|_||_ ||_ dS)zConstruct a new :class:`_expression.Join`. The usual entrypoint here is the :func:`_expression.join` function or the :meth:`_expression.FromClause.join` method of any :class:`_expression.FromClause` object. Nr?)rrrrrNrAr_match_primariesr OnClauseRolerZ_asboolrr)rrNrrrrrrr__init__s$ z Join.__init__rrcCs$d|jjt|j|jjt|jfS)Nz Join object on %s(%d) and %s(%d))rNridrrrrrrs zJoin.descriptionrrcCs(t|t|kp&|j|p&|j|Sr)hashrNrrrrrrrs   zJoin.is_derived_fromr= FromGroupingr>cCst|Sr)rWr@rrrrAszJoin.self_grouprrcCstjj}dd|jjDdd|jjD}|j|dd|D|j |j dd|D|j tjdd|DdS)NcSsg|]}|qSrrr5rrrrsz4Join._populate_column_collection..css|]}|jr|VqdSr)r/r5rrrr$sz3Join._populate_column_collection..css|]}|j|fVqdSr) _tq_key_labelr!rrrr$scSsg|] }|jqSr)r1r!rrrrs)rXrrrNr&rr/extendreduce_columnsrrr%r1update itertoolschain)rsqlutilr)rrrr,s   z Join._populate_column_collectionrrclonekwrc spttt|jt|j}fdd|Dddddfdd }|d <tjfd i|dS) Ncsi|]}||fqSrrrfr`rarr sz(Join._copy_internals../Union[BinaryExpression[Any], ColumnClause[Any]]r0Optional[KeyedColumnElement[ColumnElement[Any]]]objrarcs,t|tr(|jkr(|j|}|SdSr isinstancerJtablerriraZnewelem new_fromsrrreplacesz%Join._copy_internals..replacerpr`) r8r\r]r4rNrsuper_copy_internals_reset_memoizations)rr`ra all_the_fromsrprr`rarorrrs  zJoin._copy_internalsrrcs(t||j||j|dSr)rqrrNrrrurrrs  zJoin._refresh_for_new_columnr)rNrrcCs&t|tr|j}nd}|j|||dS)N)a_subset)rkrr_join_condition)rrNr left_rightrrrrRs zJoin._match_primaries)rwconsider_as_foreign_keysz(Optional[AbstractSet[ColumnClause[Any]]])abrwrzrcCs|||||}t|dkr,|||||t|dkrdt|trHd}nd}td|j|j|fddt| dD}t|dkr|dSt |SdS) zCreate a join condition between two tables or selectables. See sqlalchemy.sql.util.join_condition() for full docs. 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|]\}}||kqSrr)rxyrrrrPsz(Join._join_condition..N) _joincond_scan_left_rightlen_joincond_trim_constraintsrkrWrWZNoForeignKeysErrorrlistvaluesand_)clsr{r|rwrz constraintshintcritrrrrx)s6     zJoin._join_condition)rz)rNrrzrcCs0t|tr|j}nd}|j||||d}t|S)N)r{r|rwrz)rkrrrr)rrNrrzryrrrr _can_joinVs zJoin._can_joinzjcollections.defaultdict[Optional[ForeignKeyConstraint], List[Tuple[ColumnClause[Any], ColumnClause[Any]]]])r{rwr|rzrc Cstjj}ttj|}ttj|}tt }||fD]}|dkrFq6t |j dddD]}|dk rp|j |krpqXz| |} WnNtjk r} z.dd||D} | j| krnWYqXW5d} ~ XYnX| dk rX||j| |j fqX||k rt |j dddD]}|dk r(|j |kr(q z| |} WnTtjk r} z2dd||D} | j| krpn WYq W5d} ~ XYnX| dk r ||j| |j fq |r6qq6|S)NcSs|jjSrparentZ_creation_orderfkrrrz0Join._joincond_scan_left_right..r3cSsh|] }|jqSrrrtrrr sz1Join._joincond_scan_left_right..cSs|jjSrrrrrrrrcSsh|] }|jqSrrrrrrrs)rXrrrrrr collections defaultdictrsortedr1rZ get_referentrWZNoReferenceErrorZ find_tablesZ table_name constraintappend) rr{rwr|rzrrrNrr"ZnrteZ table_namesrrrrns`       zJoin._joincond_scan_left_rightzDict[Any, Any]z Optional[Any])r{r|rrzrcCs|r0t|D]"}dd|jDt|kr ||=q t|dkrrdd|D}t|dkrrt|d}|||i}t|dkrtd|j|jfdS)NcSsh|] }|jqSr)rrbrrrrsz2Join._joincond_trim_constraints..rcSsh|] }t|qSr)r)rrrrrrsrzCan'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.)relementsr8rrrWZAmbiguousForeignKeysErrorr)rr{r|rrzconstdeduper3rrrrs"        zJoin._joincond_trim_constraintsrcCst|j|j|S)aCreate a :class:`_expression.Select` from this :class:`_expression.Join`. E.g.:: stmt = table_a.join(table_b, table_a.c.id == table_b.c.a_id) stmt = stmt.select() The above will produce a SQL string resembling:: SELECT table_a.id, table_a.col, table_b.id, table_b.a_id FROM table_a JOIN table_b ON table_a.id = table_b.a_id )rrNr select_fromrrrrrsz Join.selectrTODO_Anyr c Cstjj}|rt|jttfr"|}n(|rFt|jtrF|d|jj}n|}t|j ttfr`|}n(|rt|j tr|d|j j}n|}|jj ||d|j j ||d}}| | | |}|j |||j|j|jdS|td|SdS)N_r:rr)rXrrrkrNrWrr rrr<rr]r rrrrrset_label_stylerK correlater) rrrr^Z left_nameZ right_nameZleft_aZright_aadapterrrrr<s@  zJoin._anonymous_fromclausercCstjdd|jDS)NcSsg|]}t|j|jqSr)r4rNr)rr~rrrrsz$Join._hide_froms..)r\r]rrrrrrszJoin._hide_fromsrcCs|g}||jj|jjSr)rNr4r)rZ self_listrrrr4szJoin._from_objects)NFF)N)NF)!rrrrrrTdp_clauseelement dp_booleanrOrrCrTrXrrrrArr,r+rrrrR classmethodrxrrrrr<rr4 __classcell__rrrurrtsd  . ' ,D")rc@seZdZdddddZdS)NoInitr)argracOs*td|jj|jj|jjfdS)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.)rrrlowerrrrarrrrT s  zNoInit.__init__N)rrrrTrrrrrsrc@seZdZdZdS)rz>mark a FROM clause as being able to render directly as LATERALNrrrrrr.srcseZdZUdZdZdZded<dejfdej fgZ ded<e d d d d d d dddZ d d d d ddddZ dddfdd ZddddZejddddZejddd d!Zeddd"d#Zd$dd%d&d'Zefd(d dd)fd*d+ Zed,dd-d.ZZS)/AliasedReturnsRowszLBase class of aliases against tables, subqueries, and other selectables.TFrelementrrSrONrrrr\)rrrarcKs$||}|j|fd|i||S)Nr)__new___init)rrrrarirrrrKs zAliasedReturnsRows._constructrrrrcCsptjtj||d|_||_||_|dkrft|trR|jrRt |dd}t|t rRd}t t ||pbd}||_ dS)NZapply_propagate_attrsranon)rrrReturnsRowsRolerZ _orig_namerkrrBrrEsafe_constructrUr)rrrrrrrWs"  zAliasedReturnsRows._initrrcst||j|dSr)rqrrrrurrrhs z*AliasedReturnsRows._refresh_for_new_columnrcCs|j|dSrrrrrrrr,lsz.AliasedReturnsRows._populate_column_collectionrcCs|j}t|trd}|S)NZanon_1)rrkrErrrrros zAliasedReturnsRows.descriptionrcCs|jjSr)rimplicit_returningrrrrrwsz%AliasedReturnsRows.implicit_returningcCs|jS)z9Legacy for dialects that are referring to Alias.original.rrrrroriginal{szAliasedReturnsRows.originalrrcCs||jkrdS|j|SNT)rrrrrrrrs z"AliasedReturnsRows.is_derived_fromrr_c s2|j}tjfd|i|||jk r.|dS)Nr`)rrqrrr4)rr`raZexisting_elementrurrrrs z"AliasedReturnsRows._copy_internalsrcCs|gSrrrrrrr4sz AliasedReturnsRows._from_objects)rrrr_is_from_container_supports_derived_columnsrrTr dp_anon_namerOrrrrr,rXrrrrrrr+rrr4rrrrurr<s0   rc@seZdZUded<dS)FromClauseAliasrrNrrrrrrrrrs rc@s<eZdZUdZdZdZded<edddd d d d d ZdS)raRepresents 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:`_expression.FromClause.alias` method available on all :class:`_expression.FromClause` subclasses. .. seealso:: :meth:`_expression.FromClause.alias` rTrrNFrrr )rrrrcCstjtj|ddj||dS)NT)Z allow_selectr:)rrrrr)rrrrrrr_factoryszAlias._factory)NF) rrrrrrrrrrrrrrs rcseZdZUdZdZdZdZdZdZde j fde j fde j fde j fd e j fgZd ed <d d dd ddddddfddZejddddZd$ddddddZd%ddddd Zd&dddd!d"d#ZZS)'TableValuedAliasaAn alias against a "table valued" SQL function. This construct provides for a SQL function that returns columns to be used in the FROM clause of a SELECT statement. The object is generated using the :meth:`_functions.FunctionElement.table_valued` method, e.g.: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, func >>> fn = func.json_array_elements_text('["one", "two", "three"]').table_valued("value") >>> print(select(fn.c.value)) {printsql}SELECT anon_1.value FROM json_array_elements_text(:json_array_elements_text_1) AS anon_1 .. versionadded:: 1.4.0b2 .. seealso:: :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial` Ztable_valued_aliasTFrr_tableval_type_render_derived_render_derived_w_typesrSrONrtable_value_typejoins_implicitlyrrzOptional[TableValueType]rr)rrrrrcs.tj||d||_|dkr$tjn||_dSr;)rqrrrrFr)rrrrrrurrrs zTableValuedAlias._initrErcCs t||jS)aReturn a column expression representing this :class:`_sql.TableValuedAlias`. This accessor is used to implement the :meth:`_functions.FunctionElement.column_valued` method. See that method for further details. E.g.: .. sourcecode:: pycon+sql >>> print(select(func.some_func().table_valued("value").column)) {printsql}SELECT anon_1 FROM some_func() AS anon_1 .. seealso:: :meth:`_functions.FunctionElement.column_valued` )rOrrrrrrszTableValuedAlias.columnr cCs.tj|||j|jd}|jr*d|_|j|_|S)zReturn a new alias of this :class:`_sql.TableValuedAlias`. This creates a distinct FROM object that will be distinguished from the original one when used in a SQL statement. rT)rrrrrr)rrrtvarrrrs zTableValuedAlias.aliasrrcCs|j|d}d|_|S)zReturn a new :class:`_sql.TableValuedAlias` with the lateral flag set, so that it renders as LATERAL. .. seealso:: :func:`_expression.lateral` rT)rr)rrrrrrr's zTableValuedAlias.lateral)r with_typesrcCs(tj|j||j|jd}d|_||_|S)aApply "render derived" to this :class:`_sql.TableValuedAlias`. This has the effect of the individual column names listed out after the alias name in the "AS" sequence, e.g.: .. sourcecode:: pycon+sql >>> print( ... select( ... func.unnest(array(["one", "two", "three"])). table_valued("x", with_ordinality="o").render_derived() ... ) ... ) {printsql}SELECT anon_1.x, anon_1.o FROM unnest(ARRAY[%(param_1)s, %(param_2)s, %(param_3)s]) WITH ORDINALITY AS anon_1(x, o) The ``with_types`` keyword will render column types inline within the alias expression (this syntax currently applies to the PostgreSQL database): .. sourcecode:: pycon+sql >>> print( ... select( ... func.json_to_recordset( ... '[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]' ... ) ... .table_valued(column("a", Integer), column("b", String)) ... .render_derived(with_types=True) ... ) ... ) {printsql}SELECT anon_1.a, anon_1.b FROM json_to_recordset(:json_to_recordset_1) AS anon_1(a INTEGER, b VARCHAR) :param name: optional string name that will be applied to the alias generated. If left as None, a unique anonymizing name will be used. :param with_types: if True, the derived columns will include the datatype specification with each column. This is a special syntax currently known to be required by PostgreSQL for some SQL functions. rT)rrrrrrr)rrrZ new_aliasrrrrender_derived4s8zTableValuedAlias.render_derived)NF)N)NF)rrrrrrrrrrTrrdp_typerrOrrrBmemoized_attributerrrrrrrrurrs2  rc@s4eZdZdZdZdZdZed ddddd d ZdS) raRepresent a LATERAL subquery. This object is constructed from the :func:`_expression.lateral` module level function as well as the :meth:`_expression.FromClause.lateral` method available on all :class:`_expression.FromClause` subclasses. While LATERAL is part of the SQL standard, currently only more recent PostgreSQL versions provide support for this keyword. .. seealso:: :ref:`tutorial_lateral_correlation` - overview of usage. rTNz&Union[SelectBase, _FromClauseArgument]rrrcCstjtj|ddj|dS)NT)Zexplicit_subqueryr)rrrrrrrrrrrrszLateral._factory)N) rrrrrrrrrrrrrrwsrcseZdZUdZdZejdejfdejfgZde d<e ddd d d dd d dZ e dddddd d d ddfddZddddZZS)raIRepresent a TABLESAMPLE clause. This object is constructed from the :func:`_expression.tablesample` module level function as well as the :meth:`_expression.FromClause.tablesample` method available on all :class:`_expression.FromClause` subclasses. .. seealso:: :func:`_expression.tablesample` rrrrSrONrarrr)rrrrrcCsttj|j|||dS)Nrr)rrrrr)rrrrrrrrrs zTableSample._factoryzsqlalchemy.sql.functionsrrr)rrrrrcsL|dk s ttjj}t||js,|j|}||_||_ t j ||ddSr;) r7rXrZ sql_functionsrkrfuncsystemrrrqr)rrrrr functionsrurrrs   zTableSample._initz Function[Any]rcCs|jSr)rrrrr _get_methodszTableSample._get_method)NN)rrrrrrrOrTrrrrrXrrrrrrrurrs"     rc seZdZUdZdZejdejfdejfdej fdej fge j e j Zded<d ed <ed(d d dddddZd d d d d d d ddd dddddddd fddZddddZd)d dddddZd dd!d"d#Zd dd!d$d%Zddd&d'ZZS)*CTEaURepresent a Common Table Expression. The :class:`_expression.CTE` object is obtained using the :meth:`_sql.SelectBase.cte` method from any SELECT statement. A less often available syntax also allows use of the :meth:`_sql.HasCTE.cte` method present on :term:`DML` constructs such as :class:`_sql.Insert`, :class:`_sql.Update` and :class:`_sql.Delete`. See the :meth:`_sql.HasCTE.cte` method for usage details on CTEs. .. seealso:: :ref:`tutorial_subqueries_ctes` - in the 2.0 tutorial :meth:`_sql.HasCTE.cte` - examples of calling styles cte _cte_alias _restates recursivenestingrSrOHasCTErNFrr)rrrrcCsttj|j||dS)zReturn a new :class:`_expression.CTE`, or Common Table Expression instance. Please see :meth:`_expression.HasCTE.cte` for detail on CTE usage. )rr)rrr HasCTERoler)rrrrrrrrs z CTE._factory)rrrrrrrrz Optional[CTE]zOptional[Tuple[()]]r) rrrrrrrrrc s@||_||_||_||_|r"||_|r,||_tj||ddSr;)rrrrrrrqr) rrrrrrrrrrurrr s z CTE._initrcCs(|jdk r|j|n |j|dSr)rrrrrrrr,$s zCTE._populate_column_collectionr c Cs"tj|j||j|j||j|jdS)a2Return an :class:`_expression.Alias` of this :class:`_expression.CTE`. This method is a CTE-specific specialization of the :meth:`_expression.FromClause.alias` method. .. seealso:: :ref:`tutorial_using_aliases` :func:`_expression.alias` )rrrrrr)rrrrrrrrrrrr*sz CTE.aliasrgrc GsFt|jstd|jdtj|jj||j|j|j||j |j dS)aReturn a new :class:`_expression.CTE` with a SQL ``UNION`` of the original CTE against the given selectables provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. .. seealso:: :meth:`_sql.HasCTE.cte` - examples of calling styles CTE element fz does not support union()rrrrrr) r%rr7rrrrrrrrrrrrrBs  z CTE.unionc GsFt|jstd|jdtj|jj||j|j|j||j |j dS)aReturn a new :class:`_expression.CTE` with a SQL ``UNION ALL`` of the original CTE against the given selectables provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. .. seealso:: :meth:`_sql.HasCTE.cte` - examples of calling styles rz does not support union_all()r) r%rr7rr union_allrrrrrrrrrr_s  z CTE.union_allcCs|jdk r|jS|S)z A recursive CTE is updated to attach the recursive part. Updated CTEs should still refer to the original CTE. This function returns this reference identifier. N)rrrrr_get_reference_cte}szCTE._get_reference_cte)NF)NF)rrrrrrrOrTrrrrrrrrrrr,rrrrrrrrurrs@  &rc@seZdZUded<dS)_CTEOptsrrNrrrrrrs rc@s6eZdZUded<ded<ded<ded<ded<d S) _ColumnsPlusNamesrrequired_label_name proxy_keyfallback_label_name%Union[ColumnElement[Any], TextClause]rrrepeatedNrrrrrrs rc@s2eZdZUdZeZded<d ddddd d ZdS) SelectsRowszvSub-base of ReturnsRows for elements that deliver rows directly, namely SELECT and INSERT/UPDATE/DELETE..RETURNINGrH _label_styleNrzOptional[_SelectIterable]zList[_ColumnsPlusNames])anon_for_dupe_keycolsrcCsj|dkr|j}t|j}i}g}|j}|jtk}|jtk}d} |D]} d} | jsbd} } }n|rtrvt | svt d} } | j p| j }ntrt | st |r| j } } }n| j } }d} | dkr<| j}|dkr0| j |k} | || j <d} } | r(|r| | }| d7} n| | }| d7} n| j }n |} } }| dk rLtrZt | sZt | |krDt|| t| kr|r| j} }n | j } }|r| |krt|| t| kst |r| | } }| d7} n| | } }| d7} d} n| || <n>|rL|r(| | } }| d7} n| | } }| d7} d} n| || <|t| || || | qD|S)acGenerate column names as rendered in a SELECT statement by the compiler. This is distinct from the _column_naming_convention generator that's intended for population of .c collections and similar, which has different rules. the collection returned here calls upon the _column_naming_convention as well. NrFT)r SelectState_column_naming_conventionrrrKrJZ_render_label_in_columns_clauserr$r7Z_non_anon_labelZ_anon_name_label _tq_labelZ_expression_labelZ_dedupe_anon_tq_label_idxZ_dedupe_anon_label_idxrVZ_anon_tq_labelr)rrrZkey_naming_conventionnamesresultZ result_appendtable_qualifiedZlabel_style_noneZ dedupe_hashr&rZeffective_namerrZ expr_labelrrr_generate_columns_plus_namess                   z(SelectsRows._generate_columns_plus_names)N)rrrrrJrrrrrrrrs  rc@sxeZdZUdZdejfdejfgZded<dZ ded<dZ ded<e d d d d d dddZ ddd d d dddZ dS)rz3Mixin that declares a class to include CTE support._independent_ctes_independent_ctes_optsrS_has_ctes_traverse_internalsrzTuple[CTE, ...]zTuple[_CTEOpts, ...]F nest_hererrr\ctesrrcGsDt|}|D]2}ttj|}|j|f7_|j|f7_q |S)aMAdd one or more :class:`_sql.CTE` constructs to this statement. This method will associate the given :class:`_sql.CTE` constructs with the parent statement such that they will each be unconditionally rendered in the WITH clause of the final statement, even if not referenced elsewhere within the statement or any sub-selects. The optional :paramref:`.HasCTE.add_cte.nest_here` parameter when set to True will have the effect that each given :class:`_sql.CTE` will render in a WITH clause rendered directly along with this statement, rather than being moved to the top of the ultimate rendered statement, even if this statement is rendered as a subquery within a larger statement. This method has two general uses. One is to embed CTE statements that serve some purpose without being referenced explicitly, such as the use case of embedding a DML statement such as an INSERT or UPDATE as a CTE inline with a primary statement that may draw from its results indirectly. The other is to provide control over the exact placement of a particular series of CTE constructs that should remain rendered directly in terms of a particular statement that may be nested in a larger statement. E.g.:: from sqlalchemy import table, column, select t = table('t', column('c1'), column('c2')) ins = t.insert().values({"c1": "x", "c2": "y"}).cte() stmt = select(t).add_cte(ins) Would render:: WITH anon_1 AS (INSERT INTO t (c1, c2) VALUES (:param_1, :param_2)) SELECT t.c1, t.c2 FROM t Above, the "anon_1" CTE is not referenced in the SELECT statement, however still accomplishes the task of running an INSERT statement. Similarly in a DML-related context, using the PostgreSQL :class:`_postgresql.Insert` construct to generate an "upsert":: from sqlalchemy import table, column from sqlalchemy.dialects.postgresql import insert t = table("t", column("c1"), column("c2")) delete_statement_cte = ( t.delete().where(t.c.c1 < 1).cte("deletions") ) insert_stmt = insert(t).values({"c1": 1, "c2": 2}) update_statement = insert_stmt.on_conflict_do_update( index_elements=[t.c.c1], set_={ "c1": insert_stmt.excluded.c1, "c2": insert_stmt.excluded.c2, }, ).add_cte(delete_statement_cte) print(update_statement) The above statement renders as:: WITH deletions AS (DELETE FROM t WHERE t.c1 < %(c1_1)s) INSERT INTO t (c1, c2) VALUES (%(c1)s, %(c2)s) ON CONFLICT (c1) DO UPDATE SET c1 = excluded.c1, c2 = excluded.c2 .. versionadded:: 1.4.21 :param \*ctes: zero or more :class:`.CTE` constructs. .. versionchanged:: 2.0 Multiple CTE instances are accepted :param nest_here: if True, the given CTE or CTEs will be rendered as though they specified the :paramref:`.HasCTE.cte.nesting` flag to ``True`` when they were added to this :class:`.HasCTE`. Assuming the given CTEs are not referenced in an outer-enclosing statement as well, the CTEs given should render at the level of this statement when this flag is given. .. versionadded:: 2.0 .. seealso:: :paramref:`.HasCTE.cte.nesting` )rrrr IsCTERolerr)rrroptrrrradd_cted s`zHasCTE.add_cteNr)rrrrcCstj||||dS)a%Return a new :class:`_expression.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. SQLAlchemy detects :class:`_expression.CTE` objects, which are treated similarly to :class:`_expression.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:`_expression.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:`_expression.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. :param nesting: if ``True``, will render the CTE locally to the statement in which it is referenced. For more complex scenarios, the :meth:`.HasCTE.add_cte` method using the :paramref:`.HasCTE.add_cte.nest_here` parameter may also be used to more carefully control the exact placement of a particular CTE. .. versionadded:: 1.4.24 .. seealso:: :meth:`.HasCTE.add_cte` The following examples include two from PostgreSQL's documentation at https://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) Example 4, Nesting CTE (SQLAlchemy 1.4.24 and above):: value_a = select( literal("root").label("n") ).cte("value_a") # A nested CTE with the same name as the root one value_a_nested = select( literal("nesting").label("n") ).cte("value_a", nesting=True) # Nesting CTEs takes ascendency locally # over the CTEs at a higher level value_b = select(value_a_nested.c.n).cte("value_b") value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b")) The above query will render the second CTE nested inside the first, shown with inline parameters below as:: WITH value_a AS (SELECT 'root' AS n), value_b AS (WITH value_a AS (SELECT 'nesting' AS n) SELECT value_a.n AS n FROM value_a) SELECT value_a.n AS a, value_b.n AS b FROM value_a, value_b The same CTE can be set up using the :meth:`.HasCTE.add_cte` method as follows (SQLAlchemy 2.0 and above):: value_a = select( literal("root").label("n") ).cte("value_a") # A nested CTE with the same name as the root one value_a_nested = select( literal("nesting").label("n") ).cte("value_a") # Nesting CTEs takes ascendency locally # over the CTEs at a higher level value_b = ( select(value_a_nested.c.n). add_cte(value_a_nested, nest_here=True). cte("value_b") ) value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b")) Example 5, Non-Linear CTE (SQLAlchemy 1.4.28 and above):: edge = Table( "edge", metadata, Column("id", Integer, primary_key=True), Column("left", Integer), Column("right", Integer), ) root_node = select(literal(1).label("node")).cte( "nodes", recursive=True ) left_edge = select(edge.c.left).join( root_node, edge.c.right == root_node.c.node ) right_edge = select(edge.c.right).join( root_node, edge.c.left == root_node.c.node ) subgraph_cte = root_node.union(left_edge, right_edge) subgraph = select(subgraph_cte) The above query will render 2 UNIONs inside the recursive CTE:: WITH RECURSIVE nodes(node) AS ( SELECT 1 AS node UNION SELECT edge."left" AS "left" FROM edge JOIN nodes ON edge."right" = nodes.node UNION SELECT edge."right" AS "right" FROM edge JOIN nodes ON edge."left" = nodes.node ) SELECT nodes.node FROM nodes .. seealso:: :meth:`_orm.Query.cte` - ORM version of :meth:`_expression.HasCTE.cte`. )rrr)rr)rrrrrrrr sz HasCTE.cte)NFF)rrrrrTdp_clauseelement_list dp_plain_objrrrrr5rrrrrrrY s    jrc@sXeZdZUdZdZdZdZded<edddddd d Z e d d d dddZ dS)SubqueryaRepresent a subquery of a SELECT. A :class:`.Subquery` is created by invoking the :meth:`_expression.SelectBase.subquery` method, or for convenience the :meth:`_expression.SelectBase.alias` method, on any :class:`_expression.SelectBase` subclass which includes :class:`_expression.Select`, :class:`_expression.CompoundSelect`, and :class:`_expression.TextualSelect`. As rendered in a FROM clause, it represents the body of the SELECT statement inside of parenthesis, followed by the usual "AS " that defines all "alias" objects. The :class:`.Subquery` object is very similar to the :class:`_expression.Alias` object and can be used in an equivalent way. The difference between :class:`_expression.Alias` and :class:`.Subquery` is that :class:`_expression.Alias` always contains a :class:`_expression.FromClause` object whereas :class:`.Subquery` always contains a :class:`_expression.SelectBase` object. .. versionadded:: 1.4 The :class:`.Subquery` class was added which now serves the purpose of providing an aliased version of a SELECT statement. subqueryT SelectBaserNrrcCsttj|j|dS)z#Return a :class:`.Subquery` object.r)rrrSelectStatementRolerrrrrr s zSubquery._factoryraxThe :meth:`.Subquery.as_scalar` method, which was previously ``Alias.as_scalar()`` prior to version 1.4, is deprecated and will be removed in a future release; Please use the :meth:`_expression.Select.scalar_subquery` method of the :func:`_expression.select` construct before constructing a subquery object, or with the ORM use the :meth:`_query.Query.scalar_subquery` method.ScalarSelect[Any]rcCs|jtSr)rrrJscalar_subqueryrrrr as_scalar s zSubquery.as_scalar)N) rrrrrZ _is_subqueryrrrrrXrrrrrrr s   rc@s(eZdZUdZdejfgZded<ded<ddddZd d d d Z e j d d ddZ e j d d ddZ edd ddZedd ddZdddddZd9ddd d!d"d#Zd$dd%d&d'Ze j d(d d)d*Ze j d+d d,d-Zd.d d/d0Zd.d d1d2d3Zer$d:d4d5d6d7d8ZdS);rWz%Represent a grouping of a FROM clauserrSrOrrcCsttj||_dSr)rrrrrrrrrrrT& szFromGrouping.__init__rrcCsdSrrrrrrr+) szFromGrouping._init_collectionsr'cCs|jjSrrr)rrrrr), szFromGrouping.columnscCs|jjSrrrrrrr&2 szFromGrouping.cr.cCs|jjSr)rr/rrrrr/6 szFromGrouping.primary_keyr0cCs|jjSr)rr1rrrrr1: szFromGrouping.foreign_keysrrrcCs |j|Sr)rrrrrrr> szFromGrouping.is_derived_fromNFrNamedFromGroupingr cCst|jj||dS)Nr:)rrrrrrrrA szFromGrouping.aliasrrarcKst|jjf|Sr)rWrr<rrarrrr<F sz"FromGrouping._anonymous_fromclausercCs|jjSr)rrrrrrrI szFromGrouping._hide_fromsrcCs|jjSrrr4rrrrr4M szFromGrouping._from_objectszDict[str, FromClause]cCs d|jiSNrrrrrr __getstate__Q szFromGrouping.__getstate__statercCs|d|_dSr rrr rrr __setstate__T szFromGrouping.__setstate__r=r\r>cCsdSrrr@rrrrAY szFromGrouping.self_group)NF)N)rrrrrTrrOrrTr+rXrr)r&rr/r1rrr<rr4r rrrArrrrrW s8  rWc@s*eZdZdZdZer&d dddddZdS) rzLrepresent a grouping of a named FROM clause .. versionadded:: 2.0 TNr=r\r>cCsdSrrr@rrrrAi szNamedFromGrouping.self_group)N)rrrrrrrArrrrr^ s rcsPeZdZUdZdZdejfdejfdejfgZde d<dZ d e d <d Z e j d d ddZd dddfdd Zere jdd ddZe jdd ddZd d ddZddddd Zdd d!d"Ze j d d d#d$Zddd%d&d'Ze d(d)d d*d+Ze d(d,d d-d.Ze d(d/d d0d1Ze jd2d d3d4ZZS)5 TableClausea-Represents a minimal "table" construct. This is a lightweight table object that has only a name, a collection of columns, which are typically produced by the :func:`_expression.column` function, and a schema:: from sqlalchemy import table, column user = table("user", column("id"), column("name"), column("description"), ) The :class:`_expression.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:`_schema.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. rlr)rrrSrOTrfullnameFzOptional[ColumnClause[Any]]rcCsdS)z4No PK or default support so no autoincrement column.Nrrrrr_autoincrement_column sz!TableClause._autoincrement_columnColumnClause[Any]r)rr)racst||_t|_t|_t|_|D]}| |q,| dd}|dk rV||_ |j dk rtd|j |jf|_ n|j|_ |rt dt|dS)Nrz%s.%szUnsupported argument(s): %s)rqrTrr>rr<r/r8r1 append_columnr2rrrW ArgumentErrorr)rrr)rar&rrurrrT s    zTableClause.__init__z0ReadOnlyColumnCollection[str, ColumnClause[Any]]cCsdSrrrrrrr) szTableClause.columnscCsdSrrrrrrr& sz TableClause.ccCs$|jdk r|jd|jS|jSdS)N.)rrrrrr__str__ s zTableClause.__str__rrrcCsdSrrrrrrr sz#TableClause._refresh_for_new_columncCsdSrrrrrrr+ szTableClause._init_collectionscCs|jSrrrrrrr szTableClause.description)r&rcCs@|j}|dk r*||k r*td|j|f|j|||_dS)Nz1column object '%s' already assigned to table '%s')rlrWrr3radd)rr&existingrrrr s zTableClause.append_columnzsqlalchemy.sql.dmlzutil.preloaded.sql_dml.InsertcCstjj|S)zGenerate an :class:`_sql.Insert` construct against this :class:`_expression.TableClause`. E.g.:: table.insert().values(name='foo') See :func:`_expression.insert` for argument and usage information. )rXrsql_dmlZInsertrrrrinsert s zTableClause.insertrycCstjj|S)aGenerate an :func:`_expression.update` construct against this :class:`_expression.TableClause`. E.g.:: table.update().where(table.c.id==7).values(name='foo') See :func:`_expression.update` for argument and usage information. )rXrrryrrrrr[ s zTableClause.updaterxcCstjj|S)zGenerate a :func:`_expression.delete` construct against this :class:`_expression.TableClause`. E.g.:: table.delete().where(table.c.id==7) See :func:`_expression.delete` for argument and usage information. )rXrrrxrrrrdelete s zTableClause.deletercCs|gSrrrrrrr4 szTableClause._from_objects)rrrrrrTZ)dp_fromclause_canonical_column_collection dp_stringrOrZ _is_tablerrXrDrrTrrr)r&rrr+rrrrr[rr4rrrrurrn sB    r ForUpdateArgc@seZdZUdejfdejfdejfdejfdejfgZded<ded<d ed<d ed<d ed<ed d d d dZ dd dddZ dd dddZ ddddZ ddddddd d dd d dddZ dS)rofnowaitread skip_locked key_sharerSrOz!Optional[Sequence[ClauseElement]]rForUpdateParameterOptional[ForUpdateArg])with_for_updatercCs<t|tr|S|dkrdS|dkr(tStftd|SdS)N)NFTDict[str, Any])rkrr)rr%rrr_from_argument s zForUpdateArg._from_argumentrrcCsFt|toD|j|jkoD|j|jkoD|j|jkoD|j|jkoD|j|jkSr)rkrrr r!r"rrrrr__eq__- s      zForUpdateArg.__eq__cCs || Sr)r(rrrr__ne__7 szForUpdateArg.__ne__intrcCst|Sr)rUrrrr__hash__: szForUpdateArg.__hash__FNrr rr!r"Optional[_ForUpdateOfArgument]cCsB||_||_||_||_|dk r8ddt|D|_nd|_dS)zZRepresents arguments specified to :meth:`_expression.Select.for_update`. NcSsg|]}ttj|qSrrrrZColumnsClauseRolerelemrrrrP sz)ForUpdateArg.__init__..)rr r!r"rXto_listrrrr rr!r"rrrrT= s zForUpdateArg.__init__)rrrrTrrrOrrr'r(r)r+rTrrrrr s*    cseZdZUdZdZdZded<ded<dejfdej fd ej fd ej fgZ d ed <d ddddddfddZ eddddZed.ddddddZed/ddddd Zed!dd"d#d$Zd%dd&d'Zd(dd)d*Zejd+dd,d-ZZS)0ValueszRepresent a ``VALUES`` construct that can be used as a FROM element in a statement. The :class:`_expression.Values` object is created from the :func:`_expression.values` function. .. versionadded:: 1.4 rr%Tuple[Sequence[Tuple[Any, ...]], ...]_datar_unnamed _column_argsr literal_bindsrSrONF)rr8rr)r)rr8csRt||_|dkr2d|_tt|d|_n d|_||_||_|j |_ dS)NTrF) rqrTr7r6rErrUrr8rB)rrr8r)rurrrTo s zValues.__init__List[TypeEngine[Any]]rcCsdd|jDS)NcSsg|] }|jqSrtyper!rrrr sz(Values._column_types..r7rrrr _column_types szValues._column_typesr\r cCs4|dkrtt|d}n|}||_d|_d|_|S)aYReturn a new :class:`_expression.Values` construct that is a copy of this one with the given name. This method is a VALUES-specific specialization of the :meth:`_expression.FromClause.alias` method. .. seealso:: :ref:`tutorial_using_aliases` :func:`_expression.alias` NrTF)rErrUrrBr6)rrr non_none_namerrrr sz Values.aliasrrcCs*|dkr|j}n|}d|_||_d|_|S)zReturn a new :class:`_expression.Values` with the lateral flag set, so that it renders as LATERAL. .. seealso:: :func:`_expression.lateral` NTF)rrr6)rrr>rrrr s zValues.lateralzSequence[Tuple[Any, ...]])rrcCs|j|f7_|S)ajReturn a new :class:`_expression.Values` construct, adding the given data to the data list. E.g.:: my_values = my_values.data([(1, 'value 1'), (2, 'value2')]) :param values: a sequence (i.e. list) of tuples that map to the column expressions given in the :class:`_expression.Values` constructor. )r5)rrrrrdata sz Values.data ScalarValuescCst|j|j|jS)zReturns a scalar ``VALUES`` construct that can be used as a COLUMN element in a statement. .. versionadded:: 2.0.0b4 )r@r7r5r8rrrr scalar_values szValues.scalar_valuesrcCsN|jD]B}|jdk r.|j|k r.||\}}n||j|||_qdSr)r7rlr rsrr)rr&rrrrr, s   z"Values._populate_column_collectionrcCs|gSrrrrrrr4 szValues._from_objects)NF)N)rrrrrr5rrTrdp_dml_multi_valuesrrrOrTrr=r5rrr?rAr,rXrr4rrrrurr3X s0      r3cseZdZUdZdZdejfdejfdejfgZ de d<dd d d fd d Z e ddddZ ddddZerddddddZZS)r@a{Represent a scalar ``VALUES`` construct that can be used as a COLUMN element in a statement. The :class:`_expression.ScalarValues` object is created from the :meth:`_expression.Values.scalar_values` method. It's also automatically generated when a :class:`_expression.Values` is used in an ``IN`` or ``NOT IN`` condition. .. versionadded:: 2.0.0b4 rAr7r5r8rSrOzSequence[ColumnClause[Any]]r4r)r)r?r8cs t||_||_||_dSr)rqrTr7r5r8)rr)r?r8rurrrT s zScalarValues.__init__r9rcCsdd|jDS)NcSsg|] }|jqSrr:r!rrrr sz.ScalarValues._column_types..r<rrrrr= szScalarValues._column_typescCs|Srrrrrr__clause_element__ szScalarValues.__clause_element__Nr=r\r>cCsdSrrr@rrrrA szScalarValues.self_group)N)rrrrrrTrrBrrOrrTrr=rCrrArrrrurr@ s    r@c@seZdZUdZdZdZeZded<ddddd Z e j d d d d Z ddddddddZ e j dd ddZedd ddZee dddd ddZedd d d!Zdd d"d#Zdd$d%d&d'Ze dd(d)d)d*d+d,d-Zejd.d d/d0Zd1d d2d3Ze dd4d5d d6d7Zd8d d9d:Zd5d d;d<Zd=d>d?d@dAZdNd=dBd?dCdDZdOd=d.d?dEdFZ d$d dGdHZ!dPd=dJd.dKdLdMZ"dS)QrzBase class for SELECT statements. This includes :class:`_expression.Select`, :class:`_expression.CompoundSelect` and :class:`_expression.TextualSelect`. TrHrrrrcCs |dSr)rsrrrrr* sz"SelectBase._refresh_for_new_column)ColumnCollection[str, ColumnElement[Any]]rcCs tdS)a$A :class:`_expression.ColumnCollection` representing the columns that this SELECT statement or similar construct returns in its result set. This collection differs from the :attr:`_expression.FromClause.columns` collection of a :class:`_expression.FromClause` in that the columns within this collection cannot be directly nested inside another SELECT statement; a subquery must be applied first which provides for the necessary parenthesization required by SQL. .. note:: The :attr:`_sql.SelectBase.selected_columns` collection does not include expressions established in the columns clause using the :func:`_sql.text` construct; these are silently omitted from the collection. To use plain textual column expressions inside of a :class:`_sql.Select` construct, use the :func:`_sql.literal_column` construct. .. seealso:: :attr:`_sql.Select.selected_columns` .. versionadded:: 1.4 Nrrrrrselected_columns- szSelectBase.selected_columnsNproxy_compound_columnsr0Optional[Iterable[Sequence[ColumnElement[Any]]]]rrGrcCs tdSrrrrrGrrrrM sz.SelectBase._generate_fromclause_column_proxiesrcCs tdS)a A sequence of expressions that correspond to what is rendered in the columns clause, including :class:`_sql.TextClause` constructs. .. versionadded:: 1.4.12 .. seealso:: :attr:`_sql.SelectBase.exported_columns` NrrrrrrW s z SelectBase._all_selected_columnsz1ReadOnlyColumnCollection[str, ColumnElement[Any]]cCs |jS)afA :class:`_expression.ColumnCollection` that represents the "exported" columns of this :class:`_expression.Selectable`, not including :class:`_sql.TextClause` constructs. The "exported" columns for a :class:`_expression.SelectBase` object are synonymous with the :attr:`_expression.SelectBase.selected_columns` collection. .. versionadded:: 1.4 .. seealso:: :attr:`_expression.Select.exported_columns` :attr:`_expression.Selectable.exported_columns` :attr:`_expression.FromClause.exported_columns` )rEr-rrrrrf szSelectBase.exported_columnsraThe :attr:`_expression.SelectBase.c` and :attr:`_expression.SelectBase.columns` attributes are deprecated and will be removed in a future release; these attributes implicitly create a subquery that should be explicit. Please call :meth:`_expression.SelectBase.subquery` first in order to create a subquery, which then contains this attribute. To access the columns that this SELECT object SELECTs from, use the :attr:`_expression.SelectBase.selected_columns` attribute.r'cCs|jjSr)_implicit_subqueryr)rrrrr& sz SelectBase.ccCs|jSrr(rrrrr) szSelectBase.columnscCs tdS)zX Retrieve the current label style. Implemented by subclasses. Nrrrrrget_label_style szSelectBase.get_label_styler\stylercCs tdS)zeReturn a new selectable with the specified label style. Implemented by subclasses. NrrrNrrrr szSelectBase.set_label_stylea The :meth:`_expression.SelectBase.select` method is deprecated and will be removed in a future release; this method implicitly creates a subquery that should be explicit. Please call :meth:`_expression.SelectBase.subquery` first in order to create a subquery, which then can be selected.rr)rrarcOs|jj||Sr)rKrrrrrr s zSelectBase.selectrcCs|SrrrrrrrK szSelectBase._implicit_subqueryTypeEngine[Any]cCs tdSrrrrrr _scalar_type szSelectBase._scalar_typezThe :meth:`_expression.SelectBase.as_scalar` method is deprecated and will be removed in a future release. Please refer to :meth:`_expression.SelectBase.scalar_subquery`.rcCs|Sr)rrrrrr szSelectBase.as_scalarExistscCst|S)aaReturn an :class:`_sql.Exists` representation of this selectable, which can be used as a column expression. The returned object is an instance of :class:`_sql.Exists`. .. seealso:: :func:`_sql.exists` :ref:`tutorial_exists` - in the :term:`2.0 style` tutorial. .. versionadded:: 1.4 )rSrrrrexists szSelectBase.existscCs|jtk r|t}t|S)aXReturn a 'scalar' representation of this selectable, which can be used as a column expression. The returned object is an instance of :class:`_sql.ScalarSelect`. Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression. The scalar subquery can then be used in the WHERE clause or columns clause of an enclosing SELECT. Note that the scalar subquery differentiates from the FROM-level subquery that can be produced using the :meth:`_expression.SelectBase.subquery` method. .. versionchanged: 1.4 - the ``.as_scalar()`` method was renamed to :meth:`_expression.SelectBase.scalar_subquery`. .. seealso:: :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial )rrJr ScalarSelectrrrrr s  zSelectBase.scalar_subqueryrz Label[Any]rcCs||S)zReturn a 'scalar' representation of this selectable, embedded as a subquery with a label. .. seealso:: :meth:`_expression.SelectBase.scalar_subquery`. )rlabelrrrrrV s zSelectBase.labelrcCs t||S)r)rrrrrrrs zSelectBase.lateralcCstj||dS)aReturn a subquery of this :class:`_expression.SelectBase`. A subquery is from a SQL perspective a parenthesized, named construct that can be placed in the FROM clause of another SELECT statement. Given a SELECT statement such as:: stmt = select(table.c.id, table.c.name) The above statement might look like:: SELECT table.id, table.name FROM table The subquery form by itself renders the same way, however when embedded into the FROM clause of another SELECT statement, it becomes a named sub-element:: subq = stmt.subquery() new_stmt = select(subq) The above renders as:: SELECT anon_1.id, anon_1.name FROM (SELECT table.id, table.name FROM table) AS anon_1 Historically, :meth:`_expression.SelectBase.subquery` is equivalent to calling the :meth:`_expression.FromClause.alias` method on a FROM object; however, as a :class:`_expression.SelectBase` object is not directly FROM object, the :meth:`_expression.SelectBase.subquery` method provides clearer semantics. .. versionadded:: 1.4 r)rr_ensure_disambiguated_namesrrrrr s(zSelectBase.subquerycCs tdS)ztEnsure that the names generated by this selectbase will be disambiguated in some way, if possible. NrrrrrrW9sz&SelectBase._ensure_disambiguated_namesFrr cCs |j|dS)a.Return a named subquery against this :class:`_expression.SelectBase`. For a :class:`_expression.SelectBase` (as opposed to a :class:`_expression.FromClause`), this returns a :class:`.Subquery` object which behaves mostly the same as the :class:`_expression.Alias` object that is used with a :class:`_expression.FromClause`. .. versionchanged:: 1.4 The :meth:`_expression.SelectBase.alias` method is now a synonym for the :meth:`_expression.SelectBase.subquery` method. rrPrrrrrAszSelectBase.alias)N)N)NF)#rrrrr is_selectrJrrrrXrrErrrrrr&r)rLrrrBrrKrRrrTrrVrrrWrrrrrr sZ   %       , r_SBc@seZdZUdZdZdejfgejZ de d<dZ de d<ddd d d Z d d ddZ dd ddZdd dddZedd ddZd6dddddZerdd ddZdd d!d"dd#d$d%Zejd&d d'd(Zejd)d d*d+Zejd,d d-d.Zd/d0d1d2dd3d4d5ZdS)7SelectStatementGroupingzRepresent a grouping of a :class:`_expression.SelectBase`. This differs from :class:`.Subquery` in that we are still an "inner" SELECT statement, this is strictly for grouping inside of compound selects. Zselect_statement_groupingrrSrOTrYrrrcCsttttj||_dSr)rrYrrrrrrrrrrTjs z SelectStatementGrouping.__init__zSelectStatementGrouping[_SB]rcCs$|j}||jk rt|S|SdSr)rrWrZ)r new_elementrrrrWos  z3SelectStatementGrouping._ensure_disambiguated_namesrHcCs |jSr)rrLrrrrrLvsz'SelectStatementGrouping.get_label_style label_stylercCst|j|Sr)rZrr)rr^rrrrys z'SelectStatementGrouping.set_label_stylecCs|jSrrrrrrselect_statementsz(SelectStatementGrouping.select_statementNr=r\r>cCs|Srrr@rrrrAsz"SelectStatementGrouping.self_groupcCsdSrrrrrr_ungrouprz SelectStatementGrouping._ungrouprFrrHrIcCs|jj||ddS)NrFrrJrrrrsz;SelectStatementGrouping._generate_fromclause_column_proxiesrcCs|jjSr)rrrrrrrsz-SelectStatementGrouping._all_selected_columnsrDcCs|jjS)a:A :class:`_expression.ColumnCollection` representing the columns that the embedded SELECT statement returns in its result set, not including :class:`_sql.TextClause` constructs. .. versionadded:: 1.4 .. seealso:: :attr:`_sql.Select.selected_columns` )rrErrrrrEsz(SelectStatementGrouping.selected_columnsrcCs|jjSrrrrrrr4sz%SelectStatementGrouping._from_objectsFrrrrcGstdSrr)rrrrrrrszSelectStatementGrouping.add_cte)N)rrrrrrTrr*%_clone_annotations_traverse_internalsrOrZ_is_select_containerrTrWrLrrr_rArr`rrXrrrEr4rrrrrrZXs4    rZc @seZdZUdZdZded<dZded<dZded<dZded <dZ ded <dZ d ed <dZ d ed<e fddddZ edddddddddddddddZddddZddddd Zed!dd"d#Zed!dd$d%ZdVd&d'd(d)d*d+d,Zed)d-d.d/d0d1Zed2d-d3d/d4d1Zdd-d5d/d6d1Zed3dd7d8Zd9dd:d;d<Zed3dd=d>Zeddd?d@Zed&ddAdBdCZedWd&ddddDdEdFZed&ddGdHdIZee dJdKdKddLdMdNZ!ee"j#fdOdPddQdRdSZ$ee"j#fdOdPddQdTdUZ%dS)XGenerativeSelecta&Base class for SELECT statements where additional elements can be added. This serves as the base for :class:`_expression.Select` and :class:`_expression.CompoundSelect` where elements such as ORDER BY, GROUP BY can be added and column rendering can be controlled. Compare to :class:`_expression.TextualSelect`, which, while it subclasses :class:`_expression.SelectBase` and is also a SELECT construct, represents a fixed textual string which cannot be altered at this level, only wrapped as a subquery. rTuple[ColumnElement[Any], ...]_order_by_clauses_group_by_clausesNOptional[ColumnElement[Any]] _limit_clause_offset_clause _fetch_clausezOptional[Dict[str, bool]]_fetch_clause_optionsr$_for_update_argrHrcCs ||_dSrrl)rrrrrrTszGenerativeSelect.__init__Fr,rr-r\)rr rr!r"rcCst|||||d|_|S)a"Specify a ``FOR UPDATE`` clause for this :class:`_expression.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:`_schema.Column` objects or a compatible expression, for some backends may also be a table expression) which will render into a ``FOR UPDATE OF`` clause; supported by PostgreSQL, Oracle, some MySQL versions and possibly others. 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. :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. r,)rrkr2rrrr%s7z GenerativeSelect.with_for_updatercCs|jS)zS Retrieve the current label style. .. versionadded:: 1.4 rlrrrrrLsz GenerativeSelect.get_label_stylerMcCs|j|k r|}||_|S)a{Return a new selectable with the specified label style. There are three "label styles" available, :attr:`_sql.SelectLabelStyle.LABEL_STYLE_DISAMBIGUATE_ONLY`, :attr:`_sql.SelectLabelStyle.LABEL_STYLE_TABLENAME_PLUS_COL`, and :attr:`_sql.SelectLabelStyle.LABEL_STYLE_NONE`. The default style is :attr:`_sql.SelectLabelStyle.LABEL_STYLE_DISAMBIGUATE_ONLY`. In modern SQLAlchemy, there is not generally a need to change the labeling style, as per-expression labels are more effectively used by making use of the :meth:`_sql.ColumnElement.label` method. In past versions, :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL` was used to disambiguate same-named columns from different tables, aliases, or subqueries; the newer :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` now applies labels only to names that conflict with an existing name so that the impact of this labeling is minimal. The rationale for disambiguation is mostly so that all column expressions are available from a given :attr:`_sql.FromClause.c` collection when a subquery is created. .. versionadded:: 1.4 - the :meth:`_sql.GenerativeSelect.set_label_style` method replaces the previous combination of ``.apply_labels()``, ``.with_labels()`` and ``use_labels=True`` methods and/or parameters. .. seealso:: :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL` :data:`_sql.LABEL_STYLE_NONE` :data:`_sql.LABEL_STYLE_DEFAULT` )r _generaterOrrrrs& z GenerativeSelect.set_label_stylerIcCsttj|jS)z9ClauseList access to group_by_clauses for legacy dialects)rI_construct_rawrcomma_oprerrrr_group_by_clauseHsz!GenerativeSelect._group_by_clausecCsttj|jS)z9ClauseList access to order_by_clauses for legacy dialects)rIrnrrordrrrr_order_by_clauseOsz!GenerativeSelect._order_by_clausercrz"Optional[_TypeEngineArgument[int]]r)rrtype_rcCstjtj|||dS)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. )rrr)rrrZLimitOffsetRole)rrrrrrrr_offset_or_limit_clauseVs z(GenerativeSelect._offset_or_limit_clauserr)clauseattrnamercCsdSrrrrtrurrr_offset_or_limit_clause_asintfsz.GenerativeSelect._offset_or_limit_clause_asintzOptional[_OffsetLimitParam]rcCsdSrrrvrrrrwkszUnion[NoReturn, Optional[int]]c CsX|dkr dSz |j}Wn2tk rH}ztd||W5d}~XYn Xt|SdS)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)rAttributeErrorrW CompileErrorrXZasint)rrtruvalueerrrrrrwps  cCs||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. limit)rwrgrrrr_limitszGenerativeSelect._limitrHrtrcCs t|tS)zkTrue if the clause is a simple integer, False if it is not present or is a SQL expression. )rkr)rrtrrr_simple_int_clausesz#GenerativeSelect._simple_int_clausecCs||jdS)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. offset)rwrhrrrr_offsetszGenerativeSelect._offsetcCs|jdk p|jdk p|jdk Sr)rgrhrirrrr_has_row_limiting_clauses  z)GenerativeSelect._has_row_limiting_clause)r|rcCsd|_|_|||_|S)aReturn 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. .. note:: The :meth:`_sql.GenerativeSelect.limit` method will replace any clause applied with :meth:`_sql.GenerativeSelect.fetch`. :param limit: an integer LIMIT parameter, or a SQL expression that provides an integer result. Pass ``None`` to reset it. .. seealso:: :meth:`_sql.GenerativeSelect.fetch` :meth:`_sql.GenerativeSelect.offset` N)rirjrsrg)rr|rrrr|s  zGenerativeSelect.limit)count with_tiespercentrcCs8d|_|dkrd|_|_n|||_||d|_|S)aReturn a new selectable with the given FETCH FIRST criterion applied. This is a numeric value which usually renders as ``FETCH {FIRST | NEXT} [ count ] {ROW | ROWS} {ONLY | WITH TIES}`` expression in the resulting select. This functionality is is currently implemented for Oracle, PostgreSQL, MSSQL. Use :meth:`_sql.GenerativeSelect.offset` to specify the offset. .. note:: The :meth:`_sql.GenerativeSelect.fetch` method will replace any clause applied with :meth:`_sql.GenerativeSelect.limit`. .. versionadded:: 1.4 :param count: an integer COUNT parameter, or a SQL expression that provides an integer result. When ``percent=True`` this will represent the percentage of rows to return, not the absolute value. Pass ``None`` to reset it. :param with_ties: When ``True``, the WITH TIES option is used to return any additional rows that tie for the last place in the result set according to the ``ORDER BY`` clause. The ``ORDER BY`` may be mandatory in this case. Defaults to ``False`` :param percent: When ``True``, ``count`` represents the percentage of the total number of selected rows to return. Defaults to ``False`` .. seealso:: :meth:`_sql.GenerativeSelect.limit` :meth:`_sql.GenerativeSelect.offset` N)rr)rgrirjrs)rrrrrrrfetchs- zGenerativeSelect.fetch)rrcCs|||_|S)a2Return 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. :param offset: an integer OFFSET parameter, or a SQL expression that provides an integer result. Pass ``None`` to reset it. .. seealso:: :meth:`_sql.GenerativeSelect.limit` :meth:`_sql.GenerativeSelect.fetch` )rsrh)rrrrrrs zGenerativeSelect.offsetrr*)startstoprcCs4tjj}d|_|_||j|j||\|_|_|S)aApply LIMIT / OFFSET to this statement based on a slice. The start and stop indices behave like the argument to Python's built-in :func:`range` function. This method provides an alternative to using ``LIMIT``/``OFFSET`` to get a slice of the query. For example, :: stmt = select(User).order_by(User).id.slice(1, 3) renders as .. sourcecode:: sql SELECT users.id AS users_id, users.name AS users_name FROM users ORDER BY users.id LIMIT ? OFFSET ? (2, 1) .. note:: The :meth:`_sql.GenerativeSelect.slice` method will replace any clause applied with :meth:`_sql.GenerativeSelect.fetch`. .. versionadded:: 1.4 Added the :meth:`_sql.GenerativeSelect.slice` method generalized from the ORM. .. seealso:: :meth:`_sql.GenerativeSelect.limit` :meth:`_sql.GenerativeSelect.offset` :meth:`_sql.GenerativeSelect.fetch` N)rXrrrirjZ _make_slicergrh)rrrrrrrslices-  zGenerativeSelect.slicezMUnion[Literal[None, _NoArg.NO_ARG], _ColumnExpressionOrStrLabelArgument[Any]]z(_ColumnExpressionOrStrLabelArgument[Any])_GenerativeSelect__firstclausesrcsH|s|dkrd_n0|tjk rDjtfdd|f|D7_S)aReturn a new selectable with the given list of ORDER BY criteria applied. e.g.:: stmt = select(table).order_by(table.c.id, table.c.name) Calling this method multiple times is equivalent to calling it once with all the clauses concatenated. All existing ORDER BY criteria may be cancelled by passing ``None`` by itself. New ORDER BY criteria may then be added by invoking :meth:`_orm.Query.order_by` again, e.g.:: # will erase all ORDER BY and ORDER BY new_col alone stmt = stmt.order_by(None).order_by(new_col) :param \*clauses: a series of :class:`_expression.ColumnElement` constructs which will be used to generate an ORDER BY clause. .. seealso:: :ref:`tutorial_order_by` - in the :ref:`unified_tutorial` :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial` Nrc3s |]}tjtj|dVqdSrN)rrrZ OrderByRolerrtrrrr$ts z,GenerativeSelect.order_by..)rdr8NO_ARGrrrrrrrorder_byMs$   zGenerativeSelect.order_bycsH|s|dkrd_n0|tjk rDjtfdd|f|D7_S)a~Return a new selectable with the given list of GROUP BY criterion applied. All existing GROUP BY settings can be suppressed by passing ``None``. e.g.:: stmt = select(table.c.name, func.max(table.c.stat)).\ group_by(table.c.name) :param \*clauses: a series of :class:`_expression.ColumnElement` constructs which will be used to generate an GROUP BY clause. .. seealso:: :ref:`tutorial_group_by_w_aggregates` - in the :ref:`unified_tutorial` :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial` Nrc3s |]}tjtj|dVqdSr)rrrZ GroupByRolerrrrr$s z,GenerativeSelect.group_by..)rer8rrrrrrgroup_by|s   zGenerativeSelect.group_by)NN)FF)&rrrrrdrrergrhrirjrkrMrTr5r%rLrrrprqrsrrwr}rrrr|rrrXrrr8rrrrrrrrbsl        ? +   72.rbdefaultcompound_selectc@s eZdZejddddZdS)CompoundSelectStatebTuple[Dict[str, ColumnElement[Any]], Dict[str, ColumnElement[Any]], Dict[str, ColumnElement[Any]]]rcCs*|j}d|_dd|jD}|||fS)NFcSsi|] }|j|qSrrr5rrrresz;CompoundSelectState._label_resolve_dict..) statementrrBr&)rZhacky_subquerydrrr_label_resolve_dicts z'CompoundSelectState._label_resolve_dictN)rrrrXZmemoized_propertyrrrrrrsrc@s$eZdZdZdZdZdZdZdZdS)_CompoundSelectKeywordUNIONz UNION ALLEXCEPTz EXCEPT ALL INTERSECTz INTERSECT ALLN) rrrr UNION_ALLr EXCEPT_ALLr INTERSECT_ALLrrrrrs rc seZdZUdZdZdejfdejfdejfdejfdejfdejfd ejfd ejfd ej fg e j e j Zd ed <ded<dZdZdddddZedddddZedddddZedddddZedddddZeddddd Zedddd!d"Zd#d$d%d&ZdId(d)d*d+d,Zd-d.d/d0d1Zd2dd3d4d5Zdd$d6d7Zd'd8d9d:d;d<d=d>Zd?d;d@fdAdB Z e!j"dCd$dDdEZ#e!j"dFd$dGdHZ$Z%S)JCompoundSelectaXForms the basis of ``UNION``, ``UNION ALL``, and other SELECT-based set operations. .. seealso:: :func:`_expression.union` :func:`_expression.union_all` :func:`_expression.intersect` :func:`_expression.intersect_all` :func:`_expression.except` :func:`_expression.except_all` rselectsrgrhrirjrdrerkkeywordrSrOzList[SelectBase]TFrrg)rrcs(|_fdd|D_tdS)Ncs&g|]}tjtj|djdqS)rrQ)rrrCompoundElementRolerA)rsrrrrsz+CompoundSelect.__init__..)rrrbrT)rrrrrrrTs  zCompoundSelect.__init__)rrcGsttjf|Sr)rrrrrrrr _create_unionszCompoundSelect._create_unioncGsttjf|Sr)rrrrrrr_create_union_allsz CompoundSelect._create_union_allcGsttjf|Sr)rrrrrrr_create_except szCompoundSelect._create_exceptcGsttjf|Sr)rrrrrrr_create_except_allsz!CompoundSelect._create_except_allcGsttjf|Sr)rrrrrrr_create_intersectsz CompoundSelect._create_intersectcGsttjf|Sr)rrrrrrr_create_intersect_allsz$CompoundSelect._create_intersect_allrQrcCs|jdSNr)rrRrrrrrR!szCompoundSelect._scalar_typeNr=rMr>cCst|Sr)rZr@rrrrA$szCompoundSelect.self_grouprrrcCs |jD]}||rdSqdSNTF)rr)rrrrrrr)s  zCompoundSelect.is_derived_fromrHrMcCs<|j|k r8|}|jd|}|g|jdd|_|SNrr)rrmrr)rrNselect_0rrrr/s  zCompoundSelect.set_label_stylecCs>|jd}||jdk r:|}|g|jdd|_|Sr)rrWrm)rZ new_selectrrrrW7s z*CompoundSelect._ensure_disambiguated_namesrFrrHrrIcCsT|jd}|jtk r ||j}tddddt|jDD}|j||ddS)Nrcs$g|]\}fdd|jDqS)csg|]}t|r|qSr)r$Z _annotater5ddrrrXszQCompoundSelect._generate_fromclause_column_proxies...)r)rstmtrrrrWs zFCompoundSelect._generate_fromclause_column_proxies..cSs g|]\}}d|di|fqS)weightrr)rirrrrr]srF)rrrMrzip enumerater)rrrGrextra_col_iteratorrrrr?s   z2CompoundSelect._generate_fromclause_column_proxiesrrcs&t||jD]}||qdSr)rqrr)rrrrurrrms  z&CompoundSelect._refresh_for_new_columnrcCs |jdjSr)rrrrrrrrsz$CompoundSelect._all_selected_columnsrDcCs |jdjS)a\A :class:`_expression.ColumnCollection` representing the columns that this SELECT statement or similar construct returns in its result set, not including :class:`_sql.TextClause` constructs. For a :class:`_expression.CompoundSelect`, the :attr:`_expression.CompoundSelect.selected_columns` attribute returns the selected columns of the first SELECT statement contained within the series of statements within the set operation. .. seealso:: :attr:`_sql.Select.selected_columns` .. versionadded:: 1.4 r)rrErrrrrEvszCompoundSelect.selected_columns)N)&rrrrrrTrr dp_plain_dictrr*rarrrOrr_auto_correlaterTrrrrrrrrRrArrrWrrrXrrrErrrrurrs\    .rrc@s~eZdZUdZerded<nGdddeZerDeddddd Z d d d d ddZ eddddZ ed ddddZ ed dddddZ ed ddddZedd d!d"d#Zd ddd$d%ZedNd'd(d)dd*d+d,ZdOd-d-dd.d/d0Zd1dd2d3Zed d4d5d6d7Zed d8dd9d:Zd;dd?d@ZedAd.F)rrrrrget_column_descriptionssz#SelectState.get_column_descriptionsroles.ReturnsRowsRoler)rfrom_statementrcCs |dSr)r)rrrrrrrszSelectState.from_statementrcCs|tjdd|jDS)Ncss|] }|jVqdSrr3rrrrrr$sz7SelectState.get_columns_clause_froms..)_normalize_fromsr\r] from_iterablerrrrrget_columns_clause_fromss  z$SelectState.get_columns_clause_fromsrH_LabelConventionCallabler]cs>|tk|tk ttdddddfdd }|S)Nrr)r&col_namercst|r dStrt|sts6|j}|dkr2d}|Sr@|jn|j}|dkrxd}|krh||S||Sn.|krr|jS|j S||SdS)NZ _no_label) r(rr$r7Z _proxy_keyrXZ _anon_labelrZ_anon_tq_key_labelZ_anon_key_label)r&rrrrparrrgos.    z1SelectState._column_naming_convention..go)N)rKrJrUr8)rr^rrrrrs#z%SelectState._column_naming_conventionc CsNi|_}|jt|jtjdd|jDtjdd|jD||dS)NcSsg|] }|jqSrr3rrrrrsz*SelectState._get_froms..cSsg|] }|jqSrr3rrrrr$s)check_statementambiguous_table_name_map)Z_ambiguous_table_name_maprr\r]rrr_where_criteria)rrrrrrrs$ zSelectState._get_fromsNrzOptional[Select[Any]]z Optional[_AmbiguousTableNameMap])iterable_of_fromsrrrcst}g}|D]B}t|r.|j|kr.td||js||||jq|rtt j dd|Drfdd|D}dk rfdd|D|S)a0given an iterable of things to select FROM, reduce them to what would actually render in the FROM clause of a SELECT. This does the job of checking for JOINs, tables, etc. that are in fact overlapping due to cloning, adaption, present in overlapping joins, etc. z-select() construct refers to itself as a FROMcSsg|]}t|jqSr)r2rrbrrrrMsz0SelectState._normalize_froms..csg|]}|kr|qSrrrb)toremoverrrSsNc3sL|]D}|jD]8}t|r |jr |jkr |jtt|j|jfVq qdSr)r4r'rrrErrV)ritemfr)rrrr$Vs z/SelectState._normalize_froms..) r8r&rrWInvalidRequestErrorrrrr[r\r]r)rrrrseenrrr)rrrr.s.   zSelectState._normalize_fromszOptional[Sequence[FromClause]])explicit_correlate_fromsimplicit_correlate_fromsrcsjjjr0jjr0fddDjjdk rRfddDjjrrtdkrfddDtstdjS)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. cs(g|] }|ttpdkr|qSrr-rb)rr to_correlaterrrysz2SelectState._get_display_froms..Ncs,g|]$}|ttpdjjkr|qSr)r,r.r_correlate_exceptrb)rrrrrrsrcsg|]}|tkr|qSrr-rb)rrrrrs zSelect statement '%r' returned no FROM clauses due to auto-correlation; specify correlate() to control correlation manually.)rr _correlaterrrrWr)rrrr)rrrrrr_get_display_fromsfs6     zSelectState._get_display_fromsrcCsVdd|jjD}ddt|jD}|}|D]\}}|||q6|||fS)NcSs i|]}|jr|jp|j|qSr)_allow_label_resolverr3r5rrrres zBSelectState._memoized_attr__label_resolve_dict..cSsi|]}|jr|j|qSr)rr3r5rrrres)rrr9rcopyitems setdefault)rZ with_colsZ only_fromsZ only_colsr3rzrrr"_memoized_attr__label_resolve_dictsz.SelectState._memoized_attr__label_resolve_dictzOptional[_JoinTargetElement])rrcCs|jr|jddSdSdS)Nr)r)rrrrrdetermine_last_joined_entitysz(SelectState.determine_last_joined_entityrcCsddt|jDS)NcSsg|]}|qSrrr5rrrrsz4SelectState.all_selected_columns..)r9rrrrrall_selected_columnssz SelectState.all_selected_columnsTuple[_SetupJoinsElement, ...]List[_ColumnsClauseElement]r)args raw_columnsrc Cs|D]\}}}}tr*|dk r*t|ts*t|d}|d}|dkrX|||||\}} n ||} trt|tstt|dk rt|tst| dk r|j| } |jd| t| ||||df|j| dd|_q|dk st|jt|||||df|_qdS)Nrrrr) rrkrKr7"_join_determine_implicit_left_side_join_place_explicit_left_siderrr) rrrrrrNflagsrrreplace_from_obj_indexZ left_clauserrrrsV     zSelectState._setup_joinsrr_JoinTargetElementrfz*Tuple[Optional[FromClause], Optional[int]])rrNrrrc Cstjj}d}|j}|rB||||}t|dkr|d}||}n|i} |j} ttj dd|Dtj dd| j DD] } d| | <q~t | } || ||}t|dkr| |d}t|dkrt dn|st d |f||fS) zWhen join conditions don't express the left side explicitly, determine if an existing FROM or entity in this query can serve as the left hand side. NrrcSsg|] }|jqSrr3rrrrr+szBSelectState._join_determine_implicit_left_side..cSsg|] }|jqSrr3rrrrr.sraCan't determine which FROM clause to join from, there are multiple FROMS which can join to this entity. Please use the .select_from() method to establish an explicit left side, as well as providing an explicit ON clause if not present already to help resolve the ambiguity.zDon't know how to join to %r. Please use the .select_from() method to establish an explicit left side, as well as providing an explicit ON clause if not present already to help resolve the ambiguity.)rXrrrZfind_left_clause_to_join_fromrrr\r]rrrkeysrWr) rrrNrrrrrindexesZ potentialrZ from_clauseZ all_clausesrrrr sX        z.SelectState._join_determine_implicit_left_siderr)rNrcCsXd}tjj}t|j}|r.||j|}ng}t|dkrHt d|rT|d}|S)NrzrCan't identify which entity in which to assign the left side of this join. Please use a more specific ON clause.r) rXrrrr_iterate_from_elementsZ#find_left_clause_that_matches_givenrrrWr)rrNrrrrrrrrQs  z*SelectState._join_place_explicit_left_side)NN)NN)rrr __slots__rrr:rrrrTrrrrrrrrrrrrrXrrrrrrrrsH   /9D;Grc@s8eZdZUdZded<ded<ded<dd d d Zd S) _SelectFromElementsrrrrcrTuple[FromClause, ...]rzIterator[FromClause]rccst}|jD]*}|jD]}||kr$q|||Vqq |jD]*}|jD]}||krVqH|||VqHq>|jD]}||kr~qp|||VqpdSr)r8rr4rrr)rrrrrrrr{s$          z*_SelectFromElements._iterate_from_elementsN)rrrrrrrrrrrts rc@seZdZUdZdZdejfdejfdejfgZ de d<de d <d e d<d e d<d e d<e j Z d ddddZedddddZdS)_MemoizedSelectEntitiesarepresents partial state from a Select object, for the case where Select.columns() has redefined the set of columns/entities the statement will be SELECTing from. This object represents the entities from the SELECT before that transformation was applied, so that transformations that were made in terms of the SELECT at that time, such as join() as well as options(), can access the correct context. In previous SQLAlchemy versions, this wasn't needed because these constructs calculated everything up front, like when you called join() or options(), it did everything to figure out how that would translate into specific SQL constructs that would be ready to send directly to the SQL compiler when needed. But as of 1.4, all of that stuff is done in the compilation phase, during the "compile state" portion of the process, so that the work can all be cached. So it needs to be able to resolve joins/options2 based on what the list of entities was when those methods were called. Zmemoized_select_entitiesrr _with_optionsrSrOzOptional[ClauseElement]rrrzTuple[ExecutableOption, ...]rr\rcKs8|j|j}dd|jD|_|jd||_|S)NcSsi|]\}}||qSrr)rkvrrrresz2_MemoizedSelectEntities._clone..r)rrr*rgetr)rrar&rrrr+sz_MemoizedSelectEntities._clonerr) select_stmtrcCsP|js |jrLt}|j|_|j|_|j|_|j|f7_g|_d|_|_dSr)rrrrr)rrrrrr_generate_for_statements z/_MemoizedSelectEntities._generate_for_statementN)rrrrrrTrdp_setup_join_tupleZdp_executable_optionsrOrrX EMPTY_DICTZ _annotationsr+rrrrrrrs  rcs,eZdZUdZdZdZded<dZded<ded <d Zd ed <dZ d ed<dZ ded<dZ ded<dZ d ed<dZ d ed<dZded<dZdZejZded<d ejfdejfdejfdejfdejfdejfdejfdejfdejfdejfdejfdejfdejfdejfd ejfd ejfdejfd!ejfgejej e!j"e#j$e%j&e'j(Z)d"ed#<e)dej*fgZ+d$ed%<d&ed'<e,d(d)d*d+d,Z-d-d.d/d0Z.d1d2d3d4Z/d5d6d7d8d9Z0d:d2d;d<Z1e2re3d=d>d?d@dAZ4e3dBdCd?dDdAZ4e3d>d2dEdAZ4d>d2dFdAZ4d(d6dGdHdIZ5e6d(d2dJdKZ7dLdMdNdOdPZ8e9dd d dQdRdSd d d6dTdUdVZ:dd dWdXdRdSd d6dYdZd[Z;e9dd d dQdXdRdSd d d6d\d]d^Z
e6e?@dedfdbd2dgdhZAe6did2djdkZBe6dld2dmdnZCdod dpdqdrZDeEfdsd(dtdufdvdw ZFd(dxd*fdydz ZGe9d-d)d{d|d}ZHd~dtd{ddZIe?@ddd-d)dddZJe?Kddd d)dddZLe3dddddZMe3ddddddZMe3dddddddZMe3ddddddddZMe3dddddddddZMe3ddddddddddZMe3dddddddddddZMe3dddddddddd ddZMe3d dd-d d(d)dddZMe9d dd-d d(d)dddZMe6dd2ddZNeNZOe9d5d6dddZPe9d5d6dddZQe9dd6dddZRe9dXd6dddZSe9dd6ddd„ZTe9dd6dddĄZUeVdd2ddDŽZWeVdld2ddɄZXd)d2dd˄ZYdd̜dddtdϜddфZZd d2ddӄZ[dddd֜dd؄Z\dddۜdd݄Z]dddۜdd߄Z^dddۜddZ_dddۜddZ`dddۜddZadddۜddZbZcS)raRepresents a ``SELECT`` statement. The :class:`_sql.Select` object is normally constructed using the :func:`_sql.select` function. See that function for details. .. seealso:: :func:`_sql.select` :ref:`tutorial_selecting_data` - in the 2.0 tutorial rrrrzTuple[TODO_Any, ...]rrrFr _distinctrc _distinct_onrrNz Optional[Tuple[FromClause, ...]]rr_having_criteriarTr:_compile_optionsrdrergrhrirjrkrrSrOrvrr_compile_state_factoryrrrcKstt}|j||S)zCreate a :class:`.Select` using raw ``__new__`` with no coercions. Used internally to build up :class:`.Select` constructs with pre-established state. )rrr*r[)rrarrrr_create_raw_selects  zSelect._create_raw_selectz_ColumnsClauseArgument[Any])entitiescs"fdd|D_tdS)zConstruct a new :class:`_expression.Select`. The public constructor for :class:`_expression.Select` is the :func:`_sql.select` function. csg|]}tjtj|dqSrr.rZentrrrr1s z#Select.__init__..N)rrbrTrr rrrrT*s zSelect.__init__rQrcCs(|js tS|jd}t|j}|djSr)rrRrr6r;)rr0rrrrrR:s   zSelect._scalar_type_ColumnExpressionArgument[bool]r\)criteriarcGs |j|S)z3A synonym for the :meth:`_sql.Select.where` method.where)rrrrrfilterAsz Select.filterzFUnion[FromClause, _JoinTargetProtocol, ColumnElement[Any], TextClause]cCs@|jr&t|j}||}|dk r&|S|jr6|jdS|jdSr)rrrrrr)rmethZ_last_joined_entityrrr_filter_by_zeroFs zSelect._filter_by_zerozSelect[Tuple[_MAYBE_ENTITY]]r)rrcCsdSrrrrrrrZszSelect.scalar_subqueryzSelect[Tuple[_NOT_ENTITY]]zScalarSelect[_NOT_ENTITY]cCsdSrrrrrrr_scCsdSrrrrrrrdscCsdSrrrrrrrgr)kwargsrc s(|fdd|D}|j|S)zWapply the given filtering criterion as a WHERE clause to this select. csg|]\}}t||kqSrr/)rr3rzZ from_entityrrrpsz$Select.filter_by..)rrr)rrrrrr filter_byis  zSelect.filter_bycCst|j}||S)a5Return a :term:`plugin-enabled` 'column descriptions' structure referring to the columns which are SELECTed by this statement. This attribute is generally useful when using the ORM, as an extended structure which includes information about mapped entities is returned. The section :ref:`queryguide_inspection` contains more background. For a Core-only statement, the structure returned by this accessor is derived from the same objects that are returned by the :attr:`.Select.selected_columns` accessor, formatted as a list of dictionaries which contain the keys ``name``, ``type`` and ``expr``, which indicate the column expressions to be selected:: >>> stmt = select(user_table) >>> stmt.column_descriptions [ { 'name': 'id', 'type': Integer(), 'expr': Column('id', Integer(), ...)}, { 'name': 'name', 'type': String(length=30), 'expr': Column('name', String(length=30), ...)} ] .. versionchanged:: 1.4.33 The :attr:`.Select.column_descriptions` attribute returns a structure for a Core-only set of entities, not just ORM-only entities. .. seealso:: :attr:`.UpdateBase.entity_description` - entity information for an :func:`.insert`, :func:`.update`, or :func:`.delete` :ref:`queryguide_inspection` - ORM background )rrrrrrrrcolumn_descriptionsvs) zSelect.column_descriptionsrrrcCst|j}|||S)aApply the columns which this :class:`.Select` would select onto another statement. This operation is :term:`plugin-specific` and will raise a not supported exception if this :class:`_sql.Select` does not select from plugin-enabled entities. The statement is typically either a :func:`_expression.text` or :func:`_expression.select` construct, and should return the set of columns appropriate to the entities represented by this :class:`.Select`. .. seealso:: :ref:`orm_queryguide_selecting_text` - usage examples in the ORM Querying Guide )rrr)rrrrrrrs zSelect.from_statementrrbrP)targetrrrrcCsPtjtj||d}|dk r*ttj|}nd}|j||d||dff7_|S)ah Create a SQL JOIN against this :class:`_expression.Select` object's criterion and apply generatively, returning the newly resulting :class:`_expression.Select`. E.g.:: stmt = select(user_table).join(address_table, user_table.c.id == address_table.c.user_id) The above statement generates SQL similar to:: SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id .. versionchanged:: 1.4 :meth:`_expression.Select.join` now creates a :class:`_sql.Join` object between a :class:`_sql.FromClause` source that is within the FROM clause of the existing SELECT, and a given target :class:`_sql.FromClause`, and then adds this :class:`_sql.Join` to the FROM clause of the newly generated SELECT statement. This is completely reworked from the behavior in 1.3, which would instead create a subquery of the entire :class:`_expression.Select` and then join that subquery to the target. This is a **backwards incompatible change** as the previous behavior was mostly useless, producing an unnamed subquery rejected by most databases in any case. The new behavior is modeled after that of the very successful :meth:`_orm.Query.join` method in the ORM, in order to support the functionality of :class:`_orm.Query` being available by using a :class:`_sql.Select` object with an :class:`_orm.Session`. See the notes for this change at :ref:`change_select_join`. :param target: target table to join towards :param onclause: ON clause of the join. If omitted, an ON clause is generated automatically based on the :class:`_schema.ForeignKey` linkages between the two tables, if one can be unambiguously determined, otherwise an error is raised. :param isouter: if True, generate LEFT OUTER join. Same as :meth:`_expression.Select.outerjoin`. :param full: if True, generate FULL OUTER join. .. seealso:: :ref:`tutorial_select_join` - in the :doc:`/tutorial/index` :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel` :meth:`_expression.Select.join_from` :meth:`_expression.Select.outerjoin` rNr)rrrJoinTargetRolerSr)rrrrr join_targetonclause_elementrrrr s Bz Select.join)rra)from_rrrrcCs|j|||d|dS)aCreate a SQL LEFT OUTER JOIN against this :class:`_expression.Select` object's criterion and apply generatively, returning the newly resulting :class:`_expression.Select`. Usage is the same as that of :meth:`_selectable.Select.join_from`. Trrr) join_from)rr!rrrrrrouterjoin_fromszSelect.outerjoin_from)r!rrrrrcCsbtjtj||d}tjtj||d}|dk r.csi|]}||fqSrrrbrdrrresz*Select._copy_internals..csg|]}|fqSrrrbrdrrrscSsh|]}t|tr|qSr)rkrrbrrrrs z)Select._copy_internals..rfrrgrhcs,t|tr(|jkr(|j|}|SdSrrjrmrnrrrp!sz'Select._copy_internals..replacerp)r)r` omit_attrs)r8r\r]r4rrrrr differencerrqrrrs)rr`rartZexisting_from_objZ add_fromsrprurvrrrs(  zSelect._copy_internalszIterable[ClauseElement]c s"ttjfddi||S)Nr))rrr)r\r]rq get_childrenrrrurrr+4s zSelect.get_children)r rcs&jfdd|D_S)aReturn a new :func:`_expression.select` construct with the given entities appended to its columns clause. E.g.:: my_select = my_select.add_columns(table.c.new_column) The original expressions in the columns clause remain in place. To replace the original expressions with new ones, see the method :meth:`_expression.Select.with_only_columns`. :param \*entities: column, table, or other entity expressions to be added to the columns clause .. seealso:: :meth:`_expression.Select.with_only_columns` - replaces existing expressions rather than appending. :ref:`orm_queryguide_select_multiple_entities` - ORM-centric example csg|]}tjtj|dqSrr.)rrrrrrZs z&Select.add_columns..)rsrrrrr add_columns=s  zSelect.add_columnsz%Iterable[_ColumnsClauseArgument[Any]]csfddt|D_dS)Ncsg|]}tjtj|dqSrr.rrrrres z(Select._set_entities..)rXr1rrrrr _set_entitiesbs zSelect._set_entitiesrzThe :meth:`_expression.Select.column` method is deprecated and will be removed in a future release. Please use :meth:`_expression.Select.add_columns`rcCs ||S)aReturn a new :func:`_expression.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:`_expression.Select.with_only_columns` for guidelines on adding /replacing the columns of a :class:`_expression.Select` object. )r,rrrrrlsz Select.columnr) only_synonymsrcCs.|jtjjj|jf|j|jd|i}|S)a"Return a new :func:`_expression.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:`_expression.Select.set_label_style` 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. r.)with_only_columnsrXrrrZrrr)rr.ZwocrrrrZs zSelect.reduce_columnsz _TCCA[_T0]zSelect[Tuple[_T0]]) _Select__ent0rcCsdSrr)rr0rrrr/sSelect.with_only_columnsz _TCCA[_T1]zSelect[Tuple[_T0, _T1]])r0 _Select__ent1rcCsdSrr)rr0r2rrrr/sz _TCCA[_T2]zSelect[Tuple[_T0, _T1, _T2]])r0r2 _Select__ent2rcCsdSrr)rr0r2r3rrrr/sz _TCCA[_T3]z!Select[Tuple[_T0, _T1, _T2, _T3]])r0r2r3 _Select__ent3rcCsdSrr)rr0r2r3r4rrrr/sz _TCCA[_T4]z&Select[Tuple[_T0, _T1, _T2, _T3, _T4]])r0r2r3r4 _Select__ent4rcCsdSrr)rr0r2r3r4r5rrrr/sz _TCCA[_T5]z+Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]])r0r2r3r4r5 _Select__ent5rcCsdSrr)rr0r2r3r4r5r6rrrr/s z _TCCA[_T6]z0Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]])r0r2r3r4r5r6 _Select__ent6rcCsdSrr)rr0r2r3r4r5r6r7rrrr/s z _TCCA[_T7]z5Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]) r0r2r3r4r5r6r7 _Select__ent7rc CsdSrr) rr0r2r3r4r5r6r7r8rrrr/s )maintain_column_froms)r r9 _Select__kwrcOsdSrrrr9r r:rrrr/scOsR|r t||r*|jj|f|jt|ddtdd|D|_ |S)aReturn a new :func:`_expression.select` construct with its columns clause replaced with the given entities. By default, this method is exactly equivalent to as if the original :func:`_expression.select` had been called with the given entities. E.g. 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) In this mode of operation, :meth:`_sql.Select.with_only_columns` will also dynamically alter the FROM clause of the statement if it is not explicitly stated. To maintain the existing set of FROMs including those implied by the current columns clause, add the :paramref:`_sql.Select.with_only_columns.maintain_column_froms` parameter:: s = select(table1.c.a, table2.c.b) s = s.with_only_columns(table1.c.a, maintain_column_froms=True) The above parameter performs a transfer of the effective FROMs in the columns collection to the :meth:`_sql.Select.select_from` method, as though the following were invoked:: s = select(table1.c.a, table2.c.b) s = s.select_from(table1, table2).with_only_columns(table1.c.a) The :paramref:`_sql.Select.with_only_columns.maintain_column_froms` parameter makes use of the :attr:`_sql.Select.columns_clause_froms` collection and performs an operation equivalent to the following:: s = select(table1.c.a, table2.c.b) s = s.select_from(*s.columns_clause_froms).with_only_columns(table1.c.a) :param \*entities: column expressions to be used. :param maintain_column_froms: boolean parameter that will ensure the FROM list implied from the current columns clause will be transferred to the :meth:`_sql.Select.select_from` method first. .. versionadded:: 1.4.23 cSsg|]}ttj|qSrr.r5rrrr?sz,Select.with_only_columns..r r1) r!Z_assert_no_memoizationsrZnon_generativer&rrrZ!_expression_collection_was_a_listrr;rrrr/s$8 rfcCs t|jS)a Return the completed WHERE clause for this :class:`_expression.Select` statement. This assembles the current collection of WHERE criteria into a single :class:`_expression.BooleanClauseList` construct. .. versionadded:: 1.4 )rGZ_construct_for_whereclauserrrrr whereclauseGs zSelect.whereclause)r<rcGs@t|jtst|D]&}tjtj||d}|j|f7_q|S)zReturn a new :func:`_expression.select` construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any. r)rkrrr7rrrWhereHavingRole)rr< criterionZwhere_criteriarrrrZsz Select.where)havingrcGs0|D]&}tjtj||d}|j|f7_q|S)zReturn a new :func:`_expression.select` construct with the given expression added to its HAVING clause, joined to the existing clause via AND, if any. r)rrrr=r )rr?r>Zhaving_criteriarrrr?ksz Select.havingr)rrcs4|r*d_jtfdd|D_nd_S)aReturn a new :func:`_expression.select` construct which will apply DISTINCT to the SELECT statement overall. E.g.:: from sqlalchemy import select stmt = select(users_table.c.id, users_table.c.name).distinct() The above would produce an statement resembling:: SELECT DISTINCT user.id, user.name FROM user The method also accepts an ``*expr`` parameter which produces the PostgreSQL dialect-specific ``DISTINCT ON`` expression. Using this parameter on other backends which don't support this syntax will raise an error. :param \*expr: optional column expressions. When present, the PostgreSQL dialect will render a ``DISTINCT ON ()`` construct. A deprecation warning and/or :class:`_exc.CompileError` will be raised on other backends. .. deprecated:: 1.4 Using \*expr in other dialects is deprecated and will raise :class:`_exc.CompileError` in a future version. Tc3s |]}tjtj|dVqdSr)rrrZByOfRole)rerrrr$sz"Select.distinct..)rrr)rrrrrdistinctzszSelect.distinctrrcs$jtfdd|D7_S)aReturn a new :func:`_expression.select` construct with the given FROM expression(s) 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:`_schema.Table` or other selectable will have no effect. Passing a :class:`_expression.Join` that refers to an already present :class:`_schema.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:`_expression.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) c3s |]}tjtj|dVqdSrrrrr)rrrrrr$s z%Select.select_from..)rr)rrrrrrs$ zSelect.select_from2Union[Literal[(None, False)], _FromClauseArgument] fromclausesrcGsRd|_|r|ddkr4t|dkr,tdd|_n|jtdd|D|_|S) aReturn a new :class:`_expression.Select` which will correlate the given FROM clauses to that of an enclosing :class:`_expression.Select`. Calling this method turns off the :class:`_expression.Select` object's default behavior of "auto-correlation". Normally, FROM elements which appear in a :class:`_expression.Select` that encloses this one via its :term:`WHERE clause`, ORDER BY, HAVING or :term:`columns clause` will be omitted from this :class:`_expression.Select` object's :term:`FROM clause`. Setting an explicit correlation collection using the :meth:`_expression.Select.correlate` method provides a fixed list of FROM objects that can potentially take place in this process. When :meth:`_expression.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:`_expression.Select` object is, relative to an enclosing :class:`_expression.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:`_expression.Select`. Multi-level correlation ensures that the link between enclosed and enclosing :class:`_expression.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:`_expression.Select` object will correlate none of its FROM entries, and all will render unconditionally in the local FROM clause. :param \*fromclauses: one or more :class:`.FromClause` or other FROM-compatible construct such as an ORM mapped entity to become part of the correlate collection; alternatively pass a single value ``None`` to remove all existing correlations. .. seealso:: :meth:`_expression.Select.correlate_except` :ref:`tutorial_scalar_subquery` FrFNrzKadditional FROM objects not accepted when passing None/False to correlate()rcss|]}ttj|VqdSrrCrbrrrr$sz#Select.correlate..)rrrWrrrrrFrrrrs;   zSelect.correlatecGsVd|_|r|ddkr4t|dkr,tdd|_n|jp.)rrrWrrrrHrrrcorrelate_excepts!  zSelect.correlate_exceptrDcs2tdt|jtfdd|jD}|S)aA :class:`_expression.ColumnCollection` representing the columns that this SELECT statement or similar construct returns in its result set, not including :class:`_sql.TextClause` constructs. This collection differs from the :attr:`_expression.FromClause.columns` collection of a :class:`_expression.FromClause` in that the columns within this collection cannot be directly nested inside another SELECT statement; a subquery must be applied first which provides for the necessary parenthesization required by SQL. For a :func:`_expression.select` construct, the collection here is exactly what would be rendered inside the "SELECT" statement, and the :class:`_expression.ColumnElement` objects are directly present as they were given, e.g.:: col1 = column('q', Integer) col2 = column('p', Integer) stmt = select(col1, col2) Above, ``stmt.selected_columns`` would be a collection that contains the ``col1`` and ``col2`` objects directly. For a statement that is against a :class:`_schema.Table` or other :class:`_expression.FromClause`, the collection will use the :class:`_expression.ColumnElement` objects that are in the :attr:`_expression.FromClause.c` collection of the from element. A use case for the :attr:`_sql.Select.selected_columns` collection is to allow the existing columns to be referenced when adding additional criteria, e.g.:: def filter_on_id(my_select, id): return my_select.where(my_select.selected_columns['id'] == id) stmt = select(MyModel) # adds "WHERE id=:param" to the statement stmt = filter_on_id(stmt, 42) .. note:: The :attr:`_sql.Select.selected_columns` collection does not include expressions established in the columns clause using the :func:`_sql.text` construct; these are silently omitted from the collection. To use plain textual column expressions inside of a :class:`_sql.Select` construct, use the :func:`_sql.literal_column` construct. .. versionadded:: 1.4 zCallable[[Any], str]cs g|]}t|r||fqSrr#r5convrrrsz+Select.selected_columns..)rrrrr;rr-)rccrrJrrEEs=  zSelect.selected_columnscCst|j}t||Sr)rrrrrrrrrs zSelect._all_selected_columnscCs|jtkr|t}|Sr)rrJrrLrrrrrWs  z"Select._ensure_disambiguated_namesrFrrHrIcsP|r(|}fddt|d|D}nfdd|dD}j|dS)zYGenerate column proxies to place in the exported ``.c`` collection of a subquery.c s6g|].\\}}}}}}t|r|j||d|dqS)T)r3rname_is_truncatablecompound_select_colsr$r )rrrrr&r extra_colsrPrrrs z>Select._generate_fromclause_column_proxies..Fcs0g|](\}}}}}t|r|j||ddqS)T)r3rrMrO)rrrrr&rrPrrrsN)rrrr%)rrrGrZproxrrPrrs   z*Select._generate_fromclause_column_proxiescCs|jpt|jjSr)rrrqrrrrr_needs_parens_for_groupingsz!Select._needs_parens_for_groupingr=z*Union[SelectStatementGrouping[Self], Self]r>cCs"t|tr|s|St|SdS)a@Return a 'grouping' construct as per the :class:`_expression.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. N)rkrrQrZr@rrrrAs zSelect.self_grouprgrrcGstj|f|S)aReturn a SQL ``UNION`` of this select() construct against the given selectables provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. :param \**kwargs: keyword arguments are forwarded to the constructor for the newly created :class:`_sql.CompoundSelect` object. )rrrrrrrsz Select.unioncGstj|f|S)aReturn a SQL ``UNION ALL`` of this select() construct against the given selectables provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. :param \**kwargs: keyword arguments are forwarded to the constructor for the newly created :class:`_sql.CompoundSelect` object. )rrrrrrrszSelect.union_allcGstj|f|S)a.Return a SQL ``EXCEPT`` of this select() construct against the given selectable provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. )rrrrrrexcept_szSelect.except_cGstj|f|S)a3Return a SQL ``EXCEPT ALL`` of this select() construct against the given selectables provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. )rrrrrr except_all"szSelect.except_allcGstj|f|S)aReturn a SQL ``INTERSECT`` of this select() construct against the given selectables provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. :param \**kwargs: keyword arguments are forwarded to the constructor for the newly created :class:`_sql.CompoundSelect` object. )rrrrrr intersect2szSelect.intersectcGstj|f|S)aReturn a SQL ``INTERSECT ALL`` of this select() construct against the given selectables provided as positional arguments. :param \*other: one or more elements with which to create a UNION. .. versionchanged:: 1.4.28 multiple elements are now accepted. :param \**kwargs: keyword arguments are forwarded to the constructor for the newly created :class:`_sql.CompoundSelect` object. )rrrrrr intersect_allEszSelect.intersect_all)N)N)N)N)T)N)drrrrrrrrrrrrrr rrrrrr rTrZdp_memoized_select_entitiesZdp_clauseelement_tuplerrrrrrrrrrrrrr*rar?Z_executable_traverse_internalsrOZdp_has_cache_keyrrr rTrRrrrrrrrrrr5r r$r#r r%rXrrr&r(rr+rrr+r,r-rrrZr/r<Z _whereclauserr?rArrrIrYrErrWrrQrArrrRrSrTrUrrrrurrsT               +WN+(  : $ &    O%+H/J :rc@seZdZUdZdejfdejfgZded<gZ ded<dZ e sBd Z dZ d ed<d d d d dZdddddZddddZdd dddZeddddZeZeddd d!d"Zd1d$dd%d&d'Ze rd(dd)d*Zed+dd,d-d.Zed+dd,d/d0Zd#S)2rUaRepresent a scalar subquery. A :class:`_sql.ScalarSelect` is created by invoking the :meth:`_sql.SelectBase.scalar_subquery` method. The object then participates in other SQL expressions as a SQL column expression within the :class:`_sql.ColumnElement` hierarchy. .. seealso:: :meth:`_sql.SelectBase.scalar_subquery` :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial rr;rSrOrr4TFrrr[cCs||_||_|j|_dSr)rrRr;_propagate_attrsrrrrrTys zScalarSelect.__init__rr)attrrcCs t|j|Sr)rr)rrWrrr __getattr__~szScalarSelect.__getattr__r&rcCs|j|jdS)Nrr;rYrrrrr szScalarSelect.__getstate__r cCs|d|_|d|_dS)Nrr;rYr rrrrs zScalarSelect.__setstate__rcCstddS)NzcScalar Select expression has no columns; use this object directly within a column-level expression.)rWrrrrrr)szScalarSelect.columnsrr\)rrcCstd|j||_|S)zuApply a WHERE clause to the SELECT statement referred to by this :class:`_expression.ScalarSelect`. r)rrr)rrrrrrszScalarSelect.whereNr=r>cCs|Srrr@rrrrAszScalarSelect.self_grouprcCsdSrrrrrrr`rzScalarSelect._ungrouprDrEcGstd|jj||_|S)aReturn a new :class:`_expression.ScalarSelect` which will correlate the given FROM clauses to that of an enclosing :class:`_expression.Select`. This method is mirrored from the :meth:`_sql.Select.correlate` method of the underlying :class:`_sql.Select`. The method applies the :meth:_sql.Select.correlate` method, then returns a new :class:`_sql.ScalarSelect` against that statement. .. versionadded:: 1.4 Previously, the :meth:`_sql.ScalarSelect.correlate` method was only available from :class:`_sql.Select`. :param \*fromclauses: a list of one or more :class:`_expression.FromClause` constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate collection. .. seealso:: :meth:`_expression.ScalarSelect.correlate_except` :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial r)rrrrHrrrrs zScalarSelect.correlatecGstd|jj||_|S)aReturn a new :class:`_expression.ScalarSelect` which will omit the given FROM clauses from the auto-correlation process. This method is mirrored from the :meth:`_sql.Select.correlate_except` method of the underlying :class:`_sql.Select`. The method applies the :meth:_sql.Select.correlate_except` method, then returns a new :class:`_sql.ScalarSelect` against that statement. .. versionadded:: 1.4 Previously, the :meth:`_sql.ScalarSelect.correlate_except` method was only available from :class:`_sql.Select`. :param \*fromclauses: a list of one or more :class:`_expression.FromClause` constructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate-exception collection. .. seealso:: :meth:`_expression.ScalarSelect.correlate` :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial r)rrrIrHrrrrIs! zScalarSelect.correlate_except)N)rrrrrTrrrOrr4rrZ_is_implicitly_booleanrrTrXr rrr)r&r5rrAr`rrIrrrrrUYs4   #rUc@seZdZUdZdZded<d%dddd Zejd d d d Z dddddZ dd ddZ dddddZ dddddZ ddddd Zd!dd"d#d$ZdS)&rSzRepresent an ``EXISTS`` clause. See :func:`_sql.exists` for a description of usage. An ``EXISTS`` clause can also be constructed from a :func:`_sql.select` instance by calling :meth:`_sql.SelectBase.exists`. Tz>Union[SelectStatementGrouping[Select[Any]], ScalarSelect[Any]]rNzKOptional[Union[_ColumnsClauseArgument[Any], SelectBase, ScalarSelect[Any]]])_Exists__argumentcCsn|dkrttd}n8t|tr6|}|j|_nt|trF|}n t|}tj||t j t j dddS)NrT)operatorrrZwraps_column_expression) rrNrrkrrVrUrPrTrrTrZ BOOLEANTYPE)rrZrrrrrTs     zExists.__init__rrcCsgSrrrrrrr4szExists._from_objectsz$Callable[[Select[Any]], Select[Any]]z$SelectStatementGrouping[Select[Any]])fnrcCs2|j}||}|jtjd}t|ts.t|S)NrQ)rr`rArrTrkrZr7)rr\rr\Z return_valuerrr_regroups  zExists._regroupzSelect[Tuple[bool]]cCst|S)aReturn a SELECT of this :class:`_expression.Exists`. e.g.:: stmt = exists(some_table.c.id).where(some_table.c.id == 5).select() This will produce a statement resembling:: SELECT EXISTS (SELECT id FROM some_table WHERE some_table = :param) AS anon_1 .. seealso:: :func:`_expression.select` - general purpose method which allows for arbitrary column lists. rrrrrr#sz Exists.selectrDr\rEcs |}|fdd|_|S)zApply correlation to the subquery noted by this :class:`_sql.Exists`. .. seealso:: :meth:`_sql.ScalarSelect.correlate` cs |jSr)rrrFrrrErz"Exists.correlate..r+r]rrrFr@rr^rr7s  zExists.correlatecs |}|fdd|_|S)zApply correlation to the subquery noted by this :class:`_sql.Exists`. .. seealso:: :meth:`_sql.ScalarSelect.correlate_except` cs |jSr)rIrr^rrrXrz)Exists.correlate_except..r_r`rr^rrIIs  zExists.correlate_exceptrarBcs |}|fdd|_|S)aReturn a new :class:`_expression.Exists` construct, applying the given expression to the :meth:`_expression.Select.select_from` method of the select statement contained. .. note:: it is typically preferable to build a :class:`_sql.Select` statement first, including the desired WHERE clause, then use the :meth:`_sql.SelectBase.exists` method to produce an :class:`_sql.Exists` object at once. cs |jSr)rrrrrrjrz$Exists.select_from..r_)rrr@rrarr\s zExists.select_fromrr~cs |}|fdd|_|S)aReturn a new :func:`_expression.exists` construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any. .. note:: it is typically preferable to build a :class:`_sql.Select` statement first, including the desired WHERE clause, then use the :meth:`_sql.SelectBase.exists` method to produce an :class:`_sql.Exists` object at once. cs |jSrrrrtrrrzrzExists.where..r_)rrtr@rrbrrms z Exists.where)N)rrrrrrrTrXrr4r]rrrIrrrrrrrSs   rSc@seZdZUdZdZeZdejfdej fge j e j Zded<dZdZdZd0d d d d d ddZd1d dd d d ddZeddddZejddddZdddddZddddZed d!d"d#d$d%Zd&d'd(d)d d*d+d,Zd-dd.d/Zd&S)2 TextualSelectaFWrap a :class:`_expression.TextClause` construct within a :class:`_expression.SelectBase` interface. This allows the :class:`_expression.TextClause` object to gain a ``.c`` collection and other FROM-like capabilities such as :meth:`_expression.FromClause.alias`, :meth:`_expression.SelectBase.cte`, etc. The :class:`_expression.TextualSelect` construct is produced via the :meth:`_expression.TextClause.columns` method - see that method for details. .. versionchanged:: 1.4 the :class:`_expression.TextualSelect` class was renamed from ``TextAsFrom``, to more correctly suit its role as a SELECT-oriented object and not a FROM clause. .. seealso:: :func:`_expression.text` :meth:`_expression.TextClause.columns` - primary creation interface. Ztextual_selectr column_argsrSrOTFr~z$List[_ColumnExpressionArgument[Any]]rr)rr) positionalrcCs||dd|D|dS)NcSsg|]}ttj|qSr)rrrZLabeledColumnExprRoler5rrrrsz*TextualSelect.__init__..)rrrr)rerrrrTszTextualSelect.__init__zList[NamedColumn[Any]]cCs||_||_||_dSr)rrdrerfrrrrszTextualSelect._initz.ColumnCollection[str, KeyedColumnElement[Any]]rcCstdd|jDS)amA :class:`_expression.ColumnCollection` representing the columns that this SELECT statement or similar construct returns in its result set, not including :class:`_sql.TextClause` constructs. This collection differs from the :attr:`_expression.FromClause.columns` collection of a :class:`_expression.FromClause` in that the columns within this collection cannot be directly nested inside another SELECT statement; a subquery must be applied first which provides for the necessary parenthesization required by SQL. For a :class:`_expression.TextualSelect` construct, the collection contains the :class:`_expression.ColumnElement` objects that were passed to the constructor, typically via the :meth:`_expression.TextClause.columns` method. .. versionadded:: 1.4 css|]}|j|fVqdSrrr5rrrr$sz1TextualSelect.selected_columns..)r;rdr-rrrrrEszTextualSelect.selected_columnsrcCs|jSr)rdrrrrrsz#TextualSelect._all_selected_columnsrHrMcCs|SrrrOrrrrszTextualSelect.set_label_stylecCs|SrrrrrrrWsz)TextualSelect._ensure_disambiguated_nameszBindParameter[Any]rr\)bindsbind_as_valuesrcOs|jj|||_|Sr)r bindparams)rrgrhrrrriszTextualSelect.bindparamsNrFrrH)rrGrcsZtrttst|r:jfddt|j|Dnjfdd|jDdS)Nc3s |]\}}|j|dVqdS))rNNr)rr&rPr#rrr$szDTextualSelect._generate_fromclause_column_proxies..c3s|]}|VqdSrrr5r#rrr$s)rrkrr7rr%rrd)rrrGrr#rrs z1TextualSelect._generate_fromclause_column_proxieszUnion[TypeEngine[Any], Any]cCs |jdjSr)rdr;rrrrrR szTextualSelect._scalar_type)F)F) rrrrrrJrrTrrr*rarrrOrZ _is_textualZis_textrXrTrrYrErXrrrrWr5rirrRrrrrrc~s:   rccs8eZdZdddfdd Zejdddd ZZS) AnnotatedFromClauserrrc s4tjf||ddr0|j}|jj||_dS)NZind_cols_on_fromclauseF)rqrrr_Annotated__elementrr&fget)rraeerurrrrs z#AnnotatedFromClause._copy_internalsr'rcCs |j}|jS)aoproxy the .c collection of the underlying FromClause. Originally implemented in 2008 as a simple load of the .c collection when the annotated construct was created (see d3621ae961a), in modern SQLAlchemy versions this can be expensive for statements constructed with ORM aliases. So for #8796 SQLAlchemy 2.0 we instead proxy it, which works just as well. Two different use cases seem to require the collection either copied from the underlying one, or unique to this AnnotatedFromClause. See test_selectable->test_annotated_corresponding_column )rkr&)rrmrrrr&szAnnotatedFromClause.c)rrrrrrXrDr&rrrrurrjsrj)r __future__rrenumrr\typingrrrrrrr r r r r rrrrrrrrrrr}rrrrrrrZ_typingr r!r"r$r%r&r'r( annotationr)r*baser+r,r.r0r1r2r4r5r7r8r9r:r;r<r=r>r?r@rArBrCrDrrErFrGrHrIrJrKrLrMrNrOrPrQZsqltypesrRrSrTrUrWrXrYZ util.typingrZr[r\rr]r_r`rarbrcrdrerfrgrhrirjrkrlrmrnrorprqZ_TCCArrrsrtrurvrrwZdmlrxryrzr{r|r}r~rrrrrrrrZ_ColumnsClauseElementrrrrZ_OnClauseElementZ_ForUpdateOfArgumentZ_SetupJoinsElementrr*rrrrrrrrrZAnonymizedFromClauseRolerr rHrrJrKrLrrMZ DMLTableRolerrrrrrrrrrrrrrrrrrWrrrr#rZ InElementRoler3r@rZ DMLSelectRolerrrYrZrbZ plugin_forrrrr0setattrrZ MemoizedSlotsrrZ HasCacheKeyZHasCopyInternalsZ TraversiblerrrUrSrcZ TextAsFromrjrrrrs.                                                                                                                                 TN4/c/,c.\$8!: 5!/ =A"F . E ar  O b :