
    +h                        d Z ddlmZ ddl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$  ejJ                  d      Z& G d dejN                        Z( G d de      Z) G d d e      Z* G d! d"e      Z+ G d# d$e      Z, G d% d&e      Z- G d' d(e      Z. e j^                         Z0 G d) d*e      Z1 G d+ d,e      Z2 G d- d.e      Z3 e jh                  d/d0      Z5 e jh                  d1d0      Z6 e jh                  d2d30      Z7 e jh                  d4e6e7z  0      Z8 G d5 d6e      Z9e9Z:y)7aM  
.. dialect:: postgresql+psycopg2
    :name: psycopg2
    :dbapi: psycopg2
    :connectstring: postgresql+psycopg2://user:password@host:port/dbname[?key=value&key=value...]
    :url: https://pypi.org/project/psycopg2/

psycopg2 Connect Arguments
--------------------------

Keyword arguments that are specific to the SQLAlchemy psycopg2 dialect
may be passed to :func:`_sa.create_engine()`, and include the following:


* ``isolation_level``: This option, available for all PostgreSQL dialects,
  includes the ``AUTOCOMMIT`` isolation level when using the psycopg2
  dialect.   This option sets the **default** isolation level for the
  connection that is set immediately upon connection to the database before
  the connection is pooled.  This option is generally superseded by the more
  modern :paramref:`_engine.Connection.execution_options.isolation_level`
  execution option, detailed at :ref:`dbapi_autocommit`.

  .. seealso::

    :ref:`psycopg2_isolation_level`

    :ref:`dbapi_autocommit`


* ``client_encoding``: sets the client encoding in a libpq-agnostic way,
  using psycopg2's ``set_client_encoding()`` method.

  .. seealso::

    :ref:`psycopg2_unicode`

* ``use_native_unicode``: Under Python 2 only, this can be set to False to
  disable the use of psycopg2's native Unicode support.

  .. seealso::

    :ref:`psycopg2_disable_native_unicode`


* ``executemany_mode``, ``executemany_batch_page_size``,
  ``executemany_values_page_size``: Allows use of psycopg2
  extensions for optimizing "executemany"-style queries.  See the referenced
  section below for details.

  .. seealso::

    :ref:`psycopg2_executemany_mode`

.. tip::

    The above keyword arguments are **dialect** keyword arguments, meaning
    that they are passed as explicit keyword arguments to :func:`_sa.create_engine()`::

        engine = create_engine(
            "postgresql+psycopg2://scott:tiger@localhost/test",
            isolation_level="SERIALIZABLE",
        )

    These should not be confused with **DBAPI** connect arguments, which
    are passed as part of the :paramref:`_sa.create_engine.connect_args`
    dictionary and/or are passed in the URL query string, as detailed in
    the section :ref:`custom_dbapi_args`.

.. _psycopg2_ssl:

SSL Connections
---------------

The psycopg2 module has a connection argument named ``sslmode`` for
controlling its behavior regarding secure (SSL) connections. The default is
``sslmode=prefer``; it will attempt an SSL connection and if that fails it
will fall back to an unencrypted connection. ``sslmode=require`` may be used
to ensure that only secure connections are established.  Consult the
psycopg2 / libpq documentation for further options that are available.

Note that ``sslmode`` is specific to psycopg2 so it is included in the
connection URI::

    engine = sa.create_engine(
        "postgresql+psycopg2://scott:tiger@192.168.0.199:5432/test?sslmode=require"
    )

Unix Domain Connections
------------------------

psycopg2 supports connecting via Unix domain connections.   When the ``host``
portion of the URL is omitted, SQLAlchemy passes ``None`` to psycopg2,
which specifies Unix-domain communication rather than TCP/IP communication::

    create_engine("postgresql+psycopg2://user:password@/dbname")

By default, the socket file used is to connect to a Unix-domain socket
in ``/tmp``, or whatever socket directory was specified when PostgreSQL
was built.  This value can be overridden by passing a pathname to psycopg2,
using ``host`` as an additional keyword argument::

    create_engine("postgresql+psycopg2://user:password@/dbname?host=/var/lib/postgresql")

.. seealso::

    `PQconnectdbParams \
    <https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-PQCONNECTDBPARAMS>`_

.. _psycopg2_multi_host:

Specifying multiple fallback hosts
-----------------------------------

psycopg2 supports multiple connection points in the connection string.
When the ``host`` parameter is used multiple times in the query section of
the URL, SQLAlchemy will create a single string of the host and port
information provided to make the connections.  Tokens may consist of
``host::port`` or just ``host``; in the latter case, the default port
is selected by libpq.  In the example below, three host connections
are specified, for ``HostA::PortA``, ``HostB`` connecting to the default port,
and ``HostC::PortC``::

    create_engine(
        "postgresql+psycopg2://user:password@/dbname?host=HostA:PortA&host=HostB&host=HostC:PortC"
    )

As an alternative, libpq query string format also may be used; this specifies
``host`` and ``port`` as single query string arguments with comma-separated
lists - the default port can be chosen by indicating an empty value
in the comma separated list::

    create_engine(
        "postgresql+psycopg2://user:password@/dbname?host=HostA,HostB,HostC&port=PortA,,PortC"
    )

With either URL style, connections to each host is attempted based on a
configurable strategy, which may be configured using the libpq
``target_session_attrs`` parameter.  Per libpq this defaults to ``any``
which indicates a connection to each host is then attempted until a connection is successful.
Other strategies include ``primary``, ``prefer-standby``, etc.  The complete
list is documented by PostgreSQL at
`libpq connection strings <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING>`_.

For example, to indicate two hosts using the ``primary`` strategy::

    create_engine(
        "postgresql+psycopg2://user:password@/dbname?host=HostA:PortA&host=HostB&host=HostC:PortC&target_session_attrs=primary"
    )

.. versionchanged:: 1.4.40 Port specification in psycopg2 multiple host format
   is repaired, previously ports were not correctly interpreted in this context.
   libpq comma-separated format is also now supported.

.. versionadded:: 1.3.20 Support for multiple hosts in PostgreSQL connection
   string.

.. seealso::

    `libpq connection strings <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING>`_ - please refer
    to this section in the libpq documentation for complete background on multiple host support.


Empty DSN Connections / Environment Variable Connections
---------------------------------------------------------

The psycopg2 DBAPI can connect to PostgreSQL by passing an empty DSN to the
libpq client library, which by default indicates to connect to a localhost
PostgreSQL database that is open for "trust" connections.  This behavior can be
further tailored using a particular set of environment variables which are
prefixed with ``PG_...``, which are  consumed by ``libpq`` to take the place of
any or all elements of the connection string.

For this form, the URL can be passed without any elements other than the
initial scheme::

    engine = create_engine('postgresql+psycopg2://')

In the above form, a blank "dsn" string is passed to the ``psycopg2.connect()``
function which in turn represents an empty DSN passed to libpq.

.. versionadded:: 1.3.2 support for parameter-less connections with psycopg2.

.. seealso::

    `Environment Variables\
    <https://www.postgresql.org/docs/current/libpq-envars.html>`_ -
    PostgreSQL documentation on how to use ``PG_...``
    environment variables for connections.

.. _psycopg2_execution_options:

Per-Statement/Connection Execution Options
-------------------------------------------

The following DBAPI-specific options are respected when used with
:meth:`_engine.Connection.execution_options`,
:meth:`.Executable.execution_options`,
:meth:`_query.Query.execution_options`,
in addition to those not specific to DBAPIs:

* ``isolation_level`` - Set the transaction isolation level for the lifespan
  of a :class:`_engine.Connection` (can only be set on a connection,
  not a statement
  or query).   See :ref:`psycopg2_isolation_level`.

* ``stream_results`` - Enable or disable usage of psycopg2 server side
  cursors - this feature makes use of "named" cursors in combination with
  special result handling methods so that result rows are not fully buffered.
  Defaults to False, meaning cursors are buffered by default.

* ``max_row_buffer`` - when using ``stream_results``, an integer value that
  specifies the maximum number of rows to buffer at a time.  This is
  interpreted by the :class:`.BufferedRowCursorResult`, and if omitted the
  buffer will grow to ultimately store 1000 rows at a time.

  .. versionchanged:: 1.4  The ``max_row_buffer`` size can now be greater than
     1000, and the buffer will grow to that size.

.. _psycopg2_batch_mode:

.. _psycopg2_executemany_mode:

Psycopg2 Fast Execution Helpers
-------------------------------

Modern versions of psycopg2 include a feature known as
`Fast Execution Helpers \
<https://initd.org/psycopg/docs/extras.html#fast-execution-helpers>`_, which
have been shown in benchmarking to improve psycopg2's executemany()
performance, primarily with INSERT statements, by multiple orders of magnitude.
SQLAlchemy internally makes use of these extensions for ``executemany()`` style
calls, which correspond to lists of parameters being passed to
:meth:`_engine.Connection.execute` as detailed in :ref:`multiple parameter
sets <tutorial_multiple_parameters>`.   The ORM also uses this mode internally whenever
possible.

The two available extensions on the psycopg2 side are the ``execute_values()``
and ``execute_batch()`` functions.  The psycopg2 dialect defaults to using the
``execute_values()`` extension for all qualifying INSERT statements.

.. versionchanged:: 1.4  The psycopg2 dialect now defaults to a new mode
   ``"values_only"`` for ``executemany_mode``, which allows an order of
   magnitude performance improvement for INSERT statements, but does not
   include "batch" mode for UPDATE and DELETE statements which removes the
   ability of ``cursor.rowcount`` to function correctly.

The use of these extensions is controlled by the ``executemany_mode`` flag
which may be passed to :func:`_sa.create_engine`::

    engine = create_engine(
        "postgresql+psycopg2://scott:tiger@host/dbname",
        executemany_mode='values_plus_batch')


Possible options for ``executemany_mode`` include:

* ``values_only`` - this is the default value.  the psycopg2 execute_values()
  extension is used for qualifying INSERT statements, which rewrites the INSERT
  to include multiple VALUES clauses so that many parameter sets can be
  inserted with one statement.

  .. versionadded:: 1.4 Added ``"values_only"`` setting for ``executemany_mode``
     which is also now the default.

* ``None`` - No psycopg2 extensions are not used, and the usual
  ``cursor.executemany()`` method is used when invoking statements with
  multiple parameter sets.

* ``'batch'`` - Uses ``psycopg2.extras.execute_batch`` for all qualifying
  INSERT, UPDATE and DELETE statements, so that multiple copies
  of a SQL query, each one corresponding to a parameter set passed to
  ``executemany()``, are joined into a single SQL string separated by a
  semicolon.  When using this mode, the :attr:`_engine.CursorResult.rowcount`
  attribute will not contain a value for executemany-style executions.

* ``'values_plus_batch'``- ``execute_values`` is used for qualifying INSERT
  statements, ``execute_batch`` is used for UPDATE and DELETE.
  When using this mode, the :attr:`_engine.CursorResult.rowcount`
  attribute will not contain a value for executemany-style executions against
  UPDATE and DELETE statements.

By "qualifying statements", we mean that the statement being executed
must be a Core :func:`_expression.insert`, :func:`_expression.update`
or :func:`_expression.delete` construct, and not a plain textual SQL
string or one constructed using :func:`_expression.text`.  When using the
ORM, all insert/update/delete statements used by the ORM flush process
are qualifying.

The "page size" for the "values" and "batch" strategies can be affected
by using the ``executemany_batch_page_size`` and
``executemany_values_page_size`` engine parameters.  These
control how many parameter sets
should be represented in each execution.    The "values" page size defaults
to 1000, which is different that psycopg2's default.  The "batch" page
size defaults to 100.  These can be affected by passing new values to
:func:`_engine.create_engine`::

    engine = create_engine(
        "postgresql+psycopg2://scott:tiger@host/dbname",
        executemany_mode='values',
        executemany_values_page_size=10000, executemany_batch_page_size=500)

.. versionchanged:: 1.4

    The default for ``executemany_values_page_size`` is now 1000, up from
    100.

.. seealso::

    :ref:`tutorial_multiple_parameters` - General information on using the
    :class:`_engine.Connection`
    object to execute statements in such a way as to make
    use of the DBAPI ``.executemany()`` method.


.. _psycopg2_unicode:

Unicode with Psycopg2
----------------------

The psycopg2 DBAPI driver supports Unicode data transparently.   Under Python 2
only, the SQLAlchemy psycopg2 dialect will enable the
``psycopg2.extensions.UNICODE`` extension by default to ensure Unicode is
handled properly; under Python 3, this is psycopg2's default behavior.

The client character encoding can be controlled for the psycopg2 dialect
in the following ways:

* For PostgreSQL 9.1 and above, the ``client_encoding`` parameter may be
  passed in the database URL; this parameter is consumed by the underlying
  ``libpq`` PostgreSQL client library::

    engine = create_engine("postgresql+psycopg2://user:pass@host/dbname?client_encoding=utf8")

  Alternatively, the above ``client_encoding`` value may be passed using
  :paramref:`_sa.create_engine.connect_args` for programmatic establishment with
  ``libpq``::

    engine = create_engine(
        "postgresql+psycopg2://user:pass@host/dbname",
        connect_args={'client_encoding': 'utf8'}
    )

* For all PostgreSQL versions, psycopg2 supports a client-side encoding
  value that will be passed to database connections when they are first
  established.  The SQLAlchemy psycopg2 dialect supports this using the
  ``client_encoding`` parameter passed to :func:`_sa.create_engine`::

      engine = create_engine(
          "postgresql+psycopg2://user:pass@host/dbname",
          client_encoding="utf8"
      )

  .. tip:: The above ``client_encoding`` parameter admittedly is very similar
      in appearance to usage of the parameter within the
      :paramref:`_sa.create_engine.connect_args` dictionary; the difference
      above is that the parameter is consumed by psycopg2 and is
      passed to the database connection using ``SET client_encoding TO
      'utf8'``; in the previously mentioned style, the parameter is instead
      passed through psycopg2 and consumed by the ``libpq`` library.

* A common way to set up client encoding with PostgreSQL databases is to
  ensure it is configured within the server-side postgresql.conf file;
  this is the recommended way to set encoding for a server that is
  consistently of one encoding in all databases::

    # postgresql.conf file

    # client_encoding = sql_ascii # actually, defaults to database
                                 # encoding
    client_encoding = utf8

.. _psycopg2_disable_native_unicode:

Disabling Native Unicode
^^^^^^^^^^^^^^^^^^^^^^^^

Under Python 2 only, SQLAlchemy can also be instructed to skip the usage of the
psycopg2 ``UNICODE`` extension and to instead utilize its own unicode
encode/decode services, which are normally reserved only for those DBAPIs that
don't fully support unicode directly.  Passing ``use_native_unicode=False`` to
:func:`_sa.create_engine` will disable usage of ``psycopg2.extensions.
UNICODE``. SQLAlchemy will instead encode data itself into Python bytestrings
on the way in and coerce from bytes on the way back, using the value of the
:func:`_sa.create_engine` ``encoding`` parameter, which defaults to ``utf-8``.
SQLAlchemy's own unicode encode/decode functionality is steadily becoming
obsolete as most DBAPIs now support unicode fully.


Transactions
------------

The psycopg2 dialect fully supports SAVEPOINT and two-phase commit operations.

.. _psycopg2_isolation_level:

Psycopg2 Transaction Isolation Level
-------------------------------------

As discussed in :ref:`postgresql_isolation_level`,
all PostgreSQL dialects support setting of transaction isolation level
both via the ``isolation_level`` parameter passed to :func:`_sa.create_engine`
,
as well as the ``isolation_level`` argument used by
:meth:`_engine.Connection.execution_options`.  When using the psycopg2 dialect
, these
options make use of psycopg2's ``set_isolation_level()`` connection method,
rather than emitting a PostgreSQL directive; this is because psycopg2's
API-level setting is always emitted at the start of each transaction in any
case.

The psycopg2 dialect supports these constants for isolation level:

* ``READ COMMITTED``
* ``READ UNCOMMITTED``
* ``REPEATABLE READ``
* ``SERIALIZABLE``
* ``AUTOCOMMIT``

.. seealso::

    :ref:`postgresql_isolation_level`

    :ref:`pg8000_isolation_level`


NOTICE logging
---------------

The psycopg2 dialect will log PostgreSQL NOTICE messages
via the ``sqlalchemy.dialects.postgresql`` logger.  When this logger
is set to the ``logging.INFO`` level, notice messages will be logged::

    import logging

    logging.getLogger('sqlalchemy.dialects.postgresql').setLevel(logging.INFO)

Above, it is assumed that logging is configured externally.  If this is not
the case, configuration such as ``logging.basicConfig()`` must be utilized::

    import logging

    logging.basicConfig()   # log messages to stdout
    logging.getLogger('sqlalchemy.dialects.postgresql').setLevel(logging.INFO)

.. seealso::

    `Logging HOWTO <https://docs.python.org/3/howto/logging.html>`_ - on the python.org website

.. _psycopg2_hstore:

HSTORE type
------------

The ``psycopg2`` DBAPI includes an extension to natively handle marshalling of
the HSTORE type.   The SQLAlchemy psycopg2 dialect will enable this extension
by default when psycopg2 version 2.4 or greater is used, and
it is detected that the target database has the HSTORE type set up for use.
In other words, when the dialect makes the first
connection, a sequence like the following is performed:

1. Request the available HSTORE oids using
   ``psycopg2.extras.HstoreAdapter.get_oids()``.
   If this function returns a list of HSTORE identifiers, we then determine
   that the ``HSTORE`` extension is present.
   This function is **skipped** if the version of psycopg2 installed is
   less than version 2.4.

2. If the ``use_native_hstore`` flag is at its default of ``True``, and
   we've detected that ``HSTORE`` oids are available, the
   ``psycopg2.extensions.register_hstore()`` extension is invoked for all
   connections.

The ``register_hstore()`` extension has the effect of **all Python
dictionaries being accepted as parameters regardless of the type of target
column in SQL**. The dictionaries are converted by this extension into a
textual HSTORE expression.  If this behavior is not desired, disable the
use of the hstore extension by setting ``use_native_hstore`` to ``False`` as
follows::

    engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test",
                use_native_hstore=False)

The ``HSTORE`` type is **still supported** when the
``psycopg2.extensions.register_hstore()`` extension is not used.  It merely
means that the coercion between Python dictionaries and the HSTORE
string format, on both the parameter side and the result side, will take
place within SQLAlchemy's own marshalling logic, and not that of ``psycopg2``
which may be more performant.

    )absolute_importN)UUID   )ARRAY
_ColonCast)_DECIMAL_TYPES)_FLOAT_TYPES)
_INT_TYPES)ENUM)
PGCompiler)	PGDialect)PGExecutionContext)PGIdentifierPreparer)HSTORE)JSON)JSONB   )exc)
processors)types)util)cursor)collections_abczsqlalchemy.dialects.postgresqlc                       e Zd Zd Zd Zy)
_PGNumericc                      y N )selfdialects     Z/var/www/html/venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/psycopg2.pybind_processorz_PGNumeric.bind_processor          c                 Z   | j                   r_|t        v r.t        j                  t        j
                  | j                        S |t        v s|t        v ry t        j                  d|z        |t        v ry |t        v s|t        v rt        j                  S t        j                  d|z        )NzUnknown PG numeric type: %d)	asdecimalr
   r   to_decimal_processor_factorydecimalDecimal_effective_decimal_return_scaler	   r   r   InvalidRequestErrorto_floatr    r!   coltypes      r"   result_processorz_PGNumeric.result_processor  s    >>,&!>>OOT%I%I  N*g.C--1G;  ,&N*g.C!***--1G; r%   N__name__
__module____qualname__r#   r0   r   r%   r"   r   r     s    r%   r   c                        e Zd Z fdZ xZS )_PGEnumc                 v    t         j                  r| j                  du rd| _        t        t        |   ||      S )NTforce_nocheck)r   py2k_expect_unicodesuperr6   r0   r    r!   r/   	__class__s      r"   r0   z_PGEnum.result_processor0  s5    99--5 $3D Wd4WgFFr%   )r2   r3   r4   r0   __classcell__r=   s   @r"   r6   r6   /  s    G Gr%   r6   c                   (     e Zd Z fdZ fdZ xZS )	_PGHStorec                 D    |j                   ry t        t        |   |      S r   )_has_native_hstorer;   rA   r#   )r    r!   r=   s     r"   r#   z_PGHStore.bind_processor@  s!    %%D8AAr%   c                 F    |j                   ry t        t        |   ||      S r   )rC   r;   rA   r0   r<   s      r"   r0   z_PGHStore.result_processorF  s#    %%D:7GLLr%   )r2   r3   r4   r#   r0   r>   r?   s   @r"   rA   rA   ?  s    BM Mr%   rA   c                       e Zd Zd Zy)_PGARRAYc                     t        ||       S r   r   )r    	bindvalues     r"   bind_expressionz_PGARRAY.bind_expressionN  s    )T**r%   N)r2   r3   r4   rI   r   r%   r"   rF   rF   M  s    +r%   rF   c                       e Zd Zd Zy)_PGJSONc                      y r   r   r.   s      r"   r0   z_PGJSON.result_processorS  r$   r%   Nr2   r3   r4   r0   r   r%   r"   rK   rK   R      r%   rK   c                       e Zd Zd Zy)_PGJSONBc                      y r   r   r.   s      r"   r0   z_PGJSONB.result_processorX  r$   r%   NrM   r   r%   r"   rP   rP   W  rN   r%   rP   c                       e Zd Zd Zd Zy)_PGUUIDc                 @    | j                   s|j                  rd }|S y y )Nc                      | t        |       } | S r   )_python_UUIDvalues    r"   processz'_PGUUID.bind_processor.<locals>.process`  s    $(/Er%   as_uuiduse_native_uuid)r    r!   rY   s      r"   r#   z_PGUUID.bind_processor]  $    || 7 7
 N !8|r%   c                 @    | j                   s|j                  rd }|S y y )Nc                      | t        |       } | S r   )strrW   s    r"   rY   z)_PGUUID.result_processor.<locals>.processj  s    $JEr%   rZ   )r    r!   r/   rY   s       r"   r0   z_PGUUID.result_processorg  r]   r%   Nr1   r   r%   r"   rS   rS   \  s    r%   rS   c                   "    e Zd ZdZd Zd Zd Zy)PGExecutionContext_psycopg2Nc                     dt        t        |             dd  dt        t                     dd  }| j                  j	                  |      S )Nc_   _)hexid_server_side_id_dbapi_connectionr   )r    idents     r"   create_server_side_cursorz5PGExecutionContext_psycopg2.create_server_side_cursorx  sC     !D]12.O4E0Fqr0JK%%,,U33r%   c                     | j                   rU| j                  rI| j                  j                  r3t        j                  } || j
                  | j                         | _        | j                  | j
                         y )N)initial_buffer)_psycopg2_fetched_rowscompiled	returning_cursor FullyBufferedCursorFetchStrategyr   cursor_fetch_strategy_log_notices)r    	strat_clss     r"   	post_execz%PGExecutionContext_psycopg2.post_exec~  s\    ''''  @@I)2D,G,G*D& 	$++&r%   c                 <   |j                   j                  r.t        |j                   j                  t        j                        sy |j                   j                  D ]%  }t
        j                  |j                                ' g |j                   j                  d d  y r   )
connectionnotices
isinstancer   Iterableloggerinforstrip)r    r   notices      r"   ru   z(PGExecutionContext_psycopg2._log_notices  s}    
   ((
%%'?'?1
 ''// 	)F KK(	)
 (*!!!$r%   )r2   r3   r4   ro   rl   rw   ru   r   r%   r"   rb   rb   u  s    !4'&*r%   rb   c                       e Zd Zy)PGCompiler_psycopg2Nr2   r3   r4   r   r%   r"   r   r         r%   r   c                       e Zd Zy)PGIdentifierPreparer_psycopg2Nr   r   r%   r"   r   r     r   r%   r   executemany_plain)	canonicalexecutemany_batchexecutemany_valuesre   executemany_values_plus_batchc                   *    e Zd ZdZdZej                  rdZdZdZ	dZ
eZeZeZdZdZej(                  j+                  dej,                  i      Z ej.                  ej0                  ej4                  eeeej<                  eee e!e"ejB                  e"e#e$e%e&ejN                  e(i	      Z	 	 	 	 	 	 	 ddZ) fdZ*e+d	        Z,e+d
        Z-e+d        Z.ej^                  d        Z0d Z1d Z2d Z3d Z4d Z5d Z6d Z7ddZ8ejr                  d        Z:d Z;d Z< xZ=S )PGDialect_psycopg2psycopg2TFpyformat)r   r   use_native_unicodec                    t        j                  | fi | || _        |s%t        j                  st        j                  d      |sd| _        || _        || _	        || _
        || _        t        j                  j                  |t        d gt        dgt         dgt"        ddgid      | _        | j$                  t         z  rd| _        || _        || _        | j,                  rt/        | j,                  d	      rot1        j2                  d
| j,                  j4                        }	|	r(t7        d |	j9                  ddd      D              | _        | j:                  dk  rt=        d      y y y )Nz7psycopg2 native_unicode mode is required under Python 3Fbatchvalues_onlyvalues_plus_batchvaluesexecutemany_modeT__version__z(\d+)\.(\d+)(?:\.(\d+))?c              3   8   K   | ]  }|t        |        y wr   )int).0xs     r"   	<genexpr>z.PGDialect_psycopg2.__init__.<locals>.<genexpr>  s      . CF.s   r   re   r   )re      z+psycopg2 version 2.7 or higher is required.)r   __init__r   r   r9   r   ArgumentErrorrC   use_native_hstorer\   supports_unicode_bindsclient_encodingsymbolparse_user_argumentEXECUTEMANY_PLAINEXECUTEMANY_BATCHEXECUTEMANY_VALUESEXECUTEMANY_VALUES_PLUS_BATCHr   insert_executemany_returningexecutemany_batch_page_sizeexecutemany_values_page_sizedbapihasattrrematchr   tuplegrouppsycopg2_versionImportError)
r    r   r   r   r\   r   r   r   kwargsms
             r"   r   zPGDialect_psycopg2.__init__  s_    	4*6*"4!$))##I  !&+D#!2.&8#. !% ? ?!D6!G9"]O-0CX/N	 	!
   #5504D-+F(,H)::'$**m<4djj6L6LMA(- .$%GGAq!$4. )% $$v-!A  . =:r%   c                     t         t        |   |       | j                  xr | j	                  |j
                        d u| _        | j                  sd| _        t        | _
        | j                  t        z   | _        y )NF)r;   r   
initializer   _hstore_oidsry   rC   full_returningr   r   r   r   supports_sane_multi_rowcount)r    ry   r=   s     r"   r   zPGDialect_psycopg2.initialize  sy     $2:>"" E!!*"7"78D 	 ""05D-$5D! !!$55-
)r%   c                     dd l }|S )Nr   )r   )clsr   s     r"   r   zPGDialect_psycopg2.dbapi)  s
    r%   c                     ddl m} |S )Nr   )
extensions)r   r   )r   r   s     r"   _psycopg2_extensionsz'PGDialect_psycopg2._psycopg2_extensions/  s    'r%   c                     ddl m} |S )Nr   )extras)r   r   )r   r   s     r"   _psycopg2_extrasz#PGDialect_psycopg2._psycopg2_extras5  s
    #r%   c                     | j                         }|j                  |j                  |j                  |j                  |j
                  dS )N)
AUTOCOMMITzREAD COMMITTEDzREAD UNCOMMITTEDzREPEATABLE READSERIALIZABLE)r   ISOLATION_LEVEL_AUTOCOMMITISOLATION_LEVEL_READ_COMMITTED ISOLATION_LEVEL_READ_UNCOMMITTEDISOLATION_LEVEL_REPEATABLE_READISOLATION_LEVEL_SERIALIZABLE)r    r   s     r"   _isolation_lookupz$PGDialect_psycopg2._isolation_lookup;  sG    ..0
$??(GG * K K)II&CC
 	
r%   c                 >   	 | j                   |j                  dd         }|j                  |       y # t        $ r`}t        j                  t        j                  d|d| j                  ddj                  | j                               |       Y d }~vd }~ww xY w)Nrf    zInvalid value 'z2' for isolation_level. Valid isolation levels for z are z, )replace_context)
r   replaceKeyErrorr   raise_r   r   namejoinset_isolation_level)r    ry   levelerrs       r"   r   z&PGDialect_psycopg2.set_isolation_levelF  s    
	**5==c+BCE 	&&u-  	KK!! dii43I3I)JL
 !$ 	s   3 	BABBc                     ||_         y r   readonlyr    ry   rX   s      r"   set_readonlyzPGDialect_psycopg2.set_readonlyU  s
    #
r%   c                     |j                   S r   r   r    ry   s     r"   get_readonlyzPGDialect_psycopg2.get_readonlyX  s    """r%   c                     ||_         y r   
deferrabler   s      r"   set_deferrablez!PGDialect_psycopg2.set_deferrable[  s
     %
r%   c                     |j                   S r   r   r   s     r"   get_deferrablez!PGDialect_psycopg2.get_deferrable^  s    $$$r%   c                    d }|j                   }	 |sd|_         |j                         }	 |j                  | j                         |j	                          |s|j
                  s||_         y# |j	                          |s|j
                  s||_         w w w xY w# | j                  j                  $ r}| j                  |||      rY d }~y d }~ww xY w)NTF)	
autocommitr   execute_dialect_specific_select_onecloseclosedr   Erroris_disconnect)r    dbapi_connectionr   before_autocommitr   s        r"   do_pingzPGDialect_psycopg2.do_pinga  s    ,77	$.2 +%,,.FDt@@A(1A1H1H2C$/  (1A1H1H2C$/ 2I(zz 	!!#'7@		s4   B A+ %B +)BB C0C	C		Cc                 ~     j                          j                         g  j                   fd}j                  |        j                   fd}j                  |        j
                  r" j                  rfd}j                  |       t        j                  r. j
                  r" j                  rfd}j                  |        j
                  r# j                  r fd}j                  |        j
                  r# j                  r fd}j                  |       rfd}|S y )Nc                 <    | j                  j                         y r   )set_client_encodingr   connr    s    r"   
on_connectz1PGDialect_psycopg2.on_connect.<locals>.on_connect}  s    (()=)=>r%   c                 >    j                  | j                         y r   )r   isolation_levelr   s    r"   r   z1PGDialect_psycopg2.on_connect.<locals>.on_connect  s    ((t/C/CDr%   c                 *    j                  d |        y r   )register_uuid)r   r   s    r"   r   z1PGDialect_psycopg2.on_connect.<locals>.on_connect  s    $$T40r%   c                 v    j                  j                  |        j                  j                  |        y r   )register_typeUNICODEUNICODEARRAY)r   r   s    r"   r   z1PGDialect_psycopg2.on_connect.<locals>.on_connect  s/    ((););TB(()@)@$Gr%   c                     j                  |       }|7|\  }}d|i}t        j                  rd|d<   ||d<    j                  | fi | y y )NoidTunicode	array_oid)r   r   r9   register_hstore)r   hstore_oidsr   r  kwr   r    s        r"   r   z1PGDialect_psycopg2.on_connect.<locals>.on_connect  s^    "//5*%0NCByy(,9&/B{O*F**4626 +r%   c                 z    j                  | j                         j                  | j                         y )N)loads)register_default_json_json_deserializerregister_default_jsonb)r   r   r    s    r"   r   z1PGDialect_psycopg2.on_connect.<locals>.on_connect  sA    ,, 7 7 -  -- 7 7 . r%   c                 $    D ]
  } ||         y r   r   )r   fnfnss     r"   r   z1PGDialect_psycopg2.on_connect.<locals>.on_connect  s     BtHr%   )r   r   r   appendr   r   r\   r   r9   r   r   r  )r    r   r   r   r  s   ` @@@r"   r   zPGDialect_psycopg2.on_connectv  s   &&(..0
+? JJz"+E JJz"::$..1 JJz"99(?(?H JJz"::$007 JJz"::$11 JJz" r%   c                    | j                   t        z  rk|ri|j                  r]|j                  j                  rGd|j                  j
                  z  }| j                  s|j                  | j                        }||vrd }nd }|rz|j                  |d      }| j                  rd| j                  i}ni }| j                         } |j                  |||f|t        |j                  j                        d||_        y | j                   t         z  rA| j"                  rd| j"                  i}ni } | j                         j$                  |||fi | y |j'                  ||       y )Nz(%s)z%s	page_size)templatefetch)r   r   isinsertrp   &_is_safe_for_fast_insert_values_helperinsert_single_values_exprsupports_unicode_statementsencodeencodingr   r   r   execute_valuesboolrq   ro   r   r   execute_batchexecutemany)r    r   	statement
parameterscontextr   r   xtrass           r"   do_executemanyz!PGDialect_psycopg2.do_executemany  sn   !!$66    GG ))CCC  33%7%>%>t}}%M" "2%)"!%!))*<dCI00%t'H'HI))+E-AU-A-A. ,7++556. .G* ""%66//%t'G'GH1D!!#11	:17 y*5r%   c                     | j                         }t        |d      r|j                  }|j                  j	                  |      }|
|d   r|dd S y )Nr   r   re   )r   r   r   HstoreAdapterget_oids)r    r   r   oidss       r"   r   zPGDialect_psycopg2._hstore_oids  sW    &&(4+,((D##,,T2Q!9r%   c                 ,   |j                  d      }d}d|j                  v r#t        |j                  d   t        t        f      }|s|j                  r|si }d|v rt        |d         |d<   |j                  |j                         |r~t        |j                  d   D cg c]  }d|v r|j                  d      n|df c} \  }}dj                  |      |d<   d|v rt        j                  d	      dj                  |      |d<   g |fS dg|fS c c}w )
Nuser)usernameFhostport: ,zzCan't mix 'multihost' formats together; use "host=h1,h2,h3&port=p1,p2,p3" or "host=h1:p1&host=h2:p2&host=h3:p3" separately)translate_connect_argsqueryr{   listr   r   updatezipsplitr   r   r   )r    urloptsis_multihosttokenhostsportss          r"   create_connect_argsz&PGDialect_psycopg2.create_connect_args  s&   ))6):SYY%cii&7$GL399~"4<0VKK		"" &)YYv%6! -05LC(ubkI u  #xxVT>++H 
  #xxV: D$<#s     Dc                     t        || j                  j                        rRt        |dd      ryt	        |      j                  d      d   }dD ]"  }|j                  |      }|dk\  sd|d | vs" y y)Nr   FT
r   )zterminating connectionzclosed the connectionzconnection not openz"could not receive data from serverzcould not send data to serverzconnection already closedzcursor already closedz!losed the connection unexpectedlyz'connection has been closed unexpectedlyz.SSL error: decryption failed or bad record macz&SSL SYSCALL error: Bad file descriptorzSSL SYSCALL error: EOF detectedz&SSL SYSCALL error: Operation timed outzSSL SYSCALL error: Bad address")r{   r   r   getattrr`   	partitionfind)r    ery   r   str_emsgidxs          r"   r   z PGDialect_psycopg2.is_disconnect  s~    a))*
 z8U3 F$$T*1-E  . jjo!85#; 63 4 r%   )TNTTr   d   i  r   )>r2   r3   r4   driversupports_statement_cacher   r9   r  supports_server_side_cursorsdefault_paramstyler   rb   execution_ctx_clsr   statement_compilerr   preparerr   rC   r   engine_config_typesunionasboolupdate_copycolspecssqltypesNumericr   r   r6   Enumr   rA   r   rK   r   rP   r   rS   r   rF   r   r   classmethodr   r   r   memoized_propertyr   r   r   r   r   r   r   r   r   memoized_instancemethodr   r9  r   r>   r?   s   @r"   r   r     s   F#yy ',##' ##( 3,,H#77==	t{{+  tj'MM7I'MM78'NNH
	
H"  &$'%)5n
"  
  
  
 

 
.$#&%*DL,6\ 
!! "  D&r%   r   );__doc__
__future__r   r)   loggingr   uuidr   rV   arrayr   PGARRAYbaser   r	   r
   r   r   r   r   r   r   hstorer   jsonr   r   r+  r   r   r   rQ  r   enginer   rr   r   	getLoggerr}   rR  r   r6   rA   rF   rK   rP   rS   counterri   rb   r   r   r   r   r   r   r   r   r!   r   r%   r"   <module>rc     ss  jV '   	 % #         $ &       !  ' # 
		;	<!! :Gd G M M+w +
d 
u 
d , $,,.+*"4 +*\	* 		$8 	  DKK 3qA DKK 3qA  T[[!5C  +#"44! I IX r%   