
    D6i^                     x   d dl mZ d dlmZ d dlmZ d dlmZ d dlZ	d dl
mZ d dlmZ d dlmZmZmZ d d	lmZ d d
lmZ 	 d dlmZmZ d dlmZ d dlmZ ddlm Z  d)dZ!d Z"d Z#d Z$d Z%d Z&d Z'd Z(d Z)d Z*d Z+d Z,d Z-d Z.d Z/d Z0d  Z1d! Z2d)d"Z3d# Z4d*d$Z5d% Z6d& Z7d' Z8d( Z9y# e$ r d dlmZmZ Y pw xY w)+    )OrderedDict)partial)isclass)
attrgetterN)Dialect)hybrid_property)ColumnProperty	mapperlibRelationshipProperty)InstrumentedAttribute)UnmappedInstanceError)_ColumnEntity_MapperEntity)object_session)AliasedInsp   )is_sequencec                    t        |       j                         D ch c]  }t        |d      r|j                  |u r|  }}t	        |      dkD  r|s$t        dj                  |j                              |D ]H  }t        j                  |      }|j                  j                  }||v s3||   |j                  k(  sF|c S  t        dj                  |j                              |r|j                         S yc c}w )a  
    Return declarative class associated with given table. If no class is found
    this function returns `None`. If multiple classes were found (polymorphic
    cases) additional `data` parameter can be given to hint which class
    to return.

    ::

        class User(Base):
            __tablename__ = 'entity'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.String)


        get_class_by_table(Base, User.__table__)  # User class


    This function also supports models using single table inheritance.
    Additional data paratemer should be provided in these case.

    ::

        class Entity(Base):
            __tablename__ = 'entity'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.String)
            type = sa.Column(sa.String)
            __mapper_args__ = {
                'polymorphic_on': type,
                'polymorphic_identity': 'entity'
            }

        class User(Entity):
            __mapper_args__ = {
                'polymorphic_identity': 'user'
            }


        # Entity class
        get_class_by_table(Base, Entity.__table__, {'type': 'entity'})

        # User class
        get_class_by_table(Base, Entity.__table__, {'type': 'user'})


    :param base: Declarative model base
    :param table: SQLAlchemy Table object
    :param data: Data row to determine the class in polymorphic scenarios
    :return: Declarative class or None.
    	__table__   zMultiple declarative classes found for table '{}'. Please provide data parameter for this function to be able to determine polymorphic scenarios.zMultiple declarative classes found for table '{}'. Given data row does not match any polymorphic identity of the found classes.N)_get_class_registryvalueshasattrr   len
ValueErrorformatnamesainspectpolymorphic_onpolymorphic_identitypop)basetabledatacfound_classesclsmapperr    s           a/home/azureuser/techstart-app/venv/lib/python3.12/site-packages/sqlalchemy_utils/functions/orm.pyget_class_by_tabler+      s   j %T*1131k"q{{e'; 	
M 
 =A66<fUZZ6H  % #C!'!6!6!;!;!T)N+v/J/JJ"
# !!'

!3 
 
  ""5s   #C9c                    t        | d      r| j                  S t        | t              r| j                  } t        | t
              r| j                  d   j                  S t        | t              r| j                  j                  S t        d      )a  
    Return the associated type with given Column, InstrumentedAttribute,
    ColumnProperty, RelationshipProperty or other similar SQLAlchemy construct.

    For constructs wrapping columns this is the column type. For relationships
    this function returns the relationship mapper class.

    :param expr:
        SQLAlchemy Column, InstrumentedAttribute, ColumnProperty or other
        similar SA construct.

    ::

        class User(Base):
            __tablename__ = 'user'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.String)


        class Article(Base):
            __tablename__ = 'article'
            id = sa.Column(sa.Integer, primary_key=True)
            author_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
            author = sa.orm.relationship(User)


        get_type(User.__table__.c.name)  # sa.String()
        get_type(User.name)  # sa.String()
        get_type(User.name.property)  # sa.String()

        get_type(Article.author)  # User


    .. versionadded: 0.30.9
    typer   zCouldn't inspect type.)r   r-   
isinstancer   propertyr	   columnsr   r)   class_	TypeError)exprs    r*   get_typer4   h   sr    H tVyy	D/	0}}$'||A###	D.	/{{!!!
,
--    c                     	 t        |       }|}t        ||      st	        j
                  | |      S | S # t        $ r | } |       j                  }Y Bw xY w)a  
    Produce a CAST expression but only if given expression is not of given type
    already.

    Assume we have a model with two fields id (Integer) and name (String).

    ::

        import sqlalchemy as sa
        from sqlalchemy_utils import cast_if


        cast_if(User.id, sa.Integer)    # "user".id
        cast_if(User.name, sa.String)   # "user".name
        cast_if(User.id, sa.String)     # CAST("user".id AS TEXT)


    This function supports scalar values as well.

    ::

        cast_if(1, sa.Integer)          # 1
        cast_if('text', sa.String)      # 'text'
        cast_if(1, sa.String)           # CAST(1 AS TEXT)


    :param expression:
        A SQL expression, such as a ColumnElement expression or a Python string
        which will be coerced into a bound literal value.
    :param type_:
        A TypeEngine class or instance indicating the type to which the CAST
        should apply.

    .. versionadded: 0.30.14
    )r4   r2   python_typer.   r   cast)
expressiontype_	expr_type
check_types       r*   cast_ifr=      sg    HZ(	
 
 )Z0 	
E"   )	W((
)s   3 AAc                    t        j                  |       }	 |j                  |      j                  S # t         j                  j
                  j                  $ r] |j                  j                         D ]=  \  }}|j                  |j                  k(  s |j                  |j                  u s9|c cY S  Y nw xY wt         j                  j
                  j                  d| d| d      )a:  
    Return the key for given column in given model.

    :param model: SQLAlchemy declarative model object

    ::

        class User(Base):
            __tablename__ = 'user'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column('_name', sa.String)


        get_column_key(User, User.__table__.c._name)  # 'name'

    .. versionadded: 0.26.5

    .. versionchanged: 0.27.11
        Throws UnmappedColumnError instead of ValueError when no property was
        found for given column. This is consistent with how SQLAlchemy works.
    z
No column z is configured on mapper z...)r   r   get_property_by_columnkeyormexcUnmappedColumnErrorr0   itemsr   r$   )modelcolumnr)   r@   r&   s        r*   get_column_keyrG      s    , ZZF,,V488866::)) nn**, 	FCvv$FLL)@
	 &&**
(
(
VH5fXSA s"   2 A B6B6,B62B65B6c                    t        | t              r| j                  } nCt        | t        j                        r| j
                  } nt        | t              r| j                  } t        | t        j                  j                        r| S t        | t        j                  j                  j                        rt        j                  |       j                  S t        | t        j                  j                  j                        r| j                   } t        | t"              r| j                  S t        | t        j                  j$                  j&                        r| j(                  } t        | t        j*                        rt-        t.        d      r?t1               }t/        j2                         D ]  }|j5                  |j6                          nt.        j8                  }|D cg c]  }| |j:                  v s| }}t=        |      dkD  rt?        d| j@                  z        |st?        d| j@                  z        |d   S tC        |       stE        |       } t        j                  |       S c c}w )a  
    Return related SQLAlchemy Mapper for given SQLAlchemy object.

    :param mixed: SQLAlchemy Table / Alias / Mapper / declarative model object

    ::

        from sqlalchemy_utils import get_mapper


        get_mapper(User)

        get_mapper(User())

        get_mapper(User.__table__)

        get_mapper(User.__mapper__)

        get_mapper(sa.orm.aliased(User))

        get_mapper(sa.orm.aliased(User.__table__))


    Raises:
        ValueError: if multiple mappers were found for given argument

    .. versionadded: 0.26.1
    _all_registriesr   z&Multiple mappers found for table '%s'.z$Could not get mapper for table '%s'.r   )#r.   r   r3   r   Columnr$   r   rA   MapperutilAliasedClassr   r)   sql
selectableAliaselementr   
attributesr   r1   Tabler   r
   setrI   updatemappers_mapper_registrytablesr   r   r   r   r-   )mixedall_mappersmapper_registryr)   rV   s        r*   
get_mapperr\      s   : %'

	E299	%	E=	)

%'%112zz% '''%**001%%||%**@@A%"9/0%K#,#<#<#> <""?#:#:;< $44K(3Nfu7M6NNw<!E

RSSCejjPQQ1:5>U::e Os   !I+5I+c                     t        | d      r| j                  }n	 t        |       j                  }t        |d      st	        d      |S # t        $ r | }Y &w xY w)a.  
    Return the bind for given SQLAlchemy Engine / Connection / declarative
    model object.

    :param obj: SQLAlchemy Engine / Connection / declarative model object

    ::

        from sqlalchemy_utils import get_bind


        get_bind(session)  # Connection object

        get_bind(user)

    bindexecutezSThis method accepts only Session, Engine, Connection and declarative model objects.)r   r^   r   r   r2   )objconns     r*   get_bindrb   .  sg    " sFxx	!#&++D 4#)
 	
 K % 	D	s   A	 	AAc                 T    t        d t        |       j                         D              S )a	  
    Return an OrderedDict of all primary keys for given Table object,
    declarative class or declarative class instance.

    :param mixed:
        SA Table object, SA declarative class or SA declarative class instance

    ::

        get_primary_keys(User)

        get_primary_keys(User())

        get_primary_keys(User.__table__)

        get_primary_keys(User.__mapper__)

        get_primary_keys(sa.orm.aliased(User))

        get_primary_keys(sa.orm.aliased(User.__table__))


    .. versionchanged: 0.25.3
        Made the function return an ordered dictionary instead of generator.
        This change was made to support primary key aliases.

        Renamed this function to 'get_primary_keys', formerly 'primary_keys'

    .. seealso:: :func:`get_columns`
    c              3   B   K   | ]  \  }}|j                   r||f  y wN)primary_key).0r@   rF   s      r*   	<genexpr>z#get_primary_keys.<locals>.<genexpr>o  s)      	
V!! &M	
s   )r   get_columnsrD   rY   s    r*   get_primary_keysrk   O  s,    > 	
*51779	
 r5   c                    t        | t        j                        r| gS t        | t        j                        r| j                  gS t        | t        j
                  j                  j                        r| j                  j                  S t        | t              r| j                  } t        |       }t        |      }|rt        d |D        g       }|S |j                  }|S )a  
    Return a set of tables associated with given SQLAlchemy object.

    Let's say we have three classes which use joined table inheritance
    TextItem, Article and BlogPost. Article and BlogPost inherit TextItem.

    ::

        get_tables(Article)  # set([Table('article', ...), Table('text_item')])

        get_tables(Article())

        get_tables(Article.__mapper__)


    If the TextItem entity is using with_polymorphic='*' then this function
    returns all child tables (article and blog_post) as well.

    ::


        get_tables(TextItem)  # set([Table('text_item', ...)], ...])


    .. versionadded: 0.26.0

    :param mixed:
        SQLAlchemy Mapper, Declarative class, Column, InstrumentedAttribute or
        a SA Alias object wrapping any of these objects.
    c              3   4   K   | ]  }|j                     y wre   )rX   )rg   ms     r*   rh   zget_tables.<locals>.<genexpr>  s     <1ahh<s   )r.   r   rS   rJ   r$   rA   rR   r   parentrX   r   r3   r\   get_polymorphic_mapperssum)rY   r)   polymorphic_mappersrX   s       r*   
get_tablesrs   w  s    > %"w	E299	%}	E266,,BB	C||"""	E=	)

F1&9<(;<bA M Mr5   c                    t        | t        j                  j                  j                        r	 | j
                  S t        | t        j                  j                  j                        r)t        j                  |       j                  j                  S t        | t        j                  j                        r| j                  S t        | t              r| j                   j                  S t        | t"              r| j                  S t        | t        j$                        r| gS t'        |       s| j(                  } t        j                  |       j                  S # t        $ r | j                  cY S w xY w)a8  
    Return a collection of all Column objects for given SQLAlchemy
    object.

    The type of the collection depends on the type of the object to return the
    columns from.

    ::

        get_columns(User)

        get_columns(User())

        get_columns(User.__table__)

        get_columns(User.__mapper__)

        get_columns(sa.orm.aliased(User))

        get_columns(sa.orm.alised(User.__table__))


    :param mixed:
        SA Table object, SA Mapper, SA declarative class, SA declarative class
        instance or an alias of any of these objects
    )r.   r   rN   rO   
Selectableselected_columnsAttributeErrorr&   rA   rL   rM   r   r)   r0   rK   r   r/   r	   rJ   r   	__class__rj   s    r*   ri   ri     s   6 %**556	))) %112zz% ''///%'}}%./~~%%%%(}}%#w5>::e$$$  	77N	s   E E0/E0c                     t        | d|       }	 |j                  S # t        $ r Y nw xY w	 |j                  j                  S # t        $ r Y yw xY w)z
    Return table name of given target, declarative class or the
    table name where the declarative attribute is bound to.
    r1   N)getattr__tablename__rw   r   r   )r`   r1   s     r*   
table_namer|     s^    
 S(C(F### $$$ s    	''A 	AAc                 6    t        t        t        |       |      S re   )mapr   rz   )r`   attrss     r*   getattrsr     s    ww$e,,r5   c                     t        | t              r| }nt        |       j                  }|j	                  |      j                  |      S )a  
    Conditionally quote an identifier.
    ::


        from sqlalchemy_utils import quote


        engine = create_engine('sqlite:///:memory:')

        quote(engine, 'order')
        # '"order"'

        quote(engine, 'some_other_identifier')
        # 'some_other_identifier'


    :param mixed: SQLAlchemy Session / Connection / Engine / Dialect object.
    :param ident: identifier to conditionally quote
    )r.   r   rb   dialectpreparerquote)rY   identr   s      r*   r   r     s>    * %!5/))G$**511r5   c                 >    t        | d      r| j                         S | S )N_compile_state)r   r   )querys    r*   _get_query_compile_stater   
  s!    u&'##%%r5   c                 n    t        | t              r| j                  S | j                  j	                         S re   )r.   r   with_polymorphic_mapperspolymorphic_mapr   rj   s    r*   rp   rp     s-    %%---$$++--r5   c                    t        j                  |       }t        |      j                         D ]
  \  }}||k(  st	        |d      r|j
                  nd }t        |t              rt        | t         j                  j                  j                        r1|j                  j                  D ]  }|j                  |k(  s|c c S  t        |j                  j                   |      c S t        | t         j                  j                  j                        rt        | |      c S 	 t        |j                   |      c S  y # t"        $ r Y w xY w)Nr/   )r   r   get_all_descriptorsrD   r   r/   r.   r	   rA   rL   rM   rO   r&   r@   rz   ro   r1   rw   )entityattrr)   r@   
descriptorpropr&   s          r*   get_descriptorr     s   ZZF.v6<<> Z3;*1*j*I:&&tD$/fbffkk&>&>?#..00 %55D=#$H% #4;;#5#5t<<
 fbffkk&>&>?"6400"6==$77+, & s   $D>>	E
Ec                    t        | t        j                  j                  j                        r| j
                  S t        j                  |       }	 t        |      }t        t        |       j                        }|D ].  }|j                  j                         D ]  \  }}||vs|||<    0 |S # t        j                  j                  $ r t        |       j                  cY S w xY wre   )r.   r   rN   rO   ru   r&   r   rp   dictr\   all_orm_descriptorsrD   rB   NoInspectionAvailable)r3   insprr   r   	submapperr@   r   s          r*   r   r   5  s    $))445vv::dD
5d; Z%99:, 	,I#,#@#@#F#F#H ,Ze#!+E#J,	,  66'' 4$3334s   B/ /2C$#C$c                     t        |       j                  j                         D ci c]  \  }}t        |t              r|| c}}S c c}}w )a  
    Returns a dictionary of hybrid property keys and hybrid properties for
    given SQLAlchemy declarative model / mapper.


    Consider the following model

    ::


        from sqlalchemy.ext.hybrid import hybrid_property


        class Category(Base):
            __tablename__ = 'category'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.Unicode(255))

            @hybrid_property
            def lowercase_name(self):
                return self.name.lower()

            @lowercase_name.expression
            def lowercase_name(cls):
                return sa.func.lower(cls.name)


    You can now easily get a list of all hybrid property names

    ::


        from sqlalchemy_utils import get_hybrid_properties


        get_hybrid_properties(Category).keys()  # ['lowercase_name']


    This function also supports aliased classes

    ::


        get_hybrid_properties(
            sa.orm.aliased(Category)
        ).keys()  # ['lowercase_name']


    .. versionchanged: 0.26.7
        This function now returns a dictionary instead of generator

    .. versionchanged: 0.30.15
        Added support for aliased classes

    :param model: SQLAlchemy declarative model or mapper
    )r\   r   rD   r.   r   )rE   r@   r   s      r*   get_hybrid_propertiesr   F  sK    v $E*>>DDFCdO, 	T	  s   Ac                 x    | j                   D ]  }	 |j                   t        |      c S  | S # t        $ r Y +w xY w)zm
    Returns the declarative base for given model class.

    :param model: SQLAlchemy declarative model
    )	__bases__metadataget_declarative_baserw   )rE   ro   s     r*   r   r     sI     // 	OO'// L  		s   -	99c                    | }t        |      j                  d      D ]  }t        |      }t        |      rBg }|D ]8  } ||      }t        |      r|j	                  |       (|j                  |       : |}nCt        |t              r' ||j                  j                  j                        }n| y ||      }|t        |      r|D 	cg c]  }	 ||	      s|	 }}	 ||      r y |S c c}	w )a  
    Allow dot-notated strings to be passed to `getattr`.

    ::

        getdotattr(SubSection, 'section.document')

        getdotattr(subsection, 'section.document')


    :param obj_or_class: Any object or class
    :param dot_path: Attribute path with dot mark as separator
    .N)strsplitr   r   extendappendr.   r   r/   r)   r1   )
obj_or_classdot_path	conditionlastpathgettertmprQ   valuevs
             r*   
getdotattrr     s     DH##C(  D!tC &wu%JJu%JJu%& D34$--..556D\$<D 4 #'8a9Q<88 / 2 K 9s   C0C0c                 X    | t         j                  j                  |       j                  v S re   )r   rA   r   deleted)r`   s    r*   
is_deletedr     s"    "&&'',4444r5   c                 d    |rjt        |t              rFt        j                         j                  j                  |      j                  j                         S t         fd|D              S g t        fdt        j                         j                  j                         D              S )a  
    Simple shortcut function for checking if given attributes of given
    declarative model object have changed during the session. Without
    parameters this checks if given object has any modificiations. Additionally
    exclude parameter can be given to check if given object has any changes
    in any attributes other than the ones given in exclude.


    ::


        from sqlalchemy_utils import has_changes


        user = User()

        has_changes(user, 'name')  # False

        user.name = 'someone'

        has_changes(user, 'name')  # True

        has_changes(user)  # True


    You can check multiple attributes as well.
    ::


        has_changes(user, ['age'])  # True

        has_changes(user, ['name', 'age'])  # True


    This function also supports excluding certain attributes.

    ::

        has_changes(user, exclude=['name'])  # False

        has_changes(user, exclude=['age'])  # True

    .. versionchanged: 0.26.6
        Added support for multiple attributes and exclude parameter.

    :param obj: SQLAlchemy declarative model object
    :param attrs: Names of the attributes
    :param exclude: Names of the attributes to exclude
    c              3   6   K   | ]  }t        |        y wre   )has_changes)rg   r   r`   s     r*   rh   zhas_changes.<locals>.<genexpr>  s     @${3-@   c              3   `   K   | ]%  \  }}|vr|j                   j                          ' y wre   )historyr   )rg   r@   r   excludes      r*   rh   zhas_changes.<locals>.<genexpr>  s2      
T'! LL$$&
s   +.)
r.   r   r   r   r   getr   r   anyrD   )r`   r   r   s   ` `r*   r   r     s    d eS!::c?((,,U3;;GGII@%@@@?G 
ZZ_2288:
 
 	
r5   c                 D    |t        j                  |       j                  vS )a  
    Return whether or not given property of given object has been loaded.

    ::

        class Article(Base):
            __tablename__ = 'article'
            id = sa.Column(sa.Integer, primary_key=True)
            name = sa.Column(sa.String)
            content = sa.orm.deferred(sa.Column(sa.String))


        article = session.query(Article).get(5)

        # name gets loaded since its not a deferred property
        assert is_loaded(article, 'name')

        # content has not yet been loaded since its a deferred property
        assert not is_loaded(article, 'content')


    .. versionadded: 0.27.8

    :param obj: SQLAlchemy declarative model object
    :param prop: Name of the property or InstrumentedAttribute
    )r   r   unloaded)r`   r   s     r*   	is_loadedr     s    6 rzz#////r5   c                 Z     t         fdt               j                         D              S )a  
    Return the identity of given sqlalchemy declarative model class or instance
    as a tuple. This differs from obj._sa_instance_state.identity in a way that
    it always returns the identity even if object is still in transient state (
    new object that is not yet persisted into database). Also for classes it
    returns the identity attributes.

    ::

        from sqlalchemy import inspect
        from sqlalchemy_utils import identity


        user = User(name='John Matrix')
        session.add(user)
        identity(user)  # None
        inspect(user).identity  # None

        session.flush()  # User now has id but is still in transient state

        identity(user)  # (1,)
        inspect(user).identity  # None

        session.commit()

        identity(user)  # (1,)
        inspect(user).identity  # (1, )


    You can also use identity for classes::


        identity(User)  # (User.id, )

    .. versionadded: 0.21.0

    :param obj: SQLAlchemy declarative model object
    c              3   6   K   | ]  }t        |        y wre   )rz   )rg   
column_keyr   s     r*   rh   zidentity.<locals>.<genexpr>K  s        	j)r   )tuplerk   keys)r   s   `r*   identityr   $  s.    N  *<8==?  r5   c                     t        j                  | j                        j                  j	                         D ]-  \  }}|j
                  rt        | |      t        ||      k(  r- y y)a  
    Returns whether or not two given SQLAlchemy declarative instances are
    naturally equivalent (all their non primary key properties are equivalent).


    ::

        from sqlalchemy_utils import naturally_equivalent


        user = User(name='someone')
        user2 = User(name='someone')

        user == user2  # False

        naturally_equivalent(user, user2)  # True


    :param obj: SQLAlchemy declarative model object
    :param obj2: SQLAlchemy declarative model object to compare with `obj`
    FT)r   r   rx   r0   rD   rf   rz   )r`   obj2r   rF   s       r*   naturally_equivalentr   Q  s^    , !jj7??EEG 
FZ(GD*,EE r5   c                 f    	 | j                   j                  S # t        $ r | j                  cY S w xY wre   )registry_class_registryrw   _decl_class_registry)r1   s    r*   r   r   p  s2    +... +***+s    00re   )NN):collectionsr   	functoolsr   r   r   operatorr   
sqlalchemyr   sqlalchemy.engine.interfacesr   sqlalchemy.ext.hybridr   sqlalchemy.ormr	   r
   r   sqlalchemy.orm.attributesr   sqlalchemy.orm.excr   sqlalchemy.orm.contextr   r   ImportErrorsqlalchemy.orm.querysqlalchemy.orm.sessionr   sqlalchemy.orm.utilr   utilsr   r+   r4   r=   rG   r\   rb   rk   rs   ri   r|   r   r   r   rp   r   r   r   r   r   r   r   r   r   r   r    r5   r*   <module>r      s    #     0 1 J J ; 4BC 2 + M`-.`0fD>BB%P/d,%^$-28.:"=@)X5>
B0<*Z>+C  BAABs    B) )B98B9