U
    [hC                     @  s  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 er>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% e	dedZ&G dd  d eje& Z'G d!d" d"eZ(d#d$ Z)G d%d& d&ej*e& Z+G d'd( d(e+Z,G d)d* d*e+Z-G d+d, d,e+Z.G d-d. d.e+Z/G d/d0 d0e+Z0G d1d2 d2e+Z1d3S )4    )annotations)Any)Iterable)List)Optional)overload)TYPE_CHECKING)TypeVar   )types)ARRAY   )	coercions)elements)
expression)	functions)roles)schema)ColumnCollectionConstraint)TEXT)InternalTraversal)_ColumnExpressionArgument)ClauseElement)ColumnElement)OperatorType)
FromClause)_CloneCallableType)_TraverseInternalsType_T)Zboundc                   @  s   e Zd ZU dZd ZdZdejfdejfdejfgZ	de
d< edd	d
ddZedd	d
ddZdd	d
ddZd$dddddZdddddZejfddddddZed d!d"d#ZdS )%aggregate_order_bya  Represent a PostgreSQL aggregate order by expression.

    E.g.::

        from sqlalchemy.dialects.postgresql import aggregate_order_by

        expr = func.array_agg(aggregate_order_by(table.c.a, table.c.b.desc()))
        stmt = select(expr)

    would represent the expression:

    .. sourcecode:: sql

        SELECT array_agg(a ORDER BY b DESC) FROM table;

    Similarly::

        expr = func.string_agg(
            table.c.a, aggregate_order_by(literal_column("','"), table.c.a)
        )
        stmt = select(expr)

    Would represent:

    .. sourcecode:: sql

        SELECT string_agg(a, ',' ORDER BY a) FROM table;

    .. versionchanged:: 1.2.13 - the ORDER BY argument may be multiple terms

    .. seealso::

        :class:`_functions.array_agg`

    
postgresqltargettypeorder_byr   _traverse_internalszColumnElement[_T]z_ColumnExpressionArgument[Any]r!   r#   c                 G  s   d S N selfr!   r#   r'   r'   H./venv/lib/python3.8/site-packages/sqlalchemy/dialects/postgresql/ext.py__init__X   s    zaggregate_order_by.__init__z_ColumnExpressionArgument[_T]c                 G  s   d S r&   r'   r(   r'   r'   r*   r+   _   s    c                 G  sn   t tj|| _| jj| _t|}|  |dkr8tdn2|dkrVt tj|d | _nt	j
|dtji| _d S )Nr   z)at least one ORDER BY element is requiredr
   Z_literal_as_text_role)r   expectr   ExpressionElementRoler!   r"   len	TypeErrorr#   r   Z
ClauseList)r)   r!   r#   Z_lobr'   r'   r*   r+   f   s&     

 NzOptional[OperatorType]r   )againstreturnc                 C  s   | S r&   r'   )r)   r0   r'   r'   r*   
self_group}   s    zaggregate_order_by.self_groupr   zIterable[ClauseElement])kwargsr1   c                 K  s   | j | jfS r&   r%   )r)   r3   r'   r'   r*   get_children   s    zaggregate_order_by.get_childrenr   None)clonekwr1   c                 K  s$   || j f|| _ || jf|| _d S r&   r%   )r)   r6   r7   r'   r'   r*   _copy_internals   s    z"aggregate_order_by._copy_internalszList[FromClause])r1   c                 C  s   | j j| jj S r&   )r!   _from_objectsr#   r)   r'   r'   r*   r9      s    z aggregate_order_by._from_objects)N)__name__
__module____qualname____doc____visit_name__Zstringify_dialectr   Zdp_clauseelementZdp_typer$   __annotations__r   r+   r2   r4   r   Z_cloner8   propertyr9   r'   r'   r'   r*   r   *   s&   
$ r   c                      sP   e Zd ZdZdZdZdZdZe	dddd	d
 Z
 fddZdddZ  ZS )ExcludeConstraintzA table-level EXCLUDE constraint.

    Defines an EXCLUDE constraint as described in the `PostgreSQL
    documentation`__.

    __ https://www.postgresql.org/docs/current/static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE

    Zexclude_constraintNFr    wherez:class:`.ExcludeConstraint`z$:paramref:`.ExcludeConstraint.where`c                 O  s   g }g }i | _ t| \}}tttj||D ]V\\}}}	}
}|
dk	rP||
 |dk	r^|jn|	}|dk	rt|| j |< ||||f q.|| _t	j
| f||d|d|dd |dd| _|d}|dk	rttj|| _|d	i | _dS )
a  
        Create an :class:`.ExcludeConstraint` object.

        E.g.::

            const = ExcludeConstraint(
                (Column("period"), "&&"),
                (Column("group"), "="),
                where=(Column("group") != "some group"),
                ops={"group": "my_operator_class"},
            )

        The constraint is normally embedded into the :class:`_schema.Table`
        construct
        directly, or added later using :meth:`.append_constraint`::

            some_table = Table(
                "some_table",
                metadata,
                Column("id", Integer, primary_key=True),
                Column("period", TSRANGE()),
                Column("group", String),
            )

            some_table.append_constraint(
                ExcludeConstraint(
                    (some_table.c.period, "&&"),
                    (some_table.c.group, "="),
                    where=some_table.c.group != "some group",
                    name="some_table_excl_const",
                    ops={"group": "my_operator_class"},
                )
            )

        The exclude constraint defined in this example requires the
        ``btree_gist`` extension, that can be created using the
        command ``CREATE EXTENSION btree_gist;``.

        :param \*elements:

          A sequence of two tuples of the form ``(column, operator)`` where
          "column" is either a :class:`_schema.Column` object, or a SQL
          expression element (e.g. ``func.int8range(table.from, table.to)``)
          or the name of a column as string, and "operator" is a string
          containing the operator to use (e.g. `"&&"` or `"="`).

          In order to specify a column name when a :class:`_schema.Column`
          object is not available, while ensuring
          that any necessary quoting rules take effect, an ad-hoc
          :class:`_schema.Column` or :func:`_expression.column`
          object should be used.
          The ``column`` may also be a string SQL expression when
          passed as :func:`_expression.literal_column` or
          :func:`_expression.text`

        :param name:
          Optional, the in-database name of this constraint.

        :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 using:
          Optional string.  If set, emit USING <index_method> when issuing DDL
          for this constraint. Defaults to 'gist'.

        :param where:
          Optional SQL expression construct or literal SQL string.
          If set, emit WHERE <predicate> when issuing DDL
          for this constraint.

        :param ops:
          Optional dictionary.  Used to define operator classes for the
          elements; works the same way as that of the
          :ref:`postgresql_ops <postgresql_operator_classes>`
          parameter specified to the :class:`_schema.Index` construct.

          .. versionadded:: 1.3.21

          .. seealso::

            :ref:`postgresql_operator_classes` - general description of how
            PostgreSQL operator classes are specified.

        Nname
deferrable	initially)rD   rE   rF   usingZgistrC   ops)	operatorszipr   Z expect_col_expression_collectionr   ZDDLConstraintColumnRoleappendrD   _render_exprsr   r+   getrG   r,   ZStatementOptionRolerC   rH   )r)   r   r7   columnsZrender_exprsZexpressionsrI   exprcolumnZstrnameZadd_elementoperatorrD   rC   r'   r'   r*   r+      s@    _ 


zExcludeConstraint.__init__c                   s&   t     fdd| jD | _d S )Nc                   s0   g | ](\}}}t |ts|n j| ||fqS r'   )
isinstancestrc).0rO   rD   rQ   tabler'   r*   
<listcomp>*  s
   z1ExcludeConstraint._set_parent.<locals>.<listcomp>)super_set_parentrL   )r)   rW   r7   	__class__rV   r*   rZ   '  s    
zExcludeConstraint._set_parentc                   sJ    fdd j D } j| j j j j jd}|j j |S )Nc                   s&   g | ]\}}}t | j|fqS r'   )r   Z_copy_expressionparent)rU   rO   _rQ   r)   target_tabler'   r*   rX   4  s   z+ExcludeConstraint._copy.<locals>.<listcomp>)rD   rE   rF   rC   rG   )	rL   r\   rD   rE   rF   rC   rG   dispatchZ_update)r)   r`   r7   r   rT   r'   r_   r*   _copy3  s    zExcludeConstraint._copy)N)r;   r<   r=   r>   r?   rC   inherit_cacheZcreate_drop_stringify_dialectr   Z_document_text_coercionr+   rZ   rb   __classcell__r'   r'   r[   r*   rB      s   	
 rB   c                  O  s   t |d< tjj| |S )zPostgreSQL-specific form of :class:`_functions.array_agg`, ensures
    return type is :class:`_postgresql.ARRAY` and not
    the plain :class:`_types.ARRAY`, unless an explicit ``type_``
    is passed.

    Z_default_array_type)r   r   func	array_agg)argr7   r'   r'   r*   rf   G  s    rf   c                      s    e Zd ZdZ fddZ  ZS )_regconfig_fnTc                   sn   t |}t|dkrBtjtj|dt dd  tj	d}|g}ng } fdd|D }t
 j|| | d S )Nr
   r   rD   )rD   apply_propagate_attrstype_c              	     s(   g | ] }t jtj|t d d dqS rD   N)rD   ri   r   r,   r   r-   getattrrU   rT   r:   r'   r*   rX   c  s   
z*_regconfig_fn.__init__.<locals>.<listcomp>)listr.   r   r,   r   r-   poprm   r   	REGCONFIGrY   r+   )r)   argsr3   initial_arg
addtl_argsr[   r:   r*   r+   U  s    

	z_regconfig_fn.__init__)r;   r<   r=   rc   r+   rd   r'   r'   r[   r*   rh   R  s   rh   c                   @  s   e Zd ZdZdZejZdS )to_tsvectora  The PostgreSQL ``to_tsvector`` SQL function.

    This function applies automatic casting of the REGCONFIG argument
    to use the :class:`_postgresql.REGCONFIG` datatype automatically,
    and applies a return type of :class:`_postgresql.TSVECTOR`.

    Assuming the PostgreSQL dialect has been imported, either by invoking
    ``from sqlalchemy.dialects import postgresql``, or by creating a PostgreSQL
    engine using ``create_engine("postgresql...")``,
    :class:`_postgresql.to_tsvector` will be used automatically when invoking
    ``sqlalchemy.func.to_tsvector()``, ensuring the correct argument and return
    type handlers are used at compile and execution time.

    .. versionadded:: 2.0.0rc1

    TN)r;   r<   r=   r>   rc   r   ZTSVECTORr"   r'   r'   r'   r*   ru   o  s   ru   c                   @  s   e Zd ZdZdZejZdS )
to_tsquerya  The PostgreSQL ``to_tsquery`` SQL function.

    This function applies automatic casting of the REGCONFIG argument
    to use the :class:`_postgresql.REGCONFIG` datatype automatically,
    and applies a return type of :class:`_postgresql.TSQUERY`.

    Assuming the PostgreSQL dialect has been imported, either by invoking
    ``from sqlalchemy.dialects import postgresql``, or by creating a PostgreSQL
    engine using ``create_engine("postgresql...")``,
    :class:`_postgresql.to_tsquery` will be used automatically when invoking
    ``sqlalchemy.func.to_tsquery()``, ensuring the correct argument and return
    type handlers are used at compile and execution time.

    .. versionadded:: 2.0.0rc1

    TNr;   r<   r=   r>   rc   r   TSQUERYr"   r'   r'   r'   r*   rv     s   rv   c                   @  s   e Zd ZdZdZejZdS )plainto_tsquerya  The PostgreSQL ``plainto_tsquery`` SQL function.

    This function applies automatic casting of the REGCONFIG argument
    to use the :class:`_postgresql.REGCONFIG` datatype automatically,
    and applies a return type of :class:`_postgresql.TSQUERY`.

    Assuming the PostgreSQL dialect has been imported, either by invoking
    ``from sqlalchemy.dialects import postgresql``, or by creating a PostgreSQL
    engine using ``create_engine("postgresql...")``,
    :class:`_postgresql.plainto_tsquery` will be used automatically when
    invoking ``sqlalchemy.func.plainto_tsquery()``, ensuring the correct
    argument and return type handlers are used at compile and execution time.

    .. versionadded:: 2.0.0rc1

    TNrw   r'   r'   r'   r*   ry     s   ry   c                   @  s   e Zd ZdZdZejZdS )phraseto_tsquerya  The PostgreSQL ``phraseto_tsquery`` SQL function.

    This function applies automatic casting of the REGCONFIG argument
    to use the :class:`_postgresql.REGCONFIG` datatype automatically,
    and applies a return type of :class:`_postgresql.TSQUERY`.

    Assuming the PostgreSQL dialect has been imported, either by invoking
    ``from sqlalchemy.dialects import postgresql``, or by creating a PostgreSQL
    engine using ``create_engine("postgresql...")``,
    :class:`_postgresql.phraseto_tsquery` will be used automatically when
    invoking ``sqlalchemy.func.phraseto_tsquery()``, ensuring the correct
    argument and return type handlers are used at compile and execution time.

    .. versionadded:: 2.0.0rc1

    TNrw   r'   r'   r'   r*   rz     s   rz   c                   @  s   e Zd ZdZdZejZdS )websearch_to_tsquerya  The PostgreSQL ``websearch_to_tsquery`` SQL function.

    This function applies automatic casting of the REGCONFIG argument
    to use the :class:`_postgresql.REGCONFIG` datatype automatically,
    and applies a return type of :class:`_postgresql.TSQUERY`.

    Assuming the PostgreSQL dialect has been imported, either by invoking
    ``from sqlalchemy.dialects import postgresql``, or by creating a PostgreSQL
    engine using ``create_engine("postgresql...")``,
    :class:`_postgresql.websearch_to_tsquery` will be used automatically when
    invoking ``sqlalchemy.func.websearch_to_tsquery()``, ensuring the correct
    argument and return type handlers are used at compile and execution time.

    .. versionadded:: 2.0.0rc1

    TNrw   r'   r'   r'   r*   r{     s   r{   c                      s(   e Zd ZdZdZeZ fddZ  ZS )ts_headlinea  The PostgreSQL ``ts_headline`` SQL function.

    This function applies automatic casting of the REGCONFIG argument
    to use the :class:`_postgresql.REGCONFIG` datatype automatically,
    and applies a return type of :class:`_types.TEXT`.

    Assuming the PostgreSQL dialect has been imported, either by invoking
    ``from sqlalchemy.dialects import postgresql``, or by creating a PostgreSQL
    engine using ``create_engine("postgresql...")``,
    :class:`_postgresql.ts_headline` will be used automatically when invoking
    ``sqlalchemy.func.ts_headline()``, ensuring the correct argument and return
    type handlers are used at compile and execution time.

    .. versionadded:: 2.0.0rc1

    Tc                   s   t |}t|dk rd}n,t|d tjrB|d jjtjkrBd}nd}|rxt	j
tj|d t dd tjd}|g}ng } fdd	|D }t j|| | d S )
N   Fr
   Tr   rD   )ri   rD   rj   c              	     s(   g | ] }t jtj|t d d dqS rk   rl   rn   r:   r'   r*   rX     s   
z(ts_headline.__init__.<locals>.<listcomp>)ro   r.   rR   r   r   r"   Z_type_affinityr   rx   r   r,   r   r-   rp   rm   rq   rY   r+   )r)   rr   r3   Zhas_regconfigrs   rt   r[   r:   r*   r+     s.    

	zts_headline.__init__)	r;   r<   r=   r>   rc   r   r"   r+   rd   r'   r'   r[   r*   r|     s   r|   N)2Z
__future__r   typingr   r   r   r   r   r   r	    r   Zarrayr   Zsqlr   r   r   r   r   r   Z
sql.schemar   Zsql.sqltypesr   Zsql.visitorsr   Zsql._typingr   Zsql.elementsr   r   Zsql.operatorsr   Zsql.selectabler   r   r   r   r   rB   rf   ZGenericFunctionrh   ru   rv   ry   rz   r{   r|   r'   r'   r'   r*   <module>   sL   f 8