a
    g	gIZ                     @  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/m0Z0 d$d'l1m2Z2 d$d(l1m3Z3 d$d)l4m5Z5 d$d*l4m6Z6 d$d+l.m7Z7 erd d,lm8Z8 d d-l9m:Z: d d.l;m<Z< d d/l=m>Z> d d0l?m@Z@ d d1l?mAZA d d2lmBZB d d3lmCZC d d4lDmEZE d d5lDmFZF d d6lGmHZH dd7l mIZI d$d8lJmKZK d$d9lLmMZM d$d:lNmOZO ePeQZRG d;d< d<e,ZSG d=d> d>e#ZTe%e*d?d@dAdBdCdDdEZUe%eTd?d>dAdBdCdFdGZVe%e$d?dHdAdBdCdIdJZWe%e)d?dKdAdLdMdNZXe6YdOe5YdOdPe2jZ[dQG dRdS dSe2jZZ\e0j]^e\dTdSdBdUdVdWZ_e0j`^edXdTdYdBdZd[d\ZadTdBd]d^d_ZbdXdTd`dBdadbdcZcdddTdBdedfdgZddS )h    )annotationsN)Any)cast)List)Optional)Sequence)Tuple)TYPE_CHECKING)Union)Column)Index)literal_column)Numeric)text)types)BIGINT)ExcludeConstraint)INTEGER)CreateIndex)ColumnClause)
TextClause)NULLTYPE   )alter_column)alter_table)AlterColumn)ColumnComment)compiles)format_column_name)format_table_name)format_type)IdentityColumnDefault)RenameTable)DefaultImpl   )util)render)ops)	schemaobj)BatchOperations)
Operations)sqla_compat)Literal)ARRAY)PGDDLCompiler)HSTORE)JSON)JSONB)BinaryExpression)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Zdd Zdd	 Z	d
d Z
d7ddddddddddddddd fddZdd Zdd Zdddddd Zdd!d" fd#d$Zd%d&d'd(d)d*Zd+d&dd(d,d-Zd.d&dd(d/d0Zd1d&dd(d2d3Zd4d&dd(d5d6Z  ZS )8PostgresqlImpl
postgresqlTFLOATzDOUBLE PRECISION)Zon_nullorderc                 C  sN   |j dd pd}|D ]$}||jjvr|jt|tj q| t	| d S )Npostgresql_include )
kwargsgettablecappend_columnr   sqltypesZNullType_execr   )selfindexr?   colr@   r@   Y/var/www/html/llm_bihealth/app/venv/lib/python3.9/site-packages/alembic/ddl/postgresql.pycreate_indexN   s
    zPostgresqlImpl.create_indexc                 C  s0   |j D ]$}|jd ur|j|jv r| | qd S N)constraintsnameZnamed_constraintsZdrop_constraint)rH   Z
batch_implrC   
constraintr@   r@   rK   prep_table_for_batchX   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rt|jtsxt	
dd|}d| d}t|}| jtt||k S )NFz^'|'$ ')Zprimary_keyrC   Z_autoincrement_columnserver_defaultarg
isinstancestrtyper   resubr   
connectionZscalarr+   _select)rH   Zinspector_columnZmetadata_columnZrendered_metadata_defaultZrendered_inspector_defaultZconn_col_defaultZdefaults_equalZmetadata_defaultr@   r@   rK   compare_server_defaulta   s4    	


