o
    g                    @  s  d Z ddlmZ ddlmZ ddlm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$ 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%m0Z0 dd'l%m1Z1 dd(l%m2Z2 dd)l%m3Z3 dd*l%m4Z4 dd+l%m5Z5 dd,l%m6Z6 dd-l%m7Z7 dd.l%m8Z8 dd/l%m9Z9 dd0l%m:Z: dd1l%m;Z; dd2l%m<Z< dd3l%m=Z= dd4l%m>Z> d5d6lm?Z? d5d7lm@Z@ d5d8lmAZA d5d9lmBZB d5d:lmCZC d5d;lDmEZE d5d<lDmFZF d5d=lDmGZG d5d>lDmHZH d5d?lDmIZI d5d@lDmJZJ d5dAlDmKZK d5dBlLmMZM d5dClBmNZN d5dDlBmOZO d5dElBmPZP d5dFlBmQZQ d5dGlBmRZR d5dHlBmSZS d5dIlBmTZT d5d:lBmCZU d5dJlVmWZW d5dKlXmYZY d5dLl%mZZZ d5dMl%m[Z[ d5dNl%m\Z\ d5dOl%m]Z] d5dPl%m^Z^ d5dQl%m_Z_ d5dRl%m`Z` d5dSl%maZa d5dTl%mbZb d5dUl%mcZc d5dVl%mdZd d5dWl%meZe d5dXl%mfZf d5dYlgmhZh eidZejjZkh d[ZleTjmejmeTjne.eTjoe#eTjpjqejreTjpejpeTjse9iZti d\ejmd]ed^ejpd_ejud`ejvdaejwdbejxdcejyddejzdeej{dfej|dgej}dhej~diejdjejdkejdle`i dmeZdnecdoefdpe\dqeTjdreTjdseddteadue_dvebdwe-dxe+dye,dzeed{e)d|e)d}e/i d~e0de1de2de:de^de=de=de=de<de<de]de<de*de[de.de>ZG dd dePjZG dd dePjZG dd dePjZG dd dePjZG dd dehZG dd dehZG dd deZG dd deZG dd deJjZG dd deFjZG dd deEjZG dd deEjZG dd deFjZdS )a  
.. dialect:: postgresql
    :name: PostgreSQL
    :normal_support: 9.6+
    :best_effort: 9+

.. _postgresql_sequences:

Sequences/SERIAL/IDENTITY
-------------------------

PostgreSQL supports sequences, and SQLAlchemy uses these as the default means
of creating new primary key values for integer-based primary key columns. When
creating tables, SQLAlchemy will issue the ``SERIAL`` datatype for
integer-based primary key columns, which generates a sequence and server side
default corresponding to the column.

To specify a specific named sequence to be used for primary key generation,
use the :func:`~sqlalchemy.schema.Sequence` construct::

    Table(
        "sometable",
        metadata,
        Column(
            "id", Integer, Sequence("some_id_seq", start=1), primary_key=True
        ),
    )

When SQLAlchemy issues a single INSERT statement, to fulfill the contract of
having the "last insert identifier" available, a RETURNING clause is added to
the INSERT statement which specifies the primary key columns should be
returned after the statement completes. The RETURNING functionality only takes
place if PostgreSQL 8.2 or later is in use. As a fallback approach, the
sequence, whether specified explicitly or implicitly via ``SERIAL``, is
executed independently beforehand, the returned value to be used in the
subsequent insert. Note that when an
:func:`~sqlalchemy.sql.expression.insert()` construct is executed using
"executemany" semantics, the "last inserted identifier" functionality does not
apply; no RETURNING clause is emitted nor is the sequence pre-executed in this
case.


PostgreSQL 10 and above IDENTITY columns
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

PostgreSQL 10 and above have a new IDENTITY feature that supersedes the use
of SERIAL. The :class:`_schema.Identity` construct in a
:class:`_schema.Column` can be used to control its behavior::

    from sqlalchemy import Table, Column, MetaData, Integer, Computed

    metadata = MetaData()

    data = Table(
        "data",
        metadata,
        Column(
            "id", Integer, Identity(start=42, cycle=True), primary_key=True
        ),
        Column("data", String),
    )

The CREATE TABLE for the above :class:`_schema.Table` object would be:

.. sourcecode:: sql

    CREATE TABLE data (
        id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 42 CYCLE),
        data VARCHAR,
        PRIMARY KEY (id)
    )

.. versionchanged::  1.4   Added :class:`_schema.Identity` construct
   in a :class:`_schema.Column` to specify the option of an autoincrementing
   column.

.. note::

   Previous versions of SQLAlchemy did not have built-in support for rendering
   of IDENTITY, and could use the following compilation hook to replace
   occurrences of SERIAL with IDENTITY::

       from sqlalchemy.schema import CreateColumn
       from sqlalchemy.ext.compiler import compiles


       @compiles(CreateColumn, "postgresql")
       def use_identity(element, compiler, **kw):
           text = compiler.visit_create_column(element, **kw)
           text = text.replace("SERIAL", "INT GENERATED BY DEFAULT AS IDENTITY")
           return text

   Using the above, a table such as::

       t = Table(
           "t", m, Column("id", Integer, primary_key=True), Column("data", String)
       )

   Will generate on the backing database as:

   .. sourcecode:: sql

       CREATE TABLE t (
           id INT GENERATED BY DEFAULT AS IDENTITY,
           data VARCHAR,
           PRIMARY KEY (id)
       )

.. _postgresql_ss_cursors:

Server Side Cursors
-------------------

Server-side cursor support is available for the psycopg2, asyncpg
dialects and may also be available in others.

Server side cursors are enabled on a per-statement basis by using the
:paramref:`.Connection.execution_options.stream_results` connection execution
option::

    with engine.connect() as conn:
        result = conn.execution_options(stream_results=True).execute(
            text("select * from table")
        )

Note that some kinds of SQL statements may not be supported with
server side cursors; generally, only SQL statements that return rows should be
used with this option.

.. deprecated:: 1.4  The dialect-level server_side_cursors flag is deprecated
   and will be removed in a future release.  Please use the
   :paramref:`_engine.Connection.stream_results` execution option for
   unbuffered cursor support.

.. seealso::

    :ref:`engine_stream_results`

.. _postgresql_isolation_level:

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

Most SQLAlchemy dialects support setting of transaction isolation level
using the :paramref:`_sa.create_engine.isolation_level` parameter
at the :func:`_sa.create_engine` level, and at the :class:`_engine.Connection`
level via the :paramref:`.Connection.execution_options.isolation_level`
parameter.

For PostgreSQL dialects, this feature works either by making use of the
DBAPI-specific features, such as psycopg2's isolation level flags which will
embed the isolation level setting inline with the ``"BEGIN"`` statement, or for
DBAPIs with no direct support by emitting ``SET SESSION CHARACTERISTICS AS
TRANSACTION ISOLATION LEVEL <level>`` ahead of the ``"BEGIN"`` statement
emitted by the DBAPI.   For the special AUTOCOMMIT isolation level,
DBAPI-specific techniques are used which is typically an ``.autocommit``
flag on the DBAPI connection object.

To set isolation level using :func:`_sa.create_engine`::

    engine = create_engine(
        "postgresql+pg8000://scott:tiger@localhost/test",
        isolation_level="REPEATABLE READ",
    )

To set using per-connection execution options::

    with engine.connect() as conn:
        conn = conn.execution_options(isolation_level="REPEATABLE READ")
        with conn.begin():
            ...  # work with transaction

There are also more options for isolation level configurations, such as
"sub-engine" objects linked to a main :class:`_engine.Engine` which each apply
different isolation level settings.  See the discussion at
:ref:`dbapi_autocommit` for background.

Valid values for ``isolation_level`` on most PostgreSQL dialects include:

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

.. seealso::

    :ref:`dbapi_autocommit`

    :ref:`postgresql_readonly_deferrable`

    :ref:`psycopg2_isolation_level`

    :ref:`pg8000_isolation_level`

.. _postgresql_readonly_deferrable:

Setting READ ONLY / DEFERRABLE
------------------------------

Most PostgreSQL dialects support setting the "READ ONLY" and "DEFERRABLE"
characteristics of the transaction, which is in addition to the isolation level
setting. These two attributes can be established either in conjunction with or
independently of the isolation level by passing the ``postgresql_readonly`` and
``postgresql_deferrable`` flags with
:meth:`_engine.Connection.execution_options`.  The example below illustrates
passing the ``"SERIALIZABLE"`` isolation level at the same time as setting
"READ ONLY" and "DEFERRABLE"::

    with engine.connect() as conn:
        conn = conn.execution_options(
            isolation_level="SERIALIZABLE",
            postgresql_readonly=True,
            postgresql_deferrable=True,
        )
        with conn.begin():
            ...  # work with transaction

Note that some DBAPIs such as asyncpg only support "readonly" with
SERIALIZABLE isolation.

.. versionadded:: 1.4 added support for the ``postgresql_readonly``
   and ``postgresql_deferrable`` execution options.

.. _postgresql_reset_on_return:

Temporary Table / Resource Reset for Connection Pooling
-------------------------------------------------------

The :class:`.QueuePool` connection pool implementation used
by the SQLAlchemy :class:`.Engine` object includes
:ref:`reset on return <pool_reset_on_return>` behavior that will invoke
the DBAPI ``.rollback()`` method when connections are returned to the pool.
While this rollback will clear out the immediate state used by the previous
transaction, it does not cover a wider range of session-level state, including
temporary tables as well as other server state such as prepared statement
handles and statement caches.   The PostgreSQL database includes a variety
of commands which may be used to reset this state, including
``DISCARD``, ``RESET``, ``DEALLOCATE``, and ``UNLISTEN``.


To install
one or more of these commands as the means of performing reset-on-return,
the :meth:`.PoolEvents.reset` event hook may be used, as demonstrated
in the example below. The implementation
will end transactions in progress as well as discard temporary tables
using the ``CLOSE``, ``RESET`` and ``DISCARD`` commands; see the PostgreSQL
documentation for background on what each of these statements do.

The :paramref:`_sa.create_engine.pool_reset_on_return` parameter
is set to ``None`` so that the custom scheme can replace the default behavior
completely.   The custom hook implementation calls ``.rollback()`` in any case,
as it's usually important that the DBAPI's own tracking of commit/rollback
will remain consistent with the state of the transaction::


    from sqlalchemy import create_engine
    from sqlalchemy import event

    postgresql_engine = create_engine(
        "postgresql+pyscopg2://scott:tiger@hostname/dbname",
        # disable default reset-on-return scheme
        pool_reset_on_return=None,
    )


    @event.listens_for(postgresql_engine, "reset")
    def _reset_postgresql(dbapi_connection, connection_record, reset_state):
        if not reset_state.terminate_only:
            dbapi_connection.execute("CLOSE ALL")
            dbapi_connection.execute("RESET ALL")
            dbapi_connection.execute("DISCARD TEMP")

        # so that the DBAPI itself knows that the connection has been
        # reset
        dbapi_connection.rollback()

.. versionchanged:: 2.0.0b3  Added additional state arguments to
   the :meth:`.PoolEvents.reset` event and additionally ensured the event
   is invoked for all "reset" occurrences, so that it's appropriate
   as a place for custom "reset" handlers.   Previous schemes which
   use the :meth:`.PoolEvents.checkin` handler remain usable as well.

.. seealso::

    :ref:`pool_reset_on_return` - in the :ref:`pooling_toplevel` documentation

.. _postgresql_alternate_search_path:

Setting Alternate Search Paths on Connect
------------------------------------------

The PostgreSQL ``search_path`` variable refers to the list of schema names
that will be implicitly referenced when a particular table or other
object is referenced in a SQL statement.  As detailed in the next section
:ref:`postgresql_schema_reflection`, SQLAlchemy is generally organized around
the concept of keeping this variable at its default value of ``public``,
however, in order to have it set to any arbitrary name or names when connections
are used automatically, the "SET SESSION search_path" command may be invoked
for all connections in a pool using the following event handler, as discussed
at :ref:`schema_set_default_connections`::

    from sqlalchemy import event
    from sqlalchemy import create_engine

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


    @event.listens_for(engine, "connect", insert=True)
    def set_search_path(dbapi_connection, connection_record):
        existing_autocommit = dbapi_connection.autocommit
        dbapi_connection.autocommit = True
        cursor = dbapi_connection.cursor()
        cursor.execute("SET SESSION search_path='%s'" % schema_name)
        cursor.close()
        dbapi_connection.autocommit = existing_autocommit

The reason the recipe is complicated by use of the ``.autocommit`` DBAPI
attribute is so that when the ``SET SESSION search_path`` directive is invoked,
it is invoked outside of the scope of any transaction and therefore will not
be reverted when the DBAPI connection has a rollback.

.. seealso::

  :ref:`schema_set_default_connections` - in the :ref:`metadata_toplevel` documentation

.. _postgresql_schema_reflection:

Remote-Schema Table Introspection and PostgreSQL search_path
------------------------------------------------------------

.. admonition:: Section Best Practices Summarized

    keep the ``search_path`` variable set to its default of ``public``, without
    any other schema names. Ensure the username used to connect **does not**
    match remote schemas, or ensure the ``"$user"`` token is **removed** from
    ``search_path``.  For other schema names, name these explicitly
    within :class:`_schema.Table` definitions. Alternatively, the
    ``postgresql_ignore_search_path`` option will cause all reflected
    :class:`_schema.Table` objects to have a :attr:`_schema.Table.schema`
    attribute set up.

The PostgreSQL dialect can reflect tables from any schema, as outlined in
:ref:`metadata_reflection_schemas`.

In all cases, the first thing SQLAlchemy does when reflecting tables is
to **determine the default schema for the current database connection**.
It does this using the PostgreSQL ``current_schema()``
function, illustated below using a PostgreSQL client session (i.e. using
the ``psql`` tool):

.. sourcecode:: sql

    test=> select current_schema();
    current_schema
    ----------------
    public
    (1 row)

Above we see that on a plain install of PostgreSQL, the default schema name
is the name ``public``.

However, if your database username **matches the name of a schema**, PostgreSQL's
default is to then **use that name as the default schema**.  Below, we log in
using the username ``scott``.  When we create a schema named ``scott``, **it
implicitly changes the default schema**:

.. sourcecode:: sql

    test=> select current_schema();
    current_schema
    ----------------
    public
    (1 row)

    test=> create schema scott;
    CREATE SCHEMA
    test=> select current_schema();
    current_schema
    ----------------
    scott
    (1 row)

The behavior of ``current_schema()`` is derived from the
`PostgreSQL search path
<https://www.postgresql.org/docs/current/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_
variable ``search_path``, which in modern PostgreSQL versions defaults to this:

.. sourcecode:: sql

    test=> show search_path;
    search_path
    -----------------
    "$user", public
    (1 row)

Where above, the ``"$user"`` variable will inject the current username as the
default schema, if one exists.   Otherwise, ``public`` is used.

When a :class:`_schema.Table` object is reflected, if it is present in the
schema indicated by the ``current_schema()`` function, **the schema name assigned
to the ".schema" attribute of the Table is the Python "None" value**.  Otherwise, the
".schema" attribute will be assigned the string name of that schema.

With regards to tables which these :class:`_schema.Table`
objects refer to via foreign key constraint, a decision must be made as to how
the ``.schema`` is represented in those remote tables, in the case where that
remote schema name is also a member of the current ``search_path``.

By default, the PostgreSQL dialect mimics the behavior encouraged by
PostgreSQL's own ``pg_get_constraintdef()`` builtin procedure.  This function
returns a sample definition for a particular foreign key constraint,
omitting the referenced schema name from that definition when the name is
also in the PostgreSQL schema search path.  The interaction below
illustrates this behavior:

.. sourcecode:: sql

    test=> CREATE TABLE test_schema.referred(id INTEGER PRIMARY KEY);
    CREATE TABLE
    test=> CREATE TABLE referring(
    test(>         id INTEGER PRIMARY KEY,
    test(>         referred_id INTEGER REFERENCES test_schema.referred(id));
    CREATE TABLE
    test=> SET search_path TO public, test_schema;
    test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM
    test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n
    test-> ON n.oid = c.relnamespace
    test-> JOIN pg_catalog.pg_constraint r  ON c.oid = r.conrelid
    test-> WHERE c.relname='referring' AND r.contype = 'f'
    test-> ;
                   pg_get_constraintdef
    ---------------------------------------------------
     FOREIGN KEY (referred_id) REFERENCES referred(id)
    (1 row)

Above, we created a table ``referred`` as a member of the remote schema
``test_schema``, however when we added ``test_schema`` to the
PG ``search_path`` and then asked ``pg_get_constraintdef()`` for the
``FOREIGN KEY`` syntax, ``test_schema`` was not included in the output of
the function.

On the other hand, if we set the search path back to the typical default
of ``public``:

.. sourcecode:: sql

    test=> SET search_path TO public;
    SET

The same query against ``pg_get_constraintdef()`` now returns the fully
schema-qualified name for us:

.. sourcecode:: sql

    test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM
    test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n
    test-> ON n.oid = c.relnamespace
    test-> JOIN pg_catalog.pg_constraint r  ON c.oid = r.conrelid
    test-> WHERE c.relname='referring' AND r.contype = 'f';
                         pg_get_constraintdef
    ---------------------------------------------------------------
     FOREIGN KEY (referred_id) REFERENCES test_schema.referred(id)
    (1 row)

SQLAlchemy will by default use the return value of ``pg_get_constraintdef()``
in order to determine the remote schema name.  That is, if our ``search_path``
were set to include ``test_schema``, and we invoked a table
reflection process as follows::

    >>> from sqlalchemy import Table, MetaData, create_engine, text
    >>> engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test")
    >>> with engine.connect() as conn:
    ...     conn.execute(text("SET search_path TO test_schema, public"))
    ...     metadata_obj = MetaData()
    ...     referring = Table("referring", metadata_obj, autoload_with=conn)
    <sqlalchemy.engine.result.CursorResult object at 0x101612ed0>

The above process would deliver to the :attr:`_schema.MetaData.tables`
collection
``referred`` table named **without** the schema::

    >>> metadata_obj.tables["referred"].schema is None
    True

To alter the behavior of reflection such that the referred schema is
maintained regardless of the ``search_path`` setting, use the
``postgresql_ignore_search_path`` option, which can be specified as a
dialect-specific argument to both :class:`_schema.Table` as well as
:meth:`_schema.MetaData.reflect`::

    >>> with engine.connect() as conn:
    ...     conn.execute(text("SET search_path TO test_schema, public"))
    ...     metadata_obj = MetaData()
    ...     referring = Table(
    ...         "referring",
    ...         metadata_obj,
    ...         autoload_with=conn,
    ...         postgresql_ignore_search_path=True,
    ...     )
    <sqlalchemy.engine.result.CursorResult object at 0x1016126d0>

We will now have ``test_schema.referred`` stored as schema-qualified::

    >>> metadata_obj.tables["test_schema.referred"].schema
    'test_schema'

.. sidebar:: Best Practices for PostgreSQL Schema reflection

    The description of PostgreSQL schema reflection behavior is complex, and
    is the product of many years of dealing with widely varied use cases and
    user preferences. But in fact, there's no need to understand any of it if
    you just stick to the simplest use pattern: leave the ``search_path`` set
    to its default of ``public`` only, never refer to the name ``public`` as
    an explicit schema name otherwise, and refer to all other schema names
    explicitly when building up a :class:`_schema.Table` object.  The options
    described here are only for those users who can't, or prefer not to, stay
    within these guidelines.

.. seealso::

    :ref:`reflection_schema_qualified_interaction` - discussion of the issue
    from a backend-agnostic perspective

    `The Schema Search Path
    <https://www.postgresql.org/docs/current/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_
    - on the PostgreSQL website.

INSERT/UPDATE...RETURNING
-------------------------

The dialect supports PG 8.2's ``INSERT..RETURNING``, ``UPDATE..RETURNING`` and
``DELETE..RETURNING`` syntaxes.   ``INSERT..RETURNING`` is used by default
for single-row INSERT statements in order to fetch newly generated
primary key identifiers.   To specify an explicit ``RETURNING`` clause,
use the :meth:`._UpdateBase.returning` method on a per-statement basis::

    # INSERT..RETURNING
    result = (
        table.insert().returning(table.c.col1, table.c.col2).values(name="foo")
    )
    print(result.fetchall())

    # UPDATE..RETURNING
    result = (
        table.update()
        .returning(table.c.col1, table.c.col2)
        .where(table.c.name == "foo")
        .values(name="bar")
    )
    print(result.fetchall())

    # DELETE..RETURNING
    result = (
        table.delete()
        .returning(table.c.col1, table.c.col2)
        .where(table.c.name == "foo")
    )
    print(result.fetchall())

.. _postgresql_insert_on_conflict:

INSERT...ON CONFLICT (Upsert)
------------------------------

Starting with version 9.5, PostgreSQL allows "upserts" (update or insert) of
rows into a table via the ``ON CONFLICT`` clause of the ``INSERT`` statement. A
candidate row will only be inserted if that row does not violate any unique
constraints.  In the case of a unique constraint violation, a secondary action
can occur which can be either "DO UPDATE", indicating that the data in the
target row should be updated, or "DO NOTHING", which indicates to silently skip
this row.

Conflicts are determined using existing unique constraints and indexes.  These
constraints may be identified either using their name as stated in DDL,
or they may be inferred by stating the columns and conditions that comprise
the indexes.

SQLAlchemy provides ``ON CONFLICT`` support via the PostgreSQL-specific
:func:`_postgresql.insert()` function, which provides
the generative methods :meth:`_postgresql.Insert.on_conflict_do_update`
and :meth:`~.postgresql.Insert.on_conflict_do_nothing`:

.. sourcecode:: pycon+sql

    >>> from sqlalchemy.dialects.postgresql import insert
    >>> insert_stmt = insert(my_table).values(
    ...     id="some_existing_id", data="inserted value"
    ... )
    >>> do_nothing_stmt = insert_stmt.on_conflict_do_nothing(index_elements=["id"])
    >>> print(do_nothing_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT (id) DO NOTHING
    {stop}

    >>> do_update_stmt = insert_stmt.on_conflict_do_update(
    ...     constraint="pk_my_table", set_=dict(data="updated value")
    ... )
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT ON CONSTRAINT pk_my_table DO UPDATE SET data = %(param_1)s

.. seealso::

    `INSERT .. ON CONFLICT
    <https://www.postgresql.org/docs/current/static/sql-insert.html#SQL-ON-CONFLICT>`_
    - in the PostgreSQL documentation.

Specifying the Target
^^^^^^^^^^^^^^^^^^^^^

Both methods supply the "target" of the conflict using either the
named constraint or by column inference:

* The :paramref:`_postgresql.Insert.on_conflict_do_update.index_elements` argument
  specifies a sequence containing string column names, :class:`_schema.Column`
  objects, and/or SQL expression elements, which would identify a unique
  index:

  .. sourcecode:: pycon+sql

    >>> do_update_stmt = insert_stmt.on_conflict_do_update(
    ...     index_elements=["id"], set_=dict(data="updated value")
    ... )
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT (id) DO UPDATE SET data = %(param_1)s
    {stop}

    >>> do_update_stmt = insert_stmt.on_conflict_do_update(
    ...     index_elements=[my_table.c.id], set_=dict(data="updated value")
    ... )
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT (id) DO UPDATE SET data = %(param_1)s

* When using :paramref:`_postgresql.Insert.on_conflict_do_update.index_elements` to
  infer an index, a partial index can be inferred by also specifying the
  use the :paramref:`_postgresql.Insert.on_conflict_do_update.index_where` parameter:

  .. sourcecode:: pycon+sql

    >>> stmt = insert(my_table).values(user_email="a@b.com", data="inserted data")
    >>> stmt = stmt.on_conflict_do_update(
    ...     index_elements=[my_table.c.user_email],
    ...     index_where=my_table.c.user_email.like("%@gmail.com"),
    ...     set_=dict(data=stmt.excluded.data),
    ... )
    >>> print(stmt)
    {printsql}INSERT INTO my_table (data, user_email)
    VALUES (%(data)s, %(user_email)s) ON CONFLICT (user_email)
    WHERE user_email LIKE %(user_email_1)s DO UPDATE SET data = excluded.data

* The :paramref:`_postgresql.Insert.on_conflict_do_update.constraint` argument is
  used to specify an index directly rather than inferring it.  This can be
  the name of a UNIQUE constraint, a PRIMARY KEY constraint, or an INDEX:

  .. sourcecode:: pycon+sql

    >>> do_update_stmt = insert_stmt.on_conflict_do_update(
    ...     constraint="my_table_idx_1", set_=dict(data="updated value")
    ... )
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT ON CONSTRAINT my_table_idx_1 DO UPDATE SET data = %(param_1)s
    {stop}

    >>> do_update_stmt = insert_stmt.on_conflict_do_update(
    ...     constraint="my_table_pk", set_=dict(data="updated value")
    ... )
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT ON CONSTRAINT my_table_pk DO UPDATE SET data = %(param_1)s
    {stop}

* The :paramref:`_postgresql.Insert.on_conflict_do_update.constraint` argument may
  also refer to a SQLAlchemy construct representing a constraint,
  e.g. :class:`.UniqueConstraint`, :class:`.PrimaryKeyConstraint`,
  :class:`.Index`, or :class:`.ExcludeConstraint`.   In this use,
  if the constraint has a name, it is used directly.  Otherwise, if the
  constraint is unnamed, then inference will be used, where the expressions
  and optional WHERE clause of the constraint will be spelled out in the
  construct.  This use is especially convenient
  to refer to the named or unnamed primary key of a :class:`_schema.Table`
  using the
  :attr:`_schema.Table.primary_key` attribute:

  .. sourcecode:: pycon+sql

    >>> do_update_stmt = insert_stmt.on_conflict_do_update(
    ...     constraint=my_table.primary_key, set_=dict(data="updated value")
    ... )
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT (id) DO UPDATE SET data = %(param_1)s

The SET Clause
^^^^^^^^^^^^^^^

``ON CONFLICT...DO UPDATE`` is used to perform an update of the already
existing row, using any combination of new values as well as values
from the proposed insertion.   These values are specified using the
:paramref:`_postgresql.Insert.on_conflict_do_update.set_` parameter.  This
parameter accepts a dictionary which consists of direct values
for UPDATE:

.. sourcecode:: pycon+sql

    >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
    >>> do_update_stmt = stmt.on_conflict_do_update(
    ...     index_elements=["id"], set_=dict(data="updated value")
    ... )
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT (id) DO UPDATE SET data = %(param_1)s

.. warning::

    The :meth:`_expression.Insert.on_conflict_do_update`
    method does **not** take into
    account Python-side default UPDATE values or generation functions, e.g.
    those specified using :paramref:`_schema.Column.onupdate`.
    These values will not be exercised for an ON CONFLICT style of UPDATE,
    unless they are manually specified in the
    :paramref:`_postgresql.Insert.on_conflict_do_update.set_` dictionary.

Updating using the Excluded INSERT Values
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In order to refer to the proposed insertion row, the special alias
:attr:`~.postgresql.Insert.excluded` is available as an attribute on
the :class:`_postgresql.Insert` object; this object is a
:class:`_expression.ColumnCollection`
which alias contains all columns of the target
table:

.. sourcecode:: pycon+sql

    >>> stmt = insert(my_table).values(
    ...     id="some_id", data="inserted value", author="jlh"
    ... )
    >>> do_update_stmt = stmt.on_conflict_do_update(
    ...     index_elements=["id"],
    ...     set_=dict(data="updated value", author=stmt.excluded.author),
    ... )
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data, author)
    VALUES (%(id)s, %(data)s, %(author)s)
    ON CONFLICT (id) DO UPDATE SET data = %(param_1)s, author = excluded.author

Additional WHERE Criteria
^^^^^^^^^^^^^^^^^^^^^^^^^

The :meth:`_expression.Insert.on_conflict_do_update` method also accepts
a WHERE clause using the :paramref:`_postgresql.Insert.on_conflict_do_update.where`
parameter, which will limit those rows which receive an UPDATE:

.. sourcecode:: pycon+sql

    >>> stmt = insert(my_table).values(
    ...     id="some_id", data="inserted value", author="jlh"
    ... )
    >>> on_update_stmt = stmt.on_conflict_do_update(
    ...     index_elements=["id"],
    ...     set_=dict(data="updated value", author=stmt.excluded.author),
    ...     where=(my_table.c.status == 2),
    ... )
    >>> print(on_update_stmt)
    {printsql}INSERT INTO my_table (id, data, author)
    VALUES (%(id)s, %(data)s, %(author)s)
    ON CONFLICT (id) DO UPDATE SET data = %(param_1)s, author = excluded.author
    WHERE my_table.status = %(status_1)s

Skipping Rows with DO NOTHING
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

``ON CONFLICT`` may be used to skip inserting a row entirely
if any conflict with a unique or exclusion constraint occurs; below
this is illustrated using the
:meth:`~.postgresql.Insert.on_conflict_do_nothing` method:

.. sourcecode:: pycon+sql

    >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
    >>> stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
    >>> print(stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT (id) DO NOTHING

If ``DO NOTHING`` is used without specifying any columns or constraint,
it has the effect of skipping the INSERT for any unique or exclusion
constraint violation which occurs:

.. sourcecode:: pycon+sql

    >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
    >>> stmt = stmt.on_conflict_do_nothing()
    >>> print(stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT DO NOTHING

.. _postgresql_match:

Full Text Search
----------------

PostgreSQL's full text search system is available through the use of the
:data:`.func` namespace, combined with the use of custom operators
via the :meth:`.Operators.bool_op` method.    For simple cases with some
degree of cross-backend compatibility, the :meth:`.Operators.match` operator
may also be used.

.. _postgresql_simple_match:

Simple plain text matching with ``match()``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The :meth:`.Operators.match` operator provides for cross-compatible simple
text matching.   For the PostgreSQL backend, it's hardcoded to generate
an expression using the ``@@`` operator in conjunction with the
``plainto_tsquery()`` PostgreSQL function.

On the PostgreSQL dialect, an expression like the following::

    select(sometable.c.text.match("search string"))

would emit to the database:

.. sourcecode:: sql

    SELECT text @@ plainto_tsquery('search string') FROM table

Above, passing a plain string to :meth:`.Operators.match` will automatically
make use of ``plainto_tsquery()`` to specify the type of tsquery.  This
establishes basic database cross-compatibility for :meth:`.Operators.match`
with other backends.

.. versionchanged:: 2.0 The default tsquery generation function used by the
   PostgreSQL dialect with :meth:`.Operators.match` is ``plainto_tsquery()``.

   To render exactly what was rendered in 1.4, use the following form::

        from sqlalchemy import func

        select(sometable.c.text.bool_op("@@")(func.to_tsquery("search string")))

   Which would emit:

   .. sourcecode:: sql

        SELECT text @@ to_tsquery('search string') FROM table

Using PostgreSQL full text functions and operators directly
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Text search operations beyond the simple use of :meth:`.Operators.match`
may make use of the :data:`.func` namespace to generate PostgreSQL full-text
functions, in combination with :meth:`.Operators.bool_op` to generate
any boolean operator.

For example, the query::

    select(func.to_tsquery("cat").bool_op("@>")(func.to_tsquery("cat & rat")))

would generate:

.. sourcecode:: sql

    SELECT to_tsquery('cat') @> to_tsquery('cat & rat')


The :class:`_postgresql.TSVECTOR` type can provide for explicit CAST::

    from sqlalchemy.dialects.postgresql import TSVECTOR
    from sqlalchemy import select, cast

    select(cast("some text", TSVECTOR))

produces a statement equivalent to:

.. sourcecode:: sql

    SELECT CAST('some text' AS TSVECTOR) AS anon_1

The ``func`` namespace is augmented by the PostgreSQL dialect to set up
correct argument and return types for most full text search functions.
These functions are used automatically by the :attr:`_sql.func` namespace
assuming the ``sqlalchemy.dialects.postgresql`` package has been imported,
or :func:`_sa.create_engine` has been invoked using a ``postgresql``
dialect.  These functions are documented at:

* :class:`_postgresql.to_tsvector`
* :class:`_postgresql.to_tsquery`
* :class:`_postgresql.plainto_tsquery`
* :class:`_postgresql.phraseto_tsquery`
* :class:`_postgresql.websearch_to_tsquery`
* :class:`_postgresql.ts_headline`

Specifying the "regconfig" with ``match()`` or custom operators
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

PostgreSQL's ``plainto_tsquery()`` function accepts an optional
"regconfig" argument that is used to instruct PostgreSQL to use a
particular pre-computed GIN or GiST index in order to perform the search.
When using :meth:`.Operators.match`, this additional parameter may be
specified using the ``postgresql_regconfig`` parameter, such as::

    select(mytable.c.id).where(
        mytable.c.title.match("somestring", postgresql_regconfig="english")
    )

Which would emit:

.. sourcecode:: sql

    SELECT mytable.id FROM mytable
    WHERE mytable.title @@ plainto_tsquery('english', 'somestring')

When using other PostgreSQL search functions with :data:`.func`, the
"regconfig" parameter may be passed directly as the initial argument::

    select(mytable.c.id).where(
        func.to_tsvector("english", mytable.c.title).bool_op("@@")(
            func.to_tsquery("english", "somestring")
        )
    )

produces a statement equivalent to:

.. sourcecode:: sql

    SELECT mytable.id FROM mytable
    WHERE to_tsvector('english', mytable.title) @@
        to_tsquery('english', 'somestring')

It is recommended that you use the ``EXPLAIN ANALYZE...`` tool from
PostgreSQL to ensure that you are generating queries with SQLAlchemy that
take full advantage of any indexes you may have created for full text search.

.. seealso::

    `Full Text Search <https://www.postgresql.org/docs/current/textsearch-controls.html>`_ - in the PostgreSQL documentation


FROM ONLY ...
-------------

The dialect supports PostgreSQL's ONLY keyword for targeting only a particular
table in an inheritance hierarchy. This can be used to produce the
``SELECT ... FROM ONLY``, ``UPDATE ONLY ...``, and ``DELETE FROM ONLY ...``
syntaxes. It uses SQLAlchemy's hints mechanism::

    # SELECT ... FROM ONLY ...
    result = table.select().with_hint(table, "ONLY", "postgresql")
    print(result.fetchall())

    # UPDATE ONLY ...
    table.update(values=dict(foo="bar")).with_hint(
        "ONLY", dialect_name="postgresql"
    )

    # DELETE FROM ONLY ...
    table.delete().with_hint("ONLY", dialect_name="postgresql")

.. _postgresql_indexes:

PostgreSQL-Specific Index Options
---------------------------------

Several extensions to the :class:`.Index` construct are available, specific
to the PostgreSQL dialect.

Covering Indexes
^^^^^^^^^^^^^^^^

The ``postgresql_include`` option renders INCLUDE(colname) for the given
string names::

    Index("my_index", table.c.x, postgresql_include=["y"])

would render the index as ``CREATE INDEX my_index ON table (x) INCLUDE (y)``

Note that this feature requires PostgreSQL 11 or later.

.. versionadded:: 1.4

.. _postgresql_partial_indexes:

Partial Indexes
^^^^^^^^^^^^^^^

Partial indexes add criterion to the index definition so that the index is
applied to a subset of rows.   These can be specified on :class:`.Index`
using the ``postgresql_where`` keyword argument::

  Index("my_index", my_table.c.id, postgresql_where=my_table.c.value > 10)

.. _postgresql_operator_classes:

Operator Classes
^^^^^^^^^^^^^^^^

PostgreSQL allows the specification of an *operator class* for each column of
an index (see
https://www.postgresql.org/docs/current/interactive/indexes-opclass.html).
The :class:`.Index` construct allows these to be specified via the
``postgresql_ops`` keyword argument::

    Index(
        "my_index",
        my_table.c.id,
        my_table.c.data,
        postgresql_ops={"data": "text_pattern_ops", "id": "int4_ops"},
    )

Note that the keys in the ``postgresql_ops`` dictionaries are the
"key" name of the :class:`_schema.Column`, i.e. the name used to access it from
the ``.c`` collection of :class:`_schema.Table`, which can be configured to be
different than the actual name of the column as expressed in the database.

If ``postgresql_ops`` is to be used against a complex SQL expression such
as a function call, then to apply to the column it must be given a label
that is identified in the dictionary by name, e.g.::

    Index(
        "my_index",
        my_table.c.id,
        func.lower(my_table.c.data).label("data_lower"),
        postgresql_ops={"data_lower": "text_pattern_ops", "id": "int4_ops"},
    )

Operator classes are also supported by the
:class:`_postgresql.ExcludeConstraint` construct using the
:paramref:`_postgresql.ExcludeConstraint.ops` parameter. See that parameter for
details.

.. versionadded:: 1.3.21 added support for operator classes with
   :class:`_postgresql.ExcludeConstraint`.


Index Types
^^^^^^^^^^^

PostgreSQL provides several index types: B-Tree, Hash, GiST, and GIN, as well
as the ability for users to create their own (see
https://www.postgresql.org/docs/current/static/indexes-types.html). These can be
specified on :class:`.Index` using the ``postgresql_using`` keyword argument::

    Index("my_index", my_table.c.data, postgresql_using="gin")

The value passed to the keyword argument will be simply passed through to the
underlying CREATE INDEX command, so it *must* be a valid index type for your
version of PostgreSQL.

.. _postgresql_index_storage:

Index Storage Parameters
^^^^^^^^^^^^^^^^^^^^^^^^

PostgreSQL allows storage parameters to be set on indexes. The storage
parameters available depend on the index method used by the index. Storage
parameters can be specified on :class:`.Index` using the ``postgresql_with``
keyword argument::

    Index("my_index", my_table.c.data, postgresql_with={"fillfactor": 50})

PostgreSQL allows to define the tablespace in which to create the index.
The tablespace can be specified on :class:`.Index` using the
``postgresql_tablespace`` keyword argument::

    Index("my_index", my_table.c.data, postgresql_tablespace="my_tablespace")

Note that the same option is available on :class:`_schema.Table` as well.

.. _postgresql_index_concurrently:

Indexes with CONCURRENTLY
^^^^^^^^^^^^^^^^^^^^^^^^^

The PostgreSQL index option CONCURRENTLY is supported by passing the
flag ``postgresql_concurrently`` to the :class:`.Index` construct::

    tbl = Table("testtbl", m, Column("data", Integer))

    idx1 = Index("test_idx1", tbl.c.data, postgresql_concurrently=True)

The above index construct will render DDL for CREATE INDEX, assuming
PostgreSQL 8.2 or higher is detected or for a connection-less dialect, as:

.. sourcecode:: sql

    CREATE INDEX CONCURRENTLY test_idx1 ON testtbl (data)

For DROP INDEX, assuming PostgreSQL 9.2 or higher is detected or for
a connection-less dialect, it will emit:

.. sourcecode:: sql

    DROP INDEX CONCURRENTLY test_idx1

When using CONCURRENTLY, the PostgreSQL database requires that the statement
be invoked outside of a transaction block.   The Python DBAPI enforces that
even for a single statement, a transaction is present, so to use this
construct, the DBAPI's "autocommit" mode must be used::

    metadata = MetaData()
    table = Table("foo", metadata, Column("id", String))
    index = Index("foo_idx", table.c.id, postgresql_concurrently=True)

    with engine.connect() as conn:
        with conn.execution_options(isolation_level="AUTOCOMMIT"):
            table.create(conn)

.. seealso::

    :ref:`postgresql_isolation_level`

.. _postgresql_index_reflection:

PostgreSQL Index Reflection
---------------------------

The PostgreSQL database creates a UNIQUE INDEX implicitly whenever the
UNIQUE CONSTRAINT construct is used.   When inspecting a table using
:class:`_reflection.Inspector`, the :meth:`_reflection.Inspector.get_indexes`
and the :meth:`_reflection.Inspector.get_unique_constraints`
will report on these
two constructs distinctly; in the case of the index, the key
``duplicates_constraint`` will be present in the index entry if it is
detected as mirroring a constraint.   When performing reflection using
``Table(..., autoload_with=engine)``, the UNIQUE INDEX is **not** returned
in :attr:`_schema.Table.indexes` when it is detected as mirroring a
:class:`.UniqueConstraint` in the :attr:`_schema.Table.constraints` collection
.

Special Reflection Options
--------------------------

The :class:`_reflection.Inspector`
used for the PostgreSQL backend is an instance
of :class:`.PGInspector`, which offers additional methods::

    from sqlalchemy import create_engine, inspect

    engine = create_engine("postgresql+psycopg2://localhost/test")
    insp = inspect(engine)  # will be a PGInspector

    print(insp.get_enums())

.. autoclass:: PGInspector
    :members:

.. _postgresql_table_options:

PostgreSQL Table Options
------------------------

Several options for CREATE TABLE are supported directly by the PostgreSQL
dialect in conjunction with the :class:`_schema.Table` construct:

* ``INHERITS``::

    Table("some_table", metadata, ..., postgresql_inherits="some_supertable")

    Table("some_table", metadata, ..., postgresql_inherits=("t1", "t2", ...))

* ``ON COMMIT``::

    Table("some_table", metadata, ..., postgresql_on_commit="PRESERVE ROWS")

*
  ``PARTITION BY``::

    Table(
        "some_table",
        metadata,
        ...,
        postgresql_partition_by="LIST (part_column)",
    )

  .. versionadded:: 1.2.6

*
  ``TABLESPACE``::

    Table("some_table", metadata, ..., postgresql_tablespace="some_tablespace")

  The above option is also available on the :class:`.Index` construct.

*
  ``USING``::

    Table("some_table", metadata, ..., postgresql_using="heap")

  .. versionadded:: 2.0.26

* ``WITH OIDS``::

    Table("some_table", metadata, ..., postgresql_with_oids=True)

* ``WITHOUT OIDS``::

    Table("some_table", metadata, ..., postgresql_with_oids=False)

.. seealso::

    `PostgreSQL CREATE TABLE options
    <https://www.postgresql.org/docs/current/static/sql-createtable.html>`_ -
    in the PostgreSQL documentation.

.. _postgresql_constraint_options:

PostgreSQL Constraint Options
-----------------------------

The following option(s) are supported by the PostgreSQL dialect in conjunction
with selected constraint constructs:

* ``NOT VALID``:  This option applies towards CHECK and FOREIGN KEY constraints
  when the constraint is being added to an existing table via ALTER TABLE,
  and has the effect that existing rows are not scanned during the ALTER
  operation against the constraint being added.

  When using a SQL migration tool such as `Alembic <https://alembic.sqlalchemy.org>`_
  that renders ALTER TABLE constructs, the ``postgresql_not_valid`` argument
  may be specified as an additional keyword argument within the operation
  that creates the constraint, as in the following Alembic example::

        def update():
            op.create_foreign_key(
                "fk_user_address",
                "address",
                "user",
                ["user_id"],
                ["id"],
                postgresql_not_valid=True,
            )

  The keyword is ultimately accepted directly by the
  :class:`_schema.CheckConstraint`, :class:`_schema.ForeignKeyConstraint`
  and :class:`_schema.ForeignKey` constructs; when using a tool like
  Alembic, dialect-specific keyword arguments are passed through to
  these constructs from the migration operation directives::

       CheckConstraint("some_field IS NOT NULL", postgresql_not_valid=True)

       ForeignKeyConstraint(
           ["some_id"], ["some_table.some_id"], postgresql_not_valid=True
       )

  .. versionadded:: 1.4.32

  .. seealso::

      `PostgreSQL ALTER TABLE options
      <https://www.postgresql.org/docs/current/static/sql-altertable.html>`_ -
      in the PostgreSQL documentation.

.. _postgresql_table_valued_overview:

Table values, Table and Column valued functions, Row and Tuple objects
-----------------------------------------------------------------------

PostgreSQL makes great use of modern SQL forms such as table-valued functions,
tables and rows as values.   These constructs are commonly used as part
of PostgreSQL's support for complex datatypes such as JSON, ARRAY, and other
datatypes.  SQLAlchemy's SQL expression language has native support for
most table-valued and row-valued forms.

.. _postgresql_table_valued:

Table-Valued Functions
^^^^^^^^^^^^^^^^^^^^^^^

Many PostgreSQL built-in functions are intended to be used in the FROM clause
of a SELECT statement, and are capable of returning table rows or sets of table
rows. A large portion of PostgreSQL's JSON functions for example such as
``json_array_elements()``, ``json_object_keys()``, ``json_each_text()``,
``json_each()``, ``json_to_record()``, ``json_populate_recordset()`` use such
forms. These classes of SQL function calling forms in SQLAlchemy are available
using the :meth:`_functions.FunctionElement.table_valued` method in conjunction
with :class:`_functions.Function` objects generated from the :data:`_sql.func`
namespace.

Examples from PostgreSQL's reference documentation follow below:

* ``json_each()``:

  .. sourcecode:: pycon+sql

    >>> from sqlalchemy import select, func
    >>> stmt = select(
    ...     func.json_each('{"a":"foo", "b":"bar"}').table_valued("key", "value")
    ... )
    >>> print(stmt)
    {printsql}SELECT anon_1.key, anon_1.value
    FROM json_each(:json_each_1) AS anon_1

* ``json_populate_record()``:

  .. sourcecode:: pycon+sql

    >>> from sqlalchemy import select, func, literal_column
    >>> stmt = select(
    ...     func.json_populate_record(
    ...         literal_column("null::myrowtype"), '{"a":1,"b":2}'
    ...     ).table_valued("a", "b", name="x")
    ... )
    >>> print(stmt)
    {printsql}SELECT x.a, x.b
    FROM json_populate_record(null::myrowtype, :json_populate_record_1) AS x

* ``json_to_record()`` - this form uses a PostgreSQL specific form of derived
  columns in the alias, where we may make use of :func:`_sql.column` elements with
  types to produce them.  The :meth:`_functions.FunctionElement.table_valued`
  method produces  a :class:`_sql.TableValuedAlias` construct, and the method
  :meth:`_sql.TableValuedAlias.render_derived` method sets up the derived
  columns specification:

  .. sourcecode:: pycon+sql

    >>> from sqlalchemy import select, func, column, Integer, Text
    >>> stmt = select(
    ...     func.json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}')
    ...     .table_valued(
    ...         column("a", Integer),
    ...         column("b", Text),
    ...         column("d", Text),
    ...     )
    ...     .render_derived(name="x", with_types=True)
    ... )
    >>> print(stmt)
    {printsql}SELECT x.a, x.b, x.d
    FROM json_to_record(:json_to_record_1) AS x(a INTEGER, b TEXT, d TEXT)

* ``WITH ORDINALITY`` - part of the SQL standard, ``WITH ORDINALITY`` adds an
  ordinal counter to the output of a function and is accepted by a limited set
  of PostgreSQL functions including ``unnest()`` and ``generate_series()``. The
  :meth:`_functions.FunctionElement.table_valued` method accepts a keyword
  parameter ``with_ordinality`` for this purpose, which accepts the string name
  that will be applied to the "ordinality" column:

  .. sourcecode:: pycon+sql

    >>> from sqlalchemy import select, func
    >>> stmt = select(
    ...     func.generate_series(4, 1, -1)
    ...     .table_valued("value", with_ordinality="ordinality")
    ...     .render_derived()
    ... )
    >>> print(stmt)
    {printsql}SELECT anon_1.value, anon_1.ordinality
    FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3)
    WITH ORDINALITY AS anon_1(value, ordinality)

.. versionadded:: 1.4.0b2

.. seealso::

    :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial`

.. _postgresql_column_valued:

Column Valued Functions
^^^^^^^^^^^^^^^^^^^^^^^

Similar to the table valued function, a column valued function is present
in the FROM clause, but delivers itself to the columns clause as a single
scalar value.  PostgreSQL functions such as ``json_array_elements()``,
``unnest()`` and ``generate_series()`` may use this form. Column valued functions are available using the
:meth:`_functions.FunctionElement.column_valued` method of :class:`_functions.FunctionElement`:

* ``json_array_elements()``:

  .. sourcecode:: pycon+sql

    >>> from sqlalchemy import select, func
    >>> stmt = select(
    ...     func.json_array_elements('["one", "two"]').column_valued("x")
    ... )
    >>> print(stmt)
    {printsql}SELECT x
    FROM json_array_elements(:json_array_elements_1) AS x

* ``unnest()`` - in order to generate a PostgreSQL ARRAY literal, the
  :func:`_postgresql.array` construct may be used:

  .. sourcecode:: pycon+sql

    >>> from sqlalchemy.dialects.postgresql import array
    >>> from sqlalchemy import select, func
    >>> stmt = select(func.unnest(array([1, 2])).column_valued())
    >>> print(stmt)
    {printsql}SELECT anon_1
    FROM unnest(ARRAY[%(param_1)s, %(param_2)s]) AS anon_1

  The function can of course be used against an existing table-bound column
  that's of type :class:`_types.ARRAY`:

  .. sourcecode:: pycon+sql

    >>> from sqlalchemy import table, column, ARRAY, Integer
    >>> from sqlalchemy import select, func
    >>> t = table("t", column("value", ARRAY(Integer)))
    >>> stmt = select(func.unnest(t.c.value).column_valued("unnested_value"))
    >>> print(stmt)
    {printsql}SELECT unnested_value
    FROM unnest(t.value) AS unnested_value

.. seealso::

    :ref:`tutorial_functions_column_valued` - in the :ref:`unified_tutorial`


Row Types
^^^^^^^^^

Built-in support for rendering a ``ROW`` may be approximated using
``func.ROW`` with the :attr:`_sa.func` namespace, or by using the
:func:`_sql.tuple_` construct:

.. sourcecode:: pycon+sql

    >>> from sqlalchemy import table, column, func, tuple_
    >>> t = table("t", column("id"), column("fk"))
    >>> stmt = (
    ...     t.select()
    ...     .where(tuple_(t.c.id, t.c.fk) > (1, 2))
    ...     .where(func.ROW(t.c.id, t.c.fk) < func.ROW(3, 7))
    ... )
    >>> print(stmt)
    {printsql}SELECT t.id, t.fk
    FROM t
    WHERE (t.id, t.fk) > (:param_1, :param_2) AND ROW(t.id, t.fk) < ROW(:ROW_1, :ROW_2)

.. seealso::

    `PostgreSQL Row Constructors
    <https://www.postgresql.org/docs/current/sql-expressions.html#SQL-SYNTAX-ROW-CONSTRUCTORS>`_

    `PostgreSQL Row Constructor Comparison
    <https://www.postgresql.org/docs/current/functions-comparisons.html#ROW-WISE-COMPARISON>`_

Table Types passed to Functions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

PostgreSQL supports passing a table as an argument to a function, which is
known as a "record" type. SQLAlchemy :class:`_sql.FromClause` objects
such as :class:`_schema.Table` support this special form using the
:meth:`_sql.FromClause.table_valued` method, which is comparable to the
:meth:`_functions.FunctionElement.table_valued` method except that the collection
of columns is already established by that of the :class:`_sql.FromClause`
itself:

.. sourcecode:: pycon+sql

    >>> from sqlalchemy import table, column, func, select
    >>> a = table("a", column("id"), column("x"), column("y"))
    >>> stmt = select(func.row_to_json(a.table_valued()))
    >>> print(stmt)
    {printsql}SELECT row_to_json(a) AS row_to_json_1
    FROM a

.. versionadded:: 1.4.0b2



    )annotations)defaultdict)	lru_cacheN)Any)cast)List)Optional)Tuple)TYPE_CHECKING)Union   )arraylib)json)
pg_catalog)ranges)_regconfig_fn)aggregate_order_by)HSTORE)CreateDomainType)CreateEnumType)DOMAIN)DropDomainType)DropEnumType)ENUM)	NamedType)_DECIMAL_TYPES)_FLOAT_TYPES)
_INT_TYPES)BIT)BYTEA)CIDR)CITEXT)INET)INTERVAL)MACADDR)MACADDR8)MONEY)OID)PGBit)PGCidr)PGInet)
PGInterval)	PGMacAddr)
PGMacAddr8)PGUuid)REGCLASS)	REGCONFIG)TIME)	TIMESTAMP)TSVECTOR   )exc)schema)select)sql)util)characteristics)default)
interfaces)
ObjectKind)ObjectScope)
reflection)URL)ReflectionDefaults)	bindparam)	coercions)compiler)elements)
expression)roles)sqltypes)InsertmanyvaluesSentinelOpts)InternalTraversal)BIGINT)BOOLEAN)CHAR)DATE)DOUBLE_PRECISION)FLOAT)INTEGER)NUMERIC)REAL)SMALLINT)TEXT)UUID)VARCHAR)	TypedDictz ^(?:btree|hash|gist|gin|[\w_]+)$>f   asdoinisofonortoallandanyascendfornewnotoffoldbothcaser   descelsefromfullintojoinleftlikenullonlyoversomethentrueuserwhenwitharraycheckcrossfalsefetchgrantgroupilikeinnerlimitorderouterrighttableunionusingwherebinarycolumncreateexceptfreezehavingisnulloffsetr7   uniquewindowanalyseanalyzebetweencollater;   foreignleadingnaturalnotnullplacingprimarysimilarverbosedistinctoverlapstrailingvariadic	initially	intersect	localtime	returning	symmetric
asymmetric
constraint
deferrable
referencescurrent_datecurrent_rolecurrent_timecurrent_usersession_userauthorizationcurrent_schemalocaltimestampcurrent_catalogcurrent_timestamp_arrayhstorer   jsonb	int4range	int8rangenumrange	daterangetsrange	tstzrangeint4multirangeint8multirangenummultirangedatemultirangetsmultirangetstzmultirangeintegerbigintsmallintzcharacter varying	characterz"char"nametextnumericfloatrealinetcidrcitextuuidbitbit varyingmacaddrmacaddr8moneyoidregclassdouble precision	timestamptimestamp with time zonetimestamp without time zonetime with time zonetime without time zonedatetimebyteabooleanintervaltsvectorc                      sL  e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Z	dNddZ	dNddZdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Z fd2d3Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= Z d>d? Z!d@dA Z"dBdC Z#dDdE Z$dFdG Z%dHdI Z&dJdK Z'dLdM Z(  Z)S )O
PGCompilerc                 K     | j |fi |S N_assert_pg_ts_extselfelementkw r   e/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/sqlalchemy/dialects/postgresql/base.pyvisit_to_tsvector_func     z!PGCompiler.visit_to_tsvector_funcc                 K  r   r   r   r   r   r   r   visit_to_tsquery_func  r   z PGCompiler.visit_to_tsquery_funcc                 K  r   r   r   r   r   r   r   visit_plainto_tsquery_func  r   z%PGCompiler.visit_plainto_tsquery_funcc                 K  r   r   r   r   r   r   r   visit_phraseto_tsquery_func  r   z&PGCompiler.visit_phraseto_tsquery_funcc                 K  r   r   r   r   r   r   r   visit_websearch_to_tsquery_func  r   z*PGCompiler.visit_websearch_to_tsquery_funcc                 K  r   r   r   r   r   r   r   visit_ts_headline_func  r   z!PGCompiler.visit_ts_headline_funcc                 K  sB   t |tstd|j d|j d|j | j|fi | S )NzCan't compile "z()" full text search function construct that does not originate from the "sqlalchemy.dialects.postgresql" package.  Please ensure "import sqlalchemy.dialects.postgresql" is called before constructing "sqlalchemy.func.zD()" to ensure registration of the correct argument and return types.)
isinstancer   r5   CompileErrorr   function_argspecr   r   r   r   r     s   


zPGCompiler._assert_pg_ts_extc                 C  s6   |j tju r|jrtj}| d| jjj|| jd S )Nz::)identifier_preparer)	_type_affinityrH   Stringlength
STRINGTYPEdialecttype_compiler_instanceprocesspreparer)r   type_
dbapi_typesqltextr   r   r   render_bind_cast  s   zPGCompiler.render_bind_castc                 K  s   d| j |fi | S )Nz	ARRAY[%s])visit_clauselistr   r   r   r   visit_array  s   zPGCompiler.visit_arrayc                 K  ,   d| j |jfi || j |jfi |f S )Nz%s:%s)r  startstopr   r   r   r   visit_slice     zPGCompiler.visit_slicec                 K  s   | j |dfi |S )Nz # )_generate_generic_binaryr   r   operatorr   r   r   r   visit_bitwise_xor_op_binary     z&PGCompiler.visit_bitwise_xor_op_binaryFc                 K  Z   |s|j jtjurd|d< | jt||j fi |S d|d< | j||s&dndfi |S )NT_cast_appliedeager_groupingz -> z ->> typer  rH   JSONr  r8   r   r  r   r   r  r  r   r   r   r   visit_json_getitem_op_binary
  s   z'PGCompiler.visit_json_getitem_op_binaryc                 K  r  )NTr  r  z #> z #>> r  r  r   r   r   !visit_json_path_getitem_op_binary  s   z,PGCompiler.visit_json_path_getitem_op_binaryc                 K  s,   d| j |jfi || j |jfi |f S )Nz%s[%s])r  rs   r   r  r   r   r   visit_getitem_binary)  r  zPGCompiler.visit_getitem_binaryc                 K  r  )Nz%s ORDER BY %s)r  targetorder_byr   r   r   r   visit_aggregate_order_by/  r  z#PGCompiler.visit_aggregate_order_byc                 K  s|   d|j v r(| |j d tj}|r(d| j|jfi ||| j|jfi |f S d| j|jfi || j|jfi |f S )Npostgresql_regconfigz%s @@ plainto_tsquery(%s, %s)z%s @@ plainto_tsquery(%s))	modifiersrender_literal_valuerH   r  r  rs   r   )r   r   r  r   	regconfigr   r   r   visit_match_op_binary5  s   
z PGCompiler.visit_match_op_binaryc                 K  s   |j j| fi |S r   )r   _compiler_dispatchr   r   r   r   $visit_ilike_case_insensitive_operandE  r  z/PGCompiler.visit_ilike_case_insensitive_operandc                 K  Z   |j dd }d| j|jfi || j|jfi |f |d ur*d| |tj  S d S )Nescapez%s ILIKE %s ESCAPE  r'  getr  rs   r   r(  rH   r  r   r   r  r   r.  r   r   r   visit_ilike_op_binaryH  s   z PGCompiler.visit_ilike_op_binaryc                 K  r-  )Nr.  z%s NOT ILIKE %sr/  r0  r1  r3  r   r   r   visit_not_ilike_op_binaryT  s   z$PGCompiler.visit_not_ilike_op_binaryc                 C  s   |j d }|d u r| j|d| fi |S |dkr%| j|d| fi |S d| j|jfi ||| |tj| j|jfi |f S )Nflagsz %s iz %s* z%s %s CONCAT('(?', %s, ')', %s))r'  r  r  rs   r(  rH   r  r   )r   base_opr   r  r   r6  r   r   r   _regexp_match_  s&   
zPGCompiler._regexp_matchc                 K     |  d|||S )N~r9  r  r   r   r   visit_regexp_match_op_binaryp     z'PGCompiler.visit_regexp_match_op_binaryc                 K  r:  )Nz!~r<  r  r   r   r    visit_not_regexp_match_op_binarys  r>  z+PGCompiler.visit_not_regexp_match_op_binaryc                 K  s^   | j |jfi |}| j |jfi |}|jd }|d u r#d||f S d||| |tjf S )Nr6  zREGEXP_REPLACE(%s, %s)zREGEXP_REPLACE(%s, %s, %s))r  rs   r   r'  r(  rH   r  )r   r   r  r   stringpattern_replacer6  r   r   r   visit_regexp_replace_op_binaryv  s   
z)PGCompiler.visit_regexp_replace_op_binaryc                   s&   dd  fdd|pt gD f S )NzSELECT %s WHERE 1!=1, c                 3  s.    | ]}d  j j|jrt n| V  qdS )zCAST(NULL AS %s)N)r  r  r  _isnullrQ   ).0r	  r   r   r   	<genexpr>  s    
z2PGCompiler.visit_empty_set_expr.<locals>.<genexpr>)rr   rQ   )r   element_typesr   r   rF  r   visit_empty_set_expr  s
   
zPGCompiler.visit_empty_set_exprc                   s&   t  ||}| jjr|dd}|S )N\z\\)superr(  r  _backslash_escapesreplace)r   valuer	  	__class__r   r   r(    s   zPGCompiler.render_literal_valuec                 K  s   d|  | S )Nzstring_agg%s)r   )r   fnr   r   r   r   visit_aggregate_strings_func     z'PGCompiler.visit_aggregate_strings_funcc                 K  s   d| j | S )Nznextval('%s'))r  format_sequence)r   seqr   r   r   r   visit_sequence  r>  zPGCompiler.visit_sequencec                 K  sf   d}|j d ur|d| j|j fi | 7 }|jd ur1|j d u r#|d7 }|d| j|jfi | 7 }|S )Nr0  z	 
 LIMIT z
 LIMIT ALLz OFFSET )_limit_clauser  _offset_clauser   r7   r   r   r   r   r   limit_clause  s   


zPGCompiler.limit_clausec                 C  s"   |  dkrtd| d| S )NONLYzUnrecognized hint: %rzONLY )upperr5   r   )r   r  r   hintiscrudr   r   r   format_from_hint_text  s   z PGCompiler.format_from_hint_textc                   s>   |j s|jr|jrdd fdd|jD  d S dS dS )NzDISTINCT ON (rC  c                   s   g | ]}j |fi  qS r   r  rE  colr   r   r   r   
<listcomp>  s    z4PGCompiler.get_select_precolumns.<locals>.<listcomp>z) z	DISTINCT r0  )	_distinct_distinct_onrr   )r   r7   r   r   rc  r   get_select_precolumns  s   z PGCompiler.get_select_precolumnsc                   s   |j jr|j jrd}nd}n	|j jrd}nd}|j jr?t }|j jD ]
}|t| q#|dd	 fdd|D  7 }|j j
rG|d	7 }|j jrO|d
7 }|S )Nz FOR KEY SHAREz
 FOR SHAREz FOR NO KEY UPDATEz FOR UPDATEz OF rC  c                 3  s(    | ]}j |fd dd V  qdS )TF)ashint
use_schemaNr`  )rE  r   rc  r   r   rG    s
    
z/PGCompiler.for_update_clause.<locals>.<genexpr>z NOWAITz SKIP LOCKED)_for_update_argread	key_sharer]   r9   
OrderedSetupdatesql_utilsurface_selectables_onlyrr   nowaitskip_locked)r   r7   r   tmptablescr   rc  r   for_update_clause  s&   zPGCompiler.for_update_clausec                 K  sx   | j |jjd fi |}| j |jjd fi |}t|jjdkr6| j |jjd fi |}d|||f S d||f S )Nr   r      zSUBSTRING(%s FROM %s FOR %s)zSUBSTRING(%s FROM %s))r  clauseslen)r   funcr   sr  r  r   r   r   visit_substring_func  s   zPGCompiler.visit_substring_funcc                   sx   |j d urd j|j  }|S |jd ur8dd fdd|jD  }|jd ur6|d j|jddd 7 }|S d	}|S )
NzON CONSTRAINT %s(%s)rC  c                 3  s6    | ]}t |tr j|n j|d d dV  qdS )Finclude_tableri  N)r   strr  quoter  rE  ru  rF  r   r   rG    s    
z1PGCompiler._on_conflict_target.<locals>.<genexpr>	 WHERE %sFr~  r0  )constraint_targetr  #truncate_and_render_constraint_nameinferred_target_elementsrr   inferred_target_whereclauser  )r   clauser   target_textr   rF  r   _on_conflict_target  s*   




zPGCompiler._on_conflict_targetc                 K  s"   | j |fi |}|rd| S dS )NzON CONFLICT %s DO NOTHINGzON CONFLICT DO NOTHING)r  )r   on_conflictr   r  r   r   r   visit_on_conflict_do_nothing
  s   z'PGCompiler.visit_on_conflict_do_nothingc                 K  s  |}| j |fi |}g }t|j}| jd d }|jj}|D ]T}	|	j}
|
|v r.||
}n|	|v r8||	}nqt	|rHt
jd ||	jd}nt|t
jrZ|jjrZ| }|	j|_| j| dd}| j|	j}|d||f  q|rtd| jjjdd	d
 |D f  | D ]+\}}t|tr| j|n| j|dd}| jttj|dd}|d||f  qd|}|jd ur|d| j|jddd 7 }d||f S )N
selectable)r	  F)ri  %s = %szFAdditional column names not matching any column keys in table '%s': %srC  c                 s  s    | ]}d | V  qdS )z'%s'Nr   r  r   r   r   rG  @  s    z9PGCompiler.visit_on_conflict_do_update.<locals>.<genexpr>r  Tr~  zON CONFLICT %s DO UPDATE SET %s) r  dictupdate_values_to_setstackr   ru  keypoprC   _is_literalrE   BindParameterr  r   rD  _cloner  
self_groupr  r  r   appendr9   warncurrent_executablerr   itemsr  expectrG   ExpressionElementRoleupdate_whereclause)r   r  r   r  r  action_set_opsset_parametersinsert_statementcolsru  col_keyrN  
value_textkey_textkvaction_textr   r   r   visit_on_conflict_do_update  s`   





z&PGCompiler.visit_on_conflict_do_updatec                   (   dd< dd  fdd|D  S )NTasfromzFROM rC  c                 3  &    | ]}|j fd  iV  qdS 	fromhintsNr+  rE  t
from_hintsr   r   r   r   rG  [  
    
z0PGCompiler.update_from_clause.<locals>.<genexpr>rr   )r   update_stmt
from_tableextra_fromsr  r   r   r  r   update_from_clauseW  s   
zPGCompiler.update_from_clausec                   r  )z9Render the DELETE .. USING clause specific to PostgreSQL.Tr  zUSING rC  c                 3  r  r  r  r  r  r   r   rG  e  r  z6PGCompiler.delete_extra_from_clause.<locals>.<genexpr>r  )r   delete_stmtr  r  r  r   r   r  r   delete_extra_from_clause`  s   
z#PGCompiler.delete_extra_from_clausec                 K  sv   d}|j d ur|d| j|j fi | 7 }|jd ur9|d| j|jfi ||jd r,dnd|jd r4dndf 7 }|S )	Nr0  z
 OFFSET (%s) ROWSz
 FETCH FIRST (%s)%s ROWS %spercentz PERCENT	with_tiesz	WITH TIESr[  )rX  r  _fetch_clause_fetch_clause_optionsrY  r   r   r   fetch_clausej  s    


	zPGCompiler.fetch_clauseF)*__name__
__module____qualname__r   r   r   r   r   r   r   r  r  r  r  r   r!  r"  r%  r*  r,  r4  r5  r9  r=  r?  rB  rI  r(  rR  rV  rZ  r_  rg  rv  r|  r  r  r  r  r  r  __classcell__r   r   rO  r   r     sR    


	!E	
r   c                      s   e Zd Zdd Zdd Z fddZ fddZd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Z fddZdd  Zd!d" Zd#d$ Z  ZS )%PGDDLCompilerc                 K  s^  | j |}|j| j}t|tjr|j}|j	d uo| jj
}|jr_||jju r_| jjs2t|tjs_|s_|jd u sDt|jtjr_|jjr_t|tjrO|d7 }n/t|tjrZ|d7 }n$|d7 }n|d| jjj|j|| j d 7 }| |}|d ur~|d| 7 }|jd ur|d| |j 7 }|r|d| |j	 7 }|js|s|d7 }|S |jr|r|d7 }|S )	Nz
 BIGSERIALz SMALLSERIALz SERIAL )type_expressionr   z	 DEFAULT z	 NOT NULLz NULL)r  format_columnr  dialect_implr  r   rH   TypeDecoratorimplidentitysupports_identity_columnsprimary_keyr   _autoincrement_columnsupports_smallserialSmallIntegerr;   r6   Sequenceoptional
BigIntegerr  r  get_column_default_stringcomputednullable)r   r   kwargscolspec	impl_typehas_identityr;   r   r   r   get_column_specification  sX   










z&PGDDLCompiler.get_column_specificationc                 C  s   |j d d }|rdS dS )N
postgresql	not_valid
 NOT VALIDr0  dialect_options)r   r   r  r   r   r   _define_constraint_validity  s   z)PGDDLCompiler._define_constraint_validityc                   s`   |j r!t|jd j}t|tjr!t|jtjr!|jj	s!t
dt |}|| |7 }|S )Nr   zPostgreSQL dialect cannot produce the CHECK constraint for ARRAY of non-native ENUM; please specify create_constraint=False on this Enum datatype.)_type_boundlistcolumnsr  r   rH   ARRAY	item_typeEnumnative_enumr5   r   rK  visit_check_constraintr  )r   r   r   typr   rO  r   r   r    s   
z$PGDDLCompiler.visit_check_constraintc                   s   t  |}|| |7 }|S r   )rK  visit_foreign_key_constraintr  )r   r   r   r   rO  r   r   r    s   z*PGDDLCompiler.visit_foreign_key_constraintc                   s0   |j }d j|d fdd|jD f S )NzCREATE TYPE %s AS ENUM (%s)rC  c                 3  s&    | ]} j jt|d dV  qdS )Tliteral_bindsN)sql_compilerr  r8   literal)rE  erF  r   r   rG    r  z7PGDDLCompiler.visit_create_enum_type.<locals>.<genexpr>)r   r  format_typerr   enums)r   r   r   r	  r   rF  r   visit_create_enum_type  s   
z$PGDDLCompiler.visit_create_enum_typec                 K  s   |j }d| j| S )NzDROP TYPE %sr   r  r  )r   dropr   r	  r   r   r   visit_drop_enum_type  s   z"PGDDLCompiler.visit_drop_enum_typec                 K  s   |j }g }|jd ur|d| j|j  |jd ur*| |j}|d|  |jd ur>| j|j}|d|  |j	rF|d |j
d ur^| jj|j
ddd}|d| d	 d
| j| d| j|j dd| S )NzCOLLATE zDEFAULT zCONSTRAINT zNOT NULLFTr  r  zCHECK ()zCREATE DOMAIN z AS r  )r   	collationr  r  r  r;   render_default_stringconstraint_namer  not_nullr   r  r  r  type_compiler	data_typerr   )r   r   r   domainoptionsr;   r   r   r   r   r   visit_create_domain_type  s2   




z&PGDDLCompiler.visit_create_domain_typec                 K  s   |j }d| j| S )NzDROP DOMAIN r  )r   r  r   r  r   r   r   visit_drop_domain_type  s   z$PGDDLCompiler.visit_drop_domain_typec                   s  j |j   d} jr|d7 }|d7 }jjr) jd d }|r)|d7 }|jr0|d7 }|dj d	d
	 j
f 7 } jd d }|rW|dj |t  7 } jd d |ddfdd jD  7 } jd d }|r fdd|D }|ddfdd|D  7 } jd d }|du r|d7 }n|d	u r|d7 } jd d }	|	r|dddd |	 D  7 } jd d }
|
r|d|
 7 } jd d }|d urttj|}jj|d	dd }|d!| 7 }|S )"NzCREATE zUNIQUE zINDEX r  concurrentlyCONCURRENTLY zIF NOT EXISTS z	%s ON %s Finclude_schemar   z	USING %s opsr}  rC  c                   sX   g | ](}j jt|tjs| n|d ddt|dr'|j v r'd |j  nd qS )FTr  r  r  r0  )r  r  r   rF   ColumnClauser  hasattrr  )rE  expr)r
  r   r   r   rd  #	  s     


z4PGDDLCompiler.visit_create_index.<locals>.<listcomp>includec                   s&   g | ]}t |tr jj| n|qS r   )r   r  r   ru  ra  )indexr   r   rd  9	      z INCLUDE (%s)c                   s   g | ]}  |jqS r   )r  r   r  r  r   r   rd  >	  s    nulls_not_distinctTz NULLS NOT DISTINCTz NULLS DISTINCTr}   z
 WITH (%s)c                 S  s   g | ]}d | qS )r  r   )rE  storage_parameterr   r   r   rd  M	  s    
tablespacez TABLESPACE %sr   r  z WHERE )r  r   _verify_index_tabler   r  #_supports_create_index_concurrentlyr  if_not_exists_prepared_index_nameformat_tabler   validate_sql_phrase	IDX_USINGlowerrr   expressionsr  r  rC   r  rG   DDLExpressionRoler  r  )r   r   r   r   r  r   includeclause
inclusionsr  
withclausetablespace_namewhereclausewhere_compiledr   )r  r
  r  r   r   visit_create_index	  s   



	z PGDDLCompiler.visit_create_indexc                 K  s6   |j d d }|du rd}|S |du rd}|S d}|S )Nr  r  TzNULLS NOT DISTINCT FzNULLS DISTINCT r0  r  )r   r   r   r  nulls_not_distinct_paramr   r   r   !define_unique_constraint_distincte	  s   z/PGDDLCompiler.define_unique_constraint_distinctc                 K  sP   |j }d}| jjr|jd d }|r|d7 }|jr|d7 }|| j|dd7 }|S )Nz
DROP INDEX r  r  r  z
IF EXISTS Tr  )r   r  !_supports_drop_index_concurrentlyr  	if_existsr  )r   r  r   r  r   r  r   r   r   visit_drop_indexq	  s   zPGDDLCompiler.visit_drop_indexc           	      K  s   d}|j d ur|d| j| 7 }g }d|d< d|d< |jD ]-\}}}| jj|fi |t|dr?|j|jv r?d|j|j  nd }|	d	||f  q|d
| j
|jt d|f 7 }|jd urq|d| jj|jdd 7 }|| |7 }|S )Nr0  zCONSTRAINT %s Fr  Tr  r  r  z
%s WITH %szEXCLUDE USING %s (%s)rC  z WHERE (%s)r  )r   r  format_constraint_render_exprsr  r  r  r  r
  r  r  r   r  r  rr   r   define_constraint_deferrability)	r   r   r   r   rE   r  r   opexclude_elementr   r   r   visit_exclude_constraint	  s<   




z&PGDDLCompiler.visit_exclude_constraintc                   s  g }|j d }|d}|d ur-t|ttfs|f}|dd fdd|D  d  |d r:|d	|d   |d
 rG|d|d
   |d du rS|d n|d du r^|d |d rs|d dd }|d|  |d r|d }|d j	
|  d|S )Nr  inheritsz
 INHERITS ( rC  c                 3  s    | ]	} j |V  qd S r   )r  r  )rE  r   rF  r   r   rG  	  s    z2PGDDLCompiler.post_create_table.<locals>.<genexpr>z )partition_byz
 PARTITION BY %sr   z

 USING %s	with_oidsTz
 WITH OIDSFz
 WITHOUT OIDS	on_commit_r  z
 ON COMMIT %sr  z
 TABLESPACE %sr0  )r  r2  r   r  tupler  rr   rM  r\  r  r  )r   r   
table_optspg_optsr1  on_commit_optionsr"  r   rF  r   post_create_table	  s<   



zPGDDLCompiler.post_create_tablec                 K  s,   |j du r
tdd| jj|jddd S )NFzPostrgreSQL computed columns do not support 'virtual' persistence; set the 'persisted' flag to None or True for PostgreSQL support.zGENERATED ALWAYS AS (%s) STOREDTr  )	persistedr5   r   r  r  r  )r   	generatedr   r   r   r   visit_computed_column	  s   
z#PGDDLCompiler.visit_computed_columnc                   s<   d }|j jd urd| j|j j }t j|fd|i|S )Nz AS %sprefix)r   r  r   r  rK  visit_create_sequence)r   r   r   r>  rO  r   r   r?  	  s   z#PGDDLCompiler.visit_create_sequencec                 C  sB   |j }|jd u rtd|d|jd u rtd|dd S )Nz%Can't emit COMMENT ON for constraint z: it has no namez: it has no associated table)r   r   r5   r   r   )r   ddl_instancer   r   r   r   _can_comment_on_constraint	  s   



z(PGDDLCompiler._can_comment_on_constraintc                 K  s@   |  | d| j|j| j|jj| j|jjt	
 f S )Nz$COMMENT ON CONSTRAINT %s ON %s IS %s)rA  r  r+  r   r  r   r  r(  commentrH   r  )r   r   r   r   r   r   visit_set_constraint_comment	  s   
z*PGDDLCompiler.visit_set_constraint_commentc                 K  s,   |  | d| j|j| j|jjf S )Nz&COMMENT ON CONSTRAINT %s ON %s IS NULL)rA  r  r+  r   r  r   )r   r  r   r   r   r   visit_drop_constraint_comment	  s
   
z+PGDDLCompiler.visit_drop_constraint_comment)r  r  r  r  r  r  r  r  r  r  r  r%  r'  r*  r0  r:  r=  r?  rA  rC  rD  r  r   r   rO  r   r    s&    6c%	
r  c                      s  e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z!d?d@ Z" fdAdBZ#d^dDdEZ$d^dFdGZ%dHdI Z&dJdK Z'dLdM Z(dNdO Z) fdPdQZ*dRdS Z+dTdU Z,dVdW Z-dXdY Z.dZd[ Z/d\d] Z0  Z1S )_PGTypeCompilerc                 K     dS )Nr3   r   r   r	  r   r   r   r   visit_TSVECTOR	     zPGTypeCompiler.visit_TSVECTORc                 K  rF  )NTSQUERYr   rG  r   r   r   visit_TSQUERY	  rI  zPGTypeCompiler.visit_TSQUERYc                 K  rF  )Nr"   r   rG  r   r   r   
visit_INET	  rI  zPGTypeCompiler.visit_INETc                 K  rF  )Nr    r   rG  r   r   r   
visit_CIDR
  rI  zPGTypeCompiler.visit_CIDRc                 K  rF  )Nr!   r   rG  r   r   r   visit_CITEXT
  rI  zPGTypeCompiler.visit_CITEXTc                 K  rF  )Nr$   r   rG  r   r   r   visit_MACADDR
  rI  zPGTypeCompiler.visit_MACADDRc                 K  rF  )Nr%   r   rG  r   r   r   visit_MACADDR8
  rI  zPGTypeCompiler.visit_MACADDR8c                 K  rF  )Nr&   r   rG  r   r   r   visit_MONEY
  rI  zPGTypeCompiler.visit_MONEYc                 K  rF  )Nr'   r   rG  r   r   r   	visit_OID
  rI  zPGTypeCompiler.visit_OIDc                 K  rF  )Nr0   r   rG  r   r   r   visit_REGCONFIG
  rI  zPGTypeCompiler.visit_REGCONFIGc                 K  rF  )Nr/   r   rG  r   r   r   visit_REGCLASS
  rI  zPGTypeCompiler.visit_REGCLASSc                 K  s   |j sdS dd|j i S )NrP   zFLOAT(%(precision)s)	precision)rU  rG  r   r   r   visit_FLOAT
  s   zPGTypeCompiler.visit_FLOATc                 K  s   | j tfi |S r   )visit_DOUBLE_PRECISIONr  rG  r   r   r   visit_double 
  r   zPGTypeCompiler.visit_doublec                 K  rF  )NrK   r   rG  r   r   r   visit_BIGINT#
  rI  zPGTypeCompiler.visit_BIGINTc                 K  rF  )Nr   r   rG  r   r   r   visit_HSTORE&
  rI  zPGTypeCompiler.visit_HSTOREc                 K  rF  )Nr  r   rG  r   r   r   
visit_JSON)
  rI  zPGTypeCompiler.visit_JSONc                 K  rF  )NJSONBr   rG  r   r   r   visit_JSONB,
  rI  zPGTypeCompiler.visit_JSONBc                 K  rF  )NINT4MULTIRANGEr   rG  r   r   r   visit_INT4MULTIRANGE/
  rI  z#PGTypeCompiler.visit_INT4MULTIRANGEc                 K  rF  )NINT8MULTIRANGEr   rG  r   r   r   visit_INT8MULTIRANGE2
  rI  z#PGTypeCompiler.visit_INT8MULTIRANGEc                 K  rF  )NNUMMULTIRANGEr   rG  r   r   r   visit_NUMMULTIRANGE5
  rI  z"PGTypeCompiler.visit_NUMMULTIRANGEc                 K  rF  )NDATEMULTIRANGEr   rG  r   r   r   visit_DATEMULTIRANGE8
  rI  z#PGTypeCompiler.visit_DATEMULTIRANGEc                 K  rF  )NTSMULTIRANGEr   rG  r   r   r   visit_TSMULTIRANGE;
  rI  z!PGTypeCompiler.visit_TSMULTIRANGEc                 K  rF  )NTSTZMULTIRANGEr   rG  r   r   r   visit_TSTZMULTIRANGE>
  rI  z#PGTypeCompiler.visit_TSTZMULTIRANGEc                 K  rF  )N	INT4RANGEr   rG  r   r   r   visit_INT4RANGEA
  rI  zPGTypeCompiler.visit_INT4RANGEc                 K  rF  )N	INT8RANGEr   rG  r   r   r   visit_INT8RANGED
  rI  zPGTypeCompiler.visit_INT8RANGEc                 K  rF  )NNUMRANGEr   rG  r   r   r   visit_NUMRANGEG
  rI  zPGTypeCompiler.visit_NUMRANGEc                 K  rF  )N	DATERANGEr   rG  r   r   r   visit_DATERANGEJ
  rI  zPGTypeCompiler.visit_DATERANGEc                 K  rF  )NTSRANGEr   rG  r   r   r   visit_TSRANGEM
  rI  zPGTypeCompiler.visit_TSRANGEc                 K  rF  )N	TSTZRANGEr   rG  r   r   r   visit_TSTZRANGEP
  rI  zPGTypeCompiler.visit_TSTZRANGEc                 K  rF  )NINTr   rG  r   r   r   visit_json_int_indexS
  rI  z#PGTypeCompiler.visit_json_int_indexc                 K  rF  )NrU   r   rG  r   r   r   visit_json_str_indexV
  rI  z#PGTypeCompiler.visit_json_str_indexc                 K  r   r   )visit_TIMESTAMPrG  r   r   r   visit_datetimeY
  r   zPGTypeCompiler.visit_datetimec                   s4   |j r| jjst j|fi |S | j|fi |S r   )r  r  supports_native_enumrK  
visit_enum
visit_ENUMrG  rO  r   r   r|  \
  s   zPGTypeCompiler.visit_enumNc                 K     |d u r| j j}||S r   r  r   r  r   r	  r   r   r   r   r   r}  b
     
zPGTypeCompiler.visit_ENUMc                 K  r~  r   r  r  r   r   r   visit_DOMAINg
  r  zPGTypeCompiler.visit_DOMAINc                 K  4   dt |dd d urd|j nd|jrdpdd f S )NzTIMESTAMP%s %srU  (%d)r0  WITHWITHOUT
 TIME ZONEgetattrrU  timezonerG  r   r   r   ry  l
     
zPGTypeCompiler.visit_TIMESTAMPc                 K  r  )Nz	TIME%s %srU  r  r0  r  r  r  r  rG  r   r   r   
visit_TIMEv
  r  zPGTypeCompiler.visit_TIMEc                 K  s8   d}|j d ur|d|j  7 }|jd ur|d|j 7 }|S )Nr#   r  z (%d))fieldsrU  )r   r	  r   r   r   r   r   visit_INTERVAL
  s   

zPGTypeCompiler.visit_INTERVALc                 K  s4   |j rd}|jd ur|d|j 7 }|S d|j }|S )NzBIT VARYINGr  zBIT(%d))varyingr  )r   r	  r   compiledr   r   r   	visit_BIT
  s   

zPGTypeCompiler.visit_BITc                   s,   |j r| j|fi |S t j|fi |S r   )native_uuid
visit_UUIDrK  
visit_uuidrG  rO  r   r   r  
  s   zPGTypeCompiler.visit_uuidc                 K  rF  )NrV   r   rG  r   r   r   r  
  rI  zPGTypeCompiler.visit_UUIDc                 K  r   r   )visit_BYTEArG  r   r   r   visit_large_binary
  r   z!PGTypeCompiler.visit_large_binaryc                 K  rF  )Nr   r   rG  r   r   r   r  
  rI  zPGTypeCompiler.visit_BYTEAc                 K  s>   | j |jfi |}tjddd|jd ur|jnd  |ddS )Nz((?: COLLATE.*)?)$z%s\1z[]r   )count)r  r  resub
dimensions)r   r	  r   r   r   r   r   visit_ARRAY
  s   zPGTypeCompiler.visit_ARRAYc                 K  r   r   )visit_JSONPATHrG  r   r   r   visit_json_path
  r   zPGTypeCompiler.visit_json_pathc                 K  rF  )NJSONPATHr   rG  r   r   r   r  
  rI  zPGTypeCompiler.visit_JSONPATHr   )2r  r  r  rH  rK  rL  rM  rN  rO  rP  rQ  rR  rS  rT  rV  rX  rY  rZ  r[  r]  r_  ra  rc  re  rg  ri  rk  rm  ro  rq  rs  ru  rw  rx  rz  r|  r}  r  ry  r  r  r  r  r  r  r  r  r  r  r  r   r   rO  r   rE  	  s^    



	rE  c                   @  s"   e Zd ZeZdd ZdddZdS )PGIdentifierPreparerc                 C  s*   |d | j kr|dd | j| j}|S )Nr   r   r  )initial_quoterM  escape_to_quoteescape_quote)r   rN  r   r   r   _unquote_identifier
  s
   z(PGIdentifierPreparer._unquote_identifierTc                 C  s\   |j std|jj d| |j }| |}| js,|r,|d ur,| | d| }|S )NzPostgreSQL z type requires a name..)	r   r5   r   rP  r  r  schema_for_objectomit_schemaquote_schema)r   r	  ri  r   effective_schemar   r   r   r  
  s   
z PGIdentifierPreparer.format_typeN)T)r  r  r  RESERVED_WORDSreserved_wordsr  r  r   r   r   r   r  
  s    r  c                   @  s.   e Zd ZU dZded< 	 ded< 	 ded< dS )ReflectedNamedTypez"Represents a reflected named type.r  r   r6   boolvisibleNr  r  r  __doc____annotations__r   r   r   r   r  
  s   
 r  c                   @  s$   e Zd ZU dZded< 	 ded< dS )ReflectedDomainConstraintz2Represents a reflect check constraint of a domain.r  r   r   Nr  r   r   r   r   r  
  s   
 r  c                   @  sB   e Zd ZU dZded< 	 ded< 	 ded< 	 ded	< 	 ded
< dS )ReflectedDomainRepresents a reflected enum.r  r  r  r  Optional[str]r;   zList[ReflectedDomainConstraint]constraintsr  Nr  r   r   r   r   r  
  s   
 r  c                   @  s   e Zd ZU dZded< dS )ReflectedEnumr  	List[str]labelsNr  r   r   r   r   r  
  s   
 r  c                   @  sZ   e Zd ZU ded< 	ddd
dZ	ddddZddddZ	ddddZ	dd ddZdS )!PGInspector	PGDialectr  N
table_namer  r6   r  returnintc                 C  sB   |   }| jj|||| jdW  d   S 1 sw   Y  dS )aQ  Return the OID for the given table name.

        :param table_name: string name of the table.  For special quoting,
         use :class:`.quoted_name`.

        :param schema: string schema name; if omitted, uses the default schema
         of the database connection.  For special quoting,
         use :class:`.quoted_name`.

        
info_cacheN)_operation_contextr  get_table_oidr  )r   r  r6   connr   r   r   r    
   

$zPGInspector.get_table_oidList[ReflectedDomain]c                 C  @   |   }| jj||| jdW  d   S 1 sw   Y  dS )a  Return a list of DOMAIN objects.

        Each member is a dictionary containing these fields:

            * name - name of the domain
            * schema - the schema name for the domain.
            * visible - boolean, whether or not this domain is visible
              in the default search path.
            * type - the type defined by this domain.
            * nullable - Indicates if this domain can be ``NULL``.
            * default - The default value of the domain or ``None`` if the
              domain has no default.
            * constraints - A list of dict wit the constraint defined by this
              domain. Each element constaints two keys: ``name`` of the
              constraint and ``check`` with the constraint text.

        :param schema: schema name.  If None, the default schema
         (typically 'public') is used.  May also be set to ``'*'`` to
         indicate load domains for all schemas.

        .. versionadded:: 2.0

        r  N)r  r  _load_domainsr  r   r6   r  r   r   r   get_domains  s
   
$zPGInspector.get_domainsList[ReflectedEnum]c                 C  r  )a.  Return a list of ENUM objects.

        Each member is a dictionary containing these fields:

            * name - name of the enum
            * schema - the schema name for the enum.
            * visible - boolean, whether or not this enum is visible
              in the default search path.
            * labels - a list of string labels that apply to the enum.

        :param schema: schema name.  If None, the default schema
         (typically 'public') is used.  May also be set to ``'*'`` to
         indicate load enums for all schemas.

        r  N)r  r  _load_enumsr  r  r   r   r   	get_enums5  s
   
$zPGInspector.get_enumsr  c                 C  r  )zReturn a list of FOREIGN TABLE names.

        Behavior is similar to that of
        :meth:`_reflection.Inspector.get_table_names`,
        except that the list is limited to those tables that report a
        ``relkind`` value of ``f``.

        r  N)r  r  _get_foreign_table_namesr  r  r   r   r   get_foreign_table_namesJ  s
   
$z#PGInspector.get_foreign_table_names	type_namer   r   r  c                 K  sB   |   }| jj|||| jdW  d   S 1 sw   Y  dS )aJ  Return if the database has the specified type in the provided
        schema.

        :param type_name: the type to check.
        :param schema: schema name.  If None, the default schema
         (typically 'public') is used.  May also be set to ``'*'`` to
         check in all schemas.

        .. versionadded:: 2.0

        r  N)r  r  has_typer  )r   r  r6   r   r  r   r   r   r  Z  r  zPGInspector.has_typer   )r  r  r6   r  r  r  )r6   r  r  r  )r6   r  r  r  )r6   r  r  r  )r  r  r6   r  r   r   r  r  )	r  r  r  r  r  r  r  r  r  r   r   r   r   r     s   
 r  c                      s$   e Zd Zdd Z fddZ  ZS )PGExecutionContextc                 C  s   |  d| j| |S )Nzselect nextval('%s'))_execute_scalarr   rT  )r   rU  r	  r   r   r   fire_sequenceo  s   
z PGExecutionContext.fire_sequencec                   s&  |j r||jju r|jr|jjr| d|jj |jS |jd u s(|jj	r|jj
rz|j}W n9 tyf   |jj}|j}|ddtddt|   }|ddtddt|   }d||f }| |_}Y nw |jd urt| j|j}nd }|d urd||f }nd|f }| ||jS t |S )Nz	select %sr      z	%s_%s_seqzselect nextval('"%s"."%s"')zselect nextval('"%s"'))r  r   r  server_defaulthas_argumentr  argr  r;   is_sequencer  _postgresql_seq_nameAttributeErrorr   maxry  
connectionr  rK  get_insert_default)r   r   seq_nametabrb  r   r  r5   rO  r   r   r  x  sB   



z%PGExecutionContext.get_insert_default)r  r  r  r  r  r  r   r   rO  r   r  n  s    	r  c                   @  (   e Zd ZdZdd Zdd Zdd ZdS )	"PGReadOnlyConnectionCharacteristicTc                 C     | |d d S NFset_readonlyr   r  
dbapi_connr   r   r   reset_characteristic  r>  z7PGReadOnlyConnectionCharacteristic.reset_characteristicc                 C     | || d S r   r  r   r  r  rN  r   r   r   set_characteristic  r>  z5PGReadOnlyConnectionCharacteristic.set_characteristicc                 C  
   | |S r   )get_readonlyr  r   r   r   get_characteristic     
z5PGReadOnlyConnectionCharacteristic.get_characteristicNr  r  r  transactionalr  r  r  r   r   r   r   r    
    r  c                   @  r  )	$PGDeferrableConnectionCharacteristicTc                 C  r  r  set_deferrabler  r   r   r   r    r>  z9PGDeferrableConnectionCharacteristic.reset_characteristicc                 C  r  r   r  r  r   r   r   r    r>  z7PGDeferrableConnectionCharacteristic.set_characteristicc                 C  r  r   )get_deferrabler  r   r   r   r    r  z7PGDeferrableConnectionCharacteristic.get_characteristicNr  r   r   r   r   r    r  r  c                
      s  e Zd ZdZdZdZdZdZej	j
ZdZdZdZdZdZdZdZdZdZdZejejB ejB ZdZdZdZdZdZdZ dZ!dZ"e#Z#e$Z$e%Z&e'Z(e)Z*e+Z,e-Z.e/Z0dZ1dZ2dZ3dZ4dZ5e6j7j8Z8e89e: e; dZ8e<j=dddi di dddfe<j>dddddddd	fe<j?d
dife<j@d
dife<jAddifgZBdZCdZDdZEdZF			dddZG fddZHdd ZIdd ZJdd ZKdd ZLdd ZMdd ZNdd ZOdd#d$ZPd%d& ZQd'd( ZR	dd)d*ZS	dd+d,ZTd-d. ZUd/d0 ZVeWjXd1d2 ZY	dd3d4ZZdd5d6Z[e\ d7d8 Z]eWjXdd9d:Z^eWjXdd;d<Z_eWjXdd=d>Z`d?d@ ZaeWjXddAdBZbeWjXdCdD ZcdEdF ZdeWjXddGdHZeeWjXdIdJ ZfeWjXddKdLZgeWjXddMdNZheWjXddOdPZieWjXddQdRZjeWjXddSdTZkeWjXddUdVZldWdX ZmdYdZ Zndd^d_ZoeWjXdd`daZpe\ dbdc Zqddde ZrestdfZuestdgZvestdhZwddrdsZxdtdu Zye\ dvdw ZzeW{dxe|j}fdye|j~fd[e|jfdze|jfd{d| Ze\ d}d~ Zdd ZeWjXdddZdd ZeWjX		dddZe\ dd Zejdd Z	dddZeWjXdddZejdd Zdd ZeWjX	dddZdd ZeWjXdddZe\ dd Zdd ZeWjXdddZe\ dd Zdd Zdd Ze\ dd ZeWjXdddZe\ dd ZeWjXdddZdd Z  ZS )r  r  T?   Fpyformat)postgresql_readonlypostgresql_deferrableN)r   r  r   r
  r  r}   r  r  )ignore_search_pathr  r2  r3  r4  r1  r   r  r  )postgresql_ignore_search_pathc                 K  s*   t jj| fi | || _|| _|| _d S r   )r;   DefaultDialect__init___native_inet_types_json_deserializer_json_serializer)r   native_inet_typesjson_serializerjson_deserializerr  r   r   r   r  7  s   
zPGDialect.__init__c                   s>   t  | | jdk| _| | | jdk| _| jdk| _d S )N)	   rw  
   )rK  
initializeserver_version_infor  _set_backslash_escapesr(  r  r   r  rO  r   r   r  D  s
   
zPGDialect.initializec                 C  rF  )N)SERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READr   )r   r  r   r   r   get_isolation_level_valuesR  s   z$PGDialect.get_isolation_level_valuesc                 C  s.   |  }|d|  |d |  d S )Nz;SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL COMMIT)cursorexecuteclose)r   dbapi_connectionlevelr  r   r   r   set_isolation_level\  s   
zPGDialect.set_isolation_levelc                 C  s.   |  }|d | d }|  | S )Nz show transaction isolation levelr   )r  r  fetchoner  r\  )r   r  r  valr   r   r   get_isolation_levele  s
   
zPGDialect.get_isolation_levelc                 C     t  r   NotImplementedErrorr   r  rN  r   r   r   r  l     zPGDialect.set_readonlyc                 C  r  r   r  r
  r   r   r   r  o  r  zPGDialect.get_readonlyc                 C  r  r   r  r  r   r   r   r  r  r  zPGDialect.set_deferrablec                 C  r  r   r  r
  r   r   r   r  u  r  zPGDialect.get_deferrableurlr@   r  UUnion[Tuple[None, None], Tuple[Tuple[Optional[str], ...], Tuple[Optional[int], ...]]]c           	      C  s  d }d }d}d|j v rzt|j d ttfr&d}tdd |j d D  \}}nTt|j d trzt|j d d}d|j vrzt|dkrzd	|d
 v rzt	d|d
 }|rzd}|
dd\}}trmt|tsfJ t|tsmJ |f}td|rw|fnd}d|j v r|rtdt|j d ttfr|j d }nt|j d trt|j d d}d }|rztdd |D }W n ty   td| d w |r|st|dks|r|rt|t|krt|dkst|dkrtd|d ur|d u rtdd |D }||fS )NFhostTc                 S  s&   g | ]}d |v r| d n|dfqS ):Nsplit)rE  tokenr   r   r   rd    r  z7PGDialect._split_multihost_from_url.<locals>.<listcomp>,portr   r  r   z ^([a-zA-Z0-9\-\.]*)(?:\:(\d*))?$rw  zTuple[Optional[str], ...]r   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" separatelyc                 s  s     | ]}|r
t |nd V  qd S r   r  rE  xr   r   r   rG    s    z6PGDialect._split_multihost_from_url.<locals>.<genexpr>z%Received non-integer port arguments: z%number of hosts and ports don't matchc                 s  s    | ]}d V  qd S r   r   )rE  r5  r   r   r   rG    s    )queryr   r  r6  zipr  r!  ry  r  matchr   r
   r   r5   ArgumentError
ValueError)	r   r  hosts	ports_strintegrated_multihosthost_port_matchhpportsr   r   r   _split_multihost_from_urlx  s   






z#PGDialect._split_multihost_from_urlc                 C  s   |  |j d S r   )do_beginr  r   r  xidr   r   r   do_begin_twophase  r>  zPGDialect.do_begin_twophasec                 C  s   | d|  d S )NzPREPARE TRANSACTION '%s')exec_driver_sqlr6  r   r   r   do_prepare_twophase  r   zPGDialect.do_prepare_twophasec                 C  sJ   |r|r	| d | d|  | d | |j d S | |j d S )NROLLBACKzROLLBACK PREPARED '%s'BEGIN)r9  do_rollbackr  r   r  r7  is_preparedrecoverr   r   r   do_rollback_twophase  s   

zPGDialect.do_rollback_twophasec                 C  sJ   |r|r	| d | d|  | d | |j d S | |j d S )Nr;  zCOMMIT PREPARED '%s'r<  )r9  r=  r  	do_commitr>  r   r   r   do_commit_twophase  s   

zPGDialect.do_commit_twophasec                 C  s   | td S )Nz!SELECT gid FROM pg_prepared_xacts)scalarsr8   r   ra   r
  r   r   r   do_recover_twophase  s
   zPGDialect.do_recover_twophasec                 C  s   | d S )Nzselect current_schema())r9  scalarr
  r   r   r   _get_default_schema_name  rS  z"PGDialect._get_default_schema_namec                 K  s,   t tjjjtjjj|k}t||S r   )r7   r   pg_namespaceru  nspnamer   r  rF  )r   r  r6   r   r(  r   r   r   
has_schema  s   zPGDialect.has_schemac                 C  s   |d u rt j}|t jt jjj|jjk}|tju r$|	|jj
dk}n|tju r2|	|jj
dk}|d u rH|	t |jjt jjjdk}|S |	t jjj|k}|S )Nr  r   )r   pg_classrr   rH  ru  r   relnamespacer>   DEFAULTr   relpersistence	TEMPORARYpg_table_is_visiblerI  )r   r(  r6   scopepg_class_tabler   r   r   _pg_class_filter_scope_schema  s$   

z'PGDialect._pg_class_filter_scope_schemac                 C  s&   |d u rt j}|jjtt|kS r   )r   rK  ru  relkindr8   any_r   r~   )r   relkindsrR  r   r   r   _pg_class_relkind_condition  s   z%PGDialect._pg_class_relkind_conditionc                 C  s>   t tjjjtjjjtdk| tj}| j	||t
jdS )Nr  rQ  )r7   r   rK  ru  relnamer   rB   rW  RELKINDS_ALL_TABLE_LIKErS  r>   ANY)r   r6   r(  r   r   r   _has_table_query  s   zPGDialect._has_table_queryc                 K  s(   |  | | |}t||d|iS )Nr  )_ensure_has_table_connectionr\  r  rF  )r   r  r  r6   r   r(  r   r   r   	has_table)  s   

zPGDialect.has_tablec                 K  sJ   t tjjjtjjjdktjjj|k}| j||tj	d}t
||S )NSrX  )r7   r   rK  ru  rY  r   rT  rS  r>   r[  r  rF  )r   r  sequence_namer6   r   r(  r   r   r   has_sequence/  s   zPGDialect.has_sequencec                 K  s   t tjjjtjtjjjtjjjk	tjjj|k}|d u r2|	t
tjjjtjjjdk}n|dkr@|	tjjj|k}t||S Nr   *)r7   r   pg_typeru  typnamerr   rH  r   typnamespacer   pg_type_is_visiblerI  r  rF  )r   r  r  r6   r   r(  r   r   r   r  :  s"   	zPGDialect.has_typec                 C  sF   | d }td|}|std| tdd |dddD S )	Nzselect pg_catalog.version()zQ.*(?:PostgreSQL|EnterpriseDB) (\d+)\.?(\d+)?(?:\.(\d+))?(?:\.\d+)?(?:devel|beta)?z,Could not determine version from string '%s'c                 S  s   g | ]
}|d urt |qS r   r%  r&  r   r   r   rd  [  s    z6PGDialect._get_server_version_info.<locals>.<listcomp>r   rw  r4   )r9  rF  r  r*  AssertionErrorr6  r   )r   r  r  mr   r   r   _get_server_version_infoP  s   z"PGDialect._get_server_version_infoc                 K  sn   t tjjjtjjj|k| tj}| j	||t
jd}||}|du r5t|r2| d| ||S )z$Fetch the oid for schema.table_name.rX  Nr  )r7   r   rK  ru  r   r   rY  rW  rZ  rS  r>   r[  rF  r5   NoSuchTableError)r   r  r  r6   r   r(  	table_oidr   r   r   r  ]  s"   
zPGDialect.get_table_oidc                 K  s:   t tjjjtjjjdtjjj}||	 S )Nzpg_%)
r7   r   rH  ru  rI  r   not_liker$  rD  ra   )r   r  r   r(  r   r   r   get_schema_namesp  s
   zPGDialect.get_schema_namesc                 C  s8   t tjjj| |}| j|||d}||	 S NrX  )
r7   r   rK  ru  rY  r   rW  rS  rD  ra   )r   r  r6   rV  rQ  r(  r   r   r   _get_relnames_for_relkindsy  s
   z$PGDialect._get_relnames_for_relkindsc                 K     | j ||tjtjdS ro  )rp  r   RELKINDS_TABLE_NO_FOREIGNr>   rM  r   r  r6   r   r   r   r   get_table_names     zPGDialect.get_table_namesc                 K  s   | j |d tjtjdS )N)r6   rV  rQ  )rp  r   rr  r>   rO  )r   r  r   r   r   r   get_temp_table_names  ru  zPGDialect.get_temp_table_namesc                 K     | j ||dtjdS )N)frV  rQ  rp  r>   r[  rs  r   r   r   r       
z"PGDialect._get_foreign_table_namesc                 K  rq  ro  )rp  r   RELKINDS_VIEWr>   rM  rs  r   r   r   get_view_names  ru  zPGDialect.get_view_namesc                 K  rq  ro  )rp  r   RELKINDS_MAT_VIEWr>   rM  rs  r   r   r   get_materialized_view_names  ru  z%PGDialect.get_materialized_view_namesc                 K  rq  ro  )rp  r   r|  r>   rO  rs  r   r   r   get_temp_view_names  s   zPGDialect.get_temp_view_namesc                 K  rw  )N)r_  ry  rz  rs  r   r   r   get_sequence_names  r{  zPGDialect.get_sequence_namesc                 K  s   t ttjjjtjtjjj|k| 	tj
tj }| j||tjd}||}|d u r?t|r<| d| ||S )NrX  r  )r7   r   pg_get_viewdefrK  ru  r   select_fromr   rY  rW  r|  r~  rS  r>   r[  rF  r5   rk  )r   r  	view_namer6   r   r(  resr   r   r   get_view_definition  s(   


zPGDialect.get_view_definitionc                 C  sD   z	t |||f W S  ty!   t|r| d| d |d w )Nr  )r  KeyErrorr5   rk  )r   datar   r6   r   r   r   _value_or_raise  s   zPGDialect._value_or_raisec                 C  s   |rdd|ifS di fS )NTfilter_namesFr   )r   r  r   r   r   _prepare_filter_names  s   zPGDialect._prepare_filter_nameskindr=   Tuple[str, ...]c                 C  sT   |t ju rtjS d}t j|v r|tj7 }t j|v r|tj7 }t j|v r(|tj	7 }|S )Nr   )
r=   r[  r   rZ  TABLERELKINDS_TABLEVIEWr|  MATERIALIZED_VIEWr~  )r   r  rV  r   r   r   _kind_to_relkinds  s   






zPGDialect._kind_to_relkindsc                 K  0   | j |f||gtjtjd|}| |||S N)r6   r  rQ  r  )get_multi_columnsr>   r[  r=   r  r   r  r  r6   r   r  r   r   r   get_columns     zPGDialect.get_columnsc           
      C  s  | j dkrtjjjdnt d}| j dkr{ttj	
dtjjjdkdtjjjdtjjjdtjjjd	tjjjd
tjjjdtjjjtjtjjjdktjjjttttttjjjtttjjjttktj d}nt d}tttj jj!tj jj"tj tj jj"tjjjktj jj#tjjj$ktjjj%tj d}| &|}ttjjjdt'tjjj(tjjj)d|tjjj*dtj+jj,dtj-jj.d||tj+/tjt0tj+jj1tjjjktjjj$dktjjj2 /tj-t0tj-jj3tjjjktj-jj4tjjj$k| 5|6tj+jj,tjjj$}	| j7|	||d}	|rJ|	tj+jj,8t9d}	|	S )N)   r<  r  alwaysar  	incrementminvaluemaxvaluecachecycler0  identity_optionsr;   r   r  r  r  rB  r   rX  r  ):r  r   pg_attributeru  attgeneratedlabelr8   ru   r7   rz  json_build_objectattidentitypg_sequenceseqstartseqincrementseqminseqmaxseqcacheseqcycler  r   seqrelidr   pg_get_serial_sequenceattrelidr/   rU   attnamer'   	correlatescalar_subquerypg_get_expr
pg_attrdefadbinadrelidadnumattnum	atthasdefr  r  atttypid	atttypmod
attnotnullrK  rY  pg_descriptiondescription	outerjoinand_r   attisdroppedobjoidobjsubidrW  r$  rS  in_rB   )
r   r6   has_filter_namesrQ  r  r<  r  r;   rV  r(  r   r   r   _columns_query  s   


/

		)zPGDialect._columns_queryc                 K  s   |  |\}}| ||||}	||	| }
dd | j|d|ddD }tdd | j|d|ddD }| |
|||}|	 S )Nc                 S  s0   i | ]}|d  s|d |d fn|d f|qS )r  r6   r   r   )rE  dr   r   r   
<dictcomp>  s    "z/PGDialect.get_multi_columns.<locals>.<dictcomp>rc  r  )r6   r  c                 s  s:    | ]}|d  r|d f|fn	|d |d f|fV  qdS )r  r   r6   Nr   )rE  recr   r   r   rG    s    
z.PGDialect.get_multi_columns.<locals>.<genexpr>)
r  r  r  mappingsr  r2  r  r  _get_columns_infor  )r   r  r6   r  rQ  r  r   r  paramsr(  rowsdomainsr  r  r   r   r   r  y  s   	zPGDialect.get_multi_columnsz\((.*)\)\s*,\s*z((?:\[\])*)$r  r  r  dict[str, ReflectedDomain]r  dict[str, ReflectedEnum]type_descriptionr  sqltypes.TypeEngine[Any]c              	   C  sn  |pd}|du rt d|  tjS | j|}|r)|dr)| j|d}nd}| j	|}t
|dp8dd }| jd|}	| j	d|	}	| j|	 d}
di }}|	dkrot
|dkrmtt|\}}||f}n&|	d	krwd
}n|	dkrd}n|	dv rd|d< t
|dkrt|d |d< n|	dv rd|d< t
|dkrt|d |d< n|	dkrd|d< t
|dkrt|d }|f}n|	drt}
td|	}|r|d|d< t
|dkrt|d |d< ntt |	}||v rt}
|| }t|d }|d |d< |d s|d |d< t|d }n{||v rtt}
|| }| j|d ||d|d  d}|d |f}|d |d< |d  |d < |d!  |d"< d|d#< |d$ rh|d$ d }|d |d%< |d& |d&< |d ss|d |d< n!zt|d }|g|dd R }W n ttfy   |}Y nw |
st d'|	|f  tjS |
|i |}|dkrt|}|S )(aB  
        Attempts to reconstruct a column type defined in ischema_names based
        on the information available in the format_type.

        If the `format_type` cannot be associated with a known `ischema_names`,
        it is treated as a reference to a known PostgreSQL named `ENUM` or
        `DOMAIN` type.
        zunknown typeNz-PostgreSQL format_type() returned NULL for %sr   r   r0  rw  r   r   )5   r   )r   r   Tr  r   rU  )r   r   r   Fr   r  r   zinterval (.+)r  r  r   r  r6   r  zDOMAIN '%s'r  r  r;   r  r  create_typer  r  r   z!Did not recognize type '%s' of %s)r9   r  rH   NULLTYPE_format_type_args_patternsearchr   _format_type_args_delimr!  _format_array_spec_patternry  r  ischema_namesr2  r  mapr  
startswithr#   r  r*  r6  quoted_token_parserr   r   _reflect_typer,  
IndexErrorr   r  )r   r  r  r  r  attype_args_matchattype_argsmatch_array_dim	array_dimattypeschema_typeargsr  rU  scalecharlenfield_matchenum_or_domain_keyenumr  r  check_constraintr   r   r   r    s   









zPGDialect._reflect_typec                 C  s  t t}|D ]}|d d u rt |||d f< q|||d f }| j|d ||d|d  d}|d }	|d }
|d }|d  }t|trV|	sP|jd urP|j}	|oU|j }|d	 }|d
vrit	|	|dv d}d }	nd }d}|	d urt
d|	}|d urt|jtjrd}d|dvr|d ur|dd|  d |d |d }	|
|||	|p|d u|d d}|d ur||d< |d ur||d< || q|S )Nr   r  r  zcolumn '%s'r  r;   r<  r  r  )Nr0      )r{     s)r  r;  Fz(nextval\(')([^']+)('.*$)Tr  rw  r   z"%s"r4   rB  )r   r  r  r;   autoincrementrB  r  r  )r   r  rA   r  r  r   r   r;   r  r  r  r  
issubclassr  rH   Integerr   r  )r   r  r  r  r6   r  row_dict
table_colscoltyper;   r   r<  r  r  r  r  r*  column_infor   r   r   r  /  sv   



	
zPGDialect._get_columns_infoc                 C  s^   |  |}ttjjjtjjj| |}| j	|||d}|r-|tjjj
td}|S )NrX  r  )r  r7   r   rK  ru  r   rY  r   rW  rS  r  rB   )r   r6   r  rQ  r  rV  oid_qr   r   r   _table_oids_query  s   
zPGDialect._table_oids_queryr6   r  rQ  c                 K  s2   |  |\}}| ||||}	||	|}
|
 S r   )r  r  r  ra   )r   r  r6   r  rQ  r  r   r  r  r  resultr   r   r   _get_table_oids  s   	zPGDialect._get_table_oidsc              	   C  s  t tjjjtjjjtjjjtj	tjjj
dtjtjjj
ddtjjjtjtjjjtjjjktjjjtdktjjjtdd}t |jj|jj|jj|jj|jjtjjjtj|ttjjj|jjktjjj|jjk|jjtdd}t |jjtjt |jj!t"|jjd|jjtj#|jjd	$|jj|jj%|jj|jj}|r| j&d
kr|tj'|jjtj'jj(k)tj*tj'jj+d}|S |)t, d}|S |)t- d}|S )Nr  r   ordcontypeoidsconattrr  r     indnullsnotdistinctextra).r7   r   pg_constraintru  conrelidconnameconindidr8   rz  unnestconkeyr  generate_subscriptsr  r  r  r  r   r   r  rB   r  subqueryr  r  r  r  rr   r  r  r  	array_aggr   r   rU   mingroup_byr$  r  pg_index
indexrelidadd_columnsbool_andr  r   ru   )r   	is_uniquecon_sqattr_sqconstraint_queryr   r   r   _constraint_query  s   
	
zPGDialect._constraint_queryc                 k  s   | j |||||fi |}t|}	|dk}
|	r|	dd }g |	dd< || |
dd |D |d}tt}|D ]\}}}}}|| ||||f q;|D ]3\}}||d}|r{|D ]\}}}}|
rq||||d|ifV  q^||||d fV  q^qP|d d d d fV  qP|	sd S d S )	Nur     c                 S     g | ]}|d  qS r   r   rE  rr   r   r   rd        z1PGDialect._reflect_constraint.<locals>.<listcomp>)r  r  r   nullsnotdistinct)r  r  r  r  r   r  r2  )r   r  r  r6   r  rQ  r  r   
table_oidsbatchesr  batchr  result_by_oidr   r  r  rB  r  	tablenamefor_oidr   r   r   r   _reflect_constraint  s@   


zPGDialect._reflect_constraintc                 K  r  r  )get_multi_pk_constraintr>   r[  r=   r  r  r   r   r   get_pk_constraint!  r  zPGDialect.get_pk_constraintc                   s6   | j |d|||fi |}tj  fdd|D S )Nr2  c                 3  sH    | ]\}}}}}|f|d ur|d u rg n|||dn  fV  qd S )N)constrained_columnsr   rB  r   )rE  r  r  pk_namerB  r5  r;   r6   r   r   rG  7  s    
z4PGDialect.get_multi_pk_constraint.<locals>.<genexpr>)r(  rA   pk_constraint)r   r  r6   r  rQ  r  r   r  r   r-  r   r)  -  s   z!PGDialect.get_multi_pk_constraintc                 K  s2   | j |f||g|tjtjd|}| |||S )N)r6   r  r  rQ  r  )get_multi_foreign_keysr>   r[  r=   r  )r   r  r  r6   r  r   r  r   r   r   get_foreign_keysG  s   		zPGDialect.get_foreign_keysc           	   	   C  s8  t jd}t jd}| |}tt jjjt jjj	t
jt jjjd t t jjjdfd d|jjt jjjt jt jt
t jjjt jjjkt jjjdk||jjt jjjk||jj|jjkt jt jjjt jjjkt jjjt jjj	| |}| |||}|r|t jjjtd}|S )Ncls_refnsp_refTelse_rx  r  ) r   rK  aliasrH  r  r7   ru  rY  r  r  r8   rl   r   is_notpg_get_constraintdefrI  r  r  r  r  r  r  r  	confrelidrL  r  r$  r   rW  rS  r  rB   )	r   r6   r  rQ  r  pg_class_refpg_namespace_refrV  r(  r   r   r   _foreing_key_query[  sj   

	.zPGDialect._foreing_key_queryc              	   C  s"   d}t d| d| d| dS )Nz(?:"[^"]+"|[A-Za-z0-9_]+?)z%FOREIGN KEY \((.*?)\) REFERENCES (?:(z)\.)?(z)\(((?:a  (?: *, *)?)+)\)[\s]?(MATCH (FULL|PARTIAL|SIMPLE)+)?[\s]?(ON UPDATE (CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?[\s]?(ON DELETE (CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?[\s]?(DEFERRABLE|NOT DEFERRABLE)?[\s]?(INITIALLY (DEFERRED|IMMEDIATE)+)?)r  compile)r   qtokenr   r   r   _fk_regex_pattern  s   zPGDialect._fk_regex_patternc           "        s  | j  | |\}}	| ||||}
||
|	}| j}tt}tj}|D ]\}}}}}|d u r7| |||f< q$|||f }t	
|| }|\}}}}}}}}}}}}}|d ur`|dkr^dnd} fddt	d|D }|rz|| jkrw|}n|}n|r |}n
|d ur||kr|} |} fddt	d|D }d	d
 d|fd|fd|fd|fd|ffD } |||||| |d}!||! q$| S )N
DEFERRABLETFc                      g | ]}  |qS r   r  r&  r  r   r   rd        z4PGDialect.get_multi_foreign_keys.<locals>.<listcomp>r  c                   r@  r   rA  r&  r  r   r   rd    rB  z\s*,\sc                 S  s&   i | ]\}}|d ur|dkr||qS )Nz	NO ACTIONr   )rE  r  r  r   r   r   r    s
    z4PGDialect.get_multi_foreign_keys.<locals>.<dictcomp>onupdateondeleter   r   r*  )r   r+  referred_schemareferred_tablereferred_columnsr  rB  )r   r  r;  r  r>  r   r  rA   foreign_keysr  r  groupsr!  default_schema_namer  r  r  )"r   r  r6   r  rQ  r  r  r   r  r  r(  r  FK_REGEXfkeysr;   r  r  condef	conschemarB  	table_fksri  r+  rE  rF  rG  r5  r*  rC  rD  r   r   r  fkey_dr   r  r   r/    s~   






	z PGDialect.get_multi_foreign_keysc                 K  r  r  )get_multi_indexesr>   r[  r=   r  r  r   r   r   get_indexes  r  zPGDialect.get_indexesc                 C  s4  t jd}tt jjjt jjjtj	
t jjjdtj	t jjjddt jjj t jjjtdd}t|jj|jj|jjtj|jjdkt |jj|jjd dft jjjtd	d
|jjdkd|t jtt jjj|jjkt jjj|jjk|jjtdd}t|jjtj	|jjtj	 t!|jj"|jjdtj	 t!|jj#|jjd$|jjd}| j%dkrt jjj&}nt' d}| j%dkrt jjj(}nt) d}tt jjj|jj*dt jjj+t j,jj-.d dt jjj/|jj0t j1jj2tjt jjj3.d t 4t jjj3t jjjfd d	d|||jj5|jj6t jt jjjtdt jjj 7|t jjj|jj8k7t j1|jj9t j1jj8k|t jjj|jjkt j,tt jjjt j,jj-kt jjjt j,jj:kt j,jj;t<t=>dk?t jjj|jj*S )Ncls_idxr  r   r  r  idxr   Tr3  r   is_expridx_attrrE   elements_is_expridx_cols)   r   indnkeyattsr  r  relname_indexhas_constraintfilter_definition)r2  r  r'  )@r   rK  r5  r7   r  ru  r  indrelidr8   rz  r
  indkeyr  r  r   indisprimaryr  rB   r  r  rl   r  pg_get_indexdefr  r  r   rU   r  r  r  r  r  r  r   r   rU  r  r  rZ  ru   r  r   rY  indisuniquer  r  r6  	indoption
reloptionspg_amamnameindpredr  rE   rW  rr   r   relamr	  r  rU  r   r~   r$  )r   pg_class_indexidx_sqr  cols_sqrZ  r  r   r   r   _index_query  s   


	#



	
zPGDialect._index_queryc           !      K  s  | j |||||fi |}tt}tj}	t|}
|
r^|
dd }g |
dd< || jddd |D i }tt}|D ]}||d  | q=|D ]\}}||vr\|	 |||f< qK|| D ]}|d }|||f }|d }|d	 }|d
 }|rt	||kr||d  }|d | }|d | }t
dd ||d  D sJ n|}|}g }||d d}t|rdd t||D |d< ||d< n||d< i }t|d D ]'\}}d}|d@ r|d7 }|d@ s|d7 }n|d@ r|d7 }|r|||| < q|r||d< |d r||d< i }|d rtdd |d D |d< |d } | d kr*|d |d!< |d" r5|d" |d#< | jd$krC||d%< ||d&< |d' rN|d' |d(< |rU||d)< || q`qK|
s| S )*Nr   r  r  c                 S  r  r  r   r  r   r   r   rd    r   z/PGDialect.get_multi_indexes.<locals>.<listcomp>r^  r[  rE   rW  rZ  c                 s  s    | ]}| V  qd S r   r   )rE  rU  r   r   r   rG    s
    
z.PGDialect.get_multi_indexes.<locals>.<genexpr>rb  )r   r   c                 S  s   g | ]
\}}|r
d n|qS r   r   )rE  r  rU  r   r   r   rd    s    
column_namesr  rc  r   r   )rm   rw  )
nulls_last)nulls_firstcolumn_sortingr\  duplicates_constraintrd  c                 S  s   g | ]}| d dqS )=r   r   )rE  optionr   r   r   rd     s    
postgresql_withrf  btreepostgresql_usingr]  postgresql_where)rY  include_columnspostgresql_includer  postgresql_nulls_not_distinctr  )r  r   r  rA   indexesr  rl  r  r  ry  ra   rc   r)  	enumerater  r  r  )!r   r  r6   r  rQ  r  r   r"  r{  r;   r#  r$  r  r%  r  r   r  row
index_nametable_indexesall_elementsall_elements_is_exprrZ  inc_colsidx_elementsidx_elements_is_exprr  sorting	col_index	col_flagscol_sortingr  rf  r   r   r   rQ    s   









szPGDialect.get_multi_indexesc                 K  r  r  )get_multi_unique_constraintsr>   r[  r=   r  r  r   r   r   get_unique_constraints!  s   z PGDialect.get_unique_constraintsc                 K  s   | j |d||||fi |}tt}tj}	|D ]0\}
}}}}|d u r*|	 |||
f< q|||d}|r>|d r>d|d i|d< |||
f | q| S )Nr  )rm  r   rB  r!  rz  r  )r(  r   r  rA   unique_constraintsr  r  )r   r  r6   r  rQ  r  r   r  uniquesr;   r  r  con_namerB  r  uc_dictr   r   r   r  /  s.   	z&PGDialect.get_multi_unique_constraintsc                 K  0   | j |||gftjtjd|}| |||S N)rQ  r  )get_multi_table_commentr>   r[  r=   r  r  r   r   r   get_table_commentV     zPGDialect.get_table_commentc                 C  s   |  |}ttjjjtjjjtj	tjt
tjjjtjjjktjjjdktjjjt
jdtk| |}| |||}|rQ|tjjjtd}|S )Nr   zpg_catalog.pg_classr  )r  r7   r   rK  ru  rY  r  r  r  r  r8   r  r   r  r  classoidrz  r   r/   r   rW  rS  r  rB   r   r6   r  rQ  r  rV  r(  r   r   r   _comment_queryb  s4   

zPGDialect._comment_queryc                   sD   |  |\}}| |||}	||	|}
tj  fdd|
D S )Nc                 3  s2    | ]\}}|f|d urd|in  fV  qd S )Nr   r   )rE  r   rB  r-  r   r   rG    s    
z4PGDialect.get_multi_table_comment.<locals>.<genexpr>)r  r  r  rA   table_comment)r   r  r6   r  rQ  r  r   r  r  r(  r  r   r-  r   r  ~  s   z!PGDialect.get_multi_table_commentc                 K  r  r  )get_multi_check_constraintsr>   r[  r=   r  r  r   r   r   get_check_constraints  r  zPGDialect.get_check_constraintsc              	   C  s   |  |}ttjjjtjjjtj	tjjj
d ttjjj
dfd dtjjjtjtjttjjj
tjjjktjjjdktjtjjjtjjj
ktjjjtjjj| |}| |||}|rv|tjjjtd}|S )NTr3  ru  r  )r  r7   r   rK  ru  rY  r  r  r8   rl   r   r6  r7  r  r  r  r  r  r  r  r  r$  r   rW  rS  r  rB   r  r   r   r   _check_constraint_query  sT   

	%z!PGDialect._check_constraint_queryc                 K  s  |  |\}}| ||||}	||	|}
tt}tj}|
D ]g\}}}}|d u r4|d u r4| |||f< qtjd|tj	d}|sIt
d|  d}ntjdtj	dd|d}|||d}|r|i }d	| v rld
|d< d| v rvd
|d< |r|||d< |||f | q| S )Nz,^CHECK *\((.+)\)( NO INHERIT)?( NOT VALID)?$)r6  z)Could not parse CHECK constraint text: %rr0  z^[\s\n]*\((.+)\)[\s\n]*$z\1r   )r   r  rB  r  Tr  z NO INHERIT
no_inheritr  )r  r  r  r   r  rA   check_constraintsr  r*  DOTALLr9   r  r<  r  r   rI  r  r  )r   r  r6   r  rQ  r  r   r  r  r(  r  r  r;   r  
check_namesrcrB  ri  r  entryrZ   r   r   r   r    sL   
z%PGDialect.get_multi_check_constraintsc                 C  sN   |d u r| ttjjjtjjjdk}|S |dkr%| tjjj|k}|S rb  )r   r   rg  rd  ru  r   rH  rI  )r   r(  r6   r   r   r   _pg_type_filter_schema  s   z PGDialect._pg_type_filter_schemac                 C  s   t tjjjtjttjjj	
ttjjjdtjjjd}t tjjjdttjjjdtjjjd|jjdtjtjjjtjjjk|tjjj|jjktjjjdktjjjtjjj}| ||S )Nr  lbl_aggr   r  r6   r  )r7   r   pg_enumru  	enumtypidr8   rz  r  r   	enumlabelr   rU   enumsortorderr  r  r  rd  re  rg  r   rH  rI  r  rr   rf  r  r   typtyper$  r  )r   r6   
lbl_agg_sqr(  r   r   r   _enum_query
  sH   zPGDialect._enum_queryc           	      K  sT   | j sg S || |}g }|D ]\}}}}|||||d u r"g n|d q|S )N)r   r6   r  r  )r{  r  r  r  )	r   r  r6   r   r  r  r   r  r  r   r   r   r  5  s   zPGDialect._load_enumsc              
   C  sh  t tjjjtjttjjj	d
dtjtjjjt
dtjjjdktjjjd}t tjjj
dttjjjtjjj
dtjjj 
dtjjj
d	ttjjj	
d
tjjj
d|jj|jjtjjj	tjtjjj	tjjj k!tjtjjj"tjjj	k!|tjjj	|jjktjjj#dk$tjjjtjjj}| %||S )NTcondefsconnamesr   domain_constraintsr   r  r  r;   r  r6   r  )&r7   r   r  ru  contypidr8   rz  r  r7  r   r  r  r   rU   r   r  r  rd  re  r  typbasetype	typtypmod
typnotnull
typdefaultrg  rH  rI  r  r  pg_collationcollnamerr   rf  r  typcollationr  r$  r  )r   r6   r  r(  r   r   r   _domain_queryH  sp   
$zPGDialect._domain_queryc              
   K  s   | | |}g }| D ]S}td|d d}g }|d rEtt|d |d dd d}	|	D ]\}
}|d	d
 }||
|d q2|d |d |d ||d |d ||d d}|| q|S )Nz([^\(]+)r  r   r  r  c                 S  s   | d S )Nr   r   )r  r   r   r   <lambda>  s    z)PGDialect._load_domains.<locals>.<lambda>)r     r  )r   r   r   r6   r  r  r;   r  )r   r6   r  r  r  r;   r  r  )	r  r  r  r  r  r   sortedr)  r  )r   r  r6   r   r  r  r  r  r  sorted_constraintsr   def_r   
domain_recr   r   r   r    s0   
zPGDialect._load_domainsc                 C  s   | d }|dk| _d S )Nz show standard_conforming_stringsri   )r9  rF  rL  )r   r  
std_stringr   r   r   r	    s   z PGDialect._set_backslash_escapes)NNN)r  r@   r  r  )TFr   )r  r=   r  r  )
r  r  r  r  r  r  r  r  r  r  r  r  )r  r  r  r   supports_statement_cachesupports_altermax_identifier_lengthsupports_sane_rowcountr<   
BindTypingRENDER_CASTSbind_typingr{  supports_native_booleansupports_native_uuidr  supports_sequencessequences_optional"preexecute_autoincrement_sequencespostfetch_lastrowiduse_insertmanyvaluesreturns_native_bytesrI   ANY_AUTOINCREMENTUSE_INSERT_FROM_SELECTRENDER_SELECT_COL_CASTS"insertmanyvalues_implicit_sentinelsupports_commentssupports_constraint_commentssupports_default_valuessupports_default_metavaluesupports_empty_insertsupports_multivalues_insertr  default_paramstyler  colspecsr   statement_compilerr  ddl_compilerrE  type_compiler_clsr  r  r  execution_ctx_clsr  	inspectorupdate_returningdelete_returninginsert_returningupdate_returning_multifromdelete_returning_multifromr;   r  connection_characteristicsr   r  r  r6   IndexTableCheckConstraintForeignKeyConstraintUniqueConstraintconstruct_argumentsreflection_optionsrL  r  r(  r  r  r  r  r  r  r  r  r  r4  r8  r:  rA  rC  rE  rG  r?   r  rJ  rS  rW  r   r\  r^  ra  r  rj  r  rn  rp  rt  rv  r  r}  r  r  r  r  r  r  r  r  r  r  r  r<  r  r  r  r  r  r  flexi_cacherJ   	dp_stringdp_string_listdp_plain_objr  r  r(  r*  r)  r0  r;  r9   memoized_propertyr>  r/  rR  rl  rQ  r  r  r  r  r  r  r  r  r  r  r  r  r  r	  r  r   r   rO  r   r    s   	,

	
T











 
!


 S


\&
9

a
  '

.6
*
;#r  )r  
__future__r   collectionsr   	functoolsr   r  typingr   r   r   r   r	   r
   r   r0  r   r   r   _jsonr   r   _rangesextr   r   r   r   named_typesr   r   r   r   r   r   r   typesr   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r5   r6   r7   r8   r9   enginer:   r;   r<   r=   r>   r?   r@   engine.reflectionrA   rB   rC   rD   rE   rF   rG   rH   ro  sql.compilerrI   sql.visitorsrJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   util.typingrX   r<  Ir  r  r  Intervalr  r  JSONPathTyper  Uuidr  r\  rj  rl  rn  rp  rr  rt  r^  r`  rb  rd  rf  rh  r  r  SQLCompilerr   DDLCompilerr  GenericTypeCompilerrE  IdentifierPreparerr  r  r  r  r  	Inspectorr  DefaultExecutionContextr  ConnectionCharacteristicr  r  r  r  r   r   r   r   <module>   s             Hj

	
 !"#$%&'()*+,-./0126   8  z ?	n
7
