
    D6iK                         d dl 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	 d dl
mZmZ ddlmZ dd	lmZ dd
ZddZddZd Zd Zd Zdej.                  j0                  j2                  fdZd Zd Zd ZddZd Zy)    N)MappingSequence)copy)make_url)OperationalErrorProgrammingError   )starts_with   )quotec                 x    | j                  ||dz        j                  d|dz         j                  d|dz         S )a7  
    Escape the string parameter used in SQL LIKE expressions.

    ::

        from sqlalchemy_utils import escape_like


        query = session.query(User).filter(
            User.name.ilike(escape_like('John'))
        )


    :param string: a string to escape
    :param escape_char: escape character
    r	   %_)replace)stringescape_chars     f/home/azureuser/techstart-app/venv/lib/python3.12/site-packages/sqlalchemy_utils/functions/database.pyescape_liker      s=    $ 	{K!O4	kC'	(	kC'	(    c                    |rd }nt         j                  }t        | t              rAt        j                  j
                  d t        j                  | j                          D         S t        | t              r |d|  d      S t        | t              r#t        j                  j                  d | D         S t        | t        t        f      r |t        |             S | S )a  
    Convert python data structures to PostgreSQL specific SQLAlchemy JSON
    constructs. This function is extremly useful if you need to build
    PostgreSQL JSON on python side.

    .. note::

        This function needs PostgreSQL >= 9.4

    Scalars are converted to to_json SQLAlchemy function objects

    ::

        json_sql(1)     # Equals SQL: to_json(1)

        json_sql('a')   # to_json('a')


    Mappings are converted to json_build_object constructs

    ::

        json_sql({'a': 'c', '2': 5})  # json_build_object('a', 'c', '2', 5)


    Sequences (other than strings) are converted to json_build_array constructs

    ::

        json_sql([1, 2, 3])  # json_build_array(1, 2, 3)


    You can also nest these data structures

    ::

        json_sql({'a': [1, 2, 3]})
        # json_build_object('a', json_build_array[1, 2, 3])


    :param value:
        value to be converted to SQLAlchemy PostgreSQL function constructs
    c                 f    t         j                  j                  t        j                  |             S N)safuncto_jsontextas    r   scalar_convertz json_sql.<locals>.scalar_convertT   s    77??2771:..r   c              3   6   K   | ]  }t        |d         ywF)scalars_to_jsonNjson_sql.0vs     r   	<genexpr>zjson_sql.<locals>.<genexpr>[   s"       E22   'c              3   6   K   | ]  }t        |d         ywr!   r#   r%   s     r   r(   zjson_sql.<locals>.<genexpr>d   s     @Qhq%00@r)   )r   r   
isinstancer   r   json_build_object	itertoolschainitemsstrr   json_build_arrayintfloat)valuer"   r   s      r   r$   r$   &   s    X 	/ %!ww(("%++-8
 	
 
E3	%l++	E8	$ww''@%@
 	
 
EC<	(c%j))Lr   c                    |rd }nt         j                  }t        | t              rAt        j                  j
                  d t        j                  | j                          D         S t        | t              r |d|  d      S t        | t              r#t        j                  j                  d | D         S t        | t        t        f      r |t        |             S | S )a"  
    Convert python data structures to PostgreSQL specific SQLAlchemy JSONB
    constructs. This function is extremly useful if you need to build
    PostgreSQL JSONB on python side.

    .. note::

        This function needs PostgreSQL >= 9.4

    Scalars are converted to to_jsonb SQLAlchemy function objects

    ::

        jsonb_sql(1)     # Equals SQL: to_jsonb(1)

        jsonb_sql('a')   # to_jsonb('a')


    Mappings are converted to jsonb_build_object constructs

    ::

        jsonb_sql({'a': 'c', '2': 5})  # jsonb_build_object('a', 'c', '2', 5)


    Sequences (other than strings) converted to jsonb_build_array constructs

    ::

        jsonb_sql([1, 2, 3])  # jsonb_build_array(1, 2, 3)


    You can also nest these data structures

    ::

        jsonb_sql({'a': [1, 2, 3]})
        # jsonb_build_object('a', jsonb_build_array[1, 2, 3])


    :param value:
        value to be converted to SQLAlchemy PostgreSQL function constructs
    :boolean jsonbb:
        Flag to alternatively convert the return with a to_jsonb construct
    c                 f    t         j                  j                  t        j                  |             S r   )r   r   to_jsonbr   r   s    r   r   z!jsonb_sql.<locals>.scalar_convert   s    77##BGGAJ//r   c              3   6   K   | ]  }t        |d         ywF)scalars_to_jsonbN	jsonb_sqlr%   s     r   r(   zjsonb_sql.<locals>.<genexpr>   s"       !e44r)   r*   c              3   6   K   | ]  }t        |d         ywr:   r<   r%   s     r   r(   zjsonb_sql.<locals>.<genexpr>   s     BqiE22Br)   )r   r   r,   r   r   jsonb_build_objectr.   r/   r0   r1   r   jsonb_build_arrayr3   r4   )r5   r;   r   s      r   r=   r=   k   s    \ 	0 %!ww))"%++-8
 	
 
E3	%l++	E8	$ww((BEB
 	
 
EC<	(c%j))Lr   c                    | j                   }t        |t        j                        st	        d|z        |j
                  j                  j                         }t        | t        j                        r$t        | j                  j                               n| g|xr t        |      xs t        fd|j                  D              S )a
  
    Return whether or not given column or the columns of given foreign key
    constraint have an index. A column has an index if it has a single column
    index or it is the first column in compound column index.

    A foreign key constraint has an index if the constraint columns are the
    first columns in compound column index.

    :param column_or_constraint:
        SQLAlchemy Column object or SA ForeignKeyConstraint object

    .. versionadded: 0.26.2

    .. versionchanged: 0.30.18
        Added support for foreign key constaints.

    ::

        from sqlalchemy_utils import has_index


        class Article(Base):
            __tablename__ = 'article'
            id = sa.Column(sa.Integer, primary_key=True)
            title = sa.Column(sa.String(100))
            is_published = sa.Column(sa.Boolean, index=True)
            is_deleted = sa.Column(sa.Boolean)
            is_archived = sa.Column(sa.Boolean)

            __table_args__ = (
                sa.Index('my_index', is_deleted, is_archived),
            )


        table = Article.__table__

        has_index(table.c.is_published) # True
        has_index(table.c.is_deleted)   # True
        has_index(table.c.is_archived)  # False


    Also supports primary key indexes

    ::

        from sqlalchemy_utils import has_index


        class ArticleTranslation(Base):
            __tablename__ = 'article_translation'
            id = sa.Column(sa.Integer, primary_key=True)
            locale = sa.Column(sa.String(10), primary_key=True)
            title = sa.Column(sa.String(100))


        table = ArticleTranslation.__table__

        has_index(table.c.locale)   # False
        has_index(table.c.id)       # True


    This function supports foreign key constraints as well

    ::


        class User(Base):
            __tablename__ = 'user'
            first_name = sa.Column(sa.Unicode(255), primary_key=True)
            last_name = sa.Column(sa.Unicode(255), primary_key=True)

        class Article(Base):
            __tablename__ = 'article'
            id = sa.Column(sa.Integer, primary_key=True)
            author_first_name = sa.Column(sa.Unicode(255))
            author_last_name = sa.Column(sa.Unicode(255))
            __table_args__ = (
                sa.ForeignKeyConstraint(
                    [author_first_name, author_last_name],
                    [User.first_name, User.last_name]
                ),
                sa.Index(
                    'my_index',
                    author_first_name,
                    author_last_name
                )
            )

        table = Article.__table__
        constraint = list(table.foreign_keys)[0].constraint

        has_index(constraint)  # True
    ROnly columns belonging to Table objects are supported. Given column belongs to %r.c              3   f   K   | ](  }t        |j                  j                                * y wr   )r
   columnsvaluesr&   indexrD   s     r   r(   zhas_index.<locals>.<genexpr>  s,      H9>EMM((*G4Hs   .1)tabler,   r   Table	TypeErrorprimary_keyrD   rE   ForeignKeyConstraintlistr
   anyindexescolumn_or_constraintrH   primary_keysrD   s      @r   	has_indexrS      s    | !&&EeRXX&$&+,
 	
 $$,,335L&(?(?@+33::<='(?[w? C HBG--H E r   c                    | j                   }t        |t        j                        st	        d|z        t        |j                  j                  j                               }t        | t        j                        r$t        | j                  j                               n| g|k(  xs> t        fd|j                  D              xs t        fd|j                  D              S )au	  
    Return whether or not given column or given foreign key constraint has a
    unique index.

    A column has a unique index if it has a single column primary key index or
    it has a single column UniqueConstraint.

    A foreign key constraint has a unique index if the columns of the
    constraint are the same as the columns of table primary key or the coluns
    of any unique index or any unique constraint of the given table.

    :param column: SQLAlchemy Column object

    .. versionadded: 0.27.1

    .. versionchanged: 0.30.18
        Added support for foreign key constaints.

        Fixed support for unique indexes (previously only worked for unique
        constraints)

    ::

        from sqlalchemy_utils import has_unique_index


        class Article(Base):
            __tablename__ = 'article'
            id = sa.Column(sa.Integer, primary_key=True)
            title = sa.Column(sa.String(100))
            is_published = sa.Column(sa.Boolean, unique=True)
            is_deleted = sa.Column(sa.Boolean)
            is_archived = sa.Column(sa.Boolean)


        table = Article.__table__

        has_unique_index(table.c.is_published) # True
        has_unique_index(table.c.is_deleted)   # False
        has_unique_index(table.c.id)           # True


    This function supports foreign key constraints as well

    ::


        class User(Base):
            __tablename__ = 'user'
            first_name = sa.Column(sa.Unicode(255), primary_key=True)
            last_name = sa.Column(sa.Unicode(255), primary_key=True)

        class Article(Base):
            __tablename__ = 'article'
            id = sa.Column(sa.Integer, primary_key=True)
            author_first_name = sa.Column(sa.Unicode(255))
            author_last_name = sa.Column(sa.Unicode(255))
            __table_args__ = (
                sa.ForeignKeyConstraint(
                    [author_first_name, author_last_name],
                    [User.first_name, User.last_name]
                ),
                sa.Index(
                    'my_index',
                    author_first_name,
                    author_last_name,
                    unique=True
                )
            )

        table = Article.__table__
        constraint = list(table.foreign_keys)[0].constraint

        has_unique_index(constraint)  # True


    :raises TypeError: if given column does not belong to a Table object
    rB   c              3      K   | ]X  }t        |t        j                  j                  j                        r(t        |j                  j                               k(   Z y wr   )r,   r   sqlschemaUniqueConstraintrM   rD   rE   )r&   
constraintrD   s     r   r(   z#has_unique_index.<locals>.<genexpr>~  sJ      
*bffmm&D&DE tJ..55788
s   AA!c              3      K   | ]6  }|j                   r(t        |j                  j                               k(   8 y wr   )uniquerM   rD   rE   rF   s     r   r(   z#has_unique_index.<locals>.<genexpr>  s7      
|| tEMM00233
s   <?)rH   r,   r   rI   rJ   rM   rK   rD   rE   rL   rN   constraintsrO   rP   s      @r   has_unique_indexr]   !  s    ^ !&&EeRXX&$&+,
 	
 ))1188:;L&(?(?@+33::<='( 
L	  
	
 
#//
 

	
  

 
r   c                    t        | j                  t        j                        xs$ t        | j                  t        j                        xr6 | j
                  xs( | j                  xs | j                  xs | j                  S )z
    Returns whether or not given SQLAlchemy Column object's is auto assigned
    DateTime or Date.

    :param column: SQLAlchemy Column object
    )	r,   typer   DateTimeDatedefaultserver_defaultonupdateserver_onupdate)columns    r   is_auto_assigned_date_columnrg     sg     	6;;,P
6;;0P 	 	"  	"??	" !!r   urlc                     t        | d      r| j                  |      }nt        |       } || _        | }|j                  |k(  sJ |       |S )z|Set the database of an engine URL.

    :param url: A SQLAlchemy engine URL.
    :param database: New database to set.

    _replacedatabase)hasattrrj   r   rl   )rh   rl   rets      r   _set_url_databasero     sO     sJllHl-3i<<8#(S(#Jr   c                 p    | j                         5 }|j                  |      cd d d        S # 1 sw Y   y xY wr   )connectscalar)enginerV   conns      r   _get_scalar_resultru     s/    		  T{{3     s   ,5c                     t         j                  j                  |       r"t         j                  j                  |       dk  ryt	        | d      5 }|j                  d      }d d d        d d dk(  S # 1 sw Y   xY w)Nd   Frb   s   SQLite format 3 )ospathisfilegetsizeopenread)rl   fheaders      r   _sqlite_file_existsr     sk    77>>(#rwwx'@3'F	h	  #2;000 s   A11A:c           	         t        |       } | j                  }| j                         j                  }d}	 |dk(  rd|z  }|ddddfD ]c  }t	        | |      } t        j                  | d	      }	 t        t        |t        j                  |                  c |r|j                          S S  	 |r|j                          y
y
|dk(  rbt	        | d      } t        j                  |       }d|z  }t        t        |t        j                  |                  |r|j                          S S |dk(  r_t	        | d      } t        j                  |       }|r&|dk(  xs t        |      	 |r|j                          S S 	 |r|j                          yy|dk(  red|z  }t	        | d      } t        j                  | d	      }	 t        t        |t        j                  |                  |r|j                          S S d}	 t        j                  |       }t        t        |t        j                  |                  |r|j                          S S # t        t        f$ r Y w xY w# t        t        f$ r Y |r|j                          y
y
w xY w# t        t        f$ r Y |r|j                          y
y
w xY w# |r|j                          w w xY w)a  Check if a database exists.

    :param url: A SQLAlchemy engine URL.

    Performs backend-specific testing to quickly determine if a database
    exists on the server. ::

        database_exists('postgresql://postgres@localhost/name')  #=> False
        create_database('postgresql://postgres@localhost/name')
        database_exists('postgresql://postgres@localhost/name')  #=> True

    Supports checking against a constructed URL as well. ::

        engine = create_engine('postgresql://postgres@localhost/name')
        database_exists(engine.url)  #=> False
        create_database(engine.url)
        database_exists(engine.url)  #=> True

    N
postgresqlz,SELECT 1 FROM pg_database WHERE datname='%s'postgres	template1	template0rk   
AUTOCOMMITisolation_levelFmysqlzLSELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '%s'sqlite:memory:Tmssqlz-SELECT 1 FROM sys.databases WHERE name = '%s'masterzSELECT 1)r   rl   get_dialectnamero   r   create_engineboolru   r   disposer   r   r   )rh   rl   dialect_namers   r   dbs         r   database_existsr     s   * 3-C||H??$))LF/<'AHLD[+tL 'b9))#|L 262774= IJJN NN W H NN E W$#C$7C%%c*F+-56  *62774=AB6 NN 3 X%#C$7C%%c*F:-N1DX1NN* NN # " NN ! W$BXMD#C(;C%%c<HF.vrwwt}EF NN  D))#..vrwwt}EF NN M )*:; 8 %&67  NN  %&67 NN  NN s   8J/ .'I	J/ +J/ AJ/ (:J/ .J/ ;'I 6J/ 9<J 	IJ/ IJ/ J.J/ JJ/ J,J/ +J,,J/ /Kc           	      >   t        |       } | j                  }| j                         j                  }| j                         j                  }|dk(  rt        | d      } n8|dk(  rt        | d      } n%|dk(  rt        | d      } n|dk(  st        | d	      } |dk(  r|d
v s	|dk(  r|dv rt        j                  | d      }nt        j                  |       }|dk(  rj|sd}|j                         5 }dj                  t        ||      |t        ||            }|j                  t        j                  |             d	d	d	       n|dk(  rZ|j                         5 }dj                  t        ||      |      }|j                  t        j                  |             d	d	d	       n|dk(  ri|dk7  rd|r|j                         5 }|j                  t        j                  d             |j                  t        j                  d             d	d	d	       nL|j                         5 }dt        ||       }|j                  t        j                  |             d	d	d	       |j                          y	# 1 sw Y   xY w# 1 sw Y   &xY w# 1 sw Y   2xY w# 1 sw Y   >xY w)a  Issue the appropriate CREATE DATABASE statement.

    :param url: A SQLAlchemy engine URL.
    :param encoding: The encoding to create the database as.
    :param template:
        The name of the template from which to create the new database. At the
        moment only supported by PostgreSQL driver.

    To create a database, you can pass a simple URL that would have
    been passed to ``create_engine``. ::

        create_database('postgresql://postgres@localhost/name')

    You may also pass the url from an existing engine. ::

        create_database(engine.url)

    Has full support for mysql, postgres, and sqlite. In theory,
    other database engines should be supported.
    r   r   rk   r   r   cockroachdb	defaultdbr   N>   pyodbcpymssql>   pg8000asyncpgpsycopgpsycopg2psycopg2cffir   r   r   z,CREATE DATABASE {} ENCODING '{}' TEMPLATE {}r   z'CREATE DATABASE {} CHARACTER SET = '{}'r   zCREATE TABLE DB(id int)zDROP TABLE DBzCREATE DATABASE )r   rl   r   r   driverro   r   r   beginformatr   executer   r   )	rh   encodingtemplaterl   r   dialect_driverrs   rt   r   s	            r   create_databaser     s]   , 3-C||H??$))L__&--N|#j9		 h7		&k:X%d3N6K$K$GH !!#|D!!#&|#"H\\^ 	(tAHHdH%xtX1FD LL'		( 	( 
	 \\^ 	(t<CCdH%xD LL'		( 	( 
	!h*&< 74RWW%>?@RWW_567 7
 \\^ 	(t%eD(&;%<=DLL'	( NN1	( 	(	( 	(7 7
	( 	(s3   /AI/AI; A	J"4J/I8;JJJc                    t        |       } | j                  }| j                         j                  }| j                         j                  }|dk(  rt        | d      } n8|dk(  rt        | d      } n%|dk(  rt        | d      } n|dk(  st        | d	      } |dk(  r|d
v s	|dk(  r|dv rt        j                  | d      }nt        j                  |       }|dk(  r|dk7  r|rbt        j                  |       nL|j                         5 }dt        ||       }|j                  t        j                  |             d	d	d	       |j                          y	# 1 sw Y   xY w)a>  Issue the appropriate DROP DATABASE statement.

    :param url: A SQLAlchemy engine URL.

    Works similar to the :func:`create_database` method in that both url text
    and a constructed url are accepted.

    ::

        drop_database('postgresql://postgres@localhost/name')
        drop_database(engine.url)

    r   r   rk   r   r   r   r   r   N>   r   r   >   r   r   r   r   r   r   r   r   zDROP DATABASE )r   rl   r   r   r   ro   r   r   rz   remover   r   r   r   r   )rh   rl   r   r   rs   rt   r   s          r   drop_databaser   T  sD    3-C||H??$))L__&--N|#j9		 h7		&k:X%d3N6K$K$GH !!#|D!!#&xH
$:IIh\\^ 	(t#E$$9#:;DLL'	( NN		( 	(s   4EE)*)T)utf8N) r.   rz   collections.abcr   r   r   
sqlalchemyr   sqlalchemy.engine.urlr   sqlalchemy.excr   r   utilsr
   ormr   r   r$   r=   rS   r]   rg   rs   rh   URLro   ru   r   r   r   r    r   r   <module>r      s}     	 -   * =  0BJDNl^gT"299==,, $ 
1HVIX.r   