z%PostgresqlImpl.compare_server_defaultNFrW   zOptional[bool]z%Union[_ServerDefault, Literal[False]]Optional[str]zOptional[TypeEngine]zOptional[_ServerDefault]r   None)
table_namecolumn_namenullablerT   rO   type_schemaautoincrementexisting_typeexisting_server_defaultexisting_nullableexisting_autoincrementkwreturnc                   sz   | dd }|d ur&|d u r&td|d urL| t||||||	|
|d t j||f||||||	|
||d	| d S )NZpostgresql_usingz6postgresql_using must be used with the type_ parameter)rd   usingrf   rg   rh   )	rb   rT   rO   rd   re   rf   rg   rh   ri   )popr%   CommandErrorrG   PostgresqlColumnTypesuperr   )rH   r`   ra   rb   rT   rO   rc   rd   re   rf   rg   rh   ri   rj   rl   	__class__r@   rK   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defaultrX   znextval\('(.+?)'::regclass\)a+  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.relname=:seqnamer   )seqnamerO   z^Detected sequence named '%s' as owned by integer column '%s(%s)', assuming SERIAL and omitting)rB   rV   r   r   rY   matchr+   Z_exec_on_inspectorr   groupfirstloginforO   )rH   Z	inspectorrC   Zcolumn_infoZ	seq_matchry   rt   Zcolnamer@   r@   rK   autogen_column_reflect   s0    

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)ry   rB   ).0rI   r@   r@   rK   	<setcomp>   s   zAPostgresqlImpl.correct_for_autogen_constraints.<locals>.<setcomp>)remover+   Zsqla_2Z_skip_functional_indexes)rH   Zconn_unique_constraintsZconn_indexesZmetadata_unique_constraintsZmetadata_indexesZdoubled_constraintsixr@   r@   rK   correct_for_autogen_constraints   s    z.PostgresqlImpl.correct_for_autogen_constraintsr   )rI   exprrk   c                 C  s|   |  }|dd}|jd ur8||jj   dd}|rb|d dkrb|d dkrb|dd }q8d	|v rxtd
d|}|S )N"rR   .r   ()r   z::z(::[\w ]+\w))lowerreplacerC   rO   rY   rZ   )rH   rI   r   r@   r@   rK   _cleanup_index_expr   s    
z"PostgresqlImpl._cleanup_index_exprzTuple[Any, ...])rI   rk   c                   s4   t  r$t fdd jD S t  S d S )Nc                 3  s:   | ]2}  t|tr|n|jjd didjV  qdS )Zliteral_bindsT)dialectcompile_kwargsN)r   rV   rW   compiler   string)r{   erI   rH   r@   rK   	<genexpr>  s   
z2PostgresqlImpl.create_index_sig.<locals>.<genexpr>)r+   Zis_expression_indextupleZexpressionsrp   create_index_sig)rH   rI   rq   r   rK   r     s
    

zPostgresqlImpl.create_index_sigr6   r8   zUnion[str, Literal[False]])rc   autogen_contextrk   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)rX   
__module__
startswithhasattrZ__visit_name__getattr)rH   rc   r   modmethr@   r@   rK   render_type  s    


zPostgresqlImpl.render_typer/   c                 C  s   t tt||ddS )N	text_typez(.+?\(.*text_type=)r   rW   r&   Z_render_type_w_subtyperH   rc   r   r@   r@   rK   _render_HSTORE_type)  s    z"PostgresqlImpl._render_HSTORE_typer-   c                 C  s   t tt||ddS )NZ	item_typez(.+?\()r   r   r@   r@   rK   _render_ARRAY_type3  s    z!PostgresqlImpl._render_ARRAY_typer0   c                 C  s   t tt||ddS NZastext_typez(.+?\(.*astext_type=)r   r   r@   r@   rK   _render_JSON_type=  s    z PostgresqlImpl._render_JSON_typer1   c                 C  s   t tt||ddS r   r   r   r@   r@   rK   _render_JSONB_typeG  s    z!PostgresqlImpl._render_JSONB_type)
NFNNNNNNNN)__name__r   __qualname__Z__dialect__Ztransactional_ddlr#   Ztype_synonymsZidentity_attrs_ignorerL   rQ   r]   r   rz   r   r   r   r   r   r   r   r   __classcell__r@   r@   rq   rK   r;   F   s:   
	/          .5&


r;   c                      s(   e Zd Zddddd fddZ  ZS )ro   rW   r6   r_   )rO   ra   rc   rk   c                   s8   | dd }t j||fi | t|| _|| _d S )Nrl   )rm   rp   __init__rF   Zto_instancerc   rl   )rH   rO   ra   rc   rj   rl   rq   r@   rK   r   S  s    zPostgresqlColumnType.__init__)r   r   r   r   r   r@   r@   rq   rK   ro   R  s   ro   r<   r"   r.   rW   )elementcompilerrk   c                 K  s"   dt || j| jt|| jd f S )Nz%s RENAME TO %s)r   r`   rd   r   Znew_table_namer   r   rj   r@   r@   rK   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 %srR   )r   r`   rd   r   ra   r    rc   rl   r   r@   r@   rK   visit_column_typef  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}ZNULL)r`   ra   comment)r   Zsql_compilerZrender_literal_valuerF   Stringformatr   r`   rd   r   ra   )r   r   rj   Zddlr   r@   r@   rK   visit_column_commentr  s    


r   r!   )r   r   c                 K  s   dt || j| jt|| jf }| jd u r6|d7 }|S | jd u r\|d7 }||| j7 }|S | j	| j| j\}}}| j}t
|D ]L}|dkr|d|jrdnd 7 }q|d|tjf i |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   r`   rd   r   ra   rs   rg   visit_identity_columnimplZ_compare_identity_defaultsortedr   Zget_identity_optionsr+   ZIdentityr   )r   r   rj   r   diff_identityattrr@   r@   rK   r     s0    




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 Z
dS )!CreateExcludeConstraintOpz0Represent a create exclude constraint operation.excludeNzsqla_compat._ConstraintNamezUnion[str, quoted_name]zDUnion[Sequence[Tuple[str, str]], Sequence[Tuple[ColumnClause, str]]]&Optional[Union[BinaryExpression, str]]r^   zOptional[ExcludeConstraint]r_   )constraint_namer`   elementswhererd   _orig_constraintrk   c                 K  s.   || _ || _|| _|| _|| _|| _|| _d S rM   )r   r`   r   r   rd   r   rj   )rH   r   r`   r   r   rd   r   rj   r@   r@   rK   r     s    z"CreateExcludeConstraintOp.__init__r   )rP   rk   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 r@   r@   )r{   r   rO   opr@   r@   rK   
<listcomp>  s   z=CreateExcludeConstraintOp.from_constraint.<locals>.<listcomp>r   )r   rd   r   
deferrable	initiallyrl   )
r+   Z_table_for_constraintrO   _render_exprsr   r   rd   r   r   rl   )clsrP   Zconstraint_tabler@   r@   rK   from_constraint  s     
z)CreateExcludeConstraintOp.from_constraintzOptional[MigrationContext])migration_contextrk   c                 C  sx   | j d ur| j S t|}|j| j| jd}t| j| j| j	d| j
}|jD ]\}}}|t|t qN|| |S )N)rd   )rO   r   )r   r(   ZSchemaObjectsrC   r`   rd   r   r   r   r   rj   r   rE   r   r   Zappend_constraint)rH   r   Z
schema_objtZexclr   rO   operr@   r@   rK   to_constraint  s&    



