3
a(                 @   s   d dl mZ ddlmZ ddlmZ ddlmZ dZej	ej
 Zejded	d	d
Zejded	d	d
Zejded	d	d
Zejded	d	d
Zejded	d	d
Zejded	d	d
Zejded	d	d
ZG dd dejjZG dd dejZG dd deZdS )    )absolute_import   )types)util)	operatorsJSONJSONBz->>T)
precedenceZnatural_self_precedentZeager_groupingz#>>?z?&z?|z@>z<@c               @   s   e Zd Zdd Zdd ZdS )JSONPathTypec                s   | j |  fdd}|S )Nc                s>   t | tjjstdd | D }ddj| }  r: | } | S )Nc             S   s   g | ]}t j|qS  )r   	text_type).0elemr   r   I/tmp/pip-build-6_cqtusv/SQLAlchemy/sqlalchemy/dialects/postgresql/json.py
<listcomp>K   s    z@JSONPathType.bind_processor.<locals>.process.<locals>.<listcomp>z{%s}z, )
isinstancer   collections_abcSequenceAssertionErrorjoin)valuetokens)
super_procr   r   processI   s    z,JSONPathType.bind_processor.<locals>.process)Zstring_bind_processor)selfdialectr   r   )r   r   bind_processorF   s    
zJSONPathType.bind_processorc                s   | j |  fdd}|S )Nc                s>   t | tjjstdd | D }ddj| }  r: | } | S )Nc             S   s   g | ]}t j|qS r   )r   r   )r   r   r   r   r   r   X   s    zCJSONPathType.literal_processor.<locals>.process.<locals>.<listcomp>z{%s}z, )r   r   r   r   r   r   )r   r   )r   r   r   r   V   s    z/JSONPathType.literal_processor.<locals>.process)Zstring_literal_processor)r   r   r   r   )r   r   literal_processorS   s    
zJSONPathType.literal_processorN)__name__
__module____qualname__r   r   r   r   r   r   r   E   s   r   c                   sB   e Zd ZdZej Zd fdd	ZG dd dejj	Z	e	Z
  ZS )	r   a  Represent the PostgreSQL JSON type.

    :class:`_postgresql.JSON` is used automatically whenever the base
    :class:`_types.JSON` datatype is used against a PostgreSQL backend,
    however base :class:`_types.JSON` datatype does not provide Python
    accessors for PostgreSQL-specific comparison methods such as
    :meth:`_postgresql.JSON.Comparator.astext`; additionally, to use
    PostgreSQL ``JSONB``, the :class:`_postgresql.JSONB` datatype should
    be used explicitly.

    .. seealso::

        :class:`_types.JSON` - main documentation for the generic
        cross-platform JSON datatype.

    The operators provided by the PostgreSQL version of :class:`_types.JSON`
    include:

    * Index operations (the ``->`` operator)::

        data_table.c.data['some key']

        data_table.c.data[5]


    * Index operations returning text (the ``->>`` operator)::

        data_table.c.data['some key'].astext == 'some value'

      Note that equivalent functionality is available via the
      :attr:`.JSON.Comparator.as_string` accessor.

    * Index operations with CAST
      (equivalent to ``CAST(col ->> ['some key'] AS <type>)``)::

        data_table.c.data['some key'].astext.cast(Integer) == 5

      Note that equivalent functionality is available via the
      :attr:`.JSON.Comparator.as_integer` and similar accessors.

    * Path index operations (the ``#>`` operator)::

        data_table.c.data[('key_1', 'key_2', 5, ..., 'key_n')]

    * Path index operations returning text (the ``#>>`` operator)::

        data_table.c.data[('key_1', 'key_2', 5, ..., 'key_n')].astext == 'some value'

    .. versionchanged:: 1.1  The :meth:`_expression.ColumnElement.cast`
       operator on
       JSON objects now requires that the :attr:`.JSON.Comparator.astext`
       modifier be called explicitly, if the cast works only from a textual
       string.

    Index operations return an expression object whose type defaults to
    :class:`_types.JSON` by default,
    so that further JSON-oriented instructions
    may be called upon the result type.

    Custom serializers and deserializers are specified at the dialect level,
    that is using :func:`_sa.create_engine`.  The reason for this is that when
    using psycopg2, the DBAPI only allows serializers at the per-cursor
    or per-connection level.   E.g.::

        engine = create_engine("postgresql://scott:tiger@localhost/test",
                                json_serializer=my_serialize_fn,
                                json_deserializer=my_deserialize_fn
                        )

    When using the psycopg2 dialect, the json_deserializer is registered
    against the database using ``psycopg2.extras.register_default_json``.

    .. seealso::

        :class:`_types.JSON` - Core level JSON type

        :class:`_postgresql.JSONB`

    .. versionchanged:: 1.1 :class:`_postgresql.JSON` is now a PostgreSQL-
       specific specialization of the new :class:`_types.JSON` type.

    FNc                s$   t t| j|d |dk	r || _dS )a+  Construct a :class:`_types.JSON` type.

        :param none_as_null: if True, persist the value ``None`` as a
         SQL NULL value, not the JSON encoding of ``null``.   Note that
         when this flag is False, the :func:`.null` construct can still
         be used to persist a NULL value::

             from sqlalchemy import null
             conn.execute(table.insert(), data=null())

         .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
            is now supported in order to persist a NULL value.

         .. seealso::

              :attr:`_types.JSON.NULL`

        :param astext_type: the type to use for the
         :attr:`.JSON.Comparator.astext`
         accessor on indexed attributes.  Defaults to :class:`_types.Text`.

         .. versionadded:: 1.1

        )none_as_nullN)superr   __init__astext_type)r   r"   r%   )	__class__r   r   r$      s    zJSON.__init__c               @   s   e Zd ZdZedd ZdS )zJSON.Comparatorz6Define comparison operations for :class:`_types.JSON`.c             C   sP   t | jjjtjjr0| jjjt	| jj| jj
dS | jjjt| jj| jj
dS dS )a  On an indexed expression, use the "astext" (e.g. "->>")
            conversion when rendered in SQL.

            E.g.::

                select(data_table.c.data['some key'].astext)

            .. seealso::

                :meth:`_expression.ColumnElement.cast`

            )result_typeN)r   exprrighttypesqltypesr   r   leftoperateJSONPATH_ASTEXTr%   ASTEXT)r   r   r   r   astext   s    zJSON.Comparator.astextN)r   r    r!   __doc__propertyr0   r   r   r   r   
Comparator   s   r3   )FN)r   r    r!   r1   r+   ZTextr%   r$   r   r3   comparator_factory__classcell__r   r   )r&   r   r   a   s
   Rc               @   s*   e Zd ZdZd ZG dd dejZeZdS )r   a  Represent the PostgreSQL JSONB type.

    The :class:`_postgresql.JSONB` type stores arbitrary JSONB format data,
    e.g.::

        data_table = Table('data_table', metadata,
            Column('id', Integer, primary_key=True),
            Column('data', JSONB)
        )

        with engine.connect() as conn:
            conn.execute(
                data_table.insert(),
                data = {"key1": "value1", "key2": "value2"}
            )

    The :class:`_postgresql.JSONB` type includes all operations provided by
    :class:`_types.JSON`, including the same behaviors for indexing
    operations.
    It also adds additional operators specific to JSONB, including
    :meth:`.JSONB.Comparator.has_key`, :meth:`.JSONB.Comparator.has_all`,
    :meth:`.JSONB.Comparator.has_any`, :meth:`.JSONB.Comparator.contains`,
    and :meth:`.JSONB.Comparator.contained_by`.

    Like the :class:`_types.JSON` type, the :class:`_postgresql.JSONB`
    type does not detect
    in-place changes when used with the ORM, unless the
    :mod:`sqlalchemy.ext.mutable` extension is used.

    Custom serializers and deserializers
    are shared with the :class:`_types.JSON` class,
    using the ``json_serializer``
    and ``json_deserializer`` keyword arguments.  These must be specified
    at the dialect level using :func:`_sa.create_engine`.  When using
    psycopg2, the serializers are associated with the jsonb type using
    ``psycopg2.extras.register_default_jsonb`` on a per-connection basis,
    in the same way that ``psycopg2.extras.register_default_json`` is used
    to register these handlers with the json type.

    .. versionadded:: 0.9.7

    .. seealso::

        :class:`_types.JSON`

    c               @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )zJSONB.Comparatorz6Define comparison operations for :class:`_types.JSON`.c             C   s   | j t|tjdS )zvBoolean expression.  Test for presence of a key.  Note that the
            key may be a SQLA expression.
            )r'   )r-   HAS_KEYr+   Boolean)r   otherr   r   r   has_key(  s    zJSONB.Comparator.has_keyc             C   s   | j t|tjdS )z;Boolean expression.  Test for presence of all keys in jsonb)r'   )r-   HAS_ALLr+   r7   )r   r8   r   r   r   has_all.  s    zJSONB.Comparator.has_allc             C   s   | j t|tjdS )z:Boolean expression.  Test for presence of any key in jsonb)r'   )r-   HAS_ANYr+   r7   )r   r8   r   r   r   has_any2  s    zJSONB.Comparator.has_anyc             K   s   | j t|tjdS )zBoolean expression.  Test if keys (or array) are a superset
            of/contained the keys of the argument jsonb expression.
            )r'   )r-   CONTAINSr+   r7   )r   r8   kwargsr   r   r   contains6  s    zJSONB.Comparator.containsc             C   s   | j t|tjdS )z|Boolean expression.  Test if keys are a proper subset of the
            keys of the argument jsonb expression.
            )r'   )r-   CONTAINED_BYr+   r7   )r   r8   r   r   r   contained_by<  s    zJSONB.Comparator.contained_byN)	r   r    r!   r1   r9   r;   r=   r@   rB   r   r   r   r   r3   %  s   r3   N)r   r    r!   r1   Z__visit_name__r   r3   r4   r   r   r   r   r      s   .N)r   r   )
__future__r    r   r+   r   Zsqlr   __all__Z_PRECEDENCEZjson_getitem_opZidx_precedenceZ	custom_opr/   r.   r6   r:   r<   r>   rA   r   r   r   r   r   r   r   <module>   sX    