o
    Rc+9                     @   s   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	 ej
fd	d
Zej
fddZG dd dejejZejddddZejddddZejddddZG dd dejZdd ZdS )    N   )types)util)	coercions)
expression)	operators)rolesc                 C      | | |S )zjA synonym for the ARRAY-level :meth:`.ARRAY.Comparator.any` method.
    See that method for details.

    )anyotherZarrexproperator r   FD:\Flask\env\Lib\site-packages\sqlalchemy/dialects/postgresql/array.pyAny      r   c                 C   r	   )zjA synonym for the ARRAY-level :meth:`.ARRAY.Comparator.all` method.
    See that method for details.

    )allr   r   r   r   All   r   r   c                       sL   e Zd ZdZd ZdZdZ fddZedd Z	dd
dZ
dddZ  ZS )arraya  A PostgreSQL ARRAY literal.

    This is used to produce ARRAY literals in SQL expressions, e.g.::

        from sqlalchemy.dialects.postgresql import array
        from sqlalchemy.dialects import postgresql
        from sqlalchemy import select, func

        stmt = select(array([1,2]) + array([3,4,5]))

        print(stmt.compile(dialect=postgresql.dialect()))

    Produces the SQL::

        SELECT ARRAY[%(param_1)s, %(param_2)s] ||
            ARRAY[%(param_3)s, %(param_4)s, %(param_5)s]) AS anon_1

    An instance of :class:`.array` will always have the datatype
    :class:`_types.ARRAY`.  The "inner" type of the array is inferred from
    the values present, unless the ``type_`` keyword argument is passed::

        array(['foo', 'bar'], type_=CHAR)

    Multidimensional arrays are produced by nesting :class:`.array` constructs.
    The dimensionality of the final :class:`_types.ARRAY`
    type is calculated by
    recursively adding the dimensions of the inner :class:`_types.ARRAY`
    type::

        stmt = select(
            array([
                array([1, 2]), array([3, 4]), array([column('q'), column('x')])
            ])
        )
        print(stmt.compile(dialect=postgresql.dialect()))

    Produces::

        SELECT ARRAY[ARRAY[%(param_1)s, %(param_2)s],
        ARRAY[%(param_3)s, %(param_4)s], ARRAY[q, x]] AS anon_1

    .. versionadded:: 1.3.6 added support for multidimensional array literals

    .. seealso::

        :class:`_postgresql.ARRAY`

    
postgresqlTc                    s   dd |D }t t| j|i | dd |D | _|d| jr%| jd ntj}t|trBt|j	|j
d ur;|j
d ndd| _d S t|| _d S )	Nc                 S   s   g | ]	}t tj|qS r   )r   expectr   ZExpressionElementRole).0cr   r   r   
<listcomp>]   s    z"array.__init__.<locals>.<listcomp>c                 S   s   g | ]}|j qS r   )type)r   argr   r   r   r   c   s    type_r         )
dimensions)superr   __init__Z_type_tuplepopsqltypesZNULLTYPE
isinstanceARRAY	item_typer   r   )selfZclauseskwZ	main_type	__class__r   r   r!   \   s"   
zarray.__init__c                 C   s   | fS Nr   r'   r   r   r   _select_iterables      zarray._select_iterableFNc                    s@   |s t ju rtjd | jddS t fdd|D S )NT)Z_compared_to_operatorr   Z_compared_to_typeuniquec                    s   g | ]}j  |d dqS )T)_assume_scalarr   )_bind_param)r   or   r'   r   r   r   r      s    z%array._bind_param.<locals>.<listcomp>)r   getitemr   ZBindParameterr   r   )r'   r   objr0   r   r   r3   r   r1   w   s   
zarray._bind_paramc                 C   s"   |t jt jt jfv rt| S | S r+   )r   Zany_opZall_opr4   r   ZGrouping)r'   Zagainstr   r   r   
self_group   s   
zarray.self_group)FNr+   )__name__
__module____qualname____doc__Z__visit_name__Zstringify_dialectZinherit_cacher!   propertyr-   r1   r6   __classcell__r   r   r)   r   r   $   s    1

r   z@>   T)
precedenceZis_comparisonz<@z&&c                   @   s   e Zd ZdZG dd dejjZeZ	dddZe	dd	 Z
e	d
d Zdd Zdd Zejdd Zdd Zdd Zdd ZdS )r%   a
  PostgreSQL ARRAY type.

    .. versionchanged:: 1.1 The :class:`_postgresql.ARRAY` type is now
       a subclass of the core :class:`_types.ARRAY` type.

    The :class:`_postgresql.ARRAY` type is constructed in the same way
    as the core :class:`_types.ARRAY` type; a member type is required, and a
    number of dimensions is recommended if the type is to be used for more
    than one dimension::

        from sqlalchemy.dialects import postgresql

        mytable = Table("mytable", metadata,
                Column("data", postgresql.ARRAY(Integer, dimensions=2))
            )

    The :class:`_postgresql.ARRAY` type provides all operations defined on the
    core :class:`_types.ARRAY` type, including support for "dimensions",
    indexed access, and simple matching such as
    :meth:`.types.ARRAY.Comparator.any` and
    :meth:`.types.ARRAY.Comparator.all`.  :class:`_postgresql.ARRAY`
    class also
    provides PostgreSQL-specific methods for containment operations, including
    :meth:`.postgresql.ARRAY.Comparator.contains`
    :meth:`.postgresql.ARRAY.Comparator.contained_by`, and
    :meth:`.postgresql.ARRAY.Comparator.overlap`, e.g.::

        mytable.c.data.contains([1, 2])

    The :class:`_postgresql.ARRAY` type may not be supported on all
    PostgreSQL DBAPIs; it is currently known to work on psycopg2 only.

    Additionally, the :class:`_postgresql.ARRAY`
    type does not work directly in
    conjunction with the :class:`.ENUM` type.  For a workaround, see the
    special type at :ref:`postgresql_array_of_enum`.

    .. container:: topic

        **Detecting Changes in ARRAY columns when using the ORM**

        The :class:`_postgresql.ARRAY` type, when used with the SQLAlchemy ORM,
        does not detect in-place mutations to the array. In order to detect
        these, the :mod:`sqlalchemy.ext.mutable` extension must be used, using
        the :class:`.MutableList` class::

            from sqlalchemy.dialects.postgresql import ARRAY
            from sqlalchemy.ext.mutable import MutableList

            class SomeOrmClass(Base):
                # ...

                data = Column(MutableList.as_mutable(ARRAY(Integer)))

        This extension will allow "in-place" changes such to the array
        such as ``.append()`` to produce events which will be detected by the
        unit of work.  Note that changes to elements **inside** the array,
        including subarrays that are mutated in place, are **not** detected.

        Alternatively, assigning a new array value to an ORM element that
        replaces the old one will always trigger a change event.

    .. seealso::

        :class:`_types.ARRAY` - base array type

        :class:`_postgresql.array` - produces a literal array value.

    c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	zARRAY.Comparatora*  Define comparison operations for :class:`_types.ARRAY`.

        Note that these operations are in addition to those provided
        by the base :class:`.types.ARRAY.Comparator` class, including
        :meth:`.types.ARRAY.Comparator.any` and
        :meth:`.types.ARRAY.Comparator.all`.

        c                 K      | j t|tjdS )zBoolean expression.  Test if elements are a superset of the
            elements of the argument array expression.

            kwargs may be ignored by this operator but are required for API
            conformance.
            Zresult_type)operateCONTAINSr#   Boolean)r'   r   kwargsr   r   r   contains   s   zARRAY.Comparator.containsc                 C   r?   )zBoolean expression.  Test if elements are a proper subset of the
            elements of the argument array expression.
            r@   )rA   CONTAINED_BYr#   rC   r'   r   r   r   r   contained_by   s   zARRAY.Comparator.contained_byc                 C   r?   )zuBoolean expression.  Test if array has elements in common with
            an argument array expression.
            r@   )rA   OVERLAPr#   rC   rG   r   r   r   overlap   s   zARRAY.Comparator.overlapN)r7   r8   r9   r:   rE   rH   rJ   r   r   r   r   
Comparator   s
    		rK   FNc                 C   s>   t |tr	tdt |tr| }|| _|| _|| _|| _dS )aP  Construct an ARRAY.

        E.g.::

          Column('myarray', ARRAY(Integer))

        Arguments are:

        :param item_type: The data type of items of this array. Note that
          dimensionality is irrelevant here, so multi-dimensional arrays like
          ``INTEGER[][]``, are constructed as ``ARRAY(Integer)``, not as
          ``ARRAY(ARRAY(Integer))`` or such.

        :param as_tuple=False: Specify whether return results
          should be converted to tuples from lists. DBAPIs such
          as psycopg2 return lists by default. When tuples are
          returned, the results are hashable.

        :param dimensions: if non-None, the ARRAY will assume a fixed
         number of dimensions.  This will cause the DDL emitted for this
         ARRAY to include the exact number of bracket clauses ``[]``,
         and will also optimize the performance of the type overall.
         Note that PG arrays are always implicitly "non-dimensioned",
         meaning they can store any number of dimensions no matter how
         they were declared.

        :param zero_indexes=False: when True, index values will be converted
         between Python zero-based and PostgreSQL one-based indexes, e.g.
         a value of one will be added to all index values before passing
         to the database.

         .. versionadded:: 0.9.5


        zUDo not nest ARRAY types; ARRAY(basetype) handles multi-dimensional arrays of basetypeN)r$   r%   
ValueErrorr   r&   as_tupler   zero_indexes)r'   r&   rM   r   rN   r   r   r   r!     s   
&

zARRAY.__init__c                 C   s   | j S r+   )rM   r,   r   r   r   hashable8  r.   zARRAY.hashablec                 C   s   t S r+   )listr,   r   r   r   python_type<  s   zARRAY.python_typec                 C   s   ||kS r+   r   )r'   xyr   r   r   compare_values@  s   zARRAY.compare_valuesc                    st   d u rt |}dksd u r,|rt|d t tfs,r( fdd|D S  |S   fdd|D S )Nr   r   c                 3   s    | ]} |V  qd S r+   r   r   rR   )itemprocr   r   	<genexpr>R  s    z$ARRAY._proc_array.<locals>.<genexpr>c                 3   s0    | ]} |d urd nd  V  qd S Nr   )_proc_arrayrU   
collectiondimrV   r'   r   r   rW   V  s    
)rP   r$   tuple)r'   ZarrrV   r\   r[   r   rZ   r   rY   C  s    zARRAY._proc_arrayc                 C   s   t | jtjo
| jjS r+   )r$   r&   r#   EnumZnative_enumr,   r   r   r   _against_native_enum`  s   zARRAY._against_native_enumc                 C   s   |S r+   r   )r'   Z	bindvaluer   r   r   bind_expressiong  s   zARRAY.bind_expressionc                    s$   j ||  fdd}|S )Nc                    s   | d u r| S  |  jtS r+   )rY   r   rP   value	item_procr'   r   r   processo  s
   
z%ARRAY.bind_processor.<locals>.process)r&   dialect_implbind_processor)r'   dialectre   r   rc   r   rg   j  s
   zARRAY.bind_processorc                    sT   j |||fdd}jr(|tdfdd  fdd}|S )Nc                    s*   | d u r| S  |  jjrtS tS r+   )rY   r   rM   r]   rP   ra   rc   r   r   re   ~  s   z'ARRAY.result_processor.<locals>.processz^{(.*)}$c                    s     | d}t|S rX   )matchgroup_split_enum_values)rb   inner)patternr   r   handle_raw_string  s   z1ARRAY.result_processor.<locals>.handle_raw_stringc                    s*   | d u r| S t | tjr | S | S r+   )r$   r   string_typesra   )rn   super_rpr   r   re     s   
)r&   rf   result_processorr_   recompile)r'   rh   Zcoltypere   r   )rn   rd   rm   r'   rp   r   rq   y  s   
zARRAY.result_processor)FNF)r7   r8   r9   r:   r#   r%   rK   Zcomparator_factoryr!   r;   rO   rQ   rT   rY   r   Zmemoized_propertyr_   r`   rg   rq   r   r   r   r   r%      s"    F"
2


r%   c                 C   s   d| vr| r|  dS g S | dd}|dd}g }t d|}d}|D ]}|dkr/| }q%|r;||dd q%|td	| q%|S )
N",z\"z_$ESC_QUOTE$_z\\\z(")Fz([^\s,]+),?)splitreplacerr   appendextendfindall)Zarray_stringtextresultZ	on_quotesZ	in_quotestokr   r   r   rk     s   rk   )rr    r   r#   r   sqlr   r   r   r   eqr   r   Z
ClauseListZColumnElementr   Z	custom_oprB   rF   rI   r%   rk   r   r   r   r   <module>   s"   		o  