z'CreateExcludeConstraintOp.to_constraintr*   rW   r   zOptional[Table])
operationsr   r`   r   rj   rk   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)r   r   r   r`   r   rj   r   r@   r@   rK   r     s    -z3CreateExcludeConstraintOp.create_exclude_constraintc                 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`

        rd   )r   rd   r`   r   )r   r   r   r   rj   r   r@   r@   rK   r   &  s    z9CreateExcludeConstraintOp.batch_create_exclude_constraint)NNN)N)r   r   r   __doc__Zconstraint_typer   classmethodr   r   r   r   r@   r@   r@   rK   r     s   
    /r   r8   )r   r   rk   c                 C  s   t | | ddS )NT)alter)_exclude_constraintr   )r   r   r@   r@   rK   _add_exclude_constraint:  s    r   r   r4   )rP   r   namespace_metadatark   c                 C  s&   t d| |}|dur|S t| |dS )Nr   F)r&   Z_user_defined_renderr   )rP   r   r   renderedr@   r@   rK   !_render_inline_exclude_constraintA  s    r   )r   rk   c                 C  s   | j }|d ur|d dS )Nz*from sqlalchemy.dialects import postgresqlzpostgresql.)importsadd)r   r   r@   r@   rK   _postgresql_autogenerate_prefixP  s    
r   bool)rP   r   r   rk   c                   s  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 |rDtt | j
g}|s|tt	| jj
g7 }| fdd| jD  | jd ur|dt| j   |d	d |D  d
t d|d S  fdd| jD }| jd ur||dt| j   |dd |D  dt d|d S d S )Nr   r   rl   rd   rO   c                   s$   g | ]\}}}d t | |f qS z(%s, %r)_render_potential_columnr{   ZsqltextrO   Zopstringr   r@   rK   r   u  s   z'_exclude_constraint.<locals>.<listcomp>zwhere=%sc                 S  s   g | ]\}}d ||f qS z%s=%rr@   r{   kvr@   r@   rK   r         z-%(prefix)screate_exclude_constraint(%(args)s)z, )prefixargsc                   s$   g | ]\}}}d t | |f qS r   r   r   r   r@   rK   r     s   c                 S  s   g | ]\}}d ||f qS r   r@   r   r@   r@   rK   r     r   z%%(prefix)sExcludeConstraint(%(args)s))Z
_has_batchr   appendrW   r   rl   rC   rd   r&   _identrO   Z_render_gen_namereprextendr   r   _render_potential_exprZ_alembic_autogenerate_prefixjoinr   )rP   r   r   optsZ	has_batchr   r@   r   rK   r   X  sj    



r   z'Union[ColumnClause, Column, TextClause])valuer   rk   c                 C  sJ   t | tr0| jrd}nd}|t|| jd S tj| |t | tdS d S )Nz"%(prefix)sliteral_column(%(name)r)z%(prefix)scolumn(%(name)r))r   rO   )Zwrap_in_text)rV   r   Z
is_literalr&   Z_sqlalchemy_autogenerate_prefixrO   r   r   )r   r   templater@   r@   rK   r     s    
r   )e
__future__r   loggingrY   typingr   r   r   r   r   r   r	   r
   Z
sqlalchemyr   r   r   r   r   r   rF   Zsqlalchemy.dialects.postgresqlr   r   r   Zsqlalchemy.schemar   Zsqlalchemy.sql.elementsr   r   Zsqlalchemy.typesr   baser   r   r   r   r   r   r   r    r!   r"   r   r#   rR   r%   Zautogenerater&   r   r'   r(   Zoperations.baser)   r*   r+   r,   Z$sqlalchemy.dialects.postgresql.arrayr-   Z#sqlalchemy.dialects.postgresql.baser.   Z%sqlalchemy.dialects.postgresql.hstorer/   Z#sqlalchemy.dialects.postgresql.jsonr0   r1   r2   r3   Zsqlalchemy.sql.schemar4   r5   Zsqlalchemy.sql.type_apir6   r7   Zautogenerate.apir8   Zautogenerate.renderr9   Zruntime.migrationr:   	getLoggerr   rx   r;   ro   r   r   r   r   Zregister_operationZAddConstraintOpZregister_add_constraintr   Z	renderersZdispatch_forr   Z_constraint_renderersr   r   r   r   r@   r@   r@   rK   <module>   s   
  
	"
 

F