U kfN @s8dZddlmZddlmZddlZddlmZddlm Z ddlm Z ddlm Z ddlm Z dd lm Z dd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddl!m"Z"ddl!m#Z#ddl!m$Z$ddl!m%Z%ddl!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-m1Z1dd*l-m2Z2dd+l3m4Z4dd,l3m5Z5dd-l3m6Z6dd.l3m7Z7dd/l3m8Z8dd0l3m9Z9dd1l3m:Z:dd2l3m;Z;dd3l3mZ>dd5l?m@Z@d6d7lmAZAd6dlmZd6d8lBmCZCd6d9lBmDZDerdd:lmEZEdd;lmFZFddlmIZIdd?lmJZJdd@lmKZKddAlmLZLddBlmMZMddClmNZNddDlmOZOddElmPZPddFlmQZQddGlmRZSddHl!mTZTddIlUmVZVddJl-mWZWddKl3mXZXddLl3mYZYddMl3mZZZddNl3m[Z[dOdPdQdRdSZ\dOdTdQdUdVZ]dOdWdQdXdYZ^ne_dSZ\e_dVZ]e_dYZ^edZed[Z`eeae0efZbee;e4e9fZcGd\dOdOe(Zde(ed]d^Gd_d`d`edZfe(ed]daGdbdcdcedZge(ed]ddGdedfdfedZhGdgdhdhejie7e,e)e8e+e5e/ ZjGdidjdjejZkGdkdldlekZlGdmdndnelerPTNz0Optional[MutableMapping[_DMLColumnElement, Any]]_dict_parametersz6Optional[List[MutableMapping[_DMLColumnElement, Any]]]_multi_parameters-Optional[List[Tuple[_DMLColumnElement, Any]]]_ordered_valuesz!Optional[List[_DMLColumnElement]]_parameter_orderingr._primary_tableF UpdateBase statementrJrrdcompilerkwcKs tdSrSNotImplementedError)selfrdrfrgrTrTrV__init__szDMLState.__init__Dict[str, Any]rdrRcCst|jr|jjnd|jdS)N)nametable)rrornclsrdrTrTrVget_entity_descriptions  zDMLState.get_entity_descriptionList[Dict[str, Any]]cCsdd|jDS)NcSsg|]}|j|j|dqS))rntypeexpr)keyrt.0crTrTrV s z>DMLState.get_returning_column_descriptions..)_all_selected_columnsrprTrTrV!get_returning_column_descriptionssz*DMLState.get_returning_column_descriptions_DMLTableElementrRcCs|jjSrS)rdrorjrTrTrV dml_tableszDMLState.dml_tabler#zType[DMLState]cCsdSrSrTrprTrTrVget_plugin_classszDMLState.get_plugin_classz'Iterable[Dict[_DMLColumnArgument, Any]]z"List[Dict[_DMLColumnElement, Any]])rdmulti_kv_iteratorrRcCsdd|DS)NcSsg|]}dd|DqS)cSs i|]\}}ttj||qSrTrexpectr DMLColumnRolerxkvrTrTrV s z@DMLState._get_multi_crud_kv_pairs...)items)rxmappingrTrTrVrzsz5DMLState._get_multi_crud_kv_pairs..rT)rqrdrrTrTrV_get_multi_crud_kv_pairssz!DMLState._get_multi_crud_kv_pairsz(Iterable[Tuple[_DMLColumnArgument, Any]]boolz#List[Tuple[_DMLColumnElement, Any]])rd kv_iteratorneeds_to_be_cacheablerRcsfdd|DS)Nc s<g|]4\}}ttj|s |ntjtj|tddfqS)T)type_Zis_crud)rrrrZExpressionElementRoler5rrrTrVrzs z/DMLState._get_crud_kv_pairs..rT)rqrdrrrTrrV_get_crud_kv_pairss zDMLState._get_crud_kv_pairs DMLWhereBasez#Tuple[FromClause, List[FromClause]]c Csg}tt|j}|d}|h}|j}|jr@|t|j7}|D]4}t|D]&}| |j sj| || |j qPqD| |dd||fS)Nrr)listsql_utilZtables_from_leftmostro_where_criteriar]tuplevaluesr intersectionZ _cloned_setappendupdateextend) rjrdZfromsZ all_tablesZ primary_tableseenZconsidercrititemrTrTrV_make_extra_fromss   zDMLState._make_extra_froms ValuesBaseNonecCs|jr|j|_d|_dSNF)_no_parameters_valuesr]rjrdrTrTrV_process_valuesszDMLState._process_valuescCsB|jdk stdd|jD}|jr2d|_||_n ds>tddS)NcSsi|] }|tqSrTr*rxrnrTrTrVrsz3DMLState._process_select_values..Fz%This statement already has parameters) _select_namesAssertionErrorrr]rjrd parametersrTrTrV_process_select_valuesszDMLState._process_select_valuesr cCstd|jdS)Nz6%s construct does not support multiple parameter sets.)r8InvalidRequestError__visit_name__upperrrTrTrV_no_multi_values_supporteds z#DMLState._no_multi_values_supportedcCstddS)NzCan't mix single and multiple VALUES formats in one INSERT statement; one style appends to a list while the other replaces values, so the intent is ambiguous.)r8rrrTrTrV_cant_mix_formats_errorsz DMLState._cant_mix_formats_error)__name__ __module__ __qualname__rr]__annotations__r^r`ra_supports_implicit_returningrWrYrZrk classmethodrrr|propertyrrrrrrrrrrrTrTrTrVrPps>        defaultinsertc@sbeZdZdZdZdZdddddddd Zejd d d d Z dddddZ dddddZ dS)InsertDMLStateTFInsertrJrr)rdrfdisable_implicit_returningrgcKsV||_|j|_|rd|_d|_|jr.|||jdk rB|||j rR| |dS)NFT) rdrorbrrZrrrr _multi_values_process_multi_values)rjrdrfrrgrTrTrVrk s   zInsertDMLState.__init__z List[str]r~cCsdd|jpdDS)NcSsg|]}tjtj|ddqST)Zas_keyrrxcolrTrTrVrz%sz3InsertDMLState._insert_col_keys..rT)r]rrTrTrV_insert_col_keys"szInsertDMLState._insert_col_keysrrrmcCs.|jrd|_|j|_d|_n|jr*|dSr)r_has_multi_parametersrr]rrrTrTrVr*s zInsertDMLState._process_valuescsnjD]b}fdd|D}|jrBd|_d|_||_|jd|_q|jsR|q|js\t|j|qdS)Ncs4g|],}t|tjr,ddtjj|Dn|qS)cSsi|]\}}|j|qSrTrvrxryvaluerTrTrVr6szCInsertDMLState._process_multi_values...) isinstancecollections_abcr ziprory)rxZ parameter_setrdrTrVrz4s    z8InsertDMLState._process_multi_values..FTr)rrrr^r]rrr)rjrdrZmulti_parametersrTrrVr2s     z$InsertDMLState._process_multi_valuesN)F) rrrrZinclude_table_with_column_exprsrrkrZmemoized_propertyrrrrTrTrTrVrsrrc@s6eZdZdZdZddddddZd d d d d ZdS)UpdateDMLStateTFUpdaterJrrecKs||_d|_|jdk r"||n&|jdk r8||n|jrH||||\}}||_ ||_ ||_ }t |ov|j |_dSNT)rdrWr`_process_ordered_valuesrrrrrrb _extra_froms is_multitablerZ'render_table_with_column_in_update_fromr)rjrdrfrgtefmtrTrTrVrkRs      zUpdateDMLState.__init__rrrmcCsN|j}|jr@d|_|dk stt||_||_dd|D|_n tddS)NFcSsg|] \}}|qSrTrTrxrvrrTrTrVrzmsz:UpdateDMLState._process_ordered_values..zQCan only invoke ordered_values() once, and not mixed with any other values() call)r`rrdictr]rar8rrrTrTrVres  z&UpdateDMLState._process_ordered_valuesN)rrrrWrrkrrTrTrTrVrLsrdeletec@s"eZdZdZddddddZdS) DeleteDMLStateTDeleterJrrecKs0||_d|_||\}}||_||_||_dSr)rdrYrrbrr)rjrdrfrgrrrTrTrVrkys zDeleteDMLState.__init__N)rrrrYrkrTrTrTrVrusrc@sXeZdZUdZdZejZded<dZ e j Z ded<ded <dZ d Zd ed <d Zd ed <dZded<dZdddddZddddddZedddddZed dd d!d"d#dd$d%d&Zedd'd(d#ddd)d*d+ZdDd,d#d-d.d/d0Zejd1d2d3d4Zejd5d2d6d7ZedEd9d:d9dd;dd2d?d@ZedAd2dBdCZd S)FrczDForm the base for ``INSERT``, ``UPDATE``, and ``DELETE`` statements.Z update_basez5util.immutabledict[Tuple[_DMLTableElement, str], str]_hintsFr2 _label_styler}roNz+Optional[Tuple[_ColumnsClauseElement, ...]]_return_defaults_columns_supplemental_returningrTz!Tuple[_ColumnsClauseElement, ...] _returningTr.r) fromclauserRcs jfdd|jDdS)Nc3s |]}t|r|VqdSrS)rZ _make_proxyrrrTrV szAUpdateBase._generate_fromclause_column_proxies..)Z_columnsZ_populate_separate_keysr{)rjrrTrrV#_generate_fromclause_column_proxiessz.UpdateBase._generate_fromclause_column_proxiesrr )argrgrRcOs tddS)zSet the parameters for the statement. This method raises ``NotImplementedError`` on the base class, and is overridden by :class:`.ValuesBase` to provide the SET/VALUES clause of UPDATE and INSERT. zparams() is not supported for INSERT/UPDATE/DELETE statements. To set the values for an INSERT or UPDATE statement, use stmt.values(**parameters).Nrh)rjrrgrTrTrVparamsszUpdateBase.paramsr9)optrRcKs|||S)a Add dialect options to this INSERT/UPDATE/DELETE object. e.g.:: upd = table.update().dialect_options(mysql_limit=10) .. versionadded: 1.4 - this method supersedes the dialect options associated with the constructor. )Z_validate_dialect_kwargs)rjrrTrTrVwith_dialect_optionss zUpdateBase.with_dialect_options)supplemental_colssort_by_parameter_orderr=z&Optional[Iterable[_DMLColumnArgument]]r)colsrrrRcGs|jr<|jr4|r4tt|jdd|D|_qPd|_ntdd|D|_d|_|rp|jsjtdd|_ |rdd|D}|j dkrtt ||_ ntt |j t||_ |S) aA$Make use of a :term:`RETURNING` clause for the purpose of fetching server-side expressions and defaults, for supporting backends only. .. deepalchemy:: The :meth:`.UpdateBase.return_defaults` method is used by the ORM for its internal work in fetching newly generated primary key and server default values, in particular to provide the underyling implementation of the :paramref:`_orm.Mapper.eager_defaults` ORM feature as well as to allow RETURNING support with bulk ORM inserts. Its behavior is fairly idiosyncratic and is not really intended for general use. End users should stick with using :meth:`.UpdateBase.returning` in order to add RETURNING clauses to their INSERT, UPDATE and DELETE statements. Normally, a single row INSERT statement will automatically populate the :attr:`.CursorResult.inserted_primary_key` attribute when executed, which stores the primary key of the row that was just inserted in the form of a :class:`.Row` object with column names as named tuple keys (and the :attr:`.Row._mapping` view fully populated as well). The dialect in use chooses the strategy to use in order to populate this data; if it was generated using server-side defaults and / or SQL expressions, dialect-specific approaches such as ``cursor.lastrowid`` or ``RETURNING`` are typically used to acquire the new primary key value. However, when the statement is modified by calling :meth:`.UpdateBase.return_defaults` before executing the statement, additional behaviors take place **only** for backends that support RETURNING and for :class:`.Table` objects that maintain the :paramref:`.Table.implicit_returning` parameter at its default value of ``True``. In these cases, when the :class:`.CursorResult` is returned from the statement's execution, not only will :attr:`.CursorResult.inserted_primary_key` be populated as always, the :attr:`.CursorResult.returned_defaults` attribute will also be populated with a :class:`.Row` named-tuple representing the full range of server generated values from that single row, including values for any columns that specify :paramref:`_schema.Column.server_default` or which make use of :paramref:`_schema.Column.default` using a SQL expression. When invoking INSERT statements with multiple rows using :ref:`insertmanyvalues `, the :meth:`.UpdateBase.return_defaults` modifier will have the effect of the :attr:`_engine.CursorResult.inserted_primary_key_rows` and :attr:`_engine.CursorResult.returned_defaults_rows` attributes being fully populated with lists of :class:`.Row` objects representing newly inserted primary key values as well as newly inserted server generated values for each row inserted. The :attr:`.CursorResult.inserted_primary_key` and :attr:`.CursorResult.returned_defaults` attributes will also continue to be populated with the first row of these two collections. If the backend does not support RETURNING or the :class:`.Table` in use has disabled :paramref:`.Table.implicit_returning`, then no RETURNING clause is added and no additional data is fetched, however the INSERT, UPDATE or DELETE statement proceeds normally. E.g.:: stmt = table.insert().values(data='newdata').return_defaults() result = connection.execute(stmt) server_created_at = result.returned_defaults['created_at'] When used against an UPDATE statement :meth:`.UpdateBase.return_defaults` instead looks for columns that include :paramref:`_schema.Column.onupdate` or :paramref:`_schema.Column.server_onupdate` parameters assigned, when constructing the columns that will be included in the RETURNING clause by default if explicit columns were not specified. When used against a DELETE statement, no columns are included in RETURNING by default, they instead must be specified explicitly as there are no columns that normally change values when a DELETE statement proceeds. .. versionadded:: 2.0 :meth:`.UpdateBase.return_defaults` is supported for DELETE statements also and has been moved from :class:`.ValuesBase` to :class:`.UpdateBase`. The :meth:`.UpdateBase.return_defaults` method is mutually exclusive against the :meth:`.UpdateBase.returning` method and errors will be raised during the SQL compilation process if both are used at the same time on one statement. The RETURNING clause of the INSERT, UPDATE or DELETE statement is therefore controlled by only one of these methods at a time. The :meth:`.UpdateBase.return_defaults` method differs from :meth:`.UpdateBase.returning` in these ways: 1. :meth:`.UpdateBase.return_defaults` method causes the :attr:`.CursorResult.returned_defaults` collection to be populated with the first row from the RETURNING result. This attribute is not populated when using :meth:`.UpdateBase.returning`. 2. :meth:`.UpdateBase.return_defaults` is compatible with existing logic used to fetch auto-generated primary key values that are then populated into the :attr:`.CursorResult.inserted_primary_key` attribute. By contrast, using :meth:`.UpdateBase.returning` will have the effect of the :attr:`.CursorResult.inserted_primary_key` attribute being left unpopulated. 3. :meth:`.UpdateBase.return_defaults` can be called against any backend. Backends that don't support RETURNING will skip the usage of the feature, rather than raising an exception, *unless* ``supplemental_cols`` is passed. The return value of :attr:`_engine.CursorResult.returned_defaults` will be ``None`` for backends that don't support RETURNING or for which the target :class:`.Table` sets :paramref:`.Table.implicit_returning` to ``False``. 4. An INSERT statement invoked with executemany() is supported if the backend database driver supports the :ref:`insertmanyvalues ` feature which is now supported by most SQLAlchemy-included backends. When executemany is used, the :attr:`_engine.CursorResult.returned_defaults_rows` and :attr:`_engine.CursorResult.inserted_primary_key_rows` accessors will return the inserted defaults and primary keys. .. versionadded:: 1.4 Added :attr:`_engine.CursorResult.returned_defaults_rows` and :attr:`_engine.CursorResult.inserted_primary_key_rows` accessors. In version 2.0, the underlying implementation which fetches and populates the data for these attributes was generalized to be supported by most backends, whereas in 1.4 they were only supported by the ``psycopg2`` driver. :param cols: optional list of column key names or :class:`_schema.Column` that acts as a filter for those columns that will be fetched. :param supplemental_cols: optional list of RETURNING expressions, in the same form as one would pass to the :meth:`.UpdateBase.returning` method. When present, the additional columns will be included in the RETURNING clause, and the :class:`.CursorResult` object will be "rewound" when returned, so that methods like :meth:`.CursorResult.all` will return new rows mostly as though the statement used :meth:`.UpdateBase.returning` directly. However, unlike when using :meth:`.UpdateBase.returning` directly, the **order of the columns is undefined**, so can only be targeted using names or :attr:`.Row._mapping` keys; they cannot reliably be targeted positionally. .. versionadded:: 2.0 :param sort_by_parameter_order: for a batch INSERT that is being executed against multiple parameter sets, organize the results of RETURNING so that the returned rows correspond to the order of parameter sets passed in. This applies only to an :term:`executemany` execution for supporting dialects and typically makes use of the :term:`insertmanyvalues` feature. .. versionadded:: 2.0.10 .. seealso:: :ref:`engine_insertmanyvalues_returning_order` - background on sorting of RETURNING rows for bulk INSERT .. seealso:: :meth:`.UpdateBase.returning` :attr:`_engine.CursorResult.returned_defaults` :attr:`_engine.CursorResult.returned_defaults_rows` :attr:`_engine.CursorResult.inserted_primary_key` :attr:`_engine.CursorResult.inserted_primary_key_rows` css|]}ttj|VqdSrSrrrZColumnsClauseRolerwrTrTrVrsz-UpdateBase.return_defaults..rTcss|]}ttj|VqdSrSrrwrTrTrVrsTz]The 'sort_by_parameter_order' argument to return_defaults() only applies to INSERT statementscss|]}ttj|VqdSrSrrwrTrTrVrsN) _return_defaultsrrrZ OrderedSetunion is_insertr8 ArgumentError_sort_by_parameter_orderrZ unique_list)rjrrrZsupplemental_col_tuprTrTrVreturn_defaultssF8   zUpdateBase.return_defaultsr_ColumnsClauseArgument[Any])rr_UpdateBase__kwrRcOsX|rtd||jrtd|jtdd|D7_|rT|jsNtdd|_|S)aRAdd a :term:`RETURNING` or equivalent clause to this statement. e.g.: .. sourcecode:: pycon+sql >>> stmt = ( ... table.update() ... .where(table.c.data == "value") ... .values(status="X") ... .returning(table.c.server_flag, table.c.updated_timestamp) ... ) >>> print(stmt) {printsql}UPDATE some_table SET status=:status WHERE some_table.data = :data_1 RETURNING some_table.server_flag, some_table.updated_timestamp The method may be invoked multiple times to add new entries to the list of expressions to be returned. .. versionadded:: 1.4.0b2 The method may be invoked multiple times to add new entries to the list of expressions to be returned. The given collection of column expressions should be derived from the table that is the target of the INSERT, UPDATE, or DELETE. While :class:`_schema.Column` objects are typical, the elements can also be expressions: .. sourcecode:: pycon+sql >>> stmt = table.insert().returning( ... (table.c.first_name + " " + table.c.last_name).label("fullname") ... ) >>> print(stmt) {printsql}INSERT INTO some_table (first_name, last_name) VALUES (:first_name, :last_name) RETURNING some_table.first_name || :first_name_1 || some_table.last_name AS fullname Upon compilation, a RETURNING clause, or database equivalent, will be rendered within the statement. For INSERT and UPDATE, the values are the newly inserted/updated values. For DELETE, the values are those of the rows which were deleted. Upon execution, the values of the columns to be returned are made available via the result set and can be iterated using :meth:`_engine.CursorResult.fetchone` and similar. For DBAPIs which do not natively support returning values (i.e. cx_oracle), SQLAlchemy will approximate this behavior at the result level so that a reasonable amount of behavioral neutrality is provided. Note that not all databases/DBAPIs support RETURNING. For those backends with no support, an exception is raised upon compilation and/or execution. For those who do support it, the functionality across backends varies greatly, including restrictions on executemany() and other statements which return multiple rows. Please read the documentation notes for the database in use in order to determine the availability of RETURNING. :param \*cols: series of columns, SQL expressions, or whole tables entities to be returned. :param sort_by_parameter_order: for a batch INSERT that is being executed against multiple parameter sets, organize the results of RETURNING so that the returned rows correspond to the order of parameter sets passed in. This applies only to an :term:`executemany` execution for supporting dialects and typically makes use of the :term:`insertmanyvalues` feature. .. versionadded:: 2.0.10 .. seealso:: :ref:`engine_insertmanyvalues_returning_order` - background on sorting of RETURNING rows for bulk INSERT (Core level discussion) :ref:`orm_queryguide_bulk_insert_returning_ordered` - example of use with :ref:`orm_queryguide_bulk_insert` (ORM level discussion) .. seealso:: :meth:`.UpdateBase.return_defaults` - an alternative method tailored towards efficient fetching of server-side defaults and triggers for single-row INSERTs or UPDATEs. :ref:`tutorial_insert_returning` - in the :ref:`unified_tutorial` zUpdateBase.returning()z9return_defaults() is already configured on this statementcss|]}ttj|VqdSrSrrwrTrTrVrsz'UpdateBase.returning..zWThe 'sort_by_parameter_order' argument to returning() only applies to INSERT statementsT) rrr8rrrrrr)rjrrrrTrTrV returnings _  zUpdateBase.returningzKeyedColumnElement[Any]Optional[ColumnElement[Any]])columnrequire_embeddedrRcCs|jj||dS)N)r)exported_columnscorresponding_column)rjrrrTrTrVr#szUpdateBase.corresponding_columnrMr~cCsddt|jDS)NcSsg|]}|qSrTrTrwrTrTrVrz,sz4UpdateBase._all_selected_columns..)rrrrTrTrVr{*sz UpdateBase._all_selected_columnsz;ReadOnlyColumnCollection[Optional[str], ColumnElement[Any]]cCstdd|jDS)zxReturn the RETURNING columns as a column collection for this statement. .. versionadded:: 1.4 css |]}t|r|j|fVqdSrS)rrvrwrTrTrVr8sz.UpdateBase.exported_columns..)r r{Z as_readonlyrrTrTrVr.s zUpdateBase.exported_columns*strzOptional[_DMLTableArgument])text selectable dialect_namerRcCs8|dkr|j}nttj|}|j||f|i|_|S)aAdd a table hint for a single table to this INSERT/UPDATE/DELETE statement. .. note:: :meth:`.UpdateBase.with_hint` currently applies only to Microsoft SQL Server. For MySQL INSERT/UPDATE/DELETE hints, use :meth:`.UpdateBase.prefix_with`. The text of the hint is rendered in the appropriate location for the database backend in use, relative to the :class:`_schema.Table` that is the subject of this statement, or optionally to that of the given :class:`_schema.Table` passed as the ``selectable`` argument. The ``dialect_name`` option will limit the rendering of a particular hint to a particular backend. Such as, to add a hint that only takes effect for SQL Server:: mytable.insert().with_hint("WITH (PAGLOCK)", dialect_name="mssql") :param text: Text of the hint. :param selectable: optional :class:`_schema.Table` that specifies an element of the FROM clause within an UPDATE or DELETE to be the subject of the hint - applies only to certain backends. :param dialect_name: defaults to ``*``, if specified as the name of a particular dialect, will apply these hints only when that dialect is in use. N)rorrr DMLTableRolerr)rjrrrrTrTrV with_hint>s $zUpdateBase.with_hintrlcCst|j}||S)a=Return a :term:`plugin-enabled` description of the table and/or entity which this DML construct is operating against. This attribute is generally useful when using the ORM, as an extended structure which includes information about mapped entities is returned. The section :ref:`queryguide_inspection` contains more background. For a Core statement, the structure returned by this accessor is derived from the :attr:`.UpdateBase.table` attribute, and refers to the :class:`.Table` being inserted, updated, or deleted:: >>> stmt = insert(user_table) >>> stmt.entity_description { "name": "user_table", "table": Table("user_table", ...) } .. versionadded:: 1.4.33 .. seealso:: :attr:`.UpdateBase.returning_column_descriptions` :attr:`.Select.column_descriptions` - entity information for a :func:`.select` construct :ref:`queryguide_inspection` - ORM background )rPrrrrjmethrTrTrVentity_descriptionis! zUpdateBase.entity_descriptionrscCst|j}||S)aReturn a :term:`plugin-enabled` description of the columns which this DML construct is RETURNING against, in other words the expressions established as part of :meth:`.UpdateBase.returning`. This attribute is generally useful when using the ORM, as an extended structure which includes information about mapped entities is returned. The section :ref:`queryguide_inspection` contains more background. For a Core statement, the structure returned by this accessor is derived from the same objects that are returned by the :attr:`.UpdateBase.exported_columns` accessor:: >>> stmt = insert(user_table).returning(user_table.c.id, user_table.c.name) >>> stmt.entity_description [ { "name": "id", "type": Integer, "expr": Column("id", Integer(), table=, ...) }, { "name": "name", "type": String(), "expr": Column("name", String(), table=, ...) }, ] .. versionadded:: 1.4.33 .. seealso:: :attr:`.UpdateBase.entity_description` :attr:`.Select.column_descriptions` - entity information for a :func:`.select` construct :ref:`queryguide_inspection` - ORM background )rPrr|rrTrTrVreturning_column_descriptionss*z(UpdateBase.returning_column_descriptions)F)Nr) rrr__doc__rr EMPTY_DICTrrZnamed_with_columnr2ZLABEL_STYLE_DISAMBIGUATE_ONLYrrrrrZis_dmlrrrrrrrZro_memoized_propertyr{rrrrrrTrTrTrVrcsP       gq*#rcc@seZdZUdZdZdZdZded<dZded<dZ d ed <d Z d ed <dZ ded<dZ ded<dZ ded<ddddZeeddddddddddd d!ZdS)"rzTSupplies support for :meth:`.ValuesBase.values` to INSERT and UPDATE constructs.Z values_baseFNzOptional[Select[Any]]selectzOptional[ClauseElement]_post_values_clausez4Optional[util.immutabledict[_DMLColumnElement, Any]]rrTzRTuple[Union[Sequence[Dict[_DMLColumnElement, Any]], Sequence[Sequence[Any]]], ...]rr_r`zOptional[List[str]]rr_inliner?rocCstjtj||d|_dSNZapply_propagate_attrsrrrrrorjrorTrTrVrks zValuesBase.__init__z,This construct already inserts from a SELECT1This statement already has ordered values present)rr`)Zmsgsz/Union[_DMLColumnKeyMapping[Any], Sequence[Any]]rr9)argskwargsrRcOs.|r|d}|rtdqt|dkr4tdqt|tjr|rxt|dtrxt|j }|j |||f7_ |S|rt|dt t fr|j |f7_ |St rt|tstddt|jj|D}ntd|}|rtdt|j}t|||d}|jr|j||_n t||_|S) aLSpecify a fixed VALUES clause for an INSERT statement, or the SET clause for an UPDATE. Note that the :class:`_expression.Insert` and :class:`_expression.Update` constructs support per-execution time formatting of the VALUES and/or SET clauses, based on the arguments passed to :meth:`_engine.Connection.execute`. However, the :meth:`.ValuesBase.values` method can be used to "fix" a particular set of parameters into the statement. Multiple calls to :meth:`.ValuesBase.values` will produce a new construct, each one with the parameter list modified to include the new parameters sent. In the typical case of a single dictionary of parameters, the newly passed keys will replace the same keys in the previous construct. In the case of a list-based "multiple values" construct, each new list of values is extended onto the existing list of values. :param \**kwargs: key value pairs representing the string key of a :class:`_schema.Column` mapped to the value to be rendered into the VALUES or SET clause:: users.insert().values(name="some name") users.update().where(users.c.id==5).values(name="some name") :param \*args: As an alternative to passing key/value parameters, a dictionary, tuple, or list of dictionaries or tuples can be passed as a single positional argument in order to form the VALUES or SET clause of the statement. The forms that are accepted vary based on whether this is an :class:`_expression.Insert` or an :class:`_expression.Update` construct. For either an :class:`_expression.Insert` or :class:`_expression.Update` construct, a single dictionary can be passed, which works the same as that of the kwargs form:: users.insert().values({"name": "some name"}) users.update().values({"name": "some new name"}) Also for either form but more typically for the :class:`_expression.Insert` construct, a tuple that contains an entry for every column in the table is also accepted:: users.insert().values((5, "some name")) The :class:`_expression.Insert` construct also supports being passed a list of dictionaries or full-table-tuples, which on the server will render the less common SQL syntax of "multiple values" - this syntax is supported on backends such as SQLite, PostgreSQL, MySQL, but not necessarily others:: users.insert().values([ {"name": "some name"}, {"name": "some other name"}, {"name": "yet another name"}, ]) The above form would render a multiple VALUES statement similar to:: INSERT INTO users (name) VALUES (:name_1), (:name_2), (:name_3) It is essential to note that **passing multiple values is NOT the same as using traditional executemany() form**. The above syntax is a **special** syntax not typically used. To emit an INSERT statement against multiple rows, the normal method is to pass a multiple values list to the :meth:`_engine.Connection.execute` method, which is supported by all database backends and is generally more efficient for a very large number of parameters. .. seealso:: :ref:`tutorial_multiple_parameters` - an introduction to the traditional Core method of multiple parameter set invocation for INSERTs and other statements. The UPDATE construct also supports rendering the SET parameters in a specific order. For this feature refer to the :meth:`_expression.Update.ordered_values` method. .. seealso:: :meth:`_expression.Update.ordered_values` rz;Can't pass positional and kwargs to values() simultaneouslyrzWOnly a single dictionary/tuple or list of dictionaries/tuples is accepted positionally.cSsi|]\}}|j|qSrTrrrTrTrVrtsz%ValuesBase.values..zDict[_DMLColumnArgument, Any]T)r8rlenrrr rrPrrrrrrrrrroryrrrrrrZ immutabledict)rjrrrZmulti_kv_generator kv_generatorZ coerced_argrTrTrVrsDp     zValuesBase.values)rrrrr_supports_multi_parametersr rr rrr`rr rkrrrrTrTrTrVrs*         rc sNeZdZUdZdZdZdZdZdZde d<dZ de d <d e j fd e j fd e jfd e jfd e jfde j fde j fde jfde jfde j fde jfde j fg ejejejejZddfdd ZeddddZedIddddddd Ze rFe!dd!d"dd#d$d%d&Z"e!dd!d"d'dd(d)d*d&Z"e!dd!d"d'd+dd,d-d.d&Z"e!dd!d"d'd+d/dd0d1d2d&Z"e!dd!d"d'd+d/d3dd4d5d6d&Z"e!dd!d"d'd+d/d3d7dd8d9d:d&Z"e!dd!d"d'd+d/d3d7d;ddd&Z"e!dd!d"d'd+d/d3d7d;d?dd@dA dBd&Z"e!dd!dCddDdEdFdGd&Z"dd!dCddDdEdFdHd&Z"Z#S)JrzRepresent an INSERT construct. The :class:`_expression.Insert` object is created using the :func:`_expression.insert()` function. rTNFrrr3ror rrrr r rrrrr?r cst|dSrSsuperrkr __class__rTrVrkszInsert.__init__r9r~cCs d|_|S)aMake this :class:`_expression.Insert` construct "inline" . When set, no attempt will be made to retrieve the SQL-generated default values to be provided within the statement; in particular, this allows SQL expressions to be rendered 'inline' within the statement without the need to pre-execute them beforehand; for backends that support "returning", this turns off the "implicit returning" feature for the statement. .. versionchanged:: 1.4 the :paramref:`_expression.Insert.inline` parameter is now superseded by the :meth:`_expression.Insert.inline` method. Tr rrTrTrVinlinesz Insert.inlinezSequence[_DMLColumnArgument]rO)namesr include_defaultsrRcCs@|jrtddd|D|_d|_||_ttj ||_ |S)a+Return a new :class:`_expression.Insert` construct which represents an ``INSERT...FROM SELECT`` statement. e.g.:: sel = select(table1.c.a, table1.c.b).where(table1.c.c > 5) ins = table2.insert().from_select(['a', 'b'], sel) :param names: a sequence of string column names or :class:`_schema.Column` objects representing the target columns. :param select: a :func:`_expression.select` construct, :class:`_expression.FromClause` or other construct which resolves into a :class:`_expression.FromClause`, such as an ORM :class:`_query.Query` object, etc. The order of columns returned from this FROM clause should correspond to the order of columns sent as the ``names`` parameter; while this is not checked before passing along to the database, the database would normally raise an exception if these column lists don't correspond. :param include_defaults: if True, non-server default values and SQL expressions as specified on :class:`_schema.Column` objects (as documented in :ref:`metadata_defaults_toplevel`) not otherwise specified in the list of names will be rendered into the INSERT and SELECT statements, so that these values are also included in the data to be inserted. .. note:: A Python-side default that uses a Python callable function will only be invoked **once** for the whole statement, and **not per row**. z0This construct already inserts value expressionscSsg|]}tjtj|ddqSrrrrTrTrVrzsz&Insert.from_select..T) rr8rrr #include_insert_from_select_defaultsrrrZ DMLSelectRoler )rjrr rrTrTrV from_selects)zInsert.from_selectr _TCCA[_T0]zReturningInsert[Tuple[_T0]]) _Insert__ent0rrRcCsdSrSrT)rjr"rrTrTrVrszInsert.returning _TCCA[_T1]z ReturningInsert[Tuple[_T0, _T1]])r" _Insert__ent1rrRcCsdSrSrT)rjr"r$rrTrTrVrs _TCCA[_T2]z%ReturningInsert[Tuple[_T0, _T1, _T2]])r"r$ _Insert__ent2rrRcCsdSrSrT)rjr"r$r&rrTrTrVrs _TCCA[_T3]z*ReturningInsert[Tuple[_T0, _T1, _T2, _T3]])r"r$r& _Insert__ent3rrRcCsdSrSrT)rjr"r$r&r(rrTrTrVr)s _TCCA[_T4]z/ReturningInsert[Tuple[_T0, _T1, _T2, _T3, _T4]])r"r$r&r( _Insert__ent4rrRcCsdSrSrT)rjr"r$r&r(r*rrTrTrVr4s _TCCA[_T5]z4ReturningInsert[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]])r"r$r&r(r* _Insert__ent5rrRcCsdSrSrT)rjr"r$r&r(r*r,rrTrTrVr@s _TCCA[_T6]z9ReturningInsert[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]) r"r$r&r(r*r, _Insert__ent6rrRc CsdSrSrT) rjr"r$r&r(r*r,r.rrTrTrVrMs _TCCA[_T7]z>ReturningInsert[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]) r"r$r&r(r*r,r. _Insert__ent7rrRc  CsdSrSrT) rjr"r$r&r(r*r,r.r0rrTrTrVr[srrzReturningInsert[Any])rr _Insert__kwrRcOsdSrSrTrjrrr1rTrTrVrnscOsdSrSrTr2rTrTrVrvs)T)$rrrrrrr rrrrr6dp_clauseelement dp_booleanZdp_string_list dp_dml_valuesZdp_dml_multi_valuesdp_clauseelement_tupledp_table_hint_listr0 _has_prefixes_traverse_internalsr""_dialect_kwargs_traverse_internalsr#_executable_traverse_internalsr/_has_ctes_traverse_internals_traverse_internalsrkrrr rr r __classcell__rTrTrrVrs  6     "  $  & rc@seZdZdZdS)ReturningInsertzTyping-only class that establishes a generic type form of :class:`.Insert` which tracks returned column types. This datatype is delivered when calling the :meth:`.Insert.returning` method. .. versionadded:: 2.0 NrrrrrTrTrTrVr>~sr>c@sveZdZUded<dZded<edddd d Zd dd d dZddddZdddddZ e ddddZ dS)rr}rorTzTuple[ColumnElement[Any], ...]rz_ColumnExpressionArgument[bool]r9) whereclauserRcGs0|D]&}tjtj||d}|j|f7_q|S)aReturn a new construct with the given expression(s) added to its WHERE clause, joined to the existing clause via AND, if any. Both :meth:`_dml.Update.where` and :meth:`_dml.Delete.where` support multiple-table forms, including database-specific ``UPDATE...FROM`` as well as ``DELETE..USING``. For backends that don't have multiple-table support, a backend agnostic approach to using multiple tables is to make use of correlated subqueries. See the linked tutorial sections below for examples. .. seealso:: :ref:`tutorial_correlated_updates` :ref:`tutorial_update_from` :ref:`tutorial_multi_table_deletes` r)rrrZWhereHavingRoler)rjr@ criterionZwhere_criteriarTrTrVwhereszDMLWhereBase.wherez roles.ExpressionElementRole[Any])criteriarRcGs |j|S)zbA synonym for the :meth:`_dml.DMLWhereBase.where` method. .. versionadded:: 1.4 )rB)rjrCrTrTrVfilterszDMLWhereBase.filterr~cCs|jSrSr rrTrTrV_filter_by_zeroszDMLWhereBase._filter_by_zeror)rrRc s(|fdd|D}|j|S)zWapply the given filtering criterion as a WHERE clause to this select. csg|]\}}t||kqSrTrrZ from_entityrTrVrzsz*DMLWhereBase.filter_by..)rErrD)rjrZclausesrTrFrV filter_bys  zDMLWhereBase.filter_byrcCs t|jS)aReturn the completed WHERE clause for this :class:`.DMLWhereBase` statement. This assembles the current collection of WHERE criteria into a single :class:`_expression.BooleanClauseList` construct. .. versionadded:: 1.4 )r&Z_construct_for_whereclauserrrTrTrVr@s zDMLWhereBase.whereclauseN) rrrrrrrBrDrErGrr@rTrTrTrVrs    rc seZdZdZdZdZdejfdejfdej fdej fdej fd ejfd ej fd ej fd ejfg e jejejejZd dfdd ZedddddZeddddZeredddddZedddd d!dZeddd"d#d$d%dZeddd"d&d'd(d)dZeddd"d&d*d+d,d-dZeddd"d&d*d.d/d0d1dZeddd"d&d*d.d2d3d4d5dZeddd"d&d*d.d2d6d7d8 d9dZed:d;ddZd:d;dReturningUpdate[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]) rIrJrKrLrMrNrO _Update__ent7rRc CsdSrSrT) rjrIrJrKrLrMrNrOrPrTrTrVrqs rrzReturningUpdate[Any])r _Update__kwrRcOsdSrSrTrjrrQrTrTrVrscOsdSrSrTrRrTrTrVrs)rrrrrZ is_updater6r3r6r4Zdp_dml_ordered_valuesr5r7r0r8r"r9r#r:r/r;r<rkrrHrrr rr=rTrTrrVrsb$    rc@seZdZdZdS)ReturningUpdatezTyping-only class that establishes a generic type form of :class:`.Update` which tracks returned column types. This datatype is delivered when calling the :meth:`.Update.returning` method. .. versionadded:: 2.0 Nr?rTrTrTrVrSsrSc @sheZdZdZdZdZdejfdejfdejfdej fge j e j ejejZdd d d Zerded d dddZed dddddZed ddddddZed dddddddZed ddddddd dZed ddddd!d"d#d$dZed ddddd!d%d&d'd(dZed ddddd!d%d)d*d+ d,dZed-d.d/d0d1dZd-d.d/d0d2dZd3S)4rzRepresent a DELETE construct. The :class:`_expression.Delete` object is created using the :func:`_expression.delete()` function. rTrorrrr?r cCstjtj||d|_dSr rrrTrTrVrks zDelete.__init__r!zReturningDelete[Tuple[_T0]]) _Delete__ent0rRcCsdSrSrT)rjrTrTrTrVrszDelete.returningr#z ReturningDelete[Tuple[_T0, _T1]])rT _Delete__ent1rRcCsdSrSrT)rjrTrUrTrTrVrsr%z%ReturningDelete[Tuple[_T0, _T1, _T2]])rTrU _Delete__ent2rRcCsdSrSrT)rjrTrUrVrTrTrVrsr'z*ReturningDelete[Tuple[_T0, _T1, _T2, _T3]])rTrUrV _Delete__ent3rRcCsdSrSrT)rjrTrUrVrWrTrTrVrsr)z/ReturningDelete[Tuple[_T0, _T1, _T2, _T3, _T4]])rTrUrVrW _Delete__ent4rRcCsdSrSrT)rjrTrUrVrWrXrTrTrVrsr+z4ReturningDelete[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]])rTrUrVrWrX _Delete__ent5rRcCsdSrSrT)rjrTrUrVrWrXrYrTrTrVrs r-z9ReturningDelete[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]])rTrUrVrWrXrY _Delete__ent6rRcCsdSrSrT)rjrTrUrVrWrXrYrZrTrTrVrs r/z>ReturningDelete[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]) rTrUrVrWrXrYrZ _Delete__ent7rRc CsdSrSrT) rjrTrUrVrWrXrYrZr[rTrTrVrs rrzReturningDelete[Any])r _Delete__kwrRcOsdSrSrTrjrr\rTrTrVrscOsdSrSrTr]rTrTrVr sN)rrrrrZ is_deleter6r3r6r7r0r8r"r9r#r:r/r;r<rkrr rrTrTrTrVrsL      rc@seZdZdZdS)ReturningDeletezTyping-only class that establishes a generic type form of :class:`.Delete` which tracks returned column types. This datatype is delivered when calling the :meth:`.Delete.returning` method. .. versionadded:: 2.0 Nr?rTrTrTrVr^sr^)sr __future__rcollections.abcabcroperatortypingrrrrrrr r r r r rrrrrrrrZ_typingrrrrbaserrrrrr r!r"r#r$r%elementsr&r'r(r)r+rr,r-r.r/r0r1r2r3r4Zsqltypesr5Zvisitorsr6r8Z util.typingr9r:r;r<r=r>r?r@rArBrCrDrErFrGrHZ_TCCArIrfrJrKrLrMrNrOrWrYrZ attrgetterr[rZ_DMLColumnElementr}rPZ plugin_forrrrZDMLRolercrrr>rrrSrr^rTrTrTrVs                                                                                 F (  >Sp L7 x