o
    g }                     @  s  d Z ddlmZ 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 edZG dd deZG dd deZG dd dej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 d! d!eZ#G d"d# d#eZ$G d$d% d%eZ%e%j&' \Z(Z)G d&d' d'eZ*e*Z+dS )(a%J  
.. 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_toplevel:

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`


* ``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"
    )

.. warning::  The format accepted here allows for a hostname in the main URL
   in addition to the "host" query string argument.  **When using this URL
   format, the initial host is silently ignored**.  That is, this URL::

        engine = create_engine(
            "postgresql+psycopg2://user:password@myhost1/dbname?host=myhost2"
        )

   Above, the hostname ``myhost1`` is **silently ignored and discarded.**  The
   host which is connected is the ``myhost2`` host.

   This is to maintain some degree of compatibility with PostgreSQL's own URL
   format which has been tested to behave the same way and for which tools like
   PifPaf hardcode two hostnames.

.. 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://www.psycopg.org/docs/extras.html#fast-execution-helpers>`_, which
have been shown in benchmarking to improve psycopg2's executemany()
performance, primarily with INSERT statements, by at least
an order of magnitude.

SQLAlchemy implements a native form of the "insert many values"
handler that will rewrite a single-row INSERT statement to accommodate for
many values at once within an extended VALUES clause; this handler is
equivalent to psycopg2's ``execute_values()`` handler; an overview of this
feature and its configuration are at :ref:`engine_insertmanyvalues`.

.. versionadded:: 2.0 Replaced psycopg2's ``execute_values()`` fast execution
   helper with a native SQLAlchemy mechanism known as
   :ref:`insertmanyvalues <engine_insertmanyvalues>`.

The psycopg2 dialect retains the ability to use the psycopg2-specific
``execute_batch()`` feature, although it is not expected that this is a widely
used feature.  The use of this extension may be enabled using 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.  SQLAlchemy's native
  :ref:`insertmanyvalues <engine_insertmanyvalues>` handler is used for qualifying
  INSERT statements, assuming
  :paramref:`_sa.create_engine.use_insertmanyvalues` is left at
  its default value of ``True``.  This handler rewrites simple
  INSERT statements to include multiple VALUES clauses so that many
  parameter sets can be inserted with one statement.

* ``'values_plus_batch'``- SQLAlchemy's native
  :ref:`insertmanyvalues <engine_insertmanyvalues>` handler is used for qualifying
  INSERT statements, assuming
  :paramref:`_sa.create_engine.use_insertmanyvalues` is left at its default
  value of ``True``. Then, psycopg2's ``execute_batch()`` handler is used for
  qualifying UPDATE and DELETE statements when executed with multiple parameter
  sets. When using this mode, the :attr:`_engine.CursorResult.rowcount`
  attribute will not contain a value for executemany-style executions against
  UPDATE and DELETE statements.

.. versionchanged:: 2.0 Removed the ``'batch'`` and ``'None'`` options
   from psycopg2 ``executemany_mode``.  Control over batching for INSERT
   statements is now configured via the
   :paramref:`_sa.create_engine.use_insertmanyvalues` engine-level parameter.

The term "qualifying statements" refers to the statement being executed
being 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`.  It also may **not** be
a special "extension" statement such as an "ON CONFLICT" "upsert" statement.
When using the ORM, all insert/update/delete statements used by the ORM flush process
are qualifying.

The "page size" for the psycopg2 "batch" strategy can be affected
by using the ``executemany_batch_page_size`` parameter, which defaults to
100.

For the "insertmanyvalues" feature, the page size can be controlled using the
:paramref:`_sa.create_engine.insertmanyvalues_page_size` parameter,
which defaults to 1000.  An example of modifying both parameters
is below::

    engine = create_engine(
        "postgresql+psycopg2://scott:tiger@host/dbname",
        executemany_mode="values_plus_batch",
        insertmanyvalues_page_size=5000,
        executemany_batch_page_size=500,
    )

.. seealso::

    :ref:`engine_insertmanyvalues` - background on "insertmanyvalues"

    :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.

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

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.

    )annotationsN)cast   )ranges)_PGDialect_common_psycopg)"_PGExecutionContext_common_psycopg)PGIdentifierPreparer)JSON)JSONB   )types)util)FastIntFlag)parse_user_argument_for_enumzsqlalchemy.dialects.postgresqlc                   @     e Zd Zdd ZdS )_PGJSONc                 C     d S N selfdialectcoltyper   r   i/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/sqlalchemy/dialects/postgresql/psycopg2.pyresult_processor     z_PGJSON.result_processorN__name__
__module____qualname__r   r   r   r   r   r          r   c                   @  r   )_PGJSONBc                 C  r   r   r   r   r   r   r   r     r   z_PGJSONB.result_processorNr   r   r   r   r   r!     r    r!   c                   @  s    e Zd ZdZdd Zdd ZdS )_Psycopg2Rangenonec                   s$   t tt|j| j  fdd}|S )Nc                   s&   t | tjr | j| j| j| j} | S r   )
isinstancer   Rangelowerupperboundsemptyvaluepsycopg2_Ranger   r   to_range  s
   z/_Psycopg2Range.bind_processor.<locals>.to_range)getattrr   PGDialect_psycopg2_psycopg2_extras_psycopg2_range_cls)r   r   r.   r   r,   r   bind_processor  s   
z_Psycopg2Range.bind_processorc                 C  s   dd }|S )Nc                 S  s2   | d urt j| j| j| jr| jnd| j d} | S )Nz[))r(   r)   )r   r%   _lower_upper_boundsr*   r   r   r   r.     s   z1_Psycopg2Range.result_processor.<locals>.to_ranger   )r   r   r   r.   r   r   r   r     s   
z_Psycopg2Range.result_processorN)r   r   r   r2   r3   r   r   r   r   r   r"   
  s    r"   c                   @     e Zd ZdZdS )_Psycopg2NumericRangeNumericRangeNr   r   r   r2   r   r   r   r   r8   *      r8   c                   @  r7   )_Psycopg2DateRange	DateRangeNr:   r   r   r   r   r<   .  r;   r<   c                   @  r7   )_Psycopg2DateTimeRangeDateTimeRangeNr:   r   r   r   r   r>   2  r;   r>   c                   @  r7   )_Psycopg2DateTimeTZRangeDateTimeTZRangeNr:   r   r   r   r   r@   6  r;   r@   c                   @  s    e Zd ZdZdd Zdd ZdS )PGExecutionContext_psycopg2Nc                 C  s   |  | j d S r   )_log_noticescursorr   r   r   r   	post_exec=     z%PGExecutionContext_psycopg2.post_execc                 C  sL   |j jrt|j jtjsd S |j jD ]	}t|  qg |j jd d < d S r   )
connectionnoticesr$   collections_abcIterableloggerinforstrip)r   rD   noticer   r   r   rC   @  s   

z(PGExecutionContext_psycopg2._log_notices)r   r   r   _psycopg2_fetched_rowsrF   rC   r   r   r   r   rB   :  s    rB   c                   @  s   e Zd ZdS )PGIdentifierPreparer_psycopg2N)r   r   r   r   r   r   r   rQ   R  s    rQ   c                   @  s   e Zd ZdZdZdS )ExecutemanyModer   r   N)r   r   r   EXECUTEMANY_VALUESEXECUTEMANY_VALUES_PLUS_BATCHr   r   r   r   rR   V  s    rR   c                      s\  e Zd ZdZdZdZdZdZeZ	e
ZdZdZdZdZeejeeejeeeejeejeejeejeej e!ej"e#i	Z		d3dd	Z$ fd
dZ%e&dd Z'ej(dd Z)ej(dd Z*ej(dd Z+dd Z,dd Z-dd Z.dd Z/dd Z0dd Z1d4d!d"Z2d#d$ Z3d%d& Z4d5d'd(Z5	d6d)d*Z6	d6d+d,Z7ej8d-d. Z9d/d0 Z:ej(d1d2 Z;  Z<S )7r0   psycopg2TpyformatF)r   r   values_onlyd   c                 K  s   t j| fi | | jrtdt|tdgtdgid| _|| _| j	rKt
| j	drMtd| j	j}|rBtdd |d	d
dD | _| jdk rOtdd S d S d S )NzThe psycopg2 dialect does not implement ipaddress type handling; native_inet_types cannot be set to ``True`` when using this dialect.rW   values_plus_batchexecutemany_mode__version__z(\d+)\.(\d+)(?:\.(\d+))?c                 s  s     | ]}|d urt |V  qd S r   )int).0xr   r   r   	<genexpr>  s    z.PGDialect_psycopg2.__init__.<locals>.<genexpr>r      r   )r`      z+psycopg2 version 2.7 or higher is required.)r   __init___native_inet_typesNotImplementedErrorr   rS   rT   rZ   executemany_batch_page_sizedbapihasattrrematchr[   tuplegrouppsycopg2_versionImportError)r   rZ   re   kwargsmr   r   r   rb     s2   	

zPGDialect_psycopg2.__init__c                   s6   t  | | jo| |jjd u| _| jtu| _	d S r   )
super
initializeuse_native_hstore_hstore_oidsrH   dbapi_connection_has_native_hstorerZ   rT   supports_sane_multi_rowcountr   rH   	__class__r   r   rq     s   zPGDialect_psycopg2.initializec                 C  s   dd l }|S )Nr   )rU   )clsrU   r   r   r   import_dbapi  s   zPGDialect_psycopg2.import_dbapic                 C     ddl m} |S )Nr   )
extensions)rU   r}   )rz   r}   r   r   r   _psycopg2_extensions     z'PGDialect_psycopg2._psycopg2_extensionsc                 C  r|   )Nr   extras)rU   r   )rz   r   r   r   r   r1     r   z#PGDialect_psycopg2._psycopg2_extrasc                 C  s    | 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}   r   r   r   _isolation_lookup  s   z$PGDialect_psycopg2._isolation_lookupc                 C  s   | | j|  d S r   )set_isolation_levelr   )r   rt   levelr   r   r   r     s   z&PGDialect_psycopg2.set_isolation_levelc                 C  
   ||_ d S r   readonlyr   rH   r+   r   r   r   set_readonly     
zPGDialect_psycopg2.set_readonlyc                 C     |j S r   r   rw   r   r   r   get_readonly     zPGDialect_psycopg2.get_readonlyc                 C  r   r   
deferrabler   r   r   r   set_deferrable  r   z!PGDialect_psycopg2.set_deferrablec                 C  r   r   r   rw   r   r   r   get_deferrable  r   z!PGDialect_psycopg2.get_deferrablec                   s   j  g jd urfdd}| jr# fdd}| jr5jr5 fdd}| jrGjrG fdd}| rQfdd}|S d S )Nc                   s   |   j d S r   )set_client_encodingclient_encoding
dbapi_connrE   r   r   
on_connect  rG   z1PGDialect_psycopg2.on_connect.<locals>.on_connectc                   s     d |  d S r   )register_uuidr   r   r   r   r     rG   c                   sD    | }|d ur |\}}d|i}||d<  j| fi | d S d S )Noid	array_oid)rs   register_hstore)r   hstore_oidsr   r   kwr   r   r   r   r     s   
c                   s$    j | jd  j| jd d S )N)loads)register_default_json_json_deserializerregister_default_jsonbr   r   r   r   r     s   
c                   s    D ]}||  qd S r   r   )r   fn)fnsr   r   r     s   
)r1   r   appendrf   rr   r   )r   r   r   )r   r   r   r   r     s$   




zPGDialect_psycopg2.on_connectNc                 C  sL   | j tu r| jrd| ji}ni }| jj|||fi | d S ||| d S )N	page_size)rZ   rT   re   r1   execute_batchexecutemany)r   rD   	statement
parameterscontextrn   r   r   r   do_executemany  s   

z!PGDialect_psycopg2.do_executemanyc                 C  s   |j | d S r   )rH   	tpc_beginr   rH   xidr   r   r   do_begin_twophase"  rG   z$PGDialect_psycopg2.do_begin_twophasec                 C  s   |j   d S r   )rH   tpc_preparer   r   r   r   do_prepare_twophase%  s   z&PGDialect_psycopg2.do_prepare_twophasec                 C  s0   |r|j | jjkr|  || d S |  d S r   )statusr~   STATUS_READYrollback)r   r   	operationr   recoverr   r   r   _do_twophase(  s
   
zPGDialect_psycopg2._do_twophasec                 C      |j j}| j||j||d d S N)r   )rH   rt   r   tpc_rollbackr   rH   r   is_preparedr   r   r   r   r   do_rollback_twophase0     

z'PGDialect_psycopg2.do_rollback_twophasec                 C  r   r   )rH   rt   r   
tpc_commitr   r   r   r   do_commit_twophase8  r   z%PGDialect_psycopg2.do_commit_twophasec                 C  s2   | j }|j|}|d ur|d r|dd S d S )Nr   r`   )r1   HstoreAdapterget_oids)r   rt   r   oidsr   r   r   rs   @  s
   zPGDialect_psycopg2._hstore_oidsc                 C  sh   t || jjr2t|ddrdS t|dd }| jD ]}||}|dkr1d|d | vr1 dS qdS )NclosedFT
r   ")r$   rf   Errorr/   str	partition_is_disconnect_messagesfind)r   erH   rD   str_emsgidxr   r   r   is_disconnectI  s   

z PGDialect_psycopg2.is_disconnectc                 C  s   dS )N)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 addresszSSL SYSCALL error: Successr   rE   r   r   r   r   [  s   z*PGDialect_psycopg2._is_disconnect_messages)rW   rX   r   )F)TF)=r   r   r   driversupports_statement_cachesupports_server_side_cursorsdefault_paramstylerv   rB   execution_ctx_clsrQ   preparerrl   !use_insertmanyvalues_wo_returningreturns_native_bytesru   r   update_copyr   colspecsr	   r   sqltypesr
   r!   r   	INT4RANGEr8   	INT8RANGENUMRANGE	DATERANGEr<   TSRANGEr>   	TSTZRANGEr@   rb   rq   classmethodr{   memoized_propertyr~   r1   r   r   r   r   r   r   r   r   r   r   r   r   r   memoized_instancemethodrs   r   r   __classcell__r   r   rx   r   r0   a  sp    
(





4
	
	

r0   ),__doc__
__future__r   collections.abcabcrJ   loggingrh   typingr    r   _psycopg_commonr   r   baser   jsonr	   r
   r   r   r   r   r   	getLoggerrL   r   r!   AbstractSingleRangeImplr"   r8   r<   r>   r@   rB   rQ   rR   __members__valuesrS   rT   r0   r   r   r   r   r   <module>   sL      e
   