o
    voiv                     @  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@l/mTZT d(dAlUmVZV d(dBlWmXZX d(dClYmZZZ e[e\Z]G dDdE dEe1Z^G dFdG dGe(Z_e>e.dHdsdOdPZ`e>e_dHdtdQdRZae>e)dHdudTdUZbe>e-dHdvdWdXZce;ddYe:ddYdZe7jefd[G d\d] d]e7jeZge5jhiegdwdadbZje5jkiedxdgdhZldydidjZmdzdmdnZnd{dqdrZod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)_ServerDefaultType)_ReflectedConstraint)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d/fZdfd1d2Zdgd6d7Zdhd;d<Zdid@dA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   )selfrG   rH   rK   colrL   rL   J/home/ubuntu/.local/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namenamed_constraintsdrop_constraint)rU   
batch_implrO   
constraintrL   rL   rW   prep_table_for_batche   s   


z#PostgresqlImpl.prep_table_for_batchc           	      C  s   |j r||jju rdS |}|rtd|r|dd}||k}|r#dS d |||jfv r.| S |jj}t|t	rPt|j
ttfsLtdd|}d| d}t|}| j}|d usYJ |tt||k S )NFnextval\('(.+?)'::regclass\)z
::regclass z^'|'$')primary_keyrO   _autoincrement_columnrematchreplaceserver_defaultarg
isinstancestrtyper   r   subr   
connectionscalarr   )	rU   inspector_columnmetadata_columnrendered_metadata_defaultrendered_inspector_defaultconn_col_defaultdefaults_equalmetadata_defaultconnrL   rL   rW   compare_server_defaultm   s:   

z%PostgresqlImpl.compare_server_defaultNF)
nullableri   r[   type_schemaautoincrementexisting_typeexisting_server_defaultexisting_nullableexisting_autoincrement
table_namerl   column_namerz   Optional[bool]ri   3Optional[Union[_ServerDefaultType, Literal[False]]]r[   Optional[str]r{   Optional[TypeEngine]r|   r}   r~   r   r   r   c       
           sz   | dd }|d ur|d u rtd|d ur&| t||||||	|
|d t j||f||||||	|
||d	| d S )Npostgresql_usingz6postgresql_using must be used with the type_ parameter)r|   usingr~   r   r   )	rz   ri   r[   r|   r}   r~   r   r   r   )popr)   CommandErrorrT   PostgresqlColumnTypesuperr   )rU   r   r   rz   ri   r[   r{   r|   r}   r~   r   r   r   rH   r   	__class__rL   rW   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defaultrm   ra   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   )seqnamer[   z^Detected sequence named '%s' as owned by integer column '%s(%s)', assuming SERIAL and omitting)rN   rk   r   r   rf   rg   r/   _exec_on_inspectorr   groupfirstloginfor[   )rU   	inspectorrO   column_info	seq_matchr   r   colnamerL   rL   rW   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   rN   ).0rG   rL   rL   rW   	<setcomp>  s    
zAPostgresqlImpl.correct_for_autogen_constraints.<locals>.<setcomp>)remover/   sqla_2_skip_functional_indexes)rU   conn_unique_constraintsconn_indexesmetadata_unique_constraintsmetadata_indexesdoubled_constraintsixrL   rL   rW   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"rb   rc   .z::z(::[\w ]+\w)r   ()r   z	cast\s*\(zas\s+[^)]+\) )lowerrh   rO   r[   rf   rn   _default_modifiers_researchspancompilerg   )rU   rG   r   rsrg   startendcast_rerL   rL   rW   _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 )Npostgresql_nulls_not_distinct)nulls_not_distinctrL   )dialect_kwargsrN   )rU   r   rL   rL   rW   _dialect_optionsH  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   _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)   warnr[   r   extendSkipEqual)rU   r   r   msg
unique_msgm_exprsr_exprsskipposm_er_e	m_compilem_text	r_compiler_text	m_options	r_optionsrL   rL   rW   compare_indexesQ  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   )	rU   r   r   metadata_tupreflected_tupmeta_sigconn_sigmetadata_doconn_dorL   rL   rW   compare_unique_constraint  s&   z(PostgresqlImpl.compare_unique_constraintreflected_objectr@   kindDict[str, Any]c                 C  s*   | di  }| ds|dd  |S )Ndialect_optionsrK   )rN   copyr   )rU   r   r   optionsrL   rL   rW    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)rk   rl   r   r   string)rU   r   rL   rL   rW   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   )rk   r   
self_groupr   render_ddl_sql_expr)rU   r   r   r   rH   r   rL   rW   r    s   z"PostgresqlImpl.render_ddl_sql_exprr>   autogen_contextrA   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)rm   
__module__
startswithhasattr__visit_name__getattr)rU   r{   r  modmethrL   rL   rW   render_type  s   


zPostgresqlImpl.render_typer6   c                 C     t tt||ddS )N	text_typez(.+?\(.*text_type=)r   rl   r*   _render_type_w_subtyperU   r{   r  rL   rL   rW   _render_HSTORE_type     z"PostgresqlImpl._render_HSTORE_typer4   c                 C  r  )N	item_typez(.+?\()r  r  rL   rL   rW   _render_ARRAY_type  r  z!PostgresqlImpl._render_ARRAY_typer7   c                 C  r  Nastext_typez(.+?\(.*astext_type=)r  r  rL   rL   rW   _render_JSON_type  r  z PostgresqlImpl._render_JSON_typer8   c                 C  r  r  r  r  rL   rL   rW   _render_JSONB_type  r  z!PostgresqlImpl._render_JSONB_type)rG   r2   rH   r   rI   rJ   )r   rl   r   rl   rz   r   ri   r   r[   r   r{   r   r|   r   r}   r   r~   r   r   r   r   r   r   r   rH   r   rI   rJ   )rG   r2   r   rl   rI   rl   )r   r   rI   r   )r   r2   r   r2   rI   r&   )r   r3   r   r3   rI   r&   )r   r@   r   rl   rI   r   )r   r   rI   rl   )FF)
r   r9   r   r   r   r   rH   r   rI   rl   )r{   r>   r  rA   rI   r  )r{   r6   r  rA   rI   rl   )r{   r4   r  rA   rI   rl   )r{   r7   r  rA   rI   rl   )r{   r8   r  rA   rI   rl   )__name__r  __qualname____dialect__transactional_ddlr'   type_synonymsrX   r`   ry   r   r   r   rf   r   r   r   r   r   r   r   r   r  r  r  r  r  r  __classcell__rL   rL   r   rW   rD   R   sT    
89'

"
	
<

	






rD   c                      s   e Zd Zd
 fdd	Z  ZS )r   r[   rl   r   r{   r>   rI   rJ   c                   s8   | dd }t j||fi | t|| _|| _d S )Nr   )r   r   __init__rR   to_instancer{   r   )rU   r[   r   r{   rH   r   r   rL   rW   r    s   
zPostgresqlColumnType.__init__)r[   rl   r   rl   r{   r>   rI   rJ   )r  r  r  r  r  rL   rL   r   rW   r     s    r   rE   r   r%   compilerr5   rI   rl   c                 K  s"   dt || j| jt|| jd f S )Nz%s RENAME TO %s)r   r   r|   r"   new_table_namer   r!  rH   rL   rL   rW   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 %srb   )r   r   r|   r   r   r#   r{   r   r#  rL   rL   rW   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_valuerR   Stringformatr"   r   r|   r!   r   )r   r!  rH   ddlr'  rL   rL   rW   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 rL   )r   r   r|   r   r   r   r   visit_identity_columnimpl_compare_identity_defaultsortedr.  get_identity_optionsr   r  )r   r!  rH   r   diff_identityattrrL   rL   rW   r0  =  s0   




r0  create_exclude_constraintbatch_create_exclude_constraint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]]r|   r   _orig_constraintOptional[ExcludeConstraint]rI   rJ   c                 K  s.   || _ || _|| _|| _|| _|| _|| _d S rY   )r>  r   rA  rC  r|   rE  rH   )rU   r>  r   rA  rC  r|   rE  rH   rL   rL   rW   r  j  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 rL   rL   )r   r   r[   oprL   rL   rW   
<listcomp>  s    z=CreateExcludeConstraintOp.from_constraint.<locals>.<listcomp>zColumnElement[bool] | None)rC  r|   rE  
deferrable	initiallyr   )
r/   _table_for_constraintr[   _render_exprsr   rC  r|   rI  rJ  r   )clsr_   constraint_tablerL   rL   rW   from_constraint  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)r|   )r[   rC  )rE  r,   SchemaObjectsrO   r   r|   r   rA  r>  rC  rH   rL  rQ   r   r   append_constraint)rU   rP  
schema_objtexclr   r[   operrL   rL   rW   to_constraint  s&   



z'CreateExcludeConstraintOp.to_constraint
operationsr.   rl   r   rH   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)rM  rY  r>  r   rA  rH   rG  rL   rL   rW   r9    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`

        r|   )r1  r|   r   r[  )rM  rY  r>  rA  rH   rG  rL   rL   rW   r:    s   
z9CreateExcludeConstraintOp.batch_create_exclude_constraint)NNN)r>  r?  r   r@  rA  rB  rC  rD  r|   r   rE  rF  rI   rJ   )r_   r   rI   r<  rY   )rP  rQ  rI   r   )rY  r.   r>  rl   r   rl   rA  r   rH   r   rI   rZ  )
rY  r-   r>  rl   rA  r   rH   r   rI   rZ  )r  r  r  __doc__constraint_typer  classmethodrO  rX  r9  r:  rL   rL   rL   rW   r<  `  s    
-r<  r  rA   rG  c                 C  s   t | | ddS )NT)alter)_exclude_constraintrX  )r  rG  rL   rL   rW   _add_exclude_constraint  s   ra  r_   r   namespace_metadatar<   c                 C  s&   t d| |}|dur|S t| |dS )Nr=  F)r*   _user_defined_renderr`  )r_   r  rb  renderedrL   rL   rW   !_render_inline_exclude_constraint  s   re  c                 C  s   | j }|d ur|d dS )Nz*from sqlalchemy.dialects import postgresqlzpostgresql.)importsadd)r  rf  rL   rL   rW   _postgresql_autogenerate_prefix  s   
rh  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 )NrI  rJ  r   r|   r[   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   sqltextr[   opstring)r  rL   rW   rH  "  s    	zC_exclude_constraint.<locals>.do_expr_where_opts.<locals>.<listcomp>zwhere=%sc                 S  s   g | ]
\}}d ||f qS )z%s=%rrL   )r   kvrL   rL   rW   rH  4  s    )rL  rC  r   r*   _render_potential_exprr   )argsr  r_   optsrL   rW   do_expr_where_opts!  s   
	
z/_exclude_constraint.<locals>.do_expr_where_optsz-%(prefix)screate_exclude_constraint(%(args)s)z, )prefixro  z%%(prefix)sExcludeConstraint(%(args)s))
_has_batchrI  r   rl   rJ  r   rO   r|   r*   _identr[   _render_gen_namereprr   _alembic_autogenerate_prefixjoinrh  )r_   r  r_  	has_batchrr  ro  rL   rp  rW   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))rs  r[   )wrap_in_element)	rk   r   
is_literalr*   _sqlalchemy_autogenerate_prefixr[   rn  r   r   )r{  r  templaterL   rL   rW   ri  J  s   
ri  )r   r%   r!  r5   rI   rl   )r   r   r!  r5   rI   rl   )r   r    r!  r5   rI   rl   )r   r$   r!  r5   )r  rA   rG  r<  rI   rl   )r_   r   r  rA   rb  r<   rI   rl   )r  rA   rI   rl   )r_   r   r  rA   r_  r   rI   rl   )r{  r|  r  rA   rI   rl   )p
__future__r   loggingrf   typingr   r   r   r   r   r   r	   r
   r   
sqlalchemyr   r   r   r   r   r   r   r   rR   sqlalchemy.dialects.postgresqlr   r   r   sqlalchemy.schemar   sqlalchemy.sql.elementsr   r   sqlalchemy.sql.functionsr   sqlalchemy.typesr   baser   r   r   r    r!   r"   r#   r$   r%   r1  r&   r'   rb   r)   autogenerater*   rY  r+   r,   operations.baser-   r.   r/   util.sqla_compatr0   r1   r2   r3   $sqlalchemy.dialects.postgresql.arrayr4   #sqlalchemy.dialects.postgresql.baser5   %sqlalchemy.dialects.postgresql.hstorer6   #sqlalchemy.dialects.postgresql.jsonr7   r8   r9   r:   r;   sqlalchemy.sql.schemar<   r=   sqlalchemy.sql.type_apir>   r?   r@   autogenerate.apirA   autogenerate.renderrB   runtime.migrationrC   	getLoggerr  r   rD   r   r$  r%  r-  r0  register_operationAddConstraintOpregister_add_constraintr<  	renderersdispatch_forra  _constraint_renderersre  rh  r`  ri  rL   rL   rL   rW   <module>   s   
   8
	"
 




?