U a{ @s4dZddlZddlZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd l m Z dd l mZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm 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$m.Z.dd+l$m/Z/dd,l$m0Z0dd-l m1Z1d.d/lm2Z2d.d0lm3Z3d.d1l4m5Z5Gd2d3d3e'Z6e37d4d5d6d7Z8Gd8d9d9ej9e)Z:Gd:d;d;e:Z;Gdd?d?e<Z>Gd@dAdAe<Z?GdBdCdCej@e;ZAe3BdDdEZCe3BdFdGZDe3BdHdIZEeEZFGdJdKdKejGeAZHGdLdMdMe<ZIGdNdOdOeIeAZJGdPdQdQejGeJZKGdRdSdSeKZLGdTdUdUeJZMGdVdWdWeJZNGdXdYdYejGejOee=e>eJZPGdZd[d[ejQZRGd\d]d]eJZSGd^d_d_e,eAZTGd`dadaejGe!eAZUGdbdcdce)ZVGdddedeeeAZWGdfdgdgejXejYejZej[eReee; Z\Gdhdidie,e\Z]Gdjdkdke<Z^Gdldmdme^e\Z_e`dndoGdpdqdqeZaGdrdsdsee_ZbGdtdudue<Zce`dndvGdwdxdxe3jdeZeGdydzdze<ZfGd{d|d|e jge jhe jiZjGd}d~d~e=e>e?eecefe_ ZkGdddej[ee-ZlGddde0ZmGddde\ZnenZoGddde ZpdS)ztThe :class:`_expression.FromClause` class of SQL expression elements, representing SQL tables and derived rowsets. N) attrgetter) coercions) operators)roles) traversals)type_api)visitors) Annotated)SupportsCloneAnnotations)_clone)_cloned_difference_cloned_intersection_entity_namespace_key)_expand_cloned _from_objects) _generative)_select_iterables)CacheableOptions)ColumnCollection) ColumnSet) CompileState)DedupeColumnCollection) Executable) Generative)HasCompileState) HasMemoized) Immutable)prefix_anon_map)_document_text_coercion)_anonymous_label)and_) BindParameter)BooleanClauseList) ClauseElement) ClauseList) ColumnClause)GroupedElement)Grouping)literal_column)TableValuedColumn)UnaryExpression)InternalTraversal)exc)util)inspectc@seZdZdZeddZdS)_OffsetLimitParamTcCs|jSN)Zeffective_valueselfr8ZC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\sql\selectable.py_limit_offset_valueCsz%_OffsetLimitParam._limit_offset_valueN)__name__ __module__ __qualname__ inherit_cachepropertyr:r8r8r8r9r4@sr41.4zzThe standalone :func:`.subquery` function is deprecated and will be removed in a future release. Use select().subquery().cOstj|||S)aReturn an :class:`.Subquery` object derived from a :class:`_expression.Select`. :param alias: the alias name for the subquery :param \*args, \**kwargs: all other arguments are passed through to the :func:`_expression.select` function. )Selectcreate_legacy_selectsubquery)aliasargskwargsr8r8r9rCHsrCc@sDeZdZdZdZdZdZdZeddZ eddZ edd Z d S) 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 TFcCs|Sr5r8r6r8r8r9 selectablenszReturnsRows.selectablecCs 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`. NNotImplementedErrorr6r8r8r9_all_selected_columnsrs z!ReturnsRows._all_selected_columnscCs 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` NrIr6r8r8r9exported_columns~szReturnsRows.exported_columnsN) r;r<r=__doc__Z_is_returns_rows_is_from_clause_is_select_statement _is_lateralr?rHrKrLr8r8r8r9rGZs   rGc@sTeZdZdZdZdZddZdddZej d d d e d d dZ dddZ dS) Selectablez!Mark a class as being selectable.rHTcCs tdSr5rIr7columnr8r8r9_refresh_for_new_columnsz"Selectable._refresh_for_new_columnNcCs t||SaMReturn 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. .. versionadded:: 1.1 .. seealso:: :ref:`lateral_selects` - overview of usage. )Lateral _constructr7namer8r8r9laterals zSelectable.lateralr@zThe :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.utilcCstjj||S)zReplace all occurrences of :class:`_expression.FromClause` 'old' with the given :class:`_expression.Alias` object, returning a copy of this :class:`_expression.FromClause`. )r2 preloadedsql_util ClauseAdaptertraverse)r7oldrDr8r8r9replace_selectables zSelectable.replace_selectableFcCs|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. )rLcorresponding_column)r7rSZrequire_embeddedr8r8r9rcs!zSelectable.corresponding_column)N)F) r;r<r=rM__visit_name__ is_selectablerTrZr2 deprecatedpreload_modulerbrcr8r8r8r9rQs  rQc@s>eZdZdZdejfgZeedddddZ d d d Z dS) HasPrefixesr8 _prefixesexprz+:meth:`_expression.HasPrefixes.prefix_with`z*:paramref:`.HasPrefixes.prefix_with.*expr`cOs4|dd}|r$tdd||||dS)aAdd one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative. This is used to support backend-specific prefix keywords such as those provided by MySQL. E.g.:: stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql") # MySQL 5.7 optimizer hints stmt = select(table).prefix_with( "/*+ BKA(t1) */", dialect="mysql") Multiple prefixes can be specified by multiple calls to :meth:`_expression.HasPrefixes.prefix_with`. :param \*expr: textual or :class:`_expression.ClauseElement` construct which will be rendered following the INSERT, UPDATE, or DELETE keyword. :param \**kw: A single keyword 'dialect' is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect. dialectNUnsupported argument(s): %s,)popr1 ArgumentErrorjoin_setup_prefixesr7rjkwrkr8r8r9 prefix_withs !  zHasPrefixes.prefix_withNcs"|jtfdd|D|_dS)Ncsg|]}ttj|fqSr8rexpectrZStatementOptionRole.0prkr8r9 sz/HasPrefixes._setup_prefixes..)rituple)r7prefixesrkr8rzr9rqs  zHasPrefixes._setup_prefixes)N) r;r<r=rir/dp_prefix_sequence _has_prefixes_traverse_internalsrr"rtrqr8r8r8r9rhs "rhc@s>eZdZdZdejfgZeedddddZ d d d Z dS) HasSuffixesr8 _suffixesrjz+:meth:`_expression.HasSuffixes.suffix_with`z*:paramref:`.HasSuffixes.suffix_with.*expr`cOs4|dd}|r$tdd||||dS)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 \*expr: textual or :class:`_expression.ClauseElement` construct which will be rendered following the target clause. :param \**kw: A single keyword 'dialect' is accepted. This is an optional string dialect name which will limit rendering of this suffix to only that dialect. rkNrlrm)rnr1rorp_setup_suffixesrrr8r8r9 suffix_with&s   zHasSuffixes.suffix_withNcs"|jtfdd|D|_dS)Ncsg|]}ttj|fqSr8rurwrzr8r9r{Ksz/HasSuffixes._setup_suffixes..)rr|)r7suffixesrkr8rzr9rIs  zHasSuffixes._setup_suffixes)N) r;r<r=rr/r~ _has_suffixes_traverse_internalsrr"rrr8r8r8r9rs rc@sDeZdZeZdZdejfdej fgZ d ddZ e d ddZ d S) HasHintsr8_statement_hints_hints*cCs|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. .. versionadded:: 1.0.0 .. 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)r7text dialect_namer8r8r9with_statement_hint[szHasHints.with_statement_hintcCsB|dkr|j||ff7_n |jttj||f|i|_dS)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", 'sybase') .. seealso:: :meth:`_expression.Select.with_statement_hint` N)rrunionrrvrFromClauseRole)r7rHrrr8r8r9rus$ zHasHints.with_hintN)r)r)r;r<r=r2Z immutabledictrrr/Zdp_statement_hint_listZdp_table_hint_list_has_hints_traverse_internalsrrrr8r8r8r9rRs rc@s:eZdZdZdZdZgZdZdZdZ dZ dZ e j dddd7d d Zd8d d Zd9d dZd:ddZe dddZd;ddZddZddZeddZddZeddZe jd d!Zed"d#Ze jd$d%Ze jd&d'Zd(d)Z ee!d*d+d,Z"ee!d*Z#d-d.Z$ed/d0Z%d1d2Z&d3d4Z'd>> 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) 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` )r-r TABLEVALUEr6r8r8r9 table_valuedjszFromClause.table_valuedcCst||||S)avReturn 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. .. versionadded:: 1.1 .. seealso:: :func:`_expression.tablesample` - usage guidelines and parameters ) TableSamplerW)r7samplingrYseedr8r8r9 tablesampleszFromClause.tablesamplecCs ||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_setr7rr8r8r9is_derived_froms zFromClause.is_derived_fromcCs|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. )r intersectionr7otherr8r8r9_is_lexical_equivalentsz!FromClause._is_lexical_equivalentcCst|d|jjdS)z|A brief description of this :class:`_expression.FromClause`. Used primarily for error message formatting. rYz object)getattr __class__r;r6r8r8r9 descriptionszFromClause.descriptioncs jfdd|jDdS)Nc3s|]}|VqdSr5 _make_proxyrxcolrr8r9 szAFromClause._generate_fromclause_column_proxies..)_columns_populate_separate_keyscrr8rr9#_generate_fromclause_column_proxiessz.FromClause._generate_fromclause_column_proxiescCs|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` columnsr6r8r8r9rLszFromClause.exported_columnscCs$d|jkr|||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)__dict___init_collections_populate_column_collectionr as_immutabler6r8r8r9rs zFromClause.columnscCs|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. rr6r8r8r9entity_namespaceszFromClause.entity_namespacecCs|||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. )rr primary_keyr6r8r8r9rs zFromClause.primary_keycCs|||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` )rr foreign_keysr6r8r8r9rszFromClause.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. )rrrrN)rrn)r7keyr8r8r9_reset_column_collectionsz#FromClause._reset_column_collectionra= A named-based collection of :class:`_expression.ColumnElement` objects maintained by this :class:`_expression.FromClause`. The :attr:`_sql.FromClause.c` attribute is an alias for the :attr:`_sql.FromClause.columns` atttribute. :return: a :class:`.ColumnCollection` )doccCsFd|jkstd|jkstd|jks*tt|_t|_t|_dS)Nrrr)rAssertionErrorrrrrsetrr6r8r8r9r4s zFromClause._init_collectionscCs d|jkS)Nr)rr6r8r8r9_cols_populated=szFromClause._cols_populatedcCsdS)zCalled on subclasses to establish the .c collection. Each implementation has a different way of establishing this collection. Nr8r6r8r8r9rAsz&FromClause._populate_column_collectioncCs |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)rrRr8r8r9rTIsz"FromClause._refresh_for_new_columncCs |j|dSNrY)rDrr8r8r9_anonymous_fromclausedsz FromClause._anonymous_fromclause)N)NFF)NF)NF)NN)NF))r;r<r=rMrdnamed_with_column _hide_fromsschemarerN_is_joinZ_use_schema_mapr2deprecated_paramsrrprrDrgrrrrr?rrrLmemoized_propertyrrrrrrr_select_iterablerrrrTrr8r8r8r9rs^   . .              rLABEL_STYLE_NONEavLabel style indicating no automatic labeling should be applied to the columns clause of a SELECT statement. Below, the columns named ``columna`` are both rendered as is, meaning that the name ``columna`` can only refer to the first occurrence of this name within a result set, as well as if the statement were used as a subquery:: >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_NONE >>> table1 = table("table1", column("columna"), column("columnb")) >>> table2 = table("table2", column("columna"), column("columnc")) >>> print(select(table1, table2).join(table2, true()).set_label_style(LABEL_STYLE_NONE)) SELECT table1.columna, table1.columnb, table2.columna, table2.columnc FROM table1 JOIN table2 ON true Used with the :meth:`_sql.Select.set_label_style` method. .. versionadded:: 1.4 LABEL_STYLE_TABLENAME_PLUS_COLaLLabel style indicating all columns should be labeled as ``_`` when generating the columns clause of a SELECT statement, to disambiguate same-named columns referenced from different tables, aliases, or subqueries. Below, all column names are given a label so that the two same-named columns ``columna`` are disambiguated as ``table1_columna`` and ``table2_columna`:: >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_TABLENAME_PLUS_COL >>> table1 = table("table1", column("columna"), column("columnb")) >>> table2 = table("table2", column("columna"), column("columnc")) >>> print(select(table1, table2).join(table2, true()).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)) SELECT table1.columna AS table1_columna, table1.columnb AS table1_columnb, table2.columna AS table2_columna, table2.columnc AS table2_columnc FROM table1 JOIN table2 ON true Used with the :meth:`_sql.GenerativeSelect.set_label_style` method. Equivalent to the legacy method ``Select.apply_labels()``; :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL` is SQLAlchemy's legacy auto-labeling style. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` provides a less intrusive approach to disambiguation of same-named column expressions. .. versionadded:: 1.4 LABEL_STYLE_DISAMBIGUATE_ONLYaLabel style indicating that columns with a name that conflicts with an existing name should be labeled with a semi-anonymizing label when generating the columns clause of a SELECT statement. Below, most column names are left unaffected, except for the second occurrence of the name ``columna``, which is labeled using the label ``columna_1`` to disambiguate it from that of ``tablea.columna``:: >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_DISAMBIGUATE_ONLY >>> table1 = table("table1", column("columna"), column("columnb")) >>> table2 = table("table2", column("columna"), column("columnc")) >>> print(select(table1, table2).join(table2, true()).set_label_style(LABEL_STYLE_DISAMBIGUATE_ONLY)) SELECT table1.columna, table1.columnb, table2.columna AS columna_1, table2.columnc FROM table1 JOIN table2 ON true Used with the :meth:`_sql.GenerativeSelect.set_label_style` method, :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` is the default labeling style for all SELECT statements outside of :term:`1.x style` ORM queries. .. versionadded:: 1.4 csheZdZdZdZdejfdejfdejfdejfdejfgZdZ d;d d Z e dddZedddZfddZddZe d?ddZe d@d d!Ze edd"d#Ze d$d%Zejd&d'd(dAd)d*Zeejd+d,d d-d.d/ZeddBd0d1Zejd2d3d4dCd5d6Z ed7d8Z!ed9d:Z"Z#S)DraRepresent 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` rpleftrrrrTNFcCsrtjtj|dd|_tjtj|dd|_|dkrH||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. T)Z deannotateNagainst)rrvrrr self_groupr_match_primariesr OnClauseRolerZ_asboolrr)r7rrrrrr8r8r9__init__s( z Join.__init__cCs||||d|dS)aReturn an ``OUTER JOIN`` clause element. The returned object is an instance of :class:`_expression.Join`. Similar functionality is also available via the :meth:`_expression.FromClause.outerjoin` method on any :class:`_expression.FromClause`. :param left: The left side of the join. :param right: The right side of the join. :param onclause: Optional criterion for the ``ON`` clause, is derived from foreign key relationships established between left and right otherwise. To chain joins together, use the :meth:`_expression.FromClause.join` or :meth:`_expression.FromClause.outerjoin` methods on the resulting :class:`_expression.Join` object. Trrr8)clsrrrrr8r8r9_create_outerjoinszJoin._create_outerjoincCs||||||S)a6Produce a :class:`_expression.Join` object, given two :class:`_expression.FromClause` expressions. E.g.:: j = join(user_table, address_table, user_table.c.id == address_table.c.user_id) stmt = select(user_table).select_from(j) would emit SQL along the lines of:: SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id Similar functionality is available given any :class:`_expression.FromClause` object (e.g. such as a :class:`_schema.Table`) using the :meth:`_expression.FromClause.join` method. :param left: The left side of the join. :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 JOIN. .. versionadded:: 1.1 .. seealso:: :meth:`_expression.FromClause.join` - method form, based on a given left side. :class:`_expression.Join` - the type of object produced. r8)rrrrrrr8r8r9 _create_joins4zJoin._create_joincCs$d|jjt|j|jjt|jfS)Nz Join object on %s(%d) and %s(%d))rridrr6r8r8r9rMs zJoin.descriptioncCs(t|t|kp&|j|p&|j|Sr5)hashrrrrr8r8r9rVs   zJoin.is_derived_fromcCst|Sr5) FromGroupingr7rr8r8r9r_szJoin.self_groupr\cCstjj}dd|jjDdd|jjD}|j|dd|D|j |j dd|D|j tjdd|DdS)NcSsg|]}|qSr8r8rxrr8r8r9r{esz4Join._populate_column_collection..css|]}|jr|VqdSr5)rrr8r8r9rksz3Join._populate_column_collection..css|]}|j|fVqdSr5) _tq_key_labelrr8r8r9rnscSsg|] }|jqSr8)rrr8r8r9r{rs)r2r]r^rrrrextendreduce_columnsrrrrupdate itertoolschain)r7sqlutilrr8r8r9rbs   z Join._populate_column_collectioncs,tt|||j||j|dSr5)superrrTrrrRrr8r9rTus zJoin._refresh_for_new_columncCs&t|tr|j}nd}|j|||dS)N)a_subset) isinstancerr_join_condition)r7rr left_rightr8r8r9rzs zJoin._match_primariescCs|||||}t|dkr,|||||t|dkrdt|trHd}nd}td|j|j|fddt| dD}t|dkr|dSt |SdS) a=Create a join condition between two tables or selectables. e.g.:: join_condition(tablea, tableb) would produce an expression along the lines of:: tablea.c.id==tableb.c.tablea_id The join is determined based on the foreign key relationships between the two selectables. If there are multiple ways to join, or no way to join, an error is raised. :param a_subset: An optional expression that is a sub-component of ``a``. An attempt will be made to join to just this sub-component first before looking at the full ``a`` construct, and if found will be successful even if there are other ways to join to ``a``. This allows the "right side" of a join to be passed thereby providing a "natural join". rrzI Perhaps you meant to convert the right side to a subquery using alias()?zACan't find any foreign key relationships between '%s' and '%s'.%scSsg|]\}}||kqSr8r8)rxxyr8r8r9r{sz(Join._join_condition..N) _joincond_scan_left_rightlen_joincond_trim_constraintsrrr1ZNoForeignKeysErrorrlistvaluesr$)rabrconsider_as_foreign_keys constraintshintcritr8r8r9rs6     zJoin._join_conditioncCs0t|tr|j}nd}|j||||d}t|S)N)rrrr)rrrrbool)rrrrrrr8r8r9 _can_joins zJoin._can_joinc 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|jjSr5parentZ_creation_orderfkr8r8r9z0Join._joincond_scan_left_right..rcSsh|] }|jqSr8rrxtr8r8r9 sz1Join._joincond_scan_left_right..cSs|jjSr5rr r8r8r9r r cSsh|] }|jqSr8rrr8r8r9rs)r2r]r^rrvrr collections defaultdictrsortedrrZ get_referentr1ZNoReferenceErrorZ find_tablesZ table_name constraintappend) rrrrrr^rrr rZnrteZ table_namesr8r8r9rs^       zJoin._joincond_scan_left_rightcCs|r4t|D]&}tdd|jDt|kr ||=q t|dkrztdd|D}t|dkrzt|d}|||i}t|dkrtd|j|jfdS)Ncss|] }|jVqdSr5)rrxfr8r8r9r sz2Join._joincond_trim_constraints..rcss|]}t|VqdSr5)r|)rxrr8r8r9rsrzCan'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.)rrelementsrrr1ZAmbiguousForeignKeysErrorr)rrrrrconstdeduperr8r8r9rs"       zJoin._joincond_trim_constraints)rzThe :paramref:`_sql.Join.select().whereclause` parameter is deprecated and will be removed in version 2.0. Please make use of the :meth:`.Select.where` method to add WHERE criteria to the SELECT statement.)rzThe :meth:`_sql.Join.select` method will no longer accept keyword arguments in version 2.0. Please use generative methods from the :class:`_sql.Select` construct in order to apply additional modifications.rcKs2|j|jg}|dk r||d<tj||f||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 :param whereclause: WHERE criteria, same as calling :meth:`_sql.Select.where` on the resulting statement :param \**kwargs: additional keyword arguments are passed to the legacy constructor for :class:`_sql.Select` described at :meth:`_sql.Select.create_legacy_select`. Nr)rrrAr select_from)r7rrFZcollistr8r8r9r!s) z Join.select:attr:`.Executable.bind`5Bound metadata is being removed as of SQLAlchemy 2.0. alternativeZenable_warningscCs|jjp|jjS)zsReturn the bound engine associated with either the left or right side of this :class:`_sql.Join`. )rbindrr6r8r8r9r Rs z Join.bindcCstjj}|rp|dk rtd|jjdd|jjdd}}|| ||}|j || |j |j |jdS|td|SdS)Nz"Can't send name argument with flatT)rr)r2r]r^r1rorrrr_rrpr`rrrrset_label_styler correlaterD)r7rYrrZleft_aZright_aadapterr8r8r9r`s0     zJoin._anonymous_fromclausez:meth:`_sql.Join.alias`zTCreate a select + subquery, or alias the individual tables inside the join, instead.rcCs|j||dS)a@Return an alias of this :class:`_expression.Join`. The default behavior here is to first produce a SELECT construct from this :class:`_expression.Join`, then to produce an :class:`_expression.Alias` from that. So given a join of the form:: j = table_a.join(table_b, table_a.c.id == table_b.c.a_id) The JOIN by itself would look like:: table_a JOIN table_b ON table_a.id = table_b.a_id Whereas the alias of the above, ``j.alias()``, would in a SELECT context look like:: (SELECT table_a.id AS table_a_id, table_b.id AS table_b_id, table_b.a_id AS table_b_a_id FROM table_a JOIN table_b ON table_a.id = table_b.a_id) AS anon_1 The equivalent long-hand form, given a :class:`_expression.Join` object ``j``, is:: from sqlalchemy import select, alias j = alias( select(j.left, j.right).\ select_from(j).\ set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL).\ correlate(False), name=name ) The selectable produced by :meth:`_expression.Join.alias` features the same columns as that of the two individual selectables presented under a single name - the individual columns are "auto-labeled", meaning the ``.c.`` collection of the resulting :class:`_expression.Alias` represents the names of the individual columns using a ``_`` scheme:: j.c.table_a_id j.c.table_b_a_id :meth:`_expression.Join.alias` also features an alternate option for aliasing joins which produces no enclosing SELECT and does not normally apply labels to the column names. The ``flat=True`` option will call :meth:`_expression.FromClause.alias` against the left and right sides individually. Using this option, no new ``SELECT`` is produced; we instead, from a construct as below:: j = table_a.join(table_b, table_a.c.id == table_b.c.a_id) j = j.alias(flat=True) we get a result like this:: table_a AS table_a_1 JOIN table_b AS table_b_1 ON table_a_1.id = table_b_1.a_id The ``flat=True`` argument is also propagated to the contained selectables, so that a composite join such as:: j = table_a.join( table_b.join(table_c, table_b.c.id == table_c.c.b_id), table_b.c.a_id == table_a.c.id ).alias(flat=True) Will produce an expression like:: table_a AS table_a_1 JOIN ( table_b AS table_b_1 JOIN table_c AS table_c_1 ON table_b_1.id = table_c_1.b_id ) ON table_a_1.id = table_b_1.a_id The standalone :func:`_expression.alias` function as well as the base :meth:`_expression.FromClause.alias` method also support the ``flat=True`` argument as a no-op, so that the argument can be passed to the ``alias()`` method of any selectable. :param name: name given to the alias. :param flat: if True, produce an alias of the left and right sides of this :class:`_expression.Join` and return the join of those two selectables. This produces join expression that does not include an enclosing SELECT. .. seealso:: :ref:`core_tutorial_aliases` :func:`_expression.alias` )rrY)rrr8r8r9rD|sfz Join.aliascCstjdd|jDS)NcSsg|]}t|j|jqSr8)rrr)rxrr8r8r9r{sz$Join._hide_froms..)rrrr6r8r8r9rszJoin._hide_fromscCs|g|jj|jjSr5)rrrr6r8r8r9rszJoin._from_objects)NFF)NF)NFF)N)NN)N)N)NF)NF)$r;r<r=rMrdr/dp_clauseelement dp_boolean_traverse_internalsrr classmethodrrr?rrrr2rgrrTrrrrrrr deprecated_20r rrDrr __classcell__r8r8rr9rsv   5     6  8     c rc@seZdZddZdS)NoInitcOs*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.)rJrr;lowerr7argrsr8r8r9rs  zNoInit.__init__Nr;r<r=rr8r8r8r9r+sr+cseZdZdZdZdZdZdejfdej fgZ e ddZ e dd d Z dd d Zfd dZeddZeddZddZddZeffdd ZeddZeddZZS)AliasedReturnsRowszLBase class of aliases against tables, subqueries, and other selectables.TFelementrYcOs||}|j|||Sr5)__new___init)rr.rsobjr8r8r9rWs  zAliasedReturnsRows._constructNcCs tdS)z6Base factory method. Subclasses need to provide this.NrI)rZ returnsrowsrYr8r8r9_factoryszAliasedReturnsRows._factorycCsptjtj||d|_||_||_|dkrft|trR|jrRt |dd}t|t rRd}t t ||pbd}||_ dS)NZapply_propagate_attrsrYZanon)rrvrReturnsRowsRoler1Z _orig_namerrrrr#Zsafe_constructrrY)r7rHrYr8r8r9r3s"  zAliasedReturnsRows._initcs tt|||j|dSr5)rr0rTr1rRrr8r9rT0sz*AliasedReturnsRows._refresh_for_new_columncCs.|j}t|trd}tjr|S|ddSdS)NZanon_1asciibackslashreplace)rYrr#r2py3kencoderXr8r8r9r4s  zAliasedReturnsRows.descriptioncCs|jS)z9Legacy for dialects that are referring to Alias.original.r1r6r8r8r9original?szAliasedReturnsRows.originalcCs||jkrdS|j|SNT)rr1rrr8r8r9rDs z"AliasedReturnsRows.is_derived_fromcCs|j|dSr5r1rr6r8r8r9rIsz.AliasedReturnsRows._populate_column_collectionc s6|j}tt|jfd|i|||jk r2|dS)Nclone)r1rr0_copy_internalsr)r7r@rsZexisting_elementrr8r9rALs z"AliasedReturnsRows._copy_internalscCs|gSr5r8r6r8r8r9rXsz AliasedReturnsRows._from_objectscCs|jjSr5)r1r r6r8r8r9r \szAliasedReturnsRows.bind)N)N)r;r<r=rM_is_from_containerr_supports_derived_columnsr/r% dp_anon_namer'r(rWr5r3rTr?rr=rrr rArr r*r8r8rr9r0s0        r0c@s&eZdZdZdZdZedddZdS) 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` rDTNFcCstjtj|ddj||dS)aReturn an :class:`_expression.Alias` object. An :class:`_expression.Alias` represents any :class:`_expression.FromClause` with an alternate name assigned within SQL, typically using the ``AS`` clause when generated, e.g. ``SELECT * FROM table AS aliasname``. Similar functionality is available via the :meth:`_expression.FromClause.alias` method available on all :class:`_expression.FromClause` subclasses. In terms of a SELECT object as generated from the :func:`_expression.select` function, the :meth:`_expression.SelectBase.alias` method returns an :class:`_expression.Alias` or similar object which represents a named, parenthesized subquery. When an :class:`_expression.Alias` is created from a :class:`_schema.Table` object, this has the effect of the table being rendered as ``tablename AS aliasname`` in a SELECT statement. For :func:`_expression.select` objects, the effect is that of creating a named subquery, i.e. ``(select ...) AS aliasname``. The ``name`` parameter is optional, and provides the name to use in the rendered SQL. If blank, an "anonymous" name will be deterministically generated at compile time. Deterministic means the name is guaranteed to be unique against other constructs used in the same statement, and will also be the same name for each successive compilation of the same statement object. :param selectable: any :class:`_expression.FromClause` subclass, such as a table, select statement, etc. :param name: string name to be assigned as the alias. If ``None``, a name will be deterministically generated at compile time. :param flat: Will be passed through to if the given selectable is an instance of :class:`_expression.Join` - see :meth:`_expression.Join.alias` for details. T)Z allow_select)rYr)rrvrrrD)rrHrYrr8r8r9r5ws/zAlias._factory)NF)r;r<r=rMrdr>r(r5r8r8r8r9ras rcseZdZdZdZdZdZdZdej fdej fdej fdej fd ej fgZ dfd d Zejd dZdddZdddZdddZZS)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.:: >>> from sqlalchemy import select, func >>> fn = func.json_array_elements_text('["one", "two", "three"]').table_valued("value") >>> print(select(fn.c.value)) 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_aliasTFr1rY_tableval_type_render_derived_render_derived_w_typesNcs,tt|j||d|dkr"tjn||_dSr)rrEr3rrrF)r7rHrYZtable_value_typerr8r9r3s zTableValuedAlias._initcCs 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.:: >>> print(select(func.some_func().table_valued("value").column)) SELECT anon_1 FROM some_func() AS anon_1 .. seealso:: :meth:`_functions.FunctionElement.column_valued` )r-rFr6r8r8r9rSszTableValuedAlias.columncCs&tj||d}|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. rTrErWrGrHr7rYZtvar8r8r9rDs zTableValuedAlias.aliascCs|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)rDrPrJr8r8r9rZs zTableValuedAlias.lateralcCstj||d}d|_||_|S)afApply "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.:: >>> print( ... select( ... func.unnest(array(["one", "two", "three"])). table_valued("x", with_ordinality="o").render_derived() ... ) ... ) 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):: >>> 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) ... ) ... ) 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. rTrI)r7rYZ with_typesZ new_aliasr8r8r9render_derived s-zTableValuedAlias.render_derived)NN)N)N)NF)r;r<r=rMrdrCrGrHr/r%rDZdp_typer&r'r3rmemoized_attributerSrDrZrKr*r8r8rr9rEs"    rEc@s*eZdZdZdZdZdZedddZdS)rVaRepresent 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. .. versionadded:: 1.1 .. seealso:: :ref:`lateral_selects` - overview of usage. rZTNcCstjtj|ddj|dS)aReturn a :class:`_expression.Lateral` object. :class:`_expression.Lateral` is an :class:`_expression.Alias` subclass that represents a subquery with the LATERAL keyword applied to it. The special behavior of a LATERAL subquery is that it appears in the FROM clause of an enclosing SELECT, but may correlate to other FROM clauses of that SELECT. It is a special case of subquery only supported by a small number of backends, currently more recent PostgreSQL versions. .. versionadded:: 1.1 .. seealso:: :ref:`lateral_selects` - overview of usage. T)Zexplicit_subqueryr)rrvrrrZrrHrYr8r8r9r5TszLateral._factory)N) r;r<r=rMrdrPr>r(r5r8r8r8r9rV<s rVcs`eZdZdZdZejdejfdejfgZe d ddZ e ddfd d Z d d ZZS)radRepresent 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. .. versionadded:: 1.1 .. seealso:: :func:`_expression.tablesample` rrrNcCsttj|j|||dS)aReturn a :class:`_expression.TableSample` object. :class:`_expression.TableSample` is an :class:`_expression.Alias` subclass that represents a table with the TABLESAMPLE clause applied to it. :func:`_expression.tablesample` is also available from the :class:`_expression.FromClause` class via the :meth:`_expression.FromClause.tablesample` method. The TABLESAMPLE clause allows selecting a randomly selected approximate percentage of rows from a table. It supports multiple sampling methods, most commonly BERNOULLI and SYSTEM. e.g.:: from sqlalchemy import func selectable = people.tablesample( func.bernoulli(1), name='alias', seed=func.random()) stmt = select(selectable.c.people_id) Assuming ``people`` with a column ``people_id``, the above statement would render as:: SELECT alias.people_id FROM people AS alias TABLESAMPLE bernoulli(:bernoulli_1) REPEATABLE (random()) .. versionadded:: 1.1 :param sampling: a ``float`` percentage between 0 and 100 or :class:`_functions.Function`. :param name: optional alias name :param seed: any real-valued SQL expression. When specified, the REPEATABLE sub-clause is also rendered. )rYr)rrvrrr)rrHrrYrr8r8r9r5s ,zTableSample._factoryzsqlalchemy.sql.functionscsDtjj}t||js |j|}||_||_t t |j ||ddSr) r2r]Z sql_functionsrZFunctionfuncsystemrrrrr3)r7rHrrYrZ functionsrr8r9r3s   zTableSample._initcCs|jSr5)rr6r8r8r9 _get_methodszTableSample._get_method)NN)NN)r;r<r=rMrdr0r'r/r%r(r5r2rgr3rPr*r8r8rr9rns / rcseZdZdZdZejdejfdej fdej fge j e jZeddd Zdfd d Zd dZdddZddZddZZS)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 recursiveNFcCsttj|j||dS)zReturn a new :class:`_expression.CTE`, or Common Table Expression instance. Please see :meth:`_expression.HasCTE.cte` for detail on CTE usage. rYrU)rrvr HasCTERolerR)rrHrYrUr8r8r9r5sz CTE._factoryr8cs>||_||_||_|r||_|r&||_tt|j||ddSr)rUrSrTrirrrQr3)r7rHrYrUrSrTrirrr8r9r3s z CTE._initcCs(|jdk r|j|n |j|dSr5)rSrr1r6r8r8r9r s zCTE._populate_column_collectioncCstj|j||j||j|jdS)a1Return 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:`core_tutorial_aliases` :func:`_expression.alias` )rYrUrSrir)rQrWr1rUrirrr8r8r9rDsz CTE.aliascCs.tj|j||j|j|j|f|j|jdSN)rYrUrTrir) rQrWr1rrYrUrTrirrr8r8r9r&s  z CTE.unioncCs.tj|j||j|j|j|f|j|jdSrX) rQrWr1 union_allrYrUrTrirrr8r8r9rY0s  z CTE.union_all)NF)NFNr8NN)NF)r;r<r=rMrdr0r'r/r%dp_clauseelement_listr&rhrrrr(r5r3rrDrrYr*r8r8rr9rQs4    rQc@s6eZdZdZdejfgZdZeddZ d dd Z dS) HasCTEzTMixin that declares a class to include CTE support. .. versionadded:: 1.1 _independent_ctesr8cCs"ttj|}|j|f7_dS)adAdd a :class:`_sql.CTE` to this statement object that will be independently rendered even if not referenced in the statement otherwise. This feature is useful for 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; while PostgreSQL is known to support this usage, it may not be supported by other backends. 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 referred towards 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 N)rrvr IsCTERoler\)r7rRr8r8r9add_cteHs@zHasCTE.add_cteNFcCstj|||dS)aReturn 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. .. versionchanged:: 1.1 Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE. 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. 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) .. seealso:: :meth:`_orm.Query.cte` - ORM version of :meth:`_expression.HasCTE.cte`. rV)rQrW)r7rYrUr8r8r9rRs'z HasCTE.cte)NF) r;r<r=rMr/rZ_has_ctes_traverse_internalsr\rr^rRr8r8r8r9r[;s Br[c@sFeZdZdZdZdZdZed ddZe ddd d Z d d Z 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. rCTNcCsttj|j|dS)z#Return a :class:`.Subquery` object.r)rrvrSelectStatementRolerCrMr8r8r9r5W s zSubquery._factoryr@axThe :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.cCs|jtSr5)r1r!rscalar_subqueryr6r8r8r9 as_scalar^ s zSubquery.as_scalarcCs"tdd|jj||||ddS)NzExecuting a subquery object is deprecated and will raise ObjectNotExecutableError in an upcoming release. Please execute the underlying select() statement directly.r@T)Z_force)r2Zwarn_deprecatedr1_execute_on_connection)r7 connectionZ multiparamsparamsZexecution_optionsr8r8r9rdk szSubquery._execute_on_connection)N) r;r<r=rMrd _is_subqueryr>r(r5r2rfrcrdr8r8r8r9r`4 s  r`c@seZdZdZdejfgZddZddZe ddZ e d d Z e d d Z d dZ ddZddZe ddZe ddZddZddZdS)rz%Represent a grouping of a FROM clauser1cCsttj||_dSr5)rrvrrr1r7r1r8r8r9r szFromGrouping.__init__cCsdSr5r8r6r8r8r9r szFromGrouping._init_collectionscCs|jjSr5)r1rr6r8r8r9r szFromGrouping.columnscCs|jjSr5)r1rr6r8r8r9r szFromGrouping.primary_keycCs|jjSr5)r1rr6r8r8r9r szFromGrouping.foreign_keyscCs |j|Sr5)r1rrhr8r8r9r szFromGrouping.is_derived_fromcKst|jjf|Sr5)rr1rDr7rsr8r8r9rD szFromGrouping.aliascKst|jjf|Sr5)rr1rrir8r8r9r sz"FromGrouping._anonymous_fromclausecCs|jjSr5)r1rr6r8r8r9r szFromGrouping._hide_fromscCs|jjSr5r1rr6r8r8r9r szFromGrouping._from_objectscCs d|jiSNr1r<r6r8r8r9 __getstate__ szFromGrouping.__getstate__cCs|d|_dSrkr<)r7stater8r8r9 __setstate__ szFromGrouping.__setstate__N)r;r<r=rMr/r%r'rrr?rrrrrDrrrrlrnr8r8r8r9r} s&      rcseZdZdZdZdejfdejfgZdZ dZ dZ fdd Z d d Z d d ZddZejddZddZeddddZeddddZeddddZeddZZS) 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. tablerrYTFNcsztt|||_|_t|_t|_t |_ |D]}| |q6| dd}|dk r`||_ |rvtdt|dS)aProduce a new :class:`_expression.TableClause`. The object returned is an instance of :class:`_expression.TableClause`, which represents the "syntactical" portion of the schema-level :class:`_schema.Table` object. It may be used to construct lightweight table constructs. .. versionchanged:: 1.0.0 :func:`_expression.table` can now be imported from the plain ``sqlalchemy`` namespace like any other SQL element. :param name: Name of the table. :param columns: A collection of :func:`_expression.column` constructs. :param schema: The schema name for this table. .. versionadded:: 1.3.18 :func:`_expression.table` can now accept a ``schema`` argument. rNrl)rrorrYfullnamerrrrrr append_columnrnrr1ror)r7rYrrsrrrr8r9r s   zTableClause.__init__cCs$|jdk r|jd|jS|jSdS)N.)rrYr6r8r8r9__str__ s zTableClause.__str__cCsdSr5r8rRr8r8r9rT sz#TableClause._refresh_for_new_columncCsdSr5r8r6r8r8r9r szTableClause._init_collectionscCstjr |jS|jddSdS)Nr8r9)r2r:rYr;r6r8r8r9r szTableClause.descriptioncKs@|j}|dk r*||k r*td|j|f|j|||_dS)Nz1column object '%s' already assigned to table '%s')rpr1rorradd)r7rrsexistingr8r8r9rr s zTableClause.append_columnzsqlalchemy.sql.dmlcKstjjj|f||d|S)zGenerate an :func:`_expression.insert` construct against this :class:`_expression.TableClause`. E.g.:: table.insert().values(name='foo') See :func:`_expression.insert` for argument and usage information. )rinline)r2r]sql_dmlZInsert)r7rrwrFr8r8r9insert" s zTableClause.insertcKstjjj|f|||d|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. )rrrw)r2r]rxZUpdate)r7rrrwrFr8r8r9r2 s zTableClause.updatecKstjjj||f|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. )r2r]rxZDeleterr8r8r9deleteF s zTableClause.deletecCs|gSr5r8r6r8r8r9rT szTableClause._from_objects)NF)NNF)N)r;r<r=rMrdr/Z)dp_fromclause_canonical_column_collection dp_stringr'rZimplicit_returningZ_autoincrement_columnrrtrTrr2rrrrrgryrrzr?rr*r8r8rr9ro s2 &     roc@s^eZdZdejfdejfdejfdejfgZeddZddZ d d Z d d Z dddZ dS) ForUpdateArgofnowaitread skip_lockedcCs6t|tr|S|dkrdS|dkr(tStf|SdS)N)NFT)rr|)rwith_for_updater8r8r9_from_argumenta s zForUpdateArg._from_argumentcCsFt|toD|j|jkoD|j|jkoD|j|jkoD|j|jkoD|j|jkSr5)rr|r~rr key_sharer}rr8r8r9__eq__l s      zForUpdateArg.__eq__cCs || Sr5)rrr8r8r9__ne__v szForUpdateArg.__ne__cCst|Sr5)rr6r8r8r9__hash__y szForUpdateArg.__hash__FNcCsB||_||_||_||_|dk r8ddt|D|_nd|_dS)zZRepresents arguments specified to :meth:`_expression.Select.for_update`. NcSsg|]}ttj|qSr8rrvrZColumnsClauseRole)rxelemr8r8r9r{ sz)ForUpdateArg.__init__..)r~rrrr2to_listr}r7r~rr}rrr8r8r9r| s  zForUpdateArg.__init__)FFNFF) r;r<r=r/rZr&r'r(rrrrrr8r8r8r9r|Y s   r|cseZdZdZdZdZdZdejfdej fdej fdej fgZ fd d Z ed d Zed dZedddZeddZddZeddZZS)ValueszRepresent 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 Trr8 _column_args_datarY literal_bindscs@tt|||_|dd|_|dd|_|jdk |_dS)aConstruct a :class:`_expression.Values` construct. The column expressions and the actual data for :class:`_expression.Values` are given in two separate steps. The constructor receives the column expressions typically as :func:`_expression.column` constructs, and the data is then passed via the :meth:`_expression.Values.data` method as a list, which can be called multiple times to add more data, e.g.:: from sqlalchemy import column from sqlalchemy import values value_expr = values( column('id', Integer), column('name', String), name="my_values" ).data( [(1, 'name1'), (2, 'name2'), (3, 'name3')] ) :param \*columns: column expressions, typically composed using :func:`_expression.column` objects. :param name: the name for this VALUES construct. If omitted, the VALUES construct will be unnamed in a SQL expression. Different backends may have different requirements here. :param literal_binds: Defaults to False. Whether or not to render the data values inline in the SQL output, rather than using bound parameters. rYNrF)rrrrrnrYrr)r7rrsrr8r9r s $zValues.__init__cCsdd|jDS)NcSsg|] }|jqSr8)typerr8r8r9r{ sz(Values._column_types..)rr6r8r8r9 _column_types szValues._column_typescKs||_|jdk |_dS)aXReturn 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:`core_tutorial_aliases` :func:`_expression.alias` N)rYr)r7rYrsr8r8r9rD sz Values.aliasNcCsd|_|dk r||_dS)zReturn a new :class:`_expression.Values` with the lateral flag set, so that it renders as LATERAL. .. seealso:: :func:`_expression.lateral` TN)rPrYrXr8r8r9rZ s zValues.lateralcCs|j|f7_dS)arReturn 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. N)r)r7rr8r8r9data sz Values.datacCs"|jD]}|j|||_qdSr5)rrrurp)r7rr8r8r9r s  z"Values._populate_column_collectioncCs|gSr5r8r6r8r8r9r szValues._from_objects)N)r;r<r=rMrrdrr/rZZdp_dml_multi_valuesr{r&r'rr?rrrDrZrrrr*r8r8rr9r s*  *    rc@seZdZdZdZdZddZddZeddZ ed d Z ed d Z ee d dddZeddZe d dddZejddZe d dddZddZddZdd Zd-d"d#Zed$d%Zd.d&d'Zd(d)Zd/d+d,Zd!S)0 SelectBasezBase class for SELECT statements. This includes :class:`_expression.Select`, :class:`_expression.CompoundSelect` and :class:`_expression.TextualSelect`. TcCs tdSr5rIrr8r8r9r0 sz.SelectBase._generate_fromclause_column_proxiescCs |dSr5)_reset_memoizationsrRr8r8r9rT3 sz"SelectBase._refresh_for_new_columncCs 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 NrIr6r8r8r9selected_columns6 szSelectBase.selected_columnscCs 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` NrIr6r8r8r9rKT s z SelectBase._all_selected_columnscCs|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` rr6r8r8r9rLc szSelectBase.exported_columnsr@aThe :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.cCs|jjSr5)_implicit_subqueryrr6r8r8r9r| sz SelectBase.ccCs|jSr5)rr6r8r8r9r szSelectBase.columnsa 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.cOs|jj||Sr5)rrr-r8r8r9r s zSelectBase.selectcCs|Sr5rCr6r8r8r9r szSelectBase._implicit_subqueryzThe :meth:`_expression.SelectBase.as_scalar` method is deprecated and will be removed in a future release. Please refer to :meth:`_expression.SelectBase.scalar_subquery`.cCs|Sr5)rbr6r8r8r9rc szSelectBase.as_scalarcCst|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 )Existsr6r8r8r9exists szSelectBase.existscCs|jtk r|t}t|S)aReturn 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 :ref:`scalar_selects` - in the 1.x tutorial ) _label_stylerr! ScalarSelectr6r8r8r9rb s  zSelectBase.scalar_subquerycCs||S)zReturn a 'scalar' representation of this selectable, embedded as a subquery with a label. .. seealso:: :meth:`_expression.SelectBase.as_scalar`. )rblabelrXr8r8r9r s zSelectBase.labelNcCs t||SrU)rVr5rXr8r8r9rZ s zSelectBase.lateralcCs|gSr5r8r6r8r8r9r szSelectBase._from_objectscCst||S)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`rW_ensure_disambiguated_namesrXr8r8r9rC s(zSelectBase.subquerycCs tdS)ztEnsure that the names generated by this selectbase will be disambiguated in some way, if possible. NrIr6r8r8r9r# sz&SelectBase._ensure_disambiguated_namesFcCs |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. rrrr8r8r9rD+ szSelectBase.alias)N)N)NF)r;r<r=rMrO is_selectrrTr?rrKrLr2rfrrrrrLrrcrrbrrZrrCrrDr8r8r8r9r sP             *rc@seZdZdZdZdejfgZdZddZ ddZ d d Z d d Z e d dZe ddZd ddZddZddZddZe ddZe ddZe ddZdS)!SelectStatementGroupingzRepresent 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_groupingr1TcCsttj||_dSr5)rrvrrar1rhr8r8r9rK sz SelectStatementGrouping.__init__cCs$|j}||jk rt|S|SdSr5)r1rr)r7Z new_elementr8r8r9rN s  z3SelectStatementGrouping._ensure_disambiguated_namescCs|jSr5rr6r8r8r9get_label_styleU sz'SelectStatementGrouping.get_label_stylecCst|j|Sr5)rr1r!)r7 label_styler8r8r9r!X s z'SelectStatementGrouping.set_label_stylecCs|jjSr5)r1rr6r8r8r9r] sz$SelectStatementGrouping._label_stylecCs|jSr5r<r6r8r8r9select_statementa sz(SelectStatementGrouping.select_statementNcCs|Sr5r8rr8r8r9re sz"SelectStatementGrouping.self_groupcCs |j|Sr5)r1_generate_columns_plus_names)r7anon_for_dupe_keyr8r8r9rh sz4SelectStatementGrouping._generate_columns_plus_namescCs|j|dSr5r?)r7rCr8r8r9rk sz;SelectStatementGrouping._generate_fromclause_column_proxiescCs |j|Sr5)r1_generate_proxy_for_new_column)r7rSrCr8r8r9rn sz6SelectStatementGrouping._generate_proxy_for_new_columncCs|jjSr5)r1rKr6r8r8r9rKq sz-SelectStatementGrouping._all_selected_columnscCs|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` )r1rr6r8r8r9ru sz(SelectStatementGrouping.selected_columnscCs|jjSr5rjr6r8r8r9r sz%SelectStatementGrouping._from_objects)N)r;r<r=rMrdr/r%r'Z_is_select_containerrrrr!r?rrrrrrrKrrr8r8r8r9r= s,      rc@s8eZdZdZeddddZeddddZd S) DeprecatedSelectBaseGenerationszA collection of methods available on :class:`_sql.Select` and :class:`_sql.CompoundSelect`, these are all **deprecated** methods as they modify the object in-place. r@zThe :meth:`_expression.GenerativeSelect.append_order_by` method is deprecated and will be removed in a future release. Use the generative method :meth:`_expression.GenerativeSelect.order_by`.cGs|jj|f|dS)aAppend the given ORDER BY criterion applied to this selectable. The criterion will be appended to any pre-existing ORDER BY criterion. This is an **in-place** mutation method; the :meth:`_expression.GenerativeSelect.order_by` method is preferred, as it provides standard :term:`method chaining`. .. seealso:: :meth:`_expression.GenerativeSelect.order_by` N)order_bynon_generativer7clausesr8r8r9append_order_by sz/DeprecatedSelectBaseGenerations.append_order_byzThe :meth:`_expression.GenerativeSelect.append_group_by` method is deprecated and will be removed in a future release. Use the generative method :meth:`_expression.GenerativeSelect.group_by`.cGs|jj|f|dS)a\Append the given GROUP BY criterion applied to this selectable. The criterion will be appended to any pre-existing GROUP BY criterion. This is an **in-place** mutation method; the :meth:`_expression.GenerativeSelect.group_by` method is preferred, as it provides standard :term:`method chaining`. N)group_byrrr8r8r9append_group_by sz/DeprecatedSelectBaseGenerations.append_group_byN)r;r<r=rMr2rfrrr8r8r8r9r s rc@s.eZdZdZdZdZdZdZdZdZ dZ e j dde ddddddfddZed1d d Zd d Zd dZe jdddddZeddZeddZd2ddZddZeddZddZed d!Zed"d#Zed$d%Zed3d&d'Zed(d)Z ee !d*d+d,Z"ed-d.Z#ed/d0Z$dS)4GenerativeSelecta&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. r8N)rz^The :paramref:`_sql.select.bind` argument is deprecated and will be removed in SQLAlchemy 2.0.)r FcCs|rtjrtjdddt}||_|dk r8|j|||dk rN|j|||dk rn|jj|ft ||dk r|j j|ft |||_ dS)NzThe use_labels=True keyword argument to GenerativeSelect is deprecated and will be removed in version 2.0. Please use select.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) if you need to replicate this legacy behavior. stacklevel) r2SQLALCHEMY_WARN_20warn_deprecated_20rrlimitroffsetrrr_bind)r7rZ use_labelsrrrrr r8r8r9r s"zGenerativeSelect.__init__cCst|||||d|_dS)aSpecify 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) which will render into a ``FOR UPDATE OF`` clause; supported by PostgreSQL and Oracle. May render as a table or as a column depending on backend. :param skip_locked: boolean, will render ``FOR UPDATE SKIP LOCKED`` on Oracle and PostgreSQL dialects or ``FOR SHARE SKIP LOCKED`` if ``read=True`` is also specified. :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~rr}rrN)r|_for_update_argrr8r8r9r s6z GenerativeSelect.with_for_updatecCs|jS)zS Retrieve the current label style. .. versionadded:: 1.4 rr6r8r8r9r@ sz GenerativeSelect.get_label_stylecCs|j|k r|}||_|S)a8Return a new selectable with the specified label style. There are three "label styles" available, :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`, :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL`, and :data:`_sql.LABEL_STYLE_NONE`. The default style is :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL`. 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 _generater7styler8r8r9r!I s& z GenerativeSelect.set_label_stylez*:meth:`_sql.GenerativeSelect.apply_labels`zs) zGenerativeSelect.slicecGs@t|dkr |ddkr d|_n|jtdd|D7_dS)aReturn a new selectable with the given list of ORDER BY criterion applied. e.g.:: stmt = select(table).order_by(table.c.id, table.c.name) :param \*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` rrNr8css|]}ttj|VqdSr5)rrvrZ OrderByRolerxrr8r8r9rsz,GenerativeSelect.order_by..)rrr|rr8r8r9rms zGenerativeSelect.order_bycGs@t|dkr |ddkr d|_n|jtdd|D7_dS)a/Return a new selectable with the given list of GROUP BY criterion applied. e.g.:: stmt = select(table.c.name, func.max(table.c.stat)).\ group_by(table.c.name) :param \*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` rrNr8css|]}ttj|VqdSr5)rrvrZ GroupByRolerr8r8r9rsz,GenerativeSelect.group_by..)rrr|rr8r8r9rs zGenerativeSelect.group_by)FFNFF)NN)FF)%r;r<r=rMrrrrrrrr2rLABEL_STYLE_DEFAULTrrrrr!r)rr?rrrrrrrrrrrrgrrrr8r8r8r9r sv  $ = +         1  - rdefaultcompound_selectc@seZdZejddZdS)CompoundSelectStatecCs.|j}d|_tdd|jD}|||fS)NFcss|]}|j|fVqdSr5r rr8r8r9rsz:CompoundSelectState._label_resolve_dict..) statementrCrdictr)r7Zhacky_subquerydr8r8r9_label_resolve_dicts z'CompoundSelectState._label_resolve_dictN)r;r<r=r2rrr8r8r8r9rsrc szeZdZdZdZdejfdejfdejfdejfdejfdejfd ejfd ejfd ej fg e j Z e d Ze d Ze dZe dZe dZe dZdZddZeddZeddZeddZeddZeddZedd Zd!d"Zd;d$d%Zd&d'Z d(d)Z!d*d+Z"d,d-Z#fd.d/Z$e%d0d1Z&e%d2d3Z'e%e j(d4d5d6d7d8d9Z)e)j*d:d9Z)Z+S)<CompoundSelectaXForms 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` rselectsrrrrrrrkeywordUNIONz UNION ALLEXCEPTz EXCEPT ALL INTERSECTz INTERSECT ALLTcsR|dd_|_fdd|D_|r@tjr@tjdddtjf|dS)Nr"Fcs"g|]}ttj|jdqS)r)rrvrCompoundElementRolerrxsr6r8r9r{sz+CompoundSelect.__init__..zSet functions such as union(), union_all(), extract(), etc. in SQLAlchemy 2.0 will accept a series of SELECT statements only. Please use generative methods such as order_by() for additional modifications to this CompoundSelect.rr) rn_auto_correlaterrr2rrrr)r7rrrFr8r6r9rs   zCompoundSelect.__init__cOsttjf||S)aReturn a ``UNION`` of multiple selectables. The returned object is an instance of :class:`_expression.CompoundSelect`. A similar :func:`union()` method is available on all :class:`_expression.FromClause` subclasses. :param \*selects: a list of :class:`_expression.Select` instances. :param \**kwargs: available keyword arguments are the same as those of :func:`select`. )rrrrrFr8r8r9 _create_unionszCompoundSelect._create_unioncOsttjf||S)aReturn a ``UNION ALL`` of multiple selectables. The returned object is an instance of :class:`_expression.CompoundSelect`. A similar :func:`union_all()` method is available on all :class:`_expression.FromClause` subclasses. :param \*selects: a list of :class:`_expression.Select` instances. :param \**kwargs: available keyword arguments are the same as those of :func:`select`. )r UNION_ALLrr8r8r9_create_union_all sz CompoundSelect._create_union_allcOsttjf||S)a]Return an ``EXCEPT`` of multiple selectables. The returned object is an instance of :class:`_expression.CompoundSelect`. :param \*selects: a list of :class:`_expression.Select` instances. :param \**kwargs: available keyword arguments are the same as those of :func:`select`. )rrrr8r8r9_create_exceptszCompoundSelect._create_exceptcOsttjf||S)aaReturn an ``EXCEPT ALL`` of multiple selectables. The returned object is an instance of :class:`_expression.CompoundSelect`. :param \*selects: a list of :class:`_expression.Select` instances. :param \**kwargs: available keyword arguments are the same as those of :func:`select`. )r EXCEPT_ALLrr8r8r9_create_except_all0sz!CompoundSelect._create_except_allcOsttjf||S)a`Return an ``INTERSECT`` of multiple selectables. The returned object is an instance of :class:`_expression.CompoundSelect`. :param \*selects: a list of :class:`_expression.Select` instances. :param \**kwargs: available keyword arguments are the same as those of :func:`select`. )rrrr8r8r9_create_intersectAsz CompoundSelect._create_intersectcOsttjf||S)adReturn an ``INTERSECT ALL`` of multiple selectables. The returned object is an instance of :class:`_expression.CompoundSelect`. :param \*selects: a list of :class:`_expression.Select` instances. :param \**kwargs: available keyword arguments are the same as those of :func:`select`. )r INTERSECT_ALLrr8r8r9_create_intersect_allRsz$CompoundSelect._create_intersect_allcCs|jdSNr)r _scalar_typer6r8r8r9rcszCompoundSelect._scalar_typeNcCst|Sr5)rrr8r8r9rfszCompoundSelect.self_groupcCs |jD]}||rdSqdSNTF)rr)r7rrr8r8r9ris  zCompoundSelect.is_derived_fromcCs<|j|k r8|}|jd|}|g|jdd|_|SNrr)rrr_set_label_style)r7rselect_0r8r8r9ros  zCompoundSelect._set_label_stylecCs>|jd}||jdk r:|}|g|jdd|_|Sr)rrr)r7Z new_selectr8r8r9rws z*CompoundSelect._ensure_disambiguated_namescCsj|jd}|jtk r ||j}||t|jjtdd|jDD]\}}ddt|D|_ qHdS)NrcSsg|] }|jqSr8rrr8r8r9r{szFCompoundSelect._generate_fromclause_column_proxies..cSs"g|]\}}|d|diqS)Zweightr)Z _annotate)rxirr8r8r9r{s) rrrr!rziprZ _all_columns enumerate_proxies)r7rCrZsubq_colZ select_colsr8r8r9rs     z2CompoundSelect._generate_fromclause_column_proxiescs*tt|||jD]}||qdSr5)rrrTr)r7rSrrr8r9rTs z&CompoundSelect._refresh_for_new_columncCs |jdjSr)rrKr6r8r8r9rKsz$CompoundSelect._all_selected_columnscCs |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)rrr6r8r8r9rszCompoundSelect.selected_columnsrrFrcCs.|jr |jS|jD]}|j}|r|SqdS)Returns the :class:`_engine.Engine` or :class:`_engine.Connection` to which this :class:`.Executable` is bound, or None if none found. N)rrr )r7rer8r8r9r s   zCompoundSelect.bindcCs ||_dSr5rr7r r8r8r9r s)N),r;r<r=rMrdr/rZr% dp_plain_dictr{r %_clone_annotations_traverse_internalsr'r2symbolrrrrrrrBrr(rrrrrrrrrrrrrTr?rKrr)r setterr*r8r8rr9rsl                  rc@seZdZdZeddddZeddddZedd d d Zedd d dZ eddddZ eddddZ dS)DeprecatedSelectGenerationszA collection of methods available on :class:`_sql.Select`, these are all **deprecated** methods as they modify the :class:`_sql.Select` object in -place. r@zThe :meth:`_expression.Select.append_correlation` method is deprecated and will be removed in a future release. Use the generative method :meth:`_expression.Select.correlate`.cCs|j||dS)aAppend the given correlation expression to this select() construct. This is an **in-place** mutation method; the :meth:`_expression.Select.correlate` method is preferred, as it provides standard :term:`method chaining`. N)r"rrr8r8r9append_correlationsz.DeprecatedSelectGenerations.append_correlationzThe :meth:`_expression.Select.append_column` method is deprecated and will be removed in a future release. Use the generative method :meth:`_expression.Select.add_columns`.cCs|j||dS)aoAppend the given column expression to the columns clause of this select() construct. E.g.:: my_select.append_column(some_table.c.new_column) This is an **in-place** mutation method; the :meth:`_expression.Select.add_columns` method is preferred, as it provides standard :term:`method chaining`. N) add_columnsrrRr8r8r9rrsz)DeprecatedSelectGenerations.append_columnzThe :meth:`_expression.Select.append_prefix` method is deprecated and will be removed in a future release. Use the generative method :meth:`_expression.Select.prefix_with`.cCs|j||dS)aAppend the given columns clause prefix expression to this select() construct. This is an **in-place** mutation method; the :meth:`_expression.Select.prefix_with` method is preferred, as it provides standard :term:`method chaining`. N)rtrrr8r8r9 append_prefixsz)DeprecatedSelectGenerations.append_prefixzThe :meth:`_expression.Select.append_whereclause` method is deprecated and will be removed in a future release. Use the generative method :meth:`_expression.Select.where`.cCs|j||dS)a\Append the given expression to this select() construct's WHERE criterion. The expression will be joined to existing WHERE criterion via AND. This is an **in-place** mutation method; the :meth:`_expression.Select.where` method is preferred, as it provides standard :term:`method chaining`. N)wherer)r7rr8r8r9append_whereclausesz.DeprecatedSelectGenerations.append_whereclausezThe :meth:`_expression.Select.append_having` method is deprecated and will be removed in a future release. Use the generative method :meth:`_expression.Select.having`.cCs|j||dS)a_Append the given expression to this select() construct's HAVING criterion. The expression will be joined to existing HAVING criterion via AND. This is an **in-place** mutation method; the :meth:`_expression.Select.having` method is preferred, as it provides standard :term:`method chaining`. N)havingrr7rr8r8r9 append_having/sz)DeprecatedSelectGenerations.append_havingzThe :meth:`_expression.Select.append_from` method is deprecated and will be removed in a future release. Use the generative method :meth:`_expression.Select.select_from`.cCs|j||dS)a2Append the given :class:`_expression.FromClause` expression to this select() construct's FROM clause. This is an **in-place** mutation method; the :meth:`_expression.Select.select_from` method is preferred, as it provides standard :term:`method chaining`. N)rrrr8r8r9 append_fromDsz'DeprecatedSelectGenerations.append_fromN) r;r<r=rMr2rfr rrrrrrr8r8r8r9r s>     r rc@seZdZdZGdddeZddZeddZedd Z ed d Z ed d Z ddZ d"ddZ d#ddZddZeddZeddZddZedddZedd d!ZdS)$ SelectState) from_clausesfromscolumns_plus_namesrc@seZdZgZdS)z*SelectState.default_select_compile_optionsN)r;r<r=_cache_key_traversalr8r8r8r9default_select_compile_options`srcKs\||_|j|_|jD]}||j|jq|jr@||j|j|||_|d|_ dSr>) r _from_objr_memoized_select_entities _setup_joins _raw_columns _get_fromsrrr)r7rcompilerrsZmemoized_entitiesr8r8r9rcs  zSelectState.__init__cCs tddS)NzLThe default SELECT construct without plugins does not implement this method.rI)rr8r8r9_plugin_not_implementedssz#SelectState._plugin_not_implementedcCs |dSr5r"rrr8r8r9get_column_descriptionszsz#SelectState.get_column_descriptionscCs |dSr5r#)rrfrom_statementr8r8r9r&~szSelectState.from_statementcs4|tk|tk ttdfdd }|S)Ncs|jr dSs$|j}|dkr d}|Sr.|jn|j}|dkrfd}|krV||S||Sn.|krr||jS|jS||SdS)NZ _no_label)_is_text_clauseZ _proxy_keyrZ _anon_labelruZ_anon_tq_key_labelZ_anon_key_label)rZcol_namerYrnamespatable_qualifiedr8r9gos*   z1SelectState._column_naming_convention..go)N)rrr!r)rrr,r8r(r9_column_naming_conventions z%SelectState._column_naming_conventioncCsB|jttjdd|jDtjdd|jD|j|dS)NcSsg|] }|jqSr8rrxr1r8r8r9r{sz*SelectState._get_froms..cSsg|] }|jqSr8rr.r8r8r9r{s)check_statement)_normalize_fromsrr from_iterabler_where_criteriar)r7rr8r8r9r s zSelectState._get_fromsNcst}g}|D]@}|jr,|j|kr,td||js||||jq|rtt j dd|Drfdd|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. -select() construct refers to itself as a FROMcSsg|]}t|jqSr8)rrrr8r8r9r{sz0SelectState._normalize_froms..csg|]}|kr|qSr8r8rZtoremover8r9r{s) rrgr1r1InvalidRequestErrorrrrrrrr1)r7Ziterable_of_fromsr/seenritemr8r4r9r0s&    zSelectState._normalize_fromscsjjjr0jjr0fddDjjdk 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|qSr8rr)explicit_correlate_fromsr to_correlater8r9r{sz2SelectState._get_display_froms..Ncs,g|]$}|ttpdjjkr|qSr8)r rr_correlate_exceptr)r9rr7r8r9r{srcsg|]}|tkr|qSr8rr)rimplicit_correlate_fromsr8r9r{s zSelect statement '%r' returned no FROM clauses due to auto-correlation; specify correlate() to control correlation manually.)rr _correlater;rrr1r5)r7r9r<r8)r9rr<r7r:r9_get_display_fromss6      zSelectState._get_display_fromscCs^tdd|jjD}tddt|jD}|}|D]\}}|||q>|||fS)Ncss*|]"}|jr|jp|jp|j|fVqdSr5)_allow_label_resolveZ_resolve_label _tq_labelrrr8r8r9r'szASelectState._memoized_attr__label_resolve_dict..css|]}|jr|j|fVqdSr5)r?rrr8r8r9r,s)rrrKrrcopyitems setdefault)r7Z with_colsZ only_fromsZ only_colsrrr8r8r9"_memoized_attr__label_resolve_dict&sz.SelectState._memoized_attr__label_resolve_dictcCs|jr|jddSdSdS)Nr)r)rZstmtr8r8r9determine_last_joined_entity7sz(SelectState.determine_last_joined_entitycCsddt|jDS)NcSsg|]}|qSr8r8rr8r8r9r{@sz4SelectState.all_selected_columns..)rrr$r8r8r9all_selected_columns>sz SelectState.all_selected_columnsc Cs|D]\}}}}|d}|d}|dkr>|||||\}} n ||} | dk r|j| } |jd| t| ||||df|j| dd|_q|jt|||||df|_qdS)Nrrrr)"_join_determine_implicit_left_side_join_place_explicit_left_siderr) r7rE raw_columnsrrrflagsrrreplace_from_obj_indexZ left_clauser8r8r9rBsF   zSelectState._setup_joinsr\c 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|] }|jqSr8rr.r8r8r9r{szBSelectState._join_determine_implicit_left_side..cSsg|] }|jqSr8rr.r8r8r9r{sr8aCan'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.)r2r]r^rZfind_left_clause_to_join_fromrrrrr1r2rkeysr1r5) r7rJrrrr^rLrindexesZ potentialrZ from_clauseZ all_clausesr8r8r9rHksX         z.SelectState._join_determine_implicit_left_sidecCsXd}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) r2r]r^rr_iterate_from_elementsZ#find_left_clause_that_matches_givenrrr1r5)r7rrLr^rrNr8r8r9rIs  z*SelectState._join_place_explicit_left_side)N)NN)r;r<r= __slots__rrrr(r"r%r&r-r r0r>rDrFrGrr2rgrHrIr8r8r8r9rWs4    ( $ D  ) Erc@seZdZddZdS)_SelectFromElementsccst}|jD]*}|jD]}||kr$q|||Vqq |jD]*}|jD]}||krVqH|||VqHq>|jD]}||kr~qp|||VqpdSr5)rrrrur2r)r7r6r1frr8r8r9rOs$          z*_SelectFromElements._iterate_from_elementsN)r;r<r=rOr8r8r8r9rQsrQc@sNeZdZdZdejfdejfdejfdejfgZe j Z ddZ e dd Zd S) _MemoizedSelectEntitiesZmemoized_select_entitiesrr_legacy_setup_joins _with_optionscKs.|j|j}dd|jD|_||_|S)NcSsi|]\}}||qSr8r8)rxkvr8r8r9 sz2_MemoizedSelectEntities._clone..)rr2rrBZ _is_clone_of)r7rsrr8r8r9r sz_MemoizedSelectEntities._clonecCsd|js|js|jr`t}|j|_|j|_|j|_|j|_|j|f7_d|_|_|_|_dS)Nr8)rrTrUrSrr)rZ select_stmtr7r8r8r9_generate_for_statements&z/_MemoizedSelectEntities._generate_for_statementN)r;r<r=rdr/rZdp_setup_join_tupleZdp_executable_optionsr'r2 EMPTY_DICTZ _annotationsr r(rYr8r8r8r9rSsrScsDeZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZejZdejfdejfd ejfd ejfd ejfd ejfd ejfdejfdejfdejfdejfdejfdejfdejfdejfdejfdejfdejfdejfgejeje j!e"j#e$j%e&j'Z(e(dej)fgZ*e+ddZ,e+e-.ddddd Z/e+d!d"Z0e0Z1e+d#d$Z2d%d&Z3d'd(Z4d)d*Z5d+d,Z6d-d.Z7e8d/d0Z9d1d2Z:e;dd3d4Zdd9d:Z?e8d;d<Z@e8d=d>ZAd?d@ZBeCffdAdB ZDfdCdDZEe;dEdFZFdGdHZGe-.dIdJdKdLZHe-IdMddNdOZJe;dPdQZKe8dRdSZLeLZMe;dTdUZNe;dVdWZOe;dXdYZPe;dZd[ZQe;d\d]ZRe;d^d_ZSeTjUd`daZVeTjUdbdcZWdddeZXdfdgZYdhdiZZdjdkZ[ddldmZ\dndoZ]dpdqZ^drdsZ_dtduZ`dvdwZadxdyZbe8e-jcdzd{dd|d}d~Zdedjedd~ZdZfS)rAa[Represents 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:`coretutorial_selecting` - in the 1.x tutorial :ref:`tutorial_selecting_data` - in the 2.0 tutorial rr8FNTrrrr2_having_criteriarrrrTr=r;rrrrr _distinct _distinct_onr_compile_optionscOs(|s|rtj|f||Stj|SdSr5)rArB_create_select)rtargetentitiesr.rsr8r8r9rbsz%Select._create_select_from_fromclauserzThe legacy calling style of :func:`_sql.select` is deprecated and will be removed in SQLAlchemy 2.0. Please use the new calling style described at :func:`_sql.select`.c s,|||_|dk rF|dkr.jnjjft||dk rfjjft|z t|} Wn:tk r} ztj t j ddd| dW5d} ~ XYnX| rȇfdd |D_ ng_ |dk rj ||dk rj||r ||r|tjf| S) aBConstruct a new :class:`_expression.Select` using the 1.x style API. This method is called implicitly when the :func:`_expression.select` construct is used and the first argument is a Python list or other plain sequence object, which is taken to refer to the columns collection. .. versionchanged:: 1.4 Added the :meth:`.Select.create_legacy_select` constructor which documents the calling style in use when the :func:`.select` construct is invoked using 1.x-style arguments. Similar functionality is also available via the :meth:`_expression.FromClause.select` method on any :class:`_expression.FromClause`. All arguments which accept :class:`_expression.ClauseElement` arguments also accept string arguments, which will be converted as appropriate into either :func:`_expression.text()` or :func:`_expression.literal_column()` constructs. .. seealso:: :ref:`coretutorial_selecting` - Core Tutorial description of :func:`_expression.select`. :param columns: A list of :class:`_expression.ColumnElement` or :class:`_expression.FromClause` objects which will form the columns clause of the resulting statement. For those objects that are instances of :class:`_expression.FromClause` (typically :class:`_schema.Table` or :class:`_expression.Alias` objects), the :attr:`_expression.FromClause.c` collection is extracted to form a collection of :class:`_expression.ColumnElement` objects. This parameter will also accept :class:`_expression.TextClause` constructs as given, as well as ORM-mapped classes. .. note:: The :paramref:`_expression.select.columns` parameter is not available in the method form of :func:`_expression.select`, e.g. :meth:`_expression.FromClause.select`. .. seealso:: :meth:`_expression.Select.column` :meth:`_expression.Select.with_only_columns` :param whereclause: A :class:`_expression.ClauseElement` expression which will be used to form the ``WHERE`` clause. It is typically preferable to add WHERE criterion to an existing :class:`_expression.Select` using method chaining with :meth:`_expression.Select.where`. .. seealso:: :meth:`_expression.Select.where` :param from_obj: A list of :class:`_expression.ClauseElement` objects which will be added to the ``FROM`` clause of the resulting statement. This is equivalent to calling :meth:`_expression.Select.select_from` using method chaining on an existing :class:`_expression.Select` object. .. seealso:: :meth:`_expression.Select.select_from` - full description of explicit FROM clause specification. :param bind=None: an :class:`_engine.Engine` or :class:`_engine.Connection` instance to which the resulting :class:`_expression.Select` object will be bound. The :class:`_expression.Select` object will otherwise automatically bind to whatever :class:`~.base.Connectable` instances can be located within its contained :class:`_expression.ClauseElement` members. :param correlate=True: indicates that this :class:`_expression.Select` object should have its contained :class:`_expression.FromClause` elements "correlated" to an enclosing :class:`_expression.Select` object. It is typically preferable to specify correlations on an existing :class:`_expression.Select` construct using :meth:`_expression.Select.correlate`. .. seealso:: :meth:`_expression.Select.correlate` - full description of correlation. :param distinct=False: when ``True``, applies a ``DISTINCT`` qualifier to the columns clause of the resulting statement. The boolean argument may also be a column expression or list of column expressions - this is a special calling form which is understood by the PostgreSQL dialect to render the ``DISTINCT ON ()`` syntax. ``distinct`` is also available on an existing :class:`_expression.Select` object via the :meth:`_expression.Select.distinct` method. .. seealso:: :meth:`_expression.Select.distinct` :param group_by: a list of :class:`_expression.ClauseElement` objects which will comprise the ``GROUP BY`` clause of the resulting select. This parameter is typically specified more naturally using the :meth:`_expression.Select.group_by` method on an existing :class:`_expression.Select`. .. seealso:: :meth:`_expression.Select.group_by` :param having: a :class:`_expression.ClauseElement` that will comprise the ``HAVING`` clause of the resulting select when ``GROUP BY`` is used. This parameter is typically specified more naturally using the :meth:`_expression.Select.having` method on an existing :class:`_expression.Select`. .. seealso:: :meth:`_expression.Select.having` :param limit=None: a numerical value which usually renders as a ``LIMIT`` expression in the resulting select. Backends that don't support ``LIMIT`` will attempt to provide similar functionality. This parameter is typically specified more naturally using the :meth:`_expression.Select.limit` method on an existing :class:`_expression.Select`. .. seealso:: :meth:`_expression.Select.limit` :param offset=None: a numeric value which usually renders as an ``OFFSET`` expression in the resulting select. Backends that don't support ``OFFSET`` will attempt to provide similar functionality. This parameter is typically specified more naturally using the :meth:`_expression.Select.offset` method on an existing :class:`_expression.Select`. .. seealso:: :meth:`_expression.Select.offset` :param order_by: a scalar or list of :class:`_expression.ClauseElement` objects which will comprise the ``ORDER BY`` clause of the resulting select. This parameter is typically specified more naturally using the :meth:`_expression.Select.order_by` method on an existing :class:`_expression.Select`. .. seealso:: :meth:`_expression.Select.order_by` :param use_labels=False: when ``True``, the statement will be generated using labels for each column in the columns clause, which qualify each column with its parent table's (or aliases) name so that name conflicts between columns in different tables don't occur. The format of the label is ``_``. The "c" collection of a :class:`_expression.Subquery` created against this :class:`_expression.Select` object, as well as the :attr:`_expression.Select.selected_columns` collection of the :class:`_expression.Select` itself, will use these names for targeting column members. This parameter can also be specified on an existing :class:`_expression.Select` object using the :meth:`_expression.Select.set_label_style` method. .. seealso:: :meth:`_expression.Select.set_label_style` FTNzselect() construct created in legacy mode, i.e. with keyword arguments, must provide the columns argument as a Python list or other iterable.Zc9ae)code)from_csg|]}tjtj|dqSr6rrr6r8r9r{cs z/Select.create_legacy_select..)r2rdistinctrr2rrr TypeErrorrr1rorrrrqrrr) rrrZfrom_objrfrr"r}rrFZ cols_presentrr8r6r9rBisD`       zSelect.create_legacy_selectcs,||fdd|D_tS)aConstruct a new :class:`_expression.Select` using the 2. x style API. .. versionadded:: 1.4 - The :func:`_sql.select` function now accepts column arguments positionally. The top-level :func:`_sql.select` function will automatically use the 1.x or 2.x style API based on the incoming arguments; using :func:`_future.select` from the ``sqlalchemy.future`` module will enforce that only the 2.x style constructor is used. Similar functionality is also available via the :meth:`_expression.FromClause.select` method on any :class:`_expression.FromClause`. .. seealso:: :ref:`coretutorial_selecting` - Core Tutorial description of :func:`_expression.select`. :param \*entities: Entities to SELECT from. For Core usage, this is typically a series of :class:`_expression.ColumnElement` and / or :class:`_expression.FromClause` objects which will form the columns clause of the resulting statement. For those objects that are instances of :class:`_expression.FromClause` (typically :class:`_schema.Table` or :class:`_expression.Alias` objects), the :attr:`_expression.FromClause.c` collection is extracted to form a collection of :class:`_expression.ColumnElement` objects. This parameter will also accept :class:`_expression.TextClause` constructs as given, as well as ORM-mapped classes. csg|]}tjtj|dqSrerrxentr6r8r9r{s z0Select._create_future_select..)r2rrr)rrbr8r6r9_create_future_select{s '   zSelect._create_future_selectcOsv|rXt|dts\t|ddrXt|dtjtfsXt|ddddkrXt|ddr\|rh|j||S|j|SdS)aCreate a :class:`.Select` using either the 1.x or 2.0 constructor style. For the legacy calling style, see :meth:`.Select.create_legacy_select`. If the first argument passed is a Python sequence or if keyword arguments are present, this style is used. .. versionadded:: 2.0 - the :func:`_future.select` construct is the same construct as the one returned by :func:`_expression.select`, except that the function only accepts the "columns clause" entities up front; the rest of the state of the SELECT should be built up using generative methods. Similar functionality is also available via the :meth:`_expression.FromClause.select` method on any :class:`_expression.FromClause`. .. seealso:: :ref:`coretutorial_selecting` - Core Tutorial description of :func:`_expression.select`. :param \*entities: Entities to SELECT from. For Core usage, this is typically a series of :class:`_expression.ColumnElement` and / or :class:`_expression.FromClause` objects which will form the columns clause of the resulting statement. For those objects that are instances of :class:`_expression.FromClause` (typically :class:`_schema.Table` or :class:`_expression.Alias` objects), the :attr:`_expression.FromClause.c` collection is extracted to form a collection of :class:`_expression.ColumnElement` objects. This parameter will also accept :class:`_expression.TextClause` constructs as given, as well as ORM-mapped classes. r__iter__F)ZraiseerrNZ__clause_element__) rrhasattrr2 string_typesr'r3rBrj)rrErsr8r8r9_creates&)       zSelect._createcCs tdSr5rIr6r8r8r9rszSelect.__init__cCs|jd}t|j}|djSr)rrrr)r7rcolsr8r8r9rs  zSelect._scalar_typecGs |j|S)z6A synonym for the :meth:`_future.Select.where` method.r)r7Zcriteriar8r8r9filtersz Select.filtercCs@|jr&t|j}||}|dk r&|S|jr6|jdS|jdSr)rrget_plugin_classrFrr)r7methZ_last_joined_entityr8r8r9_filter_by_zeros zSelect._filter_by_zeroc s(|fdd|D}|j|S)zWapply the given filtering criterion as a WHERE clause to this select. csg|]\}}t||kqSr8r)rxrrZ from_entityr8r9r{ sz$Select.filter_by..)rtrBrq)r7rFrr8rur9 filter_bys  zSelect.filter_bycCst|j}||S)z`Return a 'column descriptions' structure which may be :term:`plugin-specific`. )rrrr%r7rsr8r8r9column_descriptionss zSelect.column_descriptionscCst|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 )rrrr&)r7rrsr8r8r9r&s zSelect.from_statementcCsJtjtj||d}|dk r(ttj|}|j||d||dff7_dS)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` r6Nr)rrvrJoinTargetRolerr)r7rarrrr8r8r9rp2s;z Select.joincCs|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)r7rdrarrr8r8r9outerjoin_fromvs zSelect.outerjoin_fromcCs\tjtj||d}tjtj||d}|dk r:ttj|}|j|||||dff7_dS)aCreate 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, address_table).join_from( user_table, address_table, user_table.c.id == address_table.c.user_id ) The above statement generates SQL similar to:: SELECT user.id, user.name, address.id, address.email, address.user_id FROM user JOIN address ON user.id = address.user_id .. versionadded:: 1.4 :param from\_: the left side of the join, will be rendered in the FROM clause and is roughly equivalent to using the :meth:`.Select.select_from` method. :param target: target table to join towards :param onclause: ON clause of the join. :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` r6Nr)rrvrrryrr)r7rdrarrrr8r8r9r{s1zSelect.join_fromcCs|j||d|dS)aCreate a left outer join. Parameters are the same as that of :meth:`_expression.Select.join`. .. versionchanged:: 1.4 :meth:`_expression.Select.outerjoin` 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`. .. seealso:: :ref:`tutorial_select_join` - in the :doc:`/tutorial/index` :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel` :meth:`_expression.Select.join` Trz)rp)r7rarrr8r8r9rs#zSelect.outerjoincCs||dS)zXReturn the displayed list of :class:`_expression.FromClause` elements. N)Z_compile_state_factoryr>r6r8r8r9rsz Select.fromscCs t|jS)a0An iterator of all :class:`_expression.ColumnElement` expressions which would be rendered into the columns clause of the resulting SELECT statement. This method is legacy as of 1.4 and is superseded by the :attr:`_expression.Select.exported_columns` collection. )iterrKr6r8r8r9 inner_columnss zSelect.inner_columnscCs0||jkrdS|D]}||rdSqdSr)rrOr)r7rrr8r8r9rs    zSelect.is_derived_fromc sttt|jt|j}fdd|Dfdd|jD}tddD||}t |t ||_fdd}|d <t t |j fd d | dS) Ncsi|]}||fqSr8r8rr@rsr8r9rXsz*Select._copy_internals..csg|]}|fqSr8r8rrr8r9r{sz*Select._copy_internals..css|]}t|tr|VqdSr5)rrrr8r8r9rs z)Select._copy_internals..cs,t|tr(|jkr(|j|}|SdSr5)rr)rprc)r4rsZnewelem) new_fromsr8r9replace(sz'Select._copy_internals..replacer)r)r@ omit_attrs)rrrrrr2rr differencer|rrArAr)r7r@rsZ all_the_fromsZexisting_from_objZ add_fromsrr)r@rsrr9rAs0    zSelect._copy_internalsc s$ttt|jdddgd|S)Nrr=r;)r)rrrrA get_childrenrOr7rFrr8r9r9s  zSelect.get_childrencs&jfdd|D_dS)aReturn a new :func:`_expression.select` construct with the given column expressions added to its columns clause. E.g.:: my_select = my_select.add_columns(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. csg|]}tjtj|dqSrer)rxrSr6r8r9r{Rs z&Select.add_columns..N)rrr7rr8r6r9rAszSelect.add_columnscsfddt|D_dS)Ncsg|]}tjtj|dqSrerrhr6r8r9r{Zs z(Select._set_entities..)r2rr)r7rbr8r6r9 _set_entitiesYs zSelect._set_entitiesr@zThe :meth:`_expression.Select.column` method is deprecated and will be removed in a future release. Please use :meth:`_expression.Select.add_columns`cCs ||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. )rrRr8r8r9rSasz Select.columnr\cCs*|jtjjj|jf|j|jd|iS)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. only_synonyms)with_only_columnsr2r]r^rrKr2r)r7rr8r8r9rws zSelect.reduce_columnscGs0|t|ddtdd|D|_dS)aSReturn a new :func:`_expression.select` construct with its columns clause replaced with the given columns. This method is exactly equivalent to as if the original :func:`_expression.select` had been called with the given columns clause. I.e. a statement:: s = select(table1.c.a, table1.c.b) s = s.with_only_columns(table1.c.b) should be exactly equivalent to:: s = select(table1.c.b) Note that this will also dynamically alter the FROM clause of the statement if it is not explicitly stated. To maintain the FROM clause, ensure the :meth:`_sql.Select.select_from` method is used appropriately:: s = select(table1.c.a, table2.c.b) s = s.select_from(table2.c.b).with_only_columns(table1.c.a) :param \*columns: column expressions to be used. .. versionchanged:: 1.4 the :meth:`_sql.Select.with_only_columns` method accepts the list of column expressions positionally; passing the expressions as a list is deprecated. cSsg|]}ttj|qSr8rrr8r8r9r{sz,Select.with_only_columns..rSelect.with_only_columnsN)Z_assert_no_memoizationsrSrYrZ!_expression_collection_was_a_listrrr8r8r9rs# rcCs 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 )r&Z_construct_for_whereclauser2r6r8r8r9rs zSelect.whereclausecGs<t|jtst|D]"}ttj|}|j|f7_qdS)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. N)rr2r|rrrvrWhereHavingRole)r7rZ criterionZwhere_criteriar8r8r9rsz Select.wherecCs|jttj|f7_dS)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. N)r\rrvrrrr8r8r9rs z Select.havingcGs0|r&d|_|jtdd|D|_nd|_dS)aReturn a new :func:`_expression.select` construct which will apply DISTINCT to its columns clause. :param \*expr: optional column expressions. When present, the PostgreSQL dialect will render a ``DISTINCT ON (>)`` construct. .. deprecated:: 1.4 Using \*expr in other dialects is deprecated and will raise :class:`_exc.CompileError` in a future version. Tcss|]}ttj|VqdSr5)rrvrZByOfRole)rxrr8r8r9rsz"Select.distinct..N)r]r^r|)r7rjr8r8r9rfs  zSelect.distinctcs$jtfdd|D7_dS)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|dVqdS)r6Nrrvrr)rxrr6r8r9r*s z%Select.select_from..N)rr|)r7rr8r6r9rs$zSelect.select_fromcGs<d|_|r|ddkrd|_n|jtdd|D|_dS)aUReturn 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: 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.Select.correlate_except` :ref:`correlated_subqueries` FrNFr8css|]}ttj|VqdSr5rrr8r8r9rjsz#Select.correlate..N)rr=r|r7Z fromclausesr8r8r9r"1s 5 zSelect.correlatecGs@d|_|r|ddkrd|_n|jp&dtdd|D|_dS)aReturn a new :class:`_expression.Select` which will omit the given FROM clauses from the auto-correlation process. Calling :meth:`_expression.Select.correlate_except` turns off the :class:`_expression.Select` object's default behavior of "auto-correlation" for the given FROM elements. An element specified here will unconditionally appear in the FROM list, while all other FROM elements remain subject to normal auto-correlation behaviors. If ``None`` is passed, the :class:`_expression.Select` object will correlate all of its FROM entries. :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.Select.correlate` :ref:`correlated_subqueries` Frrr8css|]}ttj|VqdSr5rrr8r8r9rsz*Select.correlate_except..N)rr;r|rr8r8r9correlate_exceptns zSelect.correlate_exceptcs(t|jtfdd|jDS)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. 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. .. 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 csg|]}|js||fqSr8)r'rconvr8r9r{sz+Select.selected_columns..)rr-rrrKrr6r8rr9rs /  zSelect.selected_columnscCst|j}t||Sr5)rrrrGrrwr8r8r9rKs zSelect._all_selected_columnscCs|jtkr|t}|Sr5)rrr!rr6r8r8r9rs  z"Select._ensure_disambiguated_namescCs|j}t|j}i}g}|j}|jtk}|jtk}|D]} d} | jsVd} } } n|rpd} } | jpl| j } n|r| j } } } n| j} } d} | dkr| j }|dkr| j |k} | || j <d} } | r|r| j } q| j } q| j } n |} } } | dk r| |krt|| t| kr|r,| j} } n | j } } |r| |krt|| t| ks`t|rr| j } } n | j } } d} n| || <n&|r|r| j } } n | j } } d} n| || <|| || | | | fq8|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. FNT)rKrr-rrrrZ_render_label_in_columns_clauseZ_non_anon_labelZ_anon_name_labelr@Z_expression_labelZ_dedupe_anon_tq_labelZ_dedupe_anon_labelrZ_anon_tq_labelr)r7rroZkey_naming_conventionr)resultZ result_appendr+Zlabel_style_nonerrepeatedZeffective_namerequired_label_namefallback_label_nameZ expr_labelr8r8r9rs          z#Select._generate_columns_plus_namescs(fdd|dD}j|dS)zYGenerate column proxies to place in the exported ``.c`` collection of a subquery.cs.g|]&\}}}}}|js|j||ddqS)T)rrYZname_is_truncatable)r'r)rxr proxy_keyrrrrr8r9r{msz>Select._generate_fromclause_column_proxies..FN)rrr)r7rCZproxr8rr9ris z*Select._generate_fromclause_column_proxiescCs|jpt|jjSr5)rrrrr6r8r8r9_needs_parens_for_groupingsz!Select._needs_parens_for_groupingcCs"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)rrrrrr8r8r9rs zSelect.self_groupcKstj||f|S)zaReturn a SQL ``UNION`` of this select() construct against the given selectable. )rrr7rrFr8r8r9rsz Select.unioncKstj||f|S)zeReturn a SQL ``UNION ALL`` of this select() construct against the given selectable. )rrrr8r8r9rYszSelect.union_allcKstj||f|S)zbReturn a SQL ``EXCEPT`` of this select() construct against the given selectable. )rrrr8r8r9except_szSelect.except_cKstj||f|S)zfReturn a SQL ``EXCEPT ALL`` of this select() construct against the given selectable. )rrrr8r8r9 except_allszSelect.except_allcKstj||f|S)zeReturn a SQL ``INTERSECT`` of this select() construct against the given selectable. )rrrr8r8r9 intersectszSelect.intersectcKstj||f|S)ziReturn a SQL ``INTERSECT ALL`` of this select() construct against the given selectable. )rrrr8r8r9 intersect_allszSelect.intersect_allrrrcCsx|jr |jS|D]:}|jr2|j|kr2td|j}|rJ||_|SqPq|jD]}|j}|rV||_|SqVdS)rr3N)rrOrgr1r1r5r r)r7r7rrr8r8r9r s"   z Select.bindcCs ||_dSr5rrr8r8r9r s)NNNFNTNN)NFF)NF)NFF)NF)T)N)gr;r<r=rMrdrrTrr]r^r=r;r2r\rrrrr_r/rZZdp_memoized_select_entitiesZdp_clauseelement_tuplerZr%rr&Z dp_plain_objr[r_rhrrrrrr r rZ_executable_traverse_internalsr'Zdp_has_cache_keyrr(rr2rfrBrjr`rnrrrqrtrvr?rxr&rrpr|r{rrr~rr rArrrrSrgrrrZ _whereclauserrrfrr"rrrLrrKrrrrrrrYrrrrr)r r r*r8r8rr9rAs. !   2 9   C  = %   5     -     * < % 8   rAc@sdeZdZdZgZdZdZdZddZe ddZ e Z e dd Z d d Ze d d Ze ddZdS)raRepresent 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 :ref:`scalar_selects` - in the 1.x tutorial TFcCs||_||_dSr5)r1rrrhr8r8r9rszScalarSelect.__init__cCstddS)NzcScalar Select expression has no columns; use this object directly within a column-level expression.)r1r5r6r8r8r9rszScalarSelect.columnscCs|j||_dS)zuApply a WHERE clause to the SELECT statement referred to by this :class:`_expression.ScalarSelect`. N)r1r)r7rr8r8r9r szScalarSelect.wherecKs|Sr5r8rr8r8r9rszScalarSelect.self_groupcGs|jj||_dS)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 :ref:`correlated_subqueries` - in the 1.x tutorial N)r1r"rr8r8r9r"szScalarSelect.correlatecGs|jj||_dS)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 :ref:`correlated_subqueries` - in the 1.x tutorial N)r1rrr8r8r9r7s zScalarSelect.correlate_exceptN)r;r<r=rMrrBZ_is_implicitly_booleanr>rr?rrrrrr"rr8r8r8r9rs    rc@s`eZdZdZgZdZddZddZej ddd dd d Z d dZ ddZ ddZ ddZd S)rz^Represent an ``EXISTS`` clause. See :func:`_sql.exists` for a description of usage. TcOsZ|r t|dttfr |d}n|s.tdf}tj||}tj||t j t j dddS)a|Construct a new :class:`_expression.Exists` construct. The :func:`_sql.exists` can be invoked by itself to produce an :class:`_sql.Exists` construct, which will accept simple WHERE criteria:: exists_criteria = exists().where(table1.c.col1 == table2.c.col2) However, for greater flexibility in constructing the SELECT, an existing :class:`_sql.Select` construct may be converted to an :class:`_sql.Exists`, most conveniently by making use of the :meth:`_sql.SelectBase.exists` method:: exists_criteria = ( select(table2.c.col2). where(table1.c.col1 == table2.c.col2). exists() ) The EXISTS criteria is then used inside of an enclosing SELECT:: stmt = select(table1.c.col1).where(exists_criteria) The above statement will then be of the form:: SELECT col1 FROM table1 WHERE EXISTS (SELECT table2.col2 FROM table2 WHERE table2.col2 = table1.col1) .. seealso:: :ref:`tutorial_exists` - in the :term:`2.0 style` tutorial. rrT)operatorrZwraps_column_expressionN) rrrr,rArnrbr.rrrrZ BOOLEANTYPE)r7rErFrr8r8r9rds"  zExists.__init__cCs |j}||}|jtjdS)Nr)r1Z_ungrouprrr)r7fnr1r8r8r9_regroups zExists._regroup)rzThe :paramref:`_sql.Exists.select().whereclause` parameter is deprecated and will be removed in version 2.0. Please make use of the :meth:`.Select.where` method to add WHERE criteria to the SELECT statement.)rzThe :meth:`_sql.Exists.select` method will no longer accept keyword arguments in version 2.0. Please use generative methods from the :class:`_sql.Select` construct in order to apply additional modifications.rNcKs"|dk r||d<tj||gf|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 :param whereclause: a WHERE clause, equivalent to calling the :meth:`_sql.Select.where` method. :param **kwargs: additional keyword arguments are passed to the legacy constructor for :class:`_sql.Select` described at :meth:`_sql.Select.create_legacy_select`. .. seealso:: :func:`_expression.select` - general purpose method which allows for arbitrary column lists. Nrrrr8r8r9rs+z Exists.selectcs |}|fdd|_|S)zApply correlation to the subquery noted by this :class:`_sql.Exists`. .. seealso:: :meth:`_sql.ScalarSelect.correlate` cs |jSr5)r"r<rr8r9r r z"Exists.correlate..r rr1r7rrr8rr9r"s  zExists.correlatecs |}|fdd|_|S)zApply correlation to the subquery noted by this :class:`_sql.Exists`. .. seealso:: :meth:`_sql.ScalarSelect.correlate_except` cs |jSr5)rr<rr8r9r r z)Exists.correlate_except..rrr8rr9rs  zExists.correlate_exceptcs |}|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 |jSr5)rr<rr8r9r r z$Exists.select_from..r)r7rrr8rr9rs zExists.select_fromcs |}|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 |Sr5rpr<rr8r9r r zExists.where..r)r7rrr8rr9rs z Exists.where)N)r;r<r=rMrr>rrr2rrr"rrrr8r8r8r9rZs1 rc@seZdZdZdZeZdejfdej fge j Z dZ dZdZdddZejd d Zed d Zd dZddZeddZeddZddZddZdS) 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_selectr1 column_argsTFcCs ||_dd|D|_||_dS)NcSsg|]}ttj|qSr8rrr8r8r9r{5sz*TextualSelect.__init__..)r1r positional)r7rrrr8r8r9r2s zTextualSelect.__init__cCstdd|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|fVqdSr5r rr8r8r9rPsz1TextualSelect.selected_columns..)rrrr6r8r8r9r:szTextualSelect.selected_columnscCs|jSr5)rr6r8r8r9rKTsz#TextualSelect._all_selected_columnscCs|Sr5r8rr8r8r9rXszTextualSelect._set_label_stylecCs|Sr5r8r6r8r8r9r[sz)TextualSelect._ensure_disambiguated_namescCs|jjSr5)r1rr6r8r8r9r^szTextualSelect._bindcOs|jj|||_dSr5)r1 bindparams)r7ZbindsZbind_as_valuesr8r8r9rbszTextualSelect.bindparamscs jfdd|jDdS)Nc3s|]}|VqdSr5rrrr8r9rgszDTextualSelect._generate_fromclause_column_proxies..)rrrrr8rr9rfsz1TextualSelect._generate_fromclause_column_proxiescCs |jdjSr)rrr6r8r8r9rkszTextualSelect._scalar_typeN)F)r;r<r=rMrdrrr/r%rZr r r'Z _is_textualZis_textrrrrLrr?rKrrrrrrrr8r8r8r9rs0     rc@seZdZddZdS)AnnotatedFromClausecCs|jt|||dSr5)rr r)r7r1rr8r8r9rtszAnnotatedFromClause.__init__Nr/r8r8r8r9rssr)qrMrrrrrrrrrrr annotationr r baser r rrrrrrrrrrrrrrrr r!r"rr#r$r%r&r'r(r)r*r+r,r-r.r/r1r2Z inspectionr3r4rfrCr7rGrQobjectrhrrZAnonymizedFromClauseRolerr rrrrZ DMLTableRolerr+r0rrErVrr]rQrWr[r`rror|rraZ DMLSelectRolerZ InElementRolerrrrZ plugin_forrrr Z MemoizedSlotsrrQZ HasCacheKeyZHasCopyInternalsZ TraversiblerSrArrrZ TextAsFromrr8r8r8r9sJ                                              ?N83TE 1[J2U xzI/.= &M5n  $ | ) ]t/g