o
    8 ht                     @  s  d dl mZ d dlZd dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlm	Z	 d dlm
Z
 d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlm Z  d dl!m"Z" d dl#m$Z$ ddl%m&Z& ddl%m'Z' ddl%m(Z( dd l%m)Z) dd!l%m*Z* dd"l%m+Z+ dd#l%m,Z, dd$l%m-Z- dd%l%m.Z. dd&l/m0Z0 dd'l/m1Z1 d(d)l2m3Z3 d(d*l4m5Z5 d(d+l6m7Z7 d(d,l6m8Z8 d(d-l9m:Z: d(d.l9m;Z; d(d/l3m<Z< d(d0l=m>Z> erd d1lm?Z? d d2lm@Z@ d d3lmAZA d d4lBmCZC d d5lDmEZE d d6lFmGZG d d7lHmIZI d d8lHmJZJ d d9lmKZK d d:lmLZL d d;lmMZM d d<lNmOZO d d=lNmPZP d d>lQmRZR dd?l%mSZS d(d@lTmUZU d(dAlVmWZW d(dBlXmYZY eZe[Z\G dCdD dDe1Z]G dEdF dFe(Z^e>e.dGdrdNdOZ_e>e^dGdsdPdQZ`e>e)dGdtdSdTZae>e-dGdudVdWZbe;cdXe:cdXdYe7jdedZG d[d\ d\e7jdZfe5jghefdvd`daZie5jjhedwdfdgZkdxdhdiZldydldmZmdzdpdqZndS ){    )annotationsN)Any)cast)Dict)List)Optional)Sequence)Tuple)TYPE_CHECKING)Union)Column)Float)Identity)literal_column)Numeric)select)text)types)BIGINT)ExcludeConstraint)INTEGER)CreateIndex)ColumnClause)
TextClause)FunctionElement)NULLTYPE   )alter_column)alter_table)AlterColumn)ColumnComment)format_column_name)format_table_name)format_type)IdentityColumnDefault)RenameTable)ComparisonResult)DefaultImpl   )util)render)ops)	schemaobj)BatchOperations)
Operations)sqla_compat)compiles)Literal)Index)UniqueConstraint)ARRAY)PGDDLCompiler)HSTORE)JSON)JSONB)ClauseElement)ColumnElement)quoted_name)MetaData)Table)
TypeEngine)_ServerDefault)AutogenContext)_f_name)MigrationContextc                      s&  e Zd ZdZdZejddhf ZddddZdd Zdd Z	ddddddddddd
de fd&d'Z
d(d) Zd*d+ Zed,ed-ed.ed/ed0fZdfd2d3Zdgd7d8Zdhd<d=ZdidAdBZdjdFdGZdkdJdKZ		dldm fdPdQZdndVdWZdodYdZZdpd\d]Zdqd_d`ZdrdbdcZ  ZS )sPostgresqlImpl
postgresqlTFLOATzDOUBLE PRECISIONindexr2   kwr   returnNonec                 K  sV   |j dd pd}|D ]}||jjvr|jt|tj q| t	|fi | d S )Npostgresql_include )
kwargsgettablecappend_columnr   sqltypesNullType_execr   )selfrF   rG   rJ   colrK   rK   ^/var/www/html/figdemos/bartoux_crm/venv/lib/python3.10/site-packages/alembic/ddl/postgresql.pycreate_indexY   s   
zPostgresqlImpl.create_indexc                 C  s0   |j D ]}|jd ur|j|jv r| | qd S N)constraintsnameZnamed_constraintsdrop_constraint)rT   
batch_implrN   
constraintrK   rK   rV   prep_table_for_batche   s   


z#PostgresqlImpl.prep_table_for_batchc           	      C  s   |j r||jju rdS |}||k}|rdS d |||jfv r | S |jj}t|trBt|jtt	fs>t
dd|}d| d}t|}| j}|d usKJ |tt||k S )NFz^'|'$ ')primary_keyrN   _autoincrement_columnserver_defaultarg
isinstancestrtyper   r   resubr   
connectionscalarr   )	rT   inspector_columnmetadata_columnrendered_metadata_defaultrendered_inspector_defaultZconn_col_defaultZdefaults_equalmetadata_defaultconnrK   rK   rV   compare_server_defaultm   s2   	
z%PostgresqlImpl.compare_server_defaultNF)
nullablerc   rZ   type_schemaautoincrementexisting_typeexisting_server_defaultexisting_nullableexisting_autoincrement
table_namerf   column_namers   Optional[bool]rc   /Optional[Union[_ServerDefault, Literal[False]]]rZ   Optional[str]rt   Optional[TypeEngine]ru   rv   rw   rx   Optional[_ServerDefault]ry   rz   c       
           sz   | dd }|d ur|d u rtd|d ur&| t||||||	|
|d t j||f||||||	|
||d	| d S )NZpostgresql_usingz6postgresql_using must be used with the type_ parameter)ru   usingrw   rx   ry   )	rs   rc   rZ   ru   rv   rw   rx   ry   rz   )popr)   CommandErrorrS   PostgresqlColumnTypesuperr   )rT   r{   r|   rs   rc   rZ   rt   ru   rv   rw   rx   ry   rz   rG   r   	__class__rK   rV   r      sD   
zPostgresqlImpl.alter_columnc                 C  s   | drAt|d ttfrCtd|d }|rEtj|td|	dd
 }|rG|\}}||d krItd||j| |d= d S d S d S d S d S d S )	Ndefaultrg   znextval\('(.+?)'::regclass\)a9  select c.relname, a.attname from pg_class as c join pg_depend d on d.objid=c.oid and d.classid='pg_class'::regclass and d.refclassid='pg_class'::regclass join pg_class t on t.oid=d.refobjid join pg_attribute a on a.attrelid=t.oid and a.attnum=d.refobjsubid where c.relkind='S' and c.oid=cast(:seqname as regclass)r   )seqnamerZ   z^Detected sequence named '%s' as owned by integer column '%s(%s)', assuming SERIAL and omitting)rM   re   r   r   rh   matchr/   _exec_on_inspectorr   groupfirstloginforZ   )rT   	inspectorrN   column_infoZ	seq_matchr   r   colnamerK   rK   rV   autogen_column_reflect   s<   

z%PostgresqlImpl.autogen_column_reflectc                 C  s<   dd |D }|D ]}| | q	tjs| || d S d S )Nc                 S  s   h | ]
}|j d r|qS )duplicates_constraint)r   rM   ).0rF   rK   rK   rV   	<setcomp>   s    
zAPostgresqlImpl.correct_for_autogen_constraints.<locals>.<setcomp>)remover/   sqla_2_skip_functional_indexes)rT   conn_unique_constraintsconn_indexesmetadata_unique_constraintsmetadata_indexesZdoubled_constraintsixrK   rK   rV   correct_for_autogen_constraints   s   z.PostgresqlImpl.correct_for_autogen_constraintsz( asc nulls last)$z(?<! desc)( nulls last)$z( asc)$z( asc) nulls first$z desc( nulls first)$exprc                 C  s\  |  dddd}|jd ur||jj   dd}d|v r)tdd|}|rK|d dkrK|d	 d
krK|dd	 }|rK|d dkrK|d	 d
ks7| jD ]}|| }rl|d\}}|d | ||d   } nqN|r|d dkr|d	 d
kr|dd	 }|r|d dkr|d	 d
ks{t	d}|
|r|d|}tdd|}|dd}|S )N"r_   r`   .z::z(::[\w ]+\w)r   ()r   z	cast\s*\(zas\s+[^)]+\) )lowerreplacerN   rZ   rh   ri   _default_modifiers_researchspancompiler   )rT   rF   r   Zrsr   startendZcast_rerK   rK   rV   _cleanup_index_expr  s.   



z"PostgresqlImpl._cleanup_index_expritemUnion[Index, UniqueConstraint]Tuple[Any, ...]c                 C  s   |j drdS dS )NZpostgresql_nulls_not_distinct)Znulls_not_distinctrK   )dialect_kwargsrM   )rT   r   rK   rK   rV   _dialect_options>  s   zPostgresqlImpl._dialect_optionsmetadata_indexreflected_indexr&   c              
   C  s  g }|  ||}|r|| |j}|j}t|t|kr,|dt| dt|  |r3t|S g }tt||dD ][\}\}	}
| |	}| 	||}| |
}| 	||}||kr^q=|
 drd|v smd|v r|d| d|d td	| d|d
|jd q=|d| d|d| q=| |}| |}||kr|d| d|  |rt|S |rt|S t S )Nzexpression number  to r   Z_opsr   r   zexpression #z' detected as including operator clause.zExpression #z
 in index a   detected to include an operator clause. Expression compare cannot proceed. Please move the operator clause to the ``postgresql_ops`` dict to enable proper compare of the index expressions: https://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#operator-classeszoptions )_compare_index_uniqueappendexpressionslenr&   	Different	enumeratezip_compile_elementr   stripendswithr)   warnrZ   r   extendSkipEqual)rT   r   r   msg
unique_msgZm_exprsZr_exprsskipposZm_eZr_eZ	m_compileZm_textZ	r_compileZr_textZ	m_optionsZ	r_optionsrK   rK   rV   compare_indexesG  sP   








zPostgresqlImpl.compare_indexesmetadata_constraintr3   reflected_constraintc           	      C  s|   |  |}| |}|j}|j}||krtd| d| S | |j}| |j}||kr:td| d| S t S )Nzexpression r   )_create_metadata_constraint_sig _create_reflected_constraint_sigunnamedr&   r   r   constr   )	rT   r   r   metadata_tupreflected_tupmeta_sigconn_sigZmetadata_doZconn_dorK   rK   rV   compare_unique_constraint  s&   z(PostgresqlImpl.compare_unique_constraintreflected_optionsDict[str, Any]kindc                 C  s*   | di  }| ds|dd  |S )Ndialect_optionsrJ   )rM   copyr   )rT   r   r   optionsrK   rK   rV    adjust_reflected_dialect_options  s   
z/PostgresqlImpl.adjust_reflected_dialect_optionselementUnion[ClauseElement, str]c                 C  s&   t |tr|S |j| jddddjS )NTF)literal_bindsinclude_table)dialectcompile_kwargs)re   rf   r   r   string)rT   r   rK   rK   rV   r     s   
zPostgresqlImpl._compile_elementr9   is_server_defaultboolis_indexc                   s0   |rt |ts| }t j|f||d|S )zdRender a SQL expression that is typically a server default,
        index expression, etc.

        )r   r   )re   r   
self_groupr   render_ddl_sql_expr)rT   r   r   r   rG   r   rK   rV   r     s   z"PostgresqlImpl.render_ddl_sql_exprr>   autogen_contextr@   Union[str, Literal[False]]c                 C  sF   t |j}|dsdS t| d|j r!t| d|j }|||S dS )Nzsqlalchemy.dialects.postgresqlFz_render_%s_type)rg   
__module__
startswithhasattr__visit_name__getattr)rT   rt   r   modmethrK   rK   rV   render_type  s   


zPostgresqlImpl.render_typer6   c                 C     t tt||ddS )NZ	text_typez(.+?\(.*text_type=)r   rf   r*   Z_render_type_w_subtyperT   rt   r   rK   rK   rV   _render_HSTORE_type     z"PostgresqlImpl._render_HSTORE_typer4   c                 C  r   )N	item_typez(.+?\()r   r   rK   rK   rV   _render_ARRAY_type  r   z!PostgresqlImpl._render_ARRAY_typer7   c                 C  r   NZastext_typez(.+?\(.*astext_type=)r   r   rK   rK   rV   _render_JSON_type  r   z PostgresqlImpl._render_JSON_typer8   c                 C  r   r   r   r   rK   rK   rV   _render_JSONB_type  r   z!PostgresqlImpl._render_JSONB_type)rF   r2   rG   r   rH   rI   )r{   rf   r|   rf   rs   r}   rc   r~   rZ   r   rt   r   ru   r   rv   r}   rw   r   rx   r   ry   r}   rz   r}   rG   r   rH   rI   )rF   r2   r   rf   rH   rf   )r   r   rH   r   )r   r2   r   r2   rH   r&   )r   r3   r   r3   rH   r&   )r   r   r   rf   rH   r   )r   r   rH   rf   )FF)
r   r9   r   r   r   r   rG   r   rH   rf   )rt   r>   r   r@   rH   r   )rt   r6   r   r@   rH   rf   )rt   r4   r   r@   rH   rf   )rt   r7   r   r@   rH   rf   )rt   r8   r   r@   rH   rf   )__name__r   __qualname____dialect__transactional_ddlr'   type_synonymsrW   r^   rr   r   r   r   rh   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__rK   rK   r   rV   rC   R   sT    
07'

"
	
<

	






rC   c                      s   e Zd Zd
 fdd	Z  ZS )r   rZ   rf   r|   rt   r>   rH   rI   c                   s8   | dd }t j||fi | t|| _|| _d S )Nr   )r   r   __init__rQ   to_instancert   r   )rT   rZ   r|   rt   rG   r   r   rK   rV   r    s   
zPostgresqlColumnType.__init__)rZ   rf   r|   rf   rt   r>   rH   rI   )r   r   r   r  r  rK   rK   r   rV   r     s    r   rD   r   r%   compilerr5   rH   rf   c                 K  s"   dt || j| jt|| jd f S )Nz%s RENAME TO %s)r   r{   ru   r"   new_table_namer   r  rG   rK   rK   rV   visit_rename_table  s   r	  c                 K  sD   dt || j| jt|| jdt|| j | jrd| j f S df S )Nz%s %s %s %szTYPE %szUSING %sr_   )r   r{   ru   r   r|   r#   rt   r   r  rK   rK   rV   visit_column_type  s   
r
  r    c                 K  sJ   d}| j d ur|j| j t nd}|jt|| j| jt	|| j
|dS )Nz9COMMENT ON COLUMN {table_name}.{column_name} IS {comment}NULL)r{   r|   comment)r  sql_compilerrender_literal_valuerQ   Stringformatr"   r{   ru   r!   r|   )r   r  rG   ddlr  rK   rK   rV   visit_column_comment  s   



r  r$   c                 K  s   dt || j| jt|| jf }| jd u r|d7 }|S | jd u r.|d7 }||| j7 }|S | j	| j| j\}}}| j}t
|D ]%}|dkrS|d|jrNdnd 7 }qA|d|td	i |t||i 7 }qA|S )
Nz%s %s zDROP IDENTITYzADD alwayszSET GENERATED %s ALWAYSz
BY DEFAULTzSET %s rK   )r   r{   ru   r   r|   r   rx   visit_identity_columnimpl_compare_identity_defaultsortedr  get_identity_optionsr   r   )r   r  rG   r   diff_identityattrrK   rK   rV   r  3  s0   




r  create_exclude_constraintbatch_create_exclude_constraintZexclude_constraintc                   @  s^   e Zd ZdZdZ			d'd(ddZed)ddZ	d*d+ddZed,d"d#Z	ed-d%d&Z
dS ).CreateExcludeConstraintOpz0Represent a create exclude constraint operation.excludeNconstraint_namesqla_compat._ConstraintNamer{   Union[str, quoted_name]elementsIUnion[Sequence[Tuple[str, str]], Sequence[Tuple[ColumnClause[Any], str]]]where)Optional[Union[ColumnElement[bool], str]]ru   r   _orig_constraintOptional[ExcludeConstraint]rH   rI   c                 K  s.   || _ || _|| _|| _|| _|| _|| _d S rX   )r"  r{   r%  r'  ru   r)  rG   )rT   r"  r{   r%  r'  ru   r)  rG   rK   rK   rV   r  `  s   
z"CreateExcludeConstraintOp.__init__r]   r   c                 C  sD   t |}| |j|jdd |jD td|j|j||j|j|j	d	S )Nc                 S  s   g | ]	\}}}||fqS rK   rK   )r   r   rZ   oprK   rK   rV   
<listcomp>}  s    z=CreateExcludeConstraintOp.from_constraint.<locals>.<listcomp>zColumnElement[bool] | None)r'  ru   r)  
deferrable	initiallyr   )
r/   _table_for_constraintrZ   _render_exprsr   r'  ru   r-  r.  r   )clsr]   Zconstraint_tablerK   rK   rV   from_constraintu  s   

z)CreateExcludeConstraintOp.from_constraintmigration_contextOptional[MigrationContext]c                 C  sx   | j d ur| j S t|}|j| j| jd}t| j| j| j	d| j
}|jD ]\}}}|t|t q'|| |S )N)ru   )rZ   r'  )r)  r,   ZSchemaObjectsrN   r{   ru   r   r%  r"  r'  rG   r0  rP   r   r   append_constraint)rT   r3  Z
schema_objtZexclr   rZ   ZoperrK   rK   rV   to_constraint  s&   



z'CreateExcludeConstraintOp.to_constraint
operationsr.   rf   r   rG   Optional[Table]c                 O  s   | |||fi |}| |S )a  Issue an alter to create an EXCLUDE constraint using the
        current migration context.

        .. note::  This method is Postgresql specific, and additionally
           requires at least SQLAlchemy 1.0.

        e.g.::

            from alembic import op

            op.create_exclude_constraint(
                "user_excl",
                "user",
                ("period", "&&"),
                ("group", "="),
                where=("group != 'some group'"),
            )

        Note that the expressions work the same way as that of
        the ``ExcludeConstraint`` object itself; if plain strings are
        passed, quoting rules must be applied manually.

        :param name: Name of the constraint.
        :param table_name: String name of the source table.
        :param elements: exclude conditions.
        :param where: SQL expression or SQL string with optional WHERE
         clause.
        :param deferrable: optional bool. If set, emit DEFERRABLE or
         NOT DEFERRABLE when issuing DDL for this constraint.
        :param initially: optional string. If set, emit INITIALLY <value>
         when issuing DDL for this constraint.
        :param schema: Optional schema name to operate within.

        )invoke)r1  r8  r"  r{   r%  rG   r+  rK   rK   rV   r    s   +
z3CreateExcludeConstraintOp.create_exclude_constraintr-   c                 O  s.   |j j|d< | ||j j|fi |}||S )a3  Issue a "create exclude constraint" instruction using the
        current batch migration context.

        .. note::  This method is Postgresql specific, and additionally
           requires at least SQLAlchemy 1.0.

        .. seealso::

            :meth:`.Operations.create_exclude_constraint`

        ru   )r  ru   r{   r:  )r1  r8  r"  r%  rG   r+  rK   rK   rV   r    s   
z9CreateExcludeConstraintOp.batch_create_exclude_constraint)NNN)r"  r#  r{   r$  r%  r&  r'  r(  ru   r   r)  r*  rH   rI   )r]   r   rH   r   rX   )r3  r4  rH   r   )r8  r.   r"  rf   r{   rf   r%  r   rG   r   rH   r9  )
r8  r-   r"  rf   r%  r   rG   r   rH   r9  )r   r   r   __doc__Zconstraint_typer  classmethodr2  r7  r  r  rK   rK   rK   rV   r   V  s    
-r   r   r@   r+  c                 C  s   t | | ddS )NT)alter)_exclude_constraintr7  )r   r+  rK   rK   rV   _add_exclude_constraint  s   r?  r]   r   namespace_metadatar<   c                 C  s&   t d| |}|dur|S t| |dS )Nr!  F)r*   Z_user_defined_renderr>  )r]   r   r@  renderedrK   rK   rV   !_render_inline_exclude_constraint  s   rB  c                 C  s   | j }|d ur|d dS )Nz*from sqlalchemy.dialects import postgresqlzpostgresql.)importsadd)r   rC  rK   rK   rV   _postgresql_autogenerate_prefix  s   
rE  r=  r   c                   s*  g  j }jrdtjf jrdtjf jr,dtjf |s@|r@jjr@dt	jjf |sQj
rQdt j
f  fdd}|rtt j
g}|ss|tt	jj
g7 }||  dt d	|d
 S | }dt d	|d
 S )Nr-  r.  r   ru   rZ   c                    sN    fddj D } jd ur| dtj   | dd D  | S )Nc                   s$   g | ]\}}}d t | |f qS )z(%s, %r))_render_potential_column)r   sqltextrZ   opstring)r   rK   rV   r,    s    	zC_exclude_constraint.<locals>.do_expr_where_opts.<locals>.<listcomp>zwhere=%sc                 S  s   g | ]
\}}d ||f qS )z%s=%rrK   )r   kvrK   rK   rV   r,  *  s    )r0  r'  r   r*   _render_potential_exprr   )argsr   r]   optsrK   rV   do_expr_where_opts  s   
	
z/_exclude_constraint.<locals>.do_expr_where_optsz-%(prefix)screate_exclude_constraint(%(args)s)z, )prefixrL  z%%(prefix)sExcludeConstraint(%(args)s))Z
_has_batchr-  r   rf   r.  r   rN   ru   r*   _identrZ   Z_render_gen_namereprr   Z_alembic_autogenerate_prefixjoinrE  )r]   r   r=  Z	has_batchrO  rL  rK   rM  rV   r>    s<   
r>  valueGUnion[ColumnClause[Any], Column[Any], TextClause, FunctionElement[Any]]c                 C  sJ   t | tr| jrd}nd}|t|| jd S tj| |t | ttfdS )Nz"%(prefix)sliteral_column(%(name)r)z%(prefix)scolumn(%(name)r))rP  rZ   )Zwrap_in_element)	re   r   
is_literalr*   Z_sqlalchemy_autogenerate_prefixrZ   rK  r   r   )rT  r   templaterK   rK   rV   rF  @  s   
rF  )r   r%   r  r5   rH   rf   )r   r   r  r5   rH   rf   )r   r    r  r5   rH   rf   )r   r$   r  r5   )r   r@   r+  r   rH   rf   )r]   r   r   r@   r@  r<   rH   rf   )r   r@   rH   rf   )r]   r   r   r@   r=  r   rH   rf   )rT  rU  r   r@   rH   rf   )o
__future__r   loggingrh   typingr   r   r   r   r   r   r	   r
   r   
sqlalchemyr   r   r   r   r   r   r   r   rQ   Zsqlalchemy.dialects.postgresqlr   r   r   Zsqlalchemy.schemar   Zsqlalchemy.sql.elementsr   r   Zsqlalchemy.sql.functionsr   Zsqlalchemy.typesr   baser   r   r   r    r!   r"   r#   r$   r%   r  r&   r'   r_   r)   autogenerater*   r8  r+   r,   Zoperations.baser-   r.   r/   Zutil.sqla_compatr0   r1   r2   r3   Z$sqlalchemy.dialects.postgresql.arrayr4   Z#sqlalchemy.dialects.postgresql.baser5   Z%sqlalchemy.dialects.postgresql.hstorer6   Z#sqlalchemy.dialects.postgresql.jsonr7   r8   r9   r:   r;   sqlalchemy.sql.schemar<   r=   sqlalchemy.sql.type_apir>   r?   autogenerate.apir@   Zautogenerate.renderrA   Zruntime.migrationrB   	getLoggerr   r   rC   r   r	  r
  r  r  Zregister_operationZAddConstraintOpZregister_add_constraintr   Z	renderersdispatch_forr?  Z_constraint_renderersrB  rE  r>  rF  rK   rK   rK   rV   <module>   s   
   .
	"
 




?