U
    ^g%it                     @  s6  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'l0m1Z1 d&d(l2m3Z3 d&d)l4m5Z5 d&d*l4m6Z6 d&d+l7m8Z8 d&d,l7m9Z9 d&d-l1m:Z: d&d.l;m<Z< erd d/lm=Z= d d0lm>Z> d d1lm?Z? d d2l@mAZA d d3lBmCZC d d4lDmEZE d d5lFmGZG d d6lFmHZH d d7lmIZI d d8lmJZJ d d9lmKZK d d:lLmMZM d d;lLmNZN d d<lOmPZP dd=l#mQZQ d&d>lRmSZS d&d?lTmUZU d&d@lVmWZW eXeYZZG dAdB dBe/Z[G dCdD dDe&Z\e<e,dEdFdGdHdIdJdKZ]e<e\dEdDdGdHdIdLdMZ^e<e'dEdNdGdHdIdOdPZ_e<e+dEdQdGdRdSdTZ`e9adUe8adUdVe5jbcdWG dXdY dYe5jbZde3jefeddZdYdHd[d\d]Zge3jhfed^dZd_dHd`dadbZidZdHdcdddeZjd^dZdfdHdgdhdiZkdjdZdHdkdldmZldS )n    )annotationsN)Any)cast)Dict)List)Optional)Sequence)Tuple)TYPE_CHECKING)Union)Column)Float)literal_column)Numeric)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ddddd	d
Zdd Zdd Z	dRddddddddddddddd fddZ
dd Zdd Zededed ed!ed"fZdddd#d$d%Zd&d'd(d)d*Zddd+d,d-d.Zd/d/d+d0d1d2Zd3dd3d4d5d6Zd7dd8d9d:ZdSd;d<d<ddd= fd>d?Zd@dAdBdCdDdEZdFdAddCdGdHZdIdAddCdJdKZdLdAddCdMdNZdOdAddCdPdQZ  ZS )TPostgresqlImpl
postgresqlTFLOATzDOUBLE PRECISIONr0   r   None)indexkwreturnc                 K  sR   |j dd pd}|D ]$}||jjkr|jt|tj q| t	|f| d S )Npostgresql_include )
kwargsgettablecappend_columnr   sqltypesZNullType_execr   )selfrE   rF   rH   colrI   rI   U/var/www/html/api-medvista/venv/lib/python3.8/site-packages/alembic/ddl/postgresql.pycreate_indexV   s    
zPostgresqlImpl.create_indexc                 C  s0   |j D ]$}|jd k	r|j|jkr| | qd S N)constraintsnameZnamed_constraintsZdrop_constraint)rQ   Z
batch_implrL   
constraintrI   rI   rS   prep_table_for_batchb   s    

z#PostgresqlImpl.prep_table_for_batchc           	      C  s   |j r||jjkrdS |}||k}|r*dS d |||jfkr@| S |jj}t|trt|jtt	fs|t
dd|}d| d}t|}| j}|d k	st|tt||k S )NFz^'|'$ ')Zprimary_keyrL   Z_autoincrement_columnserver_defaultarg
isinstancestrtyper   r   resubr   
connectionAssertionErrorZscalarr-   _select)	rQ   Zinspector_columnZmetadata_columnZrendered_metadata_defaultZrendered_inspector_defaultZconn_col_defaultZdefaults_equalZmetadata_defaultconnrI   rI   rS   compare_server_defaultj   s8    	


z%PostgresqlImpl.compare_server_defaultNFr_   zOptional[bool]z%Union[_ServerDefault, Literal[False]]Optional[str]zOptional[TypeEngine]zOptional[_ServerDefault])
table_namecolumn_namenullabler\   rW   type_schemaautoincrementexisting_typeexisting_server_defaultexisting_nullableexisting_autoincrementrF   rG   c                   sz   | dd }|d k	r&|d kr&td|d k	rL| t||||||	|
|d t j||f||||||	|
||d	| d S )NZpostgresql_usingz6postgresql_using must be used with the type_ parameter)rm   usingro   rp   rq   )	rk   r\   rW   rm   rn   ro   rp   rq   rr   )popr'   CommandErrorrP   PostgresqlColumnTypesuperr   )rQ   ri   rj   rk   r\   rW   rl   rm   rn   ro   rp   rq   rr   rF   rs   	__class__rI   rS   r      sD    zPostgresqlImpl.alter_columnc                 C  s   | dr~t|d ttfr~td|d }|r~tj|td|	dd
 }|r~|\}}||d kr~td||j| |d= d S )	Ndefaultr`   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   )seqnamerW   z^Detected sequence named '%s' as owned by integer column '%s(%s)', assuming SERIAL and omitting)rK   r^   r   r   ra   matchr-   Z_exec_on_inspectorr   groupfirstloginforW   )rQ   Z	inspectorrL   Zcolumn_infoZ	seq_matchr   r{   ZcolnamerI   rI   rS   autogen_column_reflect   s4      

z%PostgresqlImpl.autogen_column_reflectc                 C  s8   dd |D }|D ]}| | qtjs4| || d S )Nc                 S  s   h | ]}|j d r|qS )Zduplicates_constraint)r   rK   ).0rE   rI   rI   rS   	<setcomp>   s   zAPostgresqlImpl.correct_for_autogen_constraints.<locals>.<setcomp>)remover-   Zsqla_2Z_skip_functional_indexes)rQ   Zconn_unique_constraintsZconn_indexesZmetadata_unique_constraintsZmetadata_indexesZdoubled_constraintsZixrI   rI   rS   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)$)rE   exprrG   c                 C  s*  |  dddd}|jd k	r<||jj   dd}d|krRtdd|}|r||d dkr||d	 d
kr||dd	 }qR| jD ]<}|| }r|d\}}|d | ||d   } qq|r|d dkr|d	 d
kr|dd	 }qt	d}|
|r|d|}tdd|}|dd}|S )N"rZ   r[   .z::z(::[\w ]+\w)r   ()r   z	cast\s*\(zas\s+[^)]+\) )lowerreplacerL   rW   ra   rb   _default_modifiers_researchspancompiler|   )rQ   rE   r   rsr|   startendZcast_rerI   rI   rS   _cleanup_index_expr  s(    


z"PostgresqlImpl._cleanup_index_exprzUnion[Index, UniqueConstraint]zTuple[Any, ...])itemrG   c                 C  s   |j drdS dS )NZpostgresql_nulls_not_distinct)Znulls_not_distinctrI   )Zdialect_kwargsrK   )rQ   r   rI   rI   rS   _dialect_options:  s    zPostgresqlImpl._dialect_optionsr$   )metadata_indexreflected_indexrG   c              
   C  s  g }|  ||}|r|| |j}|j}t|t|krX|dt| dt|  |rft|S g }tt||dD ]\}\}	}
| |	}| 	||}| |
}| 	||}||krqzqz|
 drd|ksd|kr|d| d|d td	| d|d
|jd qz|d| d|d| qz| |}| |}||krl|d| d|  |r|t|S |rt|S t S d 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 )Z_compare_index_uniqueappendZexpressionslenr$   	Different	enumeratezip_compile_elementr   stripendswithr'   warnrW   r   extendZSkipEqual)rQ   r   r   msgZ
unique_msgZm_exprsZr_exprsskipposZm_eZr_eZ	m_compileZm_textZ	r_compileZr_textZ	m_optionsZ	r_optionsrI   rI   rS   compare_indexesC  sT     









zPostgresqlImpl.compare_indexesr1   )metadata_constraintreflected_constraintrG   c           	      C  s|   |  |}| |}|j}|j}||kr>td| d| S | |j}| |j}||krttd| d| S t S )Nzexpression r   )Z_create_metadata_constraint_sigZ _create_reflected_constraint_sigunnamedr$   r   r   constr   )	rQ   r   r   Zmetadata_tupZreflected_tupZmeta_sigZconn_sigZmetadata_doZconn_dorI   rI   rS   compare_unique_constraint  s&    z(PostgresqlImpl.compare_unique_constraintzDict[str, Any])reflected_optionskindrG   c                 C  s*   | di  }| ds&|dd  |S )NZdialect_optionsrH   )rK   copyrt   )rQ   r   r   optionsrI   rI   rS    adjust_reflected_dialect_options  s    
z/PostgresqlImpl.adjust_reflected_dialect_optionszUnion[ClauseElement, str])elementrG   c                 C  s&   t |tr|S |j| jddddjS )NTF)Zliteral_bindsZinclude_table)dialectcompile_kwargs)r^   r_   r   r   string)rQ   r   rI   rI   rS   r     s    
zPostgresqlImpl._compile_elementr7   bool)r   is_server_defaultis_indexrF   rG   c                   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   )r^   r   Z
self_grouprw   render_ddl_sql_expr)rQ   r   r   r   rF   rx   rI   rS   r     s     z"PostgresqlImpl.render_ddl_sql_exprr<   r>   zUnion[str, Literal[False]])rl   autogen_contextrG   c                 C  sF   t |j}|dsdS t| d|j rBt| d|j }|||S dS )Nzsqlalchemy.dialects.postgresqlFz_render_%s_type)r`   
__module__
startswithhasattrZ__visit_name__getattr)rQ   rl   r   modmethrI   rI   rS   render_type  s    


zPostgresqlImpl.render_typer4   c                 C  s   t tt||ddS )N	text_typez(.+?\(.*text_type=)r   r_   r(   Z_render_type_w_subtyperQ   rl   r   rI   rI   rS   _render_HSTORE_type  s       z"PostgresqlImpl._render_HSTORE_typer2   c                 C  s   t tt||ddS )NZ	item_typez(.+?\()r   r   rI   rI   rS   _render_ARRAY_type  s       z!PostgresqlImpl._render_ARRAY_typer5   c                 C  s   t tt||ddS NZastext_typez(.+?\(.*astext_type=)r   r   rI   rI   rS   _render_JSON_type  s       z PostgresqlImpl._render_JSON_typer6   c                 C  s   t tt||ddS r   r   r   rI   rI   rS   _render_JSONB_type  s       z!PostgresqlImpl._render_JSONB_type)
NFNNNNNNNN)FF)__name__r   __qualname__Z__dialect__Ztransactional_ddlr%   Ztype_synonymsrT   rY   rg   r   r   r   ra   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__rI   rI   rx   rS   rA   O   sR   1          .4'"	<	  


rA   c                      s(   e Zd Zddddd fddZ  ZS )rv   r_   r<   rD   )rW   rj   rl   rG   c                   s4   | dd }t j||f| t|| _|| _d S )Nrs   )rt   rw   __init__rO   Zto_instancerl   rs   )rQ   rW   rj   rl   rF   rs   rx   rI   rS   r     s    zPostgresqlColumnType.__init__)r   r   r   r   r   rI   rI   rx   rS   rv     s   rv   rB   r#   r3   r_   )r   compilerrG   c                 K  s"   dt || j| jt|| jd f S )Nz%s RENAME TO %s)r   ri   rm   r    Znew_table_namer   r   rF   rI   rI   rS   visit_rename_table  s    r   c                 K  s@   dt || j| jt|| jdt|| j | jr8d| j ndf S )Nz%s %s %s %szTYPE %szUSING %srZ   )r   ri   rm   r   rj   r!   rl   rs   r   rI   rI   rS   visit_column_type  s    
r   r   c                 K  sJ   d}| j d k	r"|j| j t nd}|jt|| j| jt	|| j
|dS )Nz9COMMENT ON COLUMN {table_name}.{column_name} IS {comment}ZNULL)ri   rj   comment)r   Zsql_compilerZrender_literal_valuerO   Stringformatr    ri   rm   r   rj   )r   r   rF   Zddlr   rI   rI   rS   visit_column_comment  s"       
r   r"   )r   r   c                 K  s   dt || j| jt|| jf }| jd kr6|d7 }|S | jd kr\|d7 }||| j7 }|S | j	| j| j\}}}| j}t
|D ]H}|dkr|d|jrdnd 7 }q|d|tjf |t||i 7 }q|S d S )	Nz%s %s zDROP IDENTITYzADD alwayszSET GENERATED %s ZALWAYSz
BY DEFAULTzSET %s )r   ri   rm   r   rj   rz   rp   visit_identity_columnimplZ_compare_identity_defaultsortedr   Zget_identity_optionsr-   ZIdentityr   )r   r   rF   r   diff_identityattrrI   rI   rS   r   /  s2    


 

r   create_exclude_constraintbatch_create_exclude_constraintZexclude_constraintc                	   @  s   e Zd ZdZdZd!dddddd	d
dddZedd dddZd"dddddZedddddddddZ	edddddddd Z
dS )#CreateExcludeConstraintOpz0Represent a create exclude constraint operation.excludeNzsqla_compat._ConstraintNamezUnion[str, quoted_name]zIUnion[Sequence[Tuple[str, str]], Sequence[Tuple[ColumnClause[Any], str]]]z)Optional[Union[ColumnElement[bool], str]]rh   zOptional[ExcludeConstraint]rD   )constraint_nameri   elementswhererm   _orig_constraintrG   c                 K  s.   || _ || _|| _|| _|| _|| _|| _d S rU   )r   ri   r   r   rm   r   rF   )rQ   r   ri   r   r   rm   r   rF   rI   rI   rS   r   \  s    z"CreateExcludeConstraintOp.__init__r   )rX   rG   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 rI   rI   )r   r   rW   oprI   rI   rS   
<listcomp>y  s    z=CreateExcludeConstraintOp.from_constraint.<locals>.<listcomp>zColumnElement[bool] | None)r   rm   r   
deferrable	initiallyrs   )
r-   Z_table_for_constraintrW   _render_exprsr   r   rm   r   r   rs   )clsrX   Zconstraint_tablerI   rI   rS   from_constraintq  s    

z)CreateExcludeConstraintOp.from_constraintzOptional[MigrationContext])migration_contextrG   c                 C  sx   | j d k	r| j S t|}|j| j| jd}t| j| j| j	d| j
}|jD ]\}}}|t|t qN|| |S )N)rm   )rW   r   )r   r*   ZSchemaObjectsrL   ri   rm   r   r   r   r   rF   r   rN   r   r   Zappend_constraint)rQ   r   Z
schema_objtZexclr   rW   operrI   rI   rS   to_constraint  s&    



z'CreateExcludeConstraintOp.to_constraintr,   r_   r   zOptional[Table])
operationsr   ri   r   rF   rG   c                 O  s   | |||f|}| |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)r   r   r   ri   r   rF   r   rI   rI   rS   r     s    +z3CreateExcludeConstraintOp.create_exclude_constraintr+   )r   r   r   rF   rG   c                 O  s*   |j j|d< | ||j j|f|}||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`

        rm   )r   rm   ri   r   )r   r   r   r   rF   r   rI   rI   rS   r     s    z9CreateExcludeConstraintOp.batch_create_exclude_constraint)NNN)N)r   r   r   __doc__Zconstraint_typer   classmethodr   r   r   r   rI   rI   rI   rS   r   R  s   
    -r   r>   )r   r   rG   c                 C  s   t | | ddS )NT)alter)_exclude_constraintr   )r   r   rI   rI   rS   _add_exclude_constraint  s    r   r   r:   )rX   r   namespace_metadatarG   c                 C  s&   t d| |}|dk	r|S t| |dS )Nr   F)r(   Z_user_defined_renderr   )rX   r   r   renderedrI   rI   rS   !_render_inline_exclude_constraint  s      r   )r   rG   c                 C  s   | j }|d k	r|d dS )Nz*from sqlalchemy.dialects import postgresqlzpostgresql.)importsadd)r   r   rI   rI   rS   _postgresql_autogenerate_prefix  s    
r   r   )rX   r   r   rG   c                   s0  g  j }jr$dtjf jr>dtjf jrXdtjf |s|rjjrdt	jjf |sj
rdt j
f  fdd}|rtt j
g}|s|tt	jj
g7 }||  dt d	|d
 S | }dt d	|d
 S d S )Nr   r   rs   rm   rW   c                    sN    fddj D } jd k	r6| dtj   | dd D  | S )Nc                   s$   g | ]\}}}d t | |f qS )z(%s, %r))_render_potential_column)r   ZsqltextrW   Zopstring)r   rI   rS   r     s   	zC_exclude_constraint.<locals>.do_expr_where_opts.<locals>.<listcomp>zwhere=%sc                 S  s   g | ]\}}d ||f qS )z%s=%rrI   )r   kvrI   rI   rS   r   &  s     )r   r   r   r(   _render_potential_exprr   )argsr   rX   optsrI   rS   do_expr_where_opts  s    
	
 z/_exclude_constraint.<locals>.do_expr_where_optsz-%(prefix)screate_exclude_constraint(%(args)s)z, )prefixr  z%%(prefix)sExcludeConstraint(%(args)s))Z
_has_batchr   r   r_   r   rs   rL   rm   r(   _identrW   Z_render_gen_namereprr   Z_alembic_autogenerate_prefixjoinr   )rX   r   r   Z	has_batchr  r  rI   r  rS   r     s<    
r   zGUnion[ColumnClause[Any], Column[Any], TextClause, FunctionElement[Any]])valuer   rG   c                 C  sN   t | tr0| jrd}nd}|t|| jd S tj| |t | ttfdS d S )Nz"%(prefix)sliteral_column(%(name)r)z%(prefix)scolumn(%(name)r))r	  rW   )Zwrap_in_text)	r^   r   Z
is_literalr(   Z_sqlalchemy_autogenerate_prefixrW   r  r   r   )r  r   templaterI   rI   rS   r  <  s    
r  )m
__future__r   loggingra   typingr   r   r   r   r   r   r	   r
   r   Z
sqlalchemyr   r   r   r   r   r   rO   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%   rZ   r'   Zautogenerater(   r   r)   r*   Zoperations.baser+   r,   r-   Zutil.sqla_compatr.   r/   r0   r1   Z$sqlalchemy.dialects.postgresql.arrayr2   Z#sqlalchemy.dialects.postgresql.baser3   Z%sqlalchemy.dialects.postgresql.hstorer4   Z#sqlalchemy.dialects.postgresql.jsonr5   r6   r7   r8   r9   Zsqlalchemy.sql.schemar:   r;   Zsqlalchemy.sql.type_apir<   r=   Zautogenerate.apir>   Zautogenerate.renderr?   Zruntime.migrationr@   	getLoggerr   r   rA   rv   r   r   r   r   Zregister_operationZAddConstraintOpZregister_add_constraintr   Z	renderersZdispatch_forr   Z_constraint_renderersr   r   r   r  rI   rI   rI   rS   <module>   s   
   -
	" 
 


?