U kfL@s2ddlmZddlZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lm Z dd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z e r^ddlm!Z!ddlm"Z"ddlm#Z#ddl$m%Z%ed ed!Z&ed"ed!Z'Gd#d$d$ee&Z(Gd%d&d&e(e&Z)d'd(d)d*d+d,d-d.Z*Gd/d0d0Z+d'd(d1d*d2d3d4d5Z,d'd(d6d*d7d8d9d:Z-Gd;d<dZ/e.Z0e-Z1e,Z2e*Z3dS)?) annotationsN)Any)Callable)Dict)Generic)List)Optional)Sequence)Tuple)Type) TYPE_CHECKING)TypeVar)Union)base) collection)collection_adapter)exc)util) coercions) expression)roles)Missing) MissingOr)Literal)AttributeEventToken)Mapper)CollectionAdapter) ColumnElement_KT)bound_VTc@sReZdZdZdZdddddZdd d d Zd dd ddZdddddZdS)_PlainColumnGetterzPlain column getter, stores collection of Column objects directly. Serializes to a :class:`._SerializableColumnGetterV2` which has more expensive __call__() performance and some rare caveats. )cols compositeSequence[ColumnElement[_KT]]Noner$returncCs||_t|dk|_dSNr)r$lenr%)selfr$r-P/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/orm/mapped_collection.py__init__:sz_PlainColumnGetter.__init__cTuple[Type[_SerializableColumnGetterV2[_KT]], Tuple[Sequence[Tuple[Optional[str], Optional[str]]]]]r)cCs t|jSN)_SerializableColumnGetterV2_reduce_from_colsr$r,r-r-r. __reduce__>sz_PlainColumnGetter.__reduce__ Mapper[_KT]mapperr)cCs|jSr2)r$)r,r9r-r-r._colsFsz_PlainColumnGetter._colsr z&MissingOr[Union[_KT, Tuple[_KT, ...]]])valuer)csXt|tfdd|D}|jrMsz/_PlainColumnGetter.__call__..r)rinstance_stateZ _state_mapperr:r%tupler)r,r;keyobjr-r?r.__call__Is   z_PlainColumnGetter.__call__N) __name__ __module__ __qualname____doc__ __slots__r/r6r:rGr-r-r-r.r#.s  r#c@sVeZdZdZdZdddddZdd d d Zed dd ddZdd dddZ dS)r3a<Updated serializable getter which deals with multi-table mapped classes. Two extremely unusual cases are not supported. Mappings which have tables across multiple metadata objects, or which are mapped to non-Table selectables linked across inheriting mappers may fail to function here. )colkeysz-Sequence[Tuple[Optional[str], Optional[str]]]r')rMr)cCs||_t|dk|_dSr*)rMr+r%)r,rMr-r-r.r/isz$_SerializableColumnGetterV2.__init__r0r1cCs|j|jffSr2) __class__rMr5r-r-r.r6osz&_SerializableColumnGetterV2.__reduce__r&r(cs,dddddfdd|D}t|ffS)NzColumnElement[_KT]z Optional[str])cr)cSst|jtjsdS|jjSdSr2) isinstancetablerZ TableClauserE)rOr-r-r. _table_key|szA_SerializableColumnGetterV2._reduce_from_cols.._table_keycsg|]}|j|fqSr-)rE)r=rOrRr-r.rBszA_SerializableColumnGetterV2._reduce_from_cols..)r3)clsr$rMr-rSr.r4wsz-_SerializableColumnGetterV2._reduce_from_colsr7r8cCshg}t|jdd}|jD]J\}}|dks8|dks8||krL||jj|q||j|j|q|S)Nmetadata)getattrZ local_tablerMappendrOZtables)r,r9r$rUZckeyZtkeyr-r-r.r:sz!_SerializableColumnGetterV2._colsN) rHrIrJrKrLr/r6 classmethodr4r:r-r-r-r.r3[s  r3Fignore_unpopulated_attributez&Union[Type[_KT], Callable[[_KT], _VT]]boolzType[KeyFuncDict[_KT, _KT]]) mapping_specrZr)cCs(ddt|D}t|}t||dS)aA dictionary-based collection type with column-based keying. .. versionchanged:: 2.0 Renamed :data:`.column_mapped_collection` to :class:`.column_keyed_dict`. Returns a :class:`.KeyFuncDict` factory which will produce new dictionary keys based on the value of a particular :class:`.Column`-mapped attribute on ORM mapped instances to be added to the dictionary. .. note:: the value of the target attribute must be assigned with its value at the time that the object is being added to the dictionary collection. Additionally, changes to the key attribute are **not tracked**, which means the key in the dictionary is not automatically synchronized with the key value on the target object itself. See :ref:`key_collections_mutations` for further details. .. seealso:: :ref:`orm_dictionary_collection` - background on use :param mapping_spec: a :class:`_schema.Column` object that is expected to be mapped by the target mapper to a particular attribute on the mapped class, the value of which on a particular instance is to be used as the key for a new dictionary entry for that instance. :param ignore_unpopulated_attribute: if True, and the mapped attribute indicated by the given :class:`_schema.Column` target attribute on an object is not populated at all, the operation will be silently skipped. By default, an error is raised. .. versionadded:: 2.0 an error is raised by default if the attribute being used for the dictionary key is determined that it was never populated with any value. The :paramref:`_orm.column_keyed_dict.ignore_unpopulated_attribute` parameter may be set which will instead indicate that this condition should be ignored, and the append operation silently skipped. This is in contrast to the behavior of the 1.x series which would erroneously populate the value in the dictionary with an arbitrary key value of ``None``. cSsg|]}tjtj|ddqS)r\)argname)rexpectrZColumnArgumentRole)r=qr-r-r.rBsz%column_keyed_dict..rY)rZto_listr#_mapped_collection_cls)r\rZr$keyfuncr-r-r.column_keyed_dicts.rbc@s<eZdZdZddddZddddd Zd d d d ZdS) _AttrGetter) attr_namegetterstr)rdcCs||_t||_dSr2)rdoperator attrgetterre)r,rdr-r-r.r/sz_AttrGetter.__init__r) mapped_objectr)cCsZ||}|dkrVt|}|j}|j|jkrR|j}||jtj}|dkrVt Snt S|Sr2) rerrCr9rdattrsr<getNO_VALUEr)r,rirFrAmpZdict_r-r-r.rGs   z_AttrGetter.__call__z$Tuple[Type[_AttrGetter], Tuple[str]]r1cCs t|jffSr2)rcrdr5r-r-r.r6sz_AttrGetter.__reduce__N)rHrIrJrLr/rGr6r-r-r-r.rcsrcrfzType[KeyFuncDict[Any, Any]])rdrZr)cCstt||dS)adA dictionary-based collection type with attribute-based keying. .. versionchanged:: 2.0 Renamed :data:`.attribute_mapped_collection` to :func:`.attribute_keyed_dict`. Returns a :class:`.KeyFuncDict` factory which will produce new dictionary keys based on the value of a particular named attribute on ORM mapped instances to be added to the dictionary. .. note:: the value of the target attribute must be assigned with its value at the time that the object is being added to the dictionary collection. Additionally, changes to the key attribute are **not tracked**, which means the key in the dictionary is not automatically synchronized with the key value on the target object itself. See :ref:`key_collections_mutations` for further details. .. seealso:: :ref:`orm_dictionary_collection` - background on use :param attr_name: string name of an ORM-mapped attribute on the mapped class, the value of which on a particular instance is to be used as the key for a new dictionary entry for that instance. :param ignore_unpopulated_attribute: if True, and the target attribute on an object is not populated at all, the operation will be silently skipped. By default, an error is raised. .. versionadded:: 2.0 an error is raised by default if the attribute being used for the dictionary key is determined that it was never populated with any value. The :paramref:`_orm.attribute_keyed_dict.ignore_unpopulated_attribute` parameter may be set which will instead indicate that this condition should be ignored, and the append operation silently skipped. This is in contrast to the behavior of the 1.x series which would erroneously populate the value in the dictionary with an arbitrary key value of ``None``. rY)r`rc)rdrZr-r-r.attribute_keyed_dicts+rnCallable[[Any], Any]zType[KeyFuncDict[_KT, Any]])rarZr)cCs t||dS)aA dictionary-based collection type with arbitrary keying. .. versionchanged:: 2.0 Renamed :data:`.mapped_collection` to :func:`.keyfunc_mapping`. Returns a :class:`.KeyFuncDict` factory with a keying function generated from keyfunc, a callable that takes an entity and returns a key value. .. note:: the given keyfunc is called only once at the time that the target object is being added to the collection. Changes to the effective value returned by the function are not tracked. .. seealso:: :ref:`orm_dictionary_collection` - background on use :param keyfunc: a callable that will be passed the ORM-mapped instance which should then generate a new key to use in the dictionary. If the value returned is :attr:`.LoaderCallableStatus.NO_VALUE`, an error is raised. :param ignore_unpopulated_attribute: if True, and the callable returns :attr:`.LoaderCallableStatus.NO_VALUE` for a particular instance, the operation will be silently skipped. By default, an error is raised. .. versionadded:: 2.0 an error is raised by default if the callable being used for the dictionary key returns :attr:`.LoaderCallableStatus.NO_VALUE`, which in an ORM attribute context indicates an attribute that was never populated with any value. The :paramref:`_orm.mapped_collection.ignore_unpopulated_attribute` parameter may be set which will instead indicate that this condition should be ignored, and the append operation silently skipped. This is in contrast to the behavior of the 1.x series which would erroneously populate the value in the dictionary with an arbitrary key value of ``None``. rY)r`)rarZr-r-r.keyfunc_mappings,rpcseZdZdZdddddddfd d Zed!dd d ddddZddddZe dd"dddddddZ e j e j d#ddddddZe je j d$dddddd ZZS)% KeyFuncDictaBase for ORM mapped dictionary classes. Extends the ``dict`` type with additional methods needed by SQLAlchemy ORM collection classes. Use of :class:`_orm.KeyFuncDict` is most directly by using the :func:`.attribute_keyed_dict` or :func:`.column_keyed_dict` class factories. :class:`_orm.KeyFuncDict` may also serve as the base for user-defined custom dictionary classes. .. versionchanged:: 2.0 Renamed :class:`.MappedCollection` to :class:`.KeyFuncDict`. .. seealso:: :func:`_orm.attribute_keyed_dict` :func:`_orm.column_keyed_dict` :ref:`orm_dictionary_collection` :ref:`orm_custom_collection` FrYrorr[r')ra dict_argsrZr)cs||_||_tj|dS)ahCreate a new collection with keying provided by keyfunc. keyfunc may be any callable that takes an object and returns an object for use as a dictionary key. The keyfunc will be called every time the ORM needs to add a member by value-only (such as when loading instances from the database) or remove a member. The usual cautions about dictionary keying apply- ``keyfunc(object)`` should return the same output for the life of the collection. Keying based on mutable properties can result in unreachable instances "lost" in the collection. N)rarZsuperr/)r,rarZrrrNr-r.r/_szKeyFuncDict.__init__NzDict[_KT, _KT]zOptional[CollectionAdapter]z'KeyFuncDict[_KT, _KT]')ravaluesadapterr)cCst|}|||Sr2)rqupdate)rTrarurvrmr-r-r. _unreducevs zKeyFuncDict._unreducezxTuple[Callable[[_KT, _KT], KeyFuncDict[_KT, _KT]], Tuple[Any, Union[Dict[_KT, _KT], Dict[_KT, _KT]], CollectionAdapter]]r1cCstj|jt|t|ffSr2)rqrxrar<rr5r-r-r.r6s zKeyFuncDict.__reduce__zsqlalchemy.orm.attributesr z2Union[AttributeEventToken, Literal[(None, False)]])r; initiator warn_onlyr)c Cst|j}tjj}t||js&d}n"|j|j krB|j |j}n|j}|r`t d|dn0t d|dt |dt |d|d dS) Nzunknown relationshipz0Attribute keyed dictionary value for attribute 'z' was None; this will raise in a future release. To skip this assignment entirely, Set the "ignore_unpopulated_attribute=True" parameter on the mapped collection factory.z1In event triggered from population of attribute 'za' (potentially from a backref), can't populate value in KeyFuncDict; dictionary key derived from z= is not populated. Ensure appropriate state is set up on the z object before assigning to the z attribute. To skip this assignment entirely, Set the "ignore_unpopulated_attribute=True" parameter on the mapped collection factory.)rrCr9rZ preloadedZorm_attributesrPrrErjwarnsa_excInvalidRequestErrorZ instance_str)r,r;ryrzr9 attributesZ relationshipr-r-r._raise_for_unpopulateds     (z"KeyFuncDict._raise_for_unpopulated)r; _sa_initiatorr)cCsl||}|tjkr2|js,|j||ddqZdSn(|tkrZ|jsV|j||ddd}ndS||||dS)z9Add an item by value, consulting the keyfunc for the key.FrzNT)rarrlrZrr __setitem__r,r;rrEr-r-r.sets&  zKeyFuncDict.setcCs||}|tjkr.|js*|j||dddS|tkrV|jsR|j||ddd}ndS|||krztd||||f|||dS)z._MKeyfuncMappedrr')rrr)cstjf|didS)NrZ)rsr/)r,rr)rNrZrar-r.r/sz8_mapped_collection_cls.._MKeyfuncMapped.__init__)rHrIrJr/rr-rZrartr._MKeyfuncMappedsr)rqr )rarZrr-rr.r`sr`)4 __future__rrgtypingrrrrrrr r r r r rr collectionsrrrr|rsqlrrrZutil.langhelpersrrZ util.typingrrrrZ sql.elementsrr r"r#r3rbrcrnrprqr`ZMappedCollectionZmapped_collectionZattribute_mapped_collectionZcolumn_mapped_collectionr-r-r-r.s`                              -8941=