
    D6i-                         d Z ddlZddlmZmZ ddlmZ ddlZddl	m
Z
mZ ddlmZ ddlmZ  ed	g d
      Z G d d      Z e       Zd Zy)a  
This module provides a decorator function for observing changes in a given
property. Internally the decorator is implemented using SQLAlchemy event
listeners. Both column properties and relationship properties can be observed.

Property observers can be used for pre-calculating aggregates and automatic
real-time data denormalization.

Simple observers
----------------

At the heart of the observer extension is the :func:`observes` decorator. You
mark some property path as being observed and the marked method will get
notified when any changes are made to given path.

Consider the following model structure:

::

    class Director(Base):
        __tablename__ = 'director'
        id = sa.Column(sa.Integer, primary_key=True)
        name = sa.Column(sa.String)
        date_of_birth = sa.Column(sa.Date)

    class Movie(Base):
        __tablename__ = 'movie'
        id = sa.Column(sa.Integer, primary_key=True)
        name = sa.Column(sa.String)
        director_id = sa.Column(sa.Integer, sa.ForeignKey(Director.id))
        director = sa.orm.relationship(Director, backref='movies')


Now consider we want to show movies in some listing ordered by director id
first and movie id secondly. If we have many movies then using joins and
ordering by Director.name will be very slow. Here is where denormalization
and :func:`observes` comes to rescue the day. Let's add a new column called
director_name to Movie which will get automatically copied from associated
Director.


::

    from sqlalchemy_utils import observes


    class Movie(Base):
        # same as before..
        director_name = sa.Column(sa.String)

        @observes('director')
        def director_observer(self, director):
            self.director_name = director.name

.. note::

    This example could be done much more efficiently using a compound foreign
    key from director_name, director_id to Director.name, Director.id but for
    the sake of simplicity we added this as an example.


Observes vs aggregated
----------------------

:func:`observes` and :func:`.aggregates.aggregated` can be used for similar
things. However performance wise you should take the following things into
consideration:

* :func:`observes` works always inside transaction and deals with objects. If
  the relationship observer is observing has a large number of objects it's
  better to use :func:`.aggregates.aggregated`.
* :func:`.aggregates.aggregated` always executes one additional query per
  aggregate so in scenarios where the observed relationship has only a handful
  of objects it's better to use :func:`observes` instead.


Example 1. Movie with many ratings

Let's say we have a Movie object with potentially thousands of ratings. In this
case we should always use :func:`.aggregates.aggregated` since iterating
through thousands of objects is slow and very memory consuming.

Example 2. Product with denormalized catalog name

Each product belongs to one catalog. Here it is natural to use :func:`observes`
for data denormalization.


Deeply nested observing
-----------------------

Consider the following model structure where Catalog has many Categories and
Category has many Products.

::

    class Catalog(Base):
        __tablename__ = 'catalog'
        id = sa.Column(sa.Integer, primary_key=True)
        product_count = sa.Column(sa.Integer, default=0)

        @observes('categories.products')
        def product_observer(self, products):
            self.product_count = len(products)

        categories = sa.orm.relationship('Category', backref='catalog')

    class Category(Base):
        __tablename__ = 'category'
        id = sa.Column(sa.Integer, primary_key=True)
        catalog_id = sa.Column(sa.Integer, sa.ForeignKey('catalog.id'))

        products = sa.orm.relationship('Product', backref='category')

    class Product(Base):
        __tablename__ = 'product'
        id = sa.Column(sa.Integer, primary_key=True)
        price = sa.Column(sa.Numeric)

        category_id = sa.Column(sa.Integer, sa.ForeignKey('category.id'))


:func:`observes` is smart enough to:

* Notify catalog objects of any changes in associated Product objects
* Notify catalog objects of any changes in Category objects that affect
  products (for example if Category gets deleted, or a new Category is added to
  Catalog with any number of Products)


::

    category = Category(
        products=[Product(), Product()]
    )
    category2 = Category(
        product=[Product()]
    )

    catalog = Catalog(
        categories=[category, category2]
    )
    session.add(catalog)
    session.commit()
    catalog.product_count  # 2

    session.delete(category)
    session.commit()
    catalog.product_count  # 1


Observing multiple columns
--------------------------

You can also observe multiple columns by specifying all the observable columns
in the decorator.


::

    class Order(Base):
        __tablename__ = 'order'
        id = sa.Column(sa.Integer, primary_key=True)
        unit_price = sa.Column(sa.Integer)
        amount = sa.Column(sa.Integer)
        total_price = sa.Column(sa.Integer)

        @observes('amount', 'unit_price')
        def total_price_observer(self, amount, unit_price):
            self.total_price = amount * unit_price



    N)defaultdict
namedtuple)Iterable   )
getdotattrhas_changes)AttrPath)is_sequenceCallbackfuncbackreffullpathc                   H    e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zy)PropertyObserverc                 Z   t         j                  j                  d| j                  ft         j                  j                  d| j                  ft         j                  j
                  j                  d| j                  fg| _        t        t              | _        t        t              | _        y )Nmapper_configuredafter_configuredbefore_flush)saormMapperupdate_generator_registrygather_pathssessionSessioninvoke_callbackslistener_argsr   listcallback_mapgenerator_registryselfs    \/home/azureuser/techstart-app/venv/lib/python3.12/site-packages/sqlalchemy_utils/observer.py__init__zPropertyObserver.__init__   sx    VV]]/1O1OPVV]].0A0ABVV^^##^T5J5JK

 (-"-d"3    c                 ^    | j                   D ]  }t        j                  j                  |    y N)r   r   eventremover#   argss     r$   remove_listenersz!PropertyObserver.remove_listeners   s'    && 	#DHHOOT"	#r&   c                     | j                   D ];  }t        j                  j                  | r t        j                  j                  |  = y r(   )r   r   r)   containslistenr+   s     r$   register_listenersz#PropertyObserver.register_listeners   s9    && 	'D88$$d+&	'r&   c                      y)Nz<PropertyObserver> r"   s    r$   __repr__zPropertyObserver.__repr__   s    #r&   c                     |j                   j                         D ]-  }t        |d      s| j                  |   j	                  |       / y)zA
        Adds generator functions to generator_registry.
        __observes__N)__dict__valueshasattrr!   append)r#   mapperclass_	generators       r$   r   z*PropertyObserver.update_generator_registry   sE    
  //1 	BIy.1''/66yA	Br&   c                 b   | j                   j                         D ]  \  }}|D ]  }g }|j                  D ]  }|j                  t	        ||              |D ]  }| j
                  |   j                  t        |d |             t        t        |            D ]  }|dz   }||   j                  }	t        |	t        j                  j                        s<||   j                  j                  j                  }
| j
                  |
   j                  t        ||d |  |                 y )Nr   r   )r!   itemsr6   r:   r	   r    r   rangelenproperty
isinstancer   r   RelationshipPropertyr;   r<   )r#   r<   
generatorscallback
full_paths	call_pathpathindexiprop
prop_classs              r$   r   zPropertyObserver.gather_paths   s.   "&"9"9"?"?"A 	FJ& 
!)!6!6 CI%%hvy&ABC ' D%%f-44 hzR "'s4y!1 !AI#E{33%dBFF,G,GH)-e)=)=)D)D)K)KJ --j9@@ ()1.22AhK-7!"	r&   c              #   F  K   t         j                  j                  |      }|D ]m  }|j                  }|rt	        ||      n|}|s"t        |t              s|g}|j                  5  |D ]  }|s| j                  ||      }|s|   	 d d d        o y # 1 sw Y   zxY wwr(   )	r   r   object_sessionr   r   rC   r   no_autoflushget_callback_args)	r#   obj	callbacksr   rF   r   	root_objsroot_objr,   s	            r$   gather_callback_argsz%PropertyObserver.gather_callback_args   s     &&'',! 	+H&&G4;
30I!)X6!*I)) +$- +##'#9#9(H#MD#&*
	++ +	++ +s0   AB!B!%B.BB
B!B	B!c           	      :   t         j                  j                  |      |j                  D cg c]  }t	        ||fd       }}|j                  D cg c]  }t        |       }}|D ]#  }d|v st        ||      s||j                  |fc S  y c c}w c c}w )Nc                      | j                   vS r(   )deleted)rR   r   s    r$   <lambda>z4PropertyObserver.get_callback_args.<locals>.<lambda>
  s    3goo3M r&   .)r   r   rO   r   r   strr   r   )r#   rU   rF   rI   objectspathsr   s         @r$   rQ   z"PropertyObserver.get_callback_args  s    &&''1 !))
 x'MN
 
 (0'8'89tT99 	:Dd{k(D9 (--99	:
 :s   BBc              #      K   t        j                  |j                  |j                  |j                        }|D ]7  }| j
                  j                         D ]  \  }}t        ||      s||f  9 y wr(   )	itertoolschainnewdirtyrY   r    r?   rC   )r#   r   objsrR   r<   rS   s         r$   iterate_objects_and_callbacksz.PropertyObserver.iterate_objects_and_callbacks  sj     w{{GMM7??K 	)C%)%6%6%<%<%> )!	c6*y.()	)s   A'A5*A5c           
      (   t        d       }| j                  |      D ]  \  }}| j                  ||      }|D ]u  \  }}	}
||   |	   si ||   |	<   t        |
      D ]Q  \  }}t	        |      r6||   |	   j                  |t                     t        |      z  ||   |	   |<   G|||   |	   |<   S w  |j                         D ]I  \  }}|j                         D ]1  \  }} ||gt        t        |            D cg c]  }||   	 c}  3 K y c c}w )Nc                       t        t              S r(   )r   setr3   r&   r$   rZ   z3PropertyObserver.invoke_callbacks.<locals>.<lambda>  s    K,< r&   )
r   re   rV   	enumerater
   getrh   r?   r@   rA   )r#   r   ctx	instancescallback_argsrR   rS   r,   rU   r   r]   rK   object_callback_objsrF   rd   s                   r$   r   z!PropertyObserver.invoke_callbacks  sL   #$<="@@I 	CNC,,S)<D+/ 	C'$$X.t446M(+D1"+G"4 CJAw"7+;H;R <#a-#g,<7h/5a8 <Ch/5a8C	C	C (5':':'< 	I#Hm"/"5"5"7 I$HeCI6F$GT!W$GHI	I$Gs   8DN)__name__
__module____qualname__r%   r-   r1   r4   r   r   rV   rQ   re   r   r3   r&   r$   r   r      s6    4#'
$B2+"	:)Ir&   r   c                  ^     |j                  dt              }|j                           fd}|S )a  
    Mark method as property observer for the given property path. Inside
    transaction observer gathers all changes made in given property path and
    feeds the changed objects to observer-marked method at the before flush
    phase.

    ::

        from sqlalchemy_utils import observes


        class Catalog(Base):
            __tablename__ = 'catalog'
            id = sa.Column(sa.Integer, primary_key=True)
            category_count = sa.Column(sa.Integer, default=0)

            @observes('categories')
            def category_observer(self, categories):
                self.category_count = len(categories)

        class Category(Base):
            __tablename__ = 'category'
            id = sa.Column(sa.Integer, primary_key=True)
            catalog_id = sa.Column(sa.Integer, sa.ForeignKey('catalog.id'))


        catalog = Catalog(categories=[Category(), Category()])
        session.add(catalog)
        session.commit()

        catalog.category_count  # 2


    .. versionadded: 0.28.0

    :param paths: One or more dot-notated property paths, eg.
       'categories.products.price'
    :param observer_kw: A dictionary where value for key 'observer' contains
       :meth:`PropertyObserver` object
    observerc                 "      fd}|_         |S )Nc                      | g|i |S r(   r3   )r#   r,   kwargsr   s      r$   wrapperz(observes.<locals>.wraps.<locals>.wrapper]  s    .t.v..r&   )r6   )r   rx   r^   s   ` r$   wrapszobserves.<locals>.wraps\  s    	/  %r&   )poprt   r1   )r^   observer_kw	observer_ry   s   `   r$   observesr}   0  s.    R 
H5I  " Lr&   )__doc__r`   collectionsr   r   collections.abcr   
sqlalchemyr   	functionsr   r   rI   r	   utilsr
   r   r   rt   r}   r3   r&   r$   <module>r      sN   m^  / $  .  j"ABmI mI` 3r&   