o znhn@s4dZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZGdddeZejjdddGdddeZejjdddGdddeZejjdddGdddeZejjdddeddGdddeZdS)zDescriptor properties are more "auxiliary" properties that exist as configurational elements, but don't participate as actively in the load/persist ORM loop. ) attributes) properties)query)MapperProperty)PropComparator) _none_set)event)exc)schema)sql)util) expressionc@s eZdZdZdZdZddZdS)DescriptorPropertyzS:class:`.MapperProperty` which proxies access to a user-defined descriptor.NFcsGfdddt}jdur!tjjd}|r!|_jdur@fdd}fdd}fdd}t|||d _tjj jjjfd d j d }|j|_ j j|dS) NcsPeZdZdZdZdZefddZddZe dr&e j ffdd Z d Sd S) z7DescriptorProperty.instrument_class.._ProxyImplFTcsjSN) uses_objectsselfpropJ/usr/local/lib/python3.10/dist-packages/sqlalchemy/orm/descriptor_props.pyr,szDDescriptorProperty.instrument_class.._ProxyImpl.uses_objectscSs ||_dSrkey)rrrrr__init__0 z@DescriptorProperty.instrument_class.._ProxyImpl.__init__ get_historycs|||Sr)r)rstatedict_passiverrrr5szCDescriptorProperty.instrument_class.._ProxyImpl.get_historyN) __name__ __module__ __qualname__accepts_scalar_loaderexpire_missing collectionpropertyrrhasattrr PASSIVE_OFFrrrrr _ProxyImpl's r)cst|j|dSr)setattrname)objvaluerrrfsetAz1DescriptorProperty.instrument_class..fsetcst|jdSr)delattrr+r,rrrfdelDz1DescriptorProperty.instrument_class..fdelcs t|jSr)getattrr+r1rrrfgetG z1DescriptorProperty.instrument_class..fget)r5r.r2cs Sr)_comparator_factoryr)mapperrrrPs z5DescriptorProperty.instrument_class..)docoriginal_property)object descriptorr4class_r_is_userland_descriptorr&rcreate_proxied_attributeparentr:impl class_managerinstrument_attribute)rr8r)descr.r2r5 proxy_attrr)r8rrrinstrument_class$s*         z#DescriptorProperty.instrument_class)r r!r"__doc__r:rrGrrrrrs  rzsqlalchemy.orm.propertiesT) add_to_allcseZdZdZejddfddZfddZdd Zd d Z ej d d Z ej ddZ e ddZddZddZej ddZejfddZddZGdddejZGdddeZd d!ZZS)"CompositePropertyzDefines a "composite" mapped attribute, representing a collection of columns as one attribute. :class:`.CompositeProperty` is constructed using the :func:`.composite` function. .. seealso:: :ref:`mapper_composite` )0.7z:class:`.AttributeExtension` is deprecated in favor of the :class:`.AttributeEvents` listener interface. The :paramref:`.composite.extension` parameter will be removed in a future release.) extensioncstt|||_||_|dd|_|dd|_|dd|_| d|j j |_ d|vr5| d|_ t||dS)aQReturn a composite column-based property for use with a Mapper. See the mapping documentation section :ref:`mapper_composite` for a full usage example. The :class:`.MapperProperty` returned by :func:`.composite` is the :class:`.CompositeProperty`. :param class\_: The "composite type" class, or any classmethod or callable which will produce a new instance of the composite object given the column values in order. :param \*cols: List of Column objects to be mapped. :param active_history=False: When ``True``, indicates that the "previous" value for a scalar attribute should be loaded when replaced, if not already loaded. See the same flag on :func:`.column_property`. :param group: A group name for this property when marked as deferred. :param deferred: When True, the column property is "deferred", meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also :func:`~sqlalchemy.orm.deferred`. :param comparator_factory: a class which extends :class:`.CompositeProperty.Comparator` which provides custom SQL clause generation for comparison operations. :param doc: optional string that will be applied as the doc on the class-bound descriptor. :param info: Optional data dictionary which will be populated into the :attr:`.MapperProperty.info` attribute of this object. :param extension: an :class:`.AttributeExtension` instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. active_historyFdeferredgroupNcomparator_factoryinfo)superrJrattrscomposite_classgetrMrNrOpop __class__ ComparatorrPrQr set_creation_order_create_descriptor)rr>rSkwargsrWrrrfs:   zCompositeProperty.__init__cstt|||dSr)rRrJrG_setup_event_handlersrr8r\rrrGs z"CompositeProperty.instrument_classcCs |dS)zInitialization which occurs after the :class:`.CompositeProperty` has been associated with its parent mapper. N)_setup_arguments_on_columnsrrrrdo_inits zCompositeProperty.do_initcs6fdd}fdd}fdd}t|||_dS)ztCreate the Python descriptor that will serve as the access point on instances of the mapped class. cst}t}j|vr;fddjD}j|vr;|jdus(t|s;j||j<|jj |djg| jdS)Ncsg|]}t|qSr)r4.0rinstancerr s zFCompositeProperty._create_descriptor..fget..) r instance_dictinstance_stater_attribute_keysr issupersetrTmanagerdispatchrefreshrU)rdrrvaluesrrcrr5s     z2CompositeProperty._create_descriptor..fgetcst|}t|}|jj}|jtj}|jjD] }|||||j }q||j<|dur>j D]}t ||dq3dSt j | D] \}}t |||qFdSr)rrfrgrjrrUNO_VALUErksetrBrhr*zip__composite_values__)rdr-rrattrpreviousfnrrrrr.s        z2CompositeProperty._create_descriptor..fsetcs^t|}t|}|jtj}|jj}|j|||j j D]}t ||dq$dSr) rrgrfrVrrnrjrkremoverBrhr*)rdrrrsrrrrrrr2s    z2CompositeProperty._create_descriptor..fdelN)r&r=)rr5r.r2rrrrZs    z$CompositeProperty._create_descriptorcsfddjDS)Ncg|] }tjj|jqSr)r4rAr>rrbrrrrrez:CompositeProperty._comparable_elements..propsrrrr_comparable_elementsz&CompositeProperty._comparable_elementscCsxg}|jD]4}t|tr|jj|dd}nt|tjr"|jj|}nt|tj r,|j }nt d|f| |q|S)NF)_configure_mappersz[Composite expects Column objects or mapped attributes/attribute names as arguments, got: %r)rS isinstancestrrA get_propertyr Column_columntopropertyrInstrumentedAttributer&sa_exc ArgumentErrorappend)rrzrrrrrrrzs     zCompositeProperty.propscCdd|jDS)NcSsg|] }t|tjr|qSr)r~r r)rbarrrrerxz-CompositeProperty.columns..)rSrrrrcolumns zCompositeProperty.columnscCs4|jD]}|j|_|jr|j|_d|_|j|_qdS)zwPropagate configuration arguments made on this composite to the target columns, for those that apply. ))rNT) instrumentTN)rzrMrN strategy_keyrO)rrrrrr_s  z-CompositeProperty._setup_arguments_on_columnscsfdd}fdd}fddfdd}fd d }tjjd |d d tjjd|d d tjjd|d d dtjjd|d d dtjjd|d d ddS)z>Establish events that populate/expire the composite attribute.c||dddS)NF is_refreshrrargs_load_refresh_handlerrr load_handler r/z=CompositeProperty._setup_event_handlers..load_handlercr)NTrrrrrrrefresh_handler#r/z@CompositeProperty._setup_event_handlers..refresh_handlercsVj}|s j|vr dSjD] }||vrdSqjfddjD|j<dS)Ncsg|]}j|qSr)dictrarrrre4zZCompositeProperty._setup_event_handlers.._load_refresh_handler..)rrrhrT)rrrrkrrrr&s zFCompositeProperty._setup_event_handlers.._load_refresh_handlercs0|dus tj|r|jjddSdSr)rorh intersectionrrVr)rkeysrrrexpire_handler7sz?CompositeProperty._setup_event_handlers..expire_handlercs|jjddS)zAfter an insert or update, some columns may be expired due to server side defaults, or re-populated due to client side defaults. Pop out the composite value here so that it recreates. N)rrVr)r8 connectionrrrrinsert_update_handler;szFCompositeProperty._setup_event_handlers..insert_update_handler after_insertT)raw after_updateload)r propagaterlexpireN)r listenrA)rrrrrr)rrrr]s(           z'CompositeProperty._setup_event_handlerscCr)NcSsg|]}|jqSrrrwrrrreYsz5CompositeProperty._attribute_keys..ryrrrrrhWrz!CompositeProperty._attribute_keysc Csg}g}d}|jD]5}|j}|j|j||} | rd}| } | r*|| n|d| j r9|| j q |dq |rPt |j |gd|j |gSt d|j |gdS)z>Provided for userland code that uses attributes.get_history().FTNr) rzrrjrBr has_changes non_deletedextendrdeletedrHistoryrT) rrrraddedr has_historyrrhistrrrrr[s,      zCompositeProperty.get_historycC |||SrrPr^rrrr7{r6z%CompositeProperty._comparator_factorycs$eZdZfddZddZZS)z!CompositeProperty.CompositeBundlecs&||_ttj|j|jg|RdSr)r&rRrJCompositeBundlerr)r property_exprr\rrrs   z*CompositeProperty.CompositeBundle.__init__csfdd}|S)NcsjjfddDS)Ncsg|]}|qSrr)rbprocrowrrreszXCompositeProperty.CompositeBundle.create_row_processor..proc..)r&rTrprocsrrrrszDCompositeProperty.CompositeBundle.create_row_processor..procr)rrrlabelsrrrrcreate_row_processorsz6CompositeProperty.CompositeBundle.create_row_processor)r r!r"rr __classcell__rrr\rr~s rc@sVeZdZdZdZeddZddZddZd d Z e j d d Z d dZ ddZdS)zCompositeProperty.ComparatoraProduce boolean, comparison, and other operators for :class:`.CompositeProperty` attributes. See the example in :ref:`composite_operations` for an overview of usage , as well as the documentation for :class:`.PropComparator`. .. seealso:: :class:`.PropComparator` :class:`.ColumnOperators` :ref:`types_operators` :attr:`.TypeEngine.comparator_factory` NcCs|Sr)__clause_element__rrrrclausessz$CompositeProperty.Comparator.clausescCstj|jddiS)NrOF)r ClauseListr{rrrrrs z/CompositeProperty.Comparator.__clause_element__cCst|j|Sr)rJrrrrrrr_query_clause_elements z2CompositeProperty.Comparator._query_clause_elementcCsT|durdd|jjD}nt||jjr|}n td|j|ft|j|S)NcSsg|]}dqSrrrarrrreszDCompositeProperty.Comparator._bulk_update_tuples..z)Can't UPDATE composite attribute %s to %r) rrhr~rTrqrrrpr{)rr-rmrrr_bulk_update_tupless  z0CompositeProperty.Comparator._bulk_update_tuplescs$jrfddjjDSjjS)Ncrvr)r4_adapt_to_entityentityrrwrrrreszECompositeProperty.Comparator._comparable_elements..)rrr{rrrrr{s  z1CompositeProperty.Comparator._comparable_elementscs^|durdgtjj}n|}ddtjj|D}jr*fdd|D}tj|S)NcSsg|]\}}||kqSrr)rbrbrrrres z7CompositeProperty.Comparator.__eq__..csg|]}|qSr)adapter)rbxrrrrer)lenrr{rqrprr and_)rotherrm comparisonsrrr__eq__s  z#CompositeProperty.Comparator.__eq__cCst||Sr)r not_r)rrrrr__ne__r3z#CompositeProperty.Comparator.__ne__)r r!r"rH__hash__r&rrrrr memoized_propertyr{rrrrrrrXs   rXcCst|jjjd|jS)N.)rrAr>r rrrrr__str__szCompositeProperty.__str__)r r!r"rHr deprecated_paramsrrGr`rZrr{rzr&rr_r]rhrr(rr7rBundlerrrXrrrrr\rrJXs0  A;    :  IrJcs(eZdZdZddZfddZZS)ConcreteInheritedPropertya4A 'do nothing' :class:`.MapperProperty` that disables an attribute on a concrete subclass that is only present on the inherited mapper, not the concrete classes' mapper. Cases where this occurs include: * When the superclass mapper is mapped against a "polymorphic union", which includes all attributes from all subclasses. * When a relationship() is configured on an inherited mapper, but not on the subclass mapper. Concrete mappers require that relationship() is configured explicitly on each subclass. cCs:d}|jD]}|j|j}t|ts|j}|Sq|Sr)rAiterate_to_root_propsrr~rrP)rr8comparator_callablemprrrr7s  z-ConcreteInheritedProperty._comparator_factorycs<ttfddGfdddt}|_dS)Ncstdjjjf)NzgConcrete %s does not implement attribute %r at the instance level. Add this property explicitly to %s.)AttributeErrorrArrrrrwarns z0ConcreteInheritedProperty.__init__..warncs2eZdZfddZfddZfddZdS)zDConcreteInheritedProperty.__init__..NoninheritedConcretePropc dSrr)sr,r-rrr__set__rzLConcreteInheritedProperty.__init__..NoninheritedConcreteProp.__set__crrr)rr,rrr __delete__rzOConcreteInheritedProperty.__init__..NoninheritedConcreteProp.__delete__cs|durjSdSr)r=)rr,ownerrrrr__get__s zLConcreteInheritedProperty.__init__..NoninheritedConcreteProp.__get__N)r r!r"rrrrrrrNoninheritedConcreteProps  r)rRrrr<r=)rrr\rrrs  z"ConcreteInheritedProperty.__init__)r r!r"rHr7rrrrr\rrs rcsZeZdZ     dfdd ZeddZejddZdd Z d d Z d d Z Z S)SynonymPropertyNcsRtt|||_||_||_||_|p|r|jpd|_|r"||_ t |dS)a}Denote an attribute name as a synonym to a mapped property, in that the attribute will mirror the value and expression behavior of another attribute. e.g.:: class MyClass(Base): __tablename__ = 'my_table' id = Column(Integer, primary_key=True) job_status = Column(String(50)) status = synonym("job_status") :param name: the name of the existing mapped property. This can refer to the string name ORM-mapped attribute configured on the class, including column-bound attributes and relationships. :param descriptor: a Python :term:`descriptor` that will be used as a getter (and potentially a setter) when this attribute is accessed at the instance level. :param map_column: **For classical mappings and mappings against an existing Table object only**. if ``True``, the :func:`.synonym` construct will locate the :class:`.Column` object upon the mapped table that would normally be associated with the attribute name of this synonym, and produce a new :class:`.ColumnProperty` that instead maps this :class:`.Column` to the alternate name given as the "name" argument of the synonym; in this way, the usual step of redefining the mapping of the :class:`.Column` to be under a different name is unnecessary. This is usually intended to be used when a :class:`.Column` is to be replaced with an attribute that also uses a descriptor, that is, in conjunction with the :paramref:`.synonym.descriptor` parameter:: my_table = Table( "my_table", metadata, Column('id', Integer, primary_key=True), Column('job_status', String(50)) ) class MyClass(object): @property def _job_status_descriptor(self): return "Status: %s" % self._job_status mapper( MyClass, my_table, properties={ "job_status": synonym( "_job_status", map_column=True, descriptor=MyClass._job_status_descriptor) } ) Above, the attribute named ``_job_status`` is automatically mapped to the ``job_status`` column:: >>> j1 = MyClass() >>> j1._job_status = "employed" >>> j1.job_status Status: employed When using Declarative, in order to provide a descriptor in conjunction with a synonym, use the :func:`sqlalchemy.ext.declarative.synonym_for` helper. However, note that the :ref:`hybrid properties ` feature should usually be preferred, particularly when redefining attribute behavior. :param info: Optional data dictionary which will be populated into the :attr:`.InspectionAttr.info` attribute of this object. .. versionadded:: 1.0.0 :param comparator_factory: A subclass of :class:`.PropComparator` that will provide custom comparison behavior at the SQL expression level. .. note:: For the use case of providing an attribute which redefines both Python-level and SQL-expression level behavior of an attribute, please refer to the Hybrid attribute introduced at :ref:`mapper_hybrids` for a more effective technique. .. seealso:: :ref:`synonyms` - Overview of synonyms :func:`.synonym_for` - a helper oriented towards Declarative :ref:`mapper_hybrids` - The Hybrid Attribute extension provides an updated approach to augmenting attribute behavior more flexibly than can be achieved with synonyms. N) rRrrr+ map_columnr=rPrHr:rQr rY)rr+rr=rPr:rQr\rrrslzSynonymProperty.__init__cCst|jj|jjjSr)r4rAr>r+rBrrrrrrr|zSynonymProperty.uses_objectscCsHt|jj|j}t|drt|jts!t d|jjj |j|f|jS)Nr&zGsynonym() attribute "%s.%s" only supports ORM mapped attributes, got %r) r4rAr>r+r'r~r&rrInvalidRequestErrorr )rrrrrr_proxied_propertys z!SynonymProperty._proxied_propertycCs,|j}|jr|||}|S|||}|Sr)rrP)rr8rcomprrrr7s   z#SynonymProperty._comparator_factorycOs"t|jj|j}|jj|i|Sr)r4rAr>r+rBr)rargkwrrrrrrszSynonymProperty.get_historycCs|jrW|j|jjvrtd|j|jj|jf|jj|j|jvr?|j|jj|jj|jkr?td|j|j|j|jft |jj|j}|j |j||dd|j|_ ||_ dS)Nz>Can't compile synonym '%s': no column on table '%s' named '%s'zpCan't call map_column=True for synonym %r=%r, a ColumnProperty already exists keyed to the name %r for column %rT)init setparent)rrpersist_selectablecrrr+ descriptionrrColumnProperty_configure_property_mapped_by_synonymrA)rrArrrrr set_parents<    zSynonymProperty.set_parent)NNNNN) r r!r"rr&rr rrr7rrrrrr\rrsx    rrKz:func:`.comparable_property` is deprecated and will be removed in a future release. Please refer to the :mod:`~sqlalchemy.ext.hybrid` extension.cs,eZdZdZ dfdd ZddZZS)ComparablePropertyz;Instruments a Python property for use in query expressions.NcsFtt|||_||_|p|r|jpd|_|r||_t |dS)a Provides a method of applying a :class:`.PropComparator` to any Python descriptor attribute. Allows any Python descriptor to behave like a SQL-enabled attribute when used at the class level in queries, allowing redefinition of expression operator behavior. In the example below we redefine :meth:`.PropComparator.operate` to wrap both sides of an expression in ``func.lower()`` to produce case-insensitive comparison:: from sqlalchemy.orm import comparable_property from sqlalchemy.orm.interfaces import PropComparator from sqlalchemy.sql import func from sqlalchemy import Integer, String, Column from sqlalchemy.ext.declarative import declarative_base class CaseInsensitiveComparator(PropComparator): def __clause_element__(self): return self.prop def operate(self, op, other): return op( func.lower(self.__clause_element__()), func.lower(other) ) Base = declarative_base() class SearchWord(Base): __tablename__ = 'search_word' id = Column(Integer, primary_key=True) word = Column(String) word_insensitive = comparable_property(lambda prop, mapper: CaseInsensitiveComparator( mapper.c.word, mapper) ) A mapping like the above allows the ``word_insensitive`` attribute to render an expression like:: >>> print SearchWord.word_insensitive == "Trucks" lower(search_word.word) = lower(:lower_1) :param comparator_factory: A PropComparator subclass or factory that defines operator behavior for this property. :param descriptor: Optional when used in a ``properties={}`` declaration. The Python descriptor or property to layer comparison behavior on top of. The like-named descriptor will be automatically retrieved from the mapped class if left blank in a ``properties`` declaration. :param info: Optional data dictionary which will be populated into the :attr:`.InspectionAttr.info` attribute of this object. .. versionadded:: 1.0.0 N) rRrrr=rPrHr:rQr rY)rrPr=r:rQr\rrrsBzComparableProperty.__init__cCrrrr^rrrr7#r6z&ComparableProperty._comparator_factory)NNN)r r!r"rHrr7rrrr\rrs JrN)rHrrr interfacesrrr rr r rr r rr langhelpersdependency_forrJrrdeprecated_clsrrrrrs<            <5?