
    +hy                    	   d Z ddlmZ ddlZddlZddlmZ ddl	m
Z ddl	mZ ddl	mZ dd	l	mZ dd
l	mZ ddl	mZ ddl	mZ ddl	mZ ddl	mZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlmZ! ddl"m#Z# ddl$m%Z% ddl$m&Z& ddl$m'Z' ddl$m(Z( ddl$m)Z) ddl$m*Z* dd l$m+Z+ dd!l$m,Z, dd"l$m-Z- dd#l$m.Z. dd$l$m/Z/  ej`                  d%ejb                        Z2 ej`                  d&ejb                  ejf                  z        Z4 e5g d'      Z6d(Z7d)Z8d*Z9 G d+ d,e jt                        Z; G d- d.e jx                        Z= G d/ d0e j|                        Z?e?Z@ G d1 d2e j|                        ZAeAZB G d3 d4e j|                        ZCeCZD G d5 d6e j|                        ZEeEZF G d7 d8e j|                        ZG G d9 d:e j|                        ZH G d; d<e j|                        ZI G d= d>e j                        ZJ G d? d@e j                        ZK G dA dBe j                  e j                        ZNeNZO G dC dDe j|                        ZPePZQ G dE dFe j|                        ZeZR G dG dHe j|                        ZS G dI dJe j                  e j                        ZU G dK dLej                        ZWe j                  ej                  e j                  eNe j                  eUe j                  j                  ej                  e j                  ej                  iZ\i dMej                  dNej                  dOej                  dPej                  dQej                  dRej                  dSej                  dTej                  dUej                  dVej                  dWe*dXe%dYe-dZe/d[e'd\e j                  d]e j                  i d^e.d_e+d`e)dae,dbe?dceAddedeePdfePdgeCdheEdieGdjeHdkeIdle=dmeJdneJeJeKeKe(eKe;e&eNeSdo	Zf G dp dqej                        Zh G dr dsej                        Zj G dt duej                        Zl G dv dwej                        Zn G dx dyej                        Zp G dz d{ej                        Zr G d| d}ej                        Zs G d~ dej                        Zu G d dej                        Zw G d dej                        Zx G d dej                        Zzy)a  
.. dialect:: postgresql
    :name: PostgreSQL
    :full_support: 9.6, 10, 11, 12, 13, 14
    :normal_support: 9.6+
    :best_effort: 8+

.. _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'), 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.

To force the usage of RETURNING by default off, specify the flag
``implicit_returning=False`` to :func:`_sa.create_engine`.

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

       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:`_sa.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 (**requires SQLAlchemy 1.4.43 or greater**). 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):
        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:: 1.4.43  Ensured the :meth:`.PoolEvents.reset` 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 referred towards 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. 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`.

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
`PostgreSQL search path
<https://www.postgresql.org/docs/current/static/ddl-schemas.html#DDL-SCHEMAS-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::

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

    test=> SET search_path TO public;
    SET

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

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

Note that **in all cases**, the "default" schema is always reflected as
``None``. The "default" schema on PostgreSQL is that which is returned by the
PostgreSQL ``current_schema()`` function.  On a typical PostgreSQL
installation, this is the name ``public``.  So a table that refers to another
which is in the ``public`` (i.e. default) schema will always have the
``.schema`` attribute set to ``None``.

.. 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)
    {opensql}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)
    {opensql}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

.. versionadded:: 1.1

.. 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)
    {opensql}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)
    {opensql}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)
    {opensql}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)
    {opensql}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)
    {opensql}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)
    {opensql}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)
    {opensql}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)
    {opensql}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)
    {opensql}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)
    {opensql}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)
    {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
    ON CONFLICT DO NOTHING

.. _postgresql_match:

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

SQLAlchemy makes available the PostgreSQL ``@@`` operator via the
:meth:`_expression.ColumnElement.match` method on any textual column expression.

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

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

will emit to the database::

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

Various other PostgreSQL text search functions such as ``to_tsquery()``,
``to_tsvector()``, and ``plainto_tsquery()`` are available by explicitly using
the standard SQLAlchemy :data:`.func` construct.

For example::

    select(func.to_tsvector('fat cats ate rats').match('cat & rat'))

Emits the equivalent of::

    SELECT to_tsvector('fat cats ate rats') @@ 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::

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

.. tip::

    It's important to remember that text searching in PostgreSQL is powerful but complicated,
    and SQLAlchemy users are advised to reference the PostgreSQL documentation
    regarding
    `Full Text Search <https://www.postgresql.org/docs/current/textsearch-controls.html>`_.

    There are important differences between ``to_tsquery`` and
    ``plainto_tsquery``, the most significant of which is that ``to_tsquery``
    expects specially formatted "querytext" that is written to PostgreSQL's own
    specification, while ``plainto_tsquery`` expects unformatted text that is
    transformed into ``to_tsquery`` compatible querytext. This means the input to
    ``.match()`` under PostgreSQL may be incompatible with the input to
    ``.match()`` under another database backend. SQLAlchemy users who support
    multiple backends are advised to carefully implement their usage of
    ``.match()`` to work around these constraints.

Full Text Searches in PostgreSQL are influenced by a combination of: the
PostgreSQL setting of ``default_text_search_config``, the ``regconfig`` used
to build the GIN/GiST indexes, and the ``regconfig`` optionally passed in
during a query.

When performing a Full Text Search against a column that has a GIN or
GiST index that is already pre-computed (which is common on full text
searches) one may need to explicitly pass in a particular PostgreSQL
``regconfig`` value to ensure the query-planner utilizes the index and does
not re-compute the column on demand.

In order to provide for this explicit query planning, or to use different
search strategies, the ``match`` method accepts a ``postgresql_regconfig``
keyword argument::

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

Emits the equivalent of::

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

One can also specifically pass in a `'regconfig'` value to the
``to_tsvector()`` command as the initial argument::

    select(mytable.c.id).where(
            func.to_tsvector('english', mytable.c.title )\
            .match('somestring', postgresql_regconfig='english')
        )

produces a statement equivalent to::

    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})

.. versionadded:: 1.0.6

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')

.. versionadded:: 1.1

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

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

    DROP INDEX CONCURRENTLY test_idx1

.. versionadded:: 1.1 support for CONCURRENTLY on DROP INDEX.  The
   CONCURRENTLY keyword is now only emitted if a high enough version
   of PostgreSQL is detected on the connection (or for a connection-less
   dialect).

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
.

.. versionchanged:: 1.0.0 - :class:`_schema.Table` reflection now includes
   :class:`.UniqueConstraint` objects present in the
   :attr:`_schema.Table.constraints`
   collection; the PostgreSQL backend will no longer include a "mirrored"
   :class:`.Index` construct in :attr:`_schema.Table.indexes`
   if it is detected
   as corresponding to a unique constraint.

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:

* ``TABLESPACE``::

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

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

* ``ON COMMIT``::

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

* ``WITH OIDS``::

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

* ``WITHOUT OIDS``::

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

* ``INHERITS``::

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

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

    .. versionadded:: 1.0.0

* ``PARTITION BY``::

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

    .. versionadded:: 1.2.6

.. 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()``::

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

* ``json_populate_record()``::

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

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

    >>> from sqlalchemy import select, func
    >>> stmt = select(
    ...     func.generate_series(4, 1, -1).
    ...     table_valued("value", with_ordinality="ordinality").
    ...     render_derived()
    ... )
    >>> print(stmt)
    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()``::

    >>> from sqlalchemy import select, func
    >>> stmt = select(func.json_array_elements('["one", "two"]').column_valued("x"))
    >>> print(stmt)
    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::


    >>> from sqlalchemy.dialects.postgresql import array
    >>> from sqlalchemy import select, func
    >>> stmt = select(func.unnest(array([1, 2])).column_valued())
    >>> print(stmt)
    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`::

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

    >>> 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)
    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 it
refers towards 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::


    >>> 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)
    SELECT row_to_json(a) AS row_to_json_1
    FROM a

.. versionadded:: 1.4.0b2


ARRAY Types
-----------

The PostgreSQL dialect supports arrays, both as multidimensional column types
as well as array literals:

* :class:`_postgresql.ARRAY` - ARRAY datatype

* :class:`_postgresql.array` - array literal

* :func:`_postgresql.array_agg` - ARRAY_AGG SQL function

* :class:`_postgresql.aggregate_order_by` - helper for PG's ORDER BY aggregate
  function syntax.

JSON Types
----------

The PostgreSQL dialect supports both JSON and JSONB datatypes, including
psycopg2's native support and support for all of PostgreSQL's special
operators:

* :class:`_postgresql.JSON`

* :class:`_postgresql.JSONB`

HSTORE Type
-----------

The PostgreSQL HSTORE type as well as hstore literals are supported:

* :class:`_postgresql.HSTORE` - HSTORE datatype

* :class:`_postgresql.hstore` - hstore literal

ENUM Types
----------

PostgreSQL has an independently creatable TYPE structure which is used
to implement an enumerated type.   This approach introduces significant
complexity on the SQLAlchemy side in terms of when this type should be
CREATED and DROPPED.   The type object is also an independently reflectable
entity.   The following sections should be consulted:

* :class:`_postgresql.ENUM` - DDL and typing support for ENUM.

* :meth:`.PGInspector.get_enums` - retrieve a listing of current ENUM types

* :meth:`.postgresql.ENUM.create` , :meth:`.postgresql.ENUM.drop` - individual
  CREATE and DROP commands for ENUM.

.. _postgresql_array_of_enum:

Using ENUM with ARRAY
^^^^^^^^^^^^^^^^^^^^^

The combination of ENUM and ARRAY is not directly supported by backend
DBAPIs at this time.   Prior to SQLAlchemy 1.3.17, a special workaround
was needed in order to allow this combination to work, described below.

.. versionchanged:: 1.3.17 The combination of ENUM and ARRAY is now directly
   handled by SQLAlchemy's implementation without any workarounds needed.

.. sourcecode:: python

    from sqlalchemy import TypeDecorator
    from sqlalchemy.dialects.postgresql import ARRAY

    class ArrayOfEnum(TypeDecorator):
        impl = ARRAY

        def bind_expression(self, bindvalue):
            return sa.cast(bindvalue, self)

        def result_processor(self, dialect, coltype):
            super_rp = super(ArrayOfEnum, self).result_processor(
                dialect, coltype)

            def handle_raw_string(value):
                inner = re.match(r"^{(.*)}$", value).group(1)
                return inner.split(",") if inner else []

            def process(value):
                if value is None:
                    return None
                return super_rp(handle_raw_string(value))
            return process

E.g.::

    Table(
        'mydata', metadata,
        Column('id', Integer, primary_key=True),
        Column('data', ArrayOfEnum(ENUM('a', 'b, 'c', name='myenum')))

    )

This type is not included as a built-in type as it would be incompatible
with a DBAPI that suddenly decides to support ARRAY of ENUM directly in
a new version.

.. _postgresql_array_of_json:

Using JSON/JSONB with ARRAY
^^^^^^^^^^^^^^^^^^^^^^^^^^^

Similar to using ENUM, prior to SQLAlchemy 1.3.17, for an ARRAY of JSON/JSONB
we need to render the appropriate CAST.   Current psycopg2 drivers accommodate
the result set correctly without any special steps.

.. versionchanged:: 1.3.17 The combination of JSON/JSONB and ARRAY is now
   directly handled by SQLAlchemy's implementation without any workarounds
   needed.

.. sourcecode:: python

    class CastingArray(ARRAY):
        def bind_expression(self, bindvalue):
            return sa.cast(bindvalue, self)

E.g.::

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


    )defaultdictN)UUID   )array)dml)hstore)json)ranges   )excschema)sql)util)characteristics)default)
reflection)	coercions)compiler)elements)
expression)roles)sqltypes)DDLBase)BIGINT)BOOLEAN)CHAR)DATE)FLOAT)INTEGER)NUMERIC)REAL)SMALLINT)TEXT)VARCHARz ^(?:btree|hash|gist|gin|[\w_]+)$zs\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|GRANT|REVOKE|IMPORT FOREIGN SCHEMA|REFRESH MATERIALIZED VIEW|TRUNCATE))fallanalyseanalyzeandanyr   asasc
asymmetricbothcasecastcheckcollatecolumn
constraintcreatecurrent_catalogcurrent_datecurrent_rolecurrent_timecurrent_timestampcurrent_userr   
deferrabledescdistinctdoelseendexceptfalsefetchforforeignfromgrantgrouphavingin	initially	intersectintoleadinglimit	localtimelocaltimestampnewnotnullofoffoffsetoldononlyororderplacingprimary
references	returningselectsession_usersome	symmetrictablethentotrailingtrueunionuniqueuserusingvariadicwhenwherewindowwithauthorizationbetweenbinarycrosscurrent_schemafreezefullilikeinnerisisnulljoinleftlikenaturalnotnullouteroveroverlapsrightsimilarverbose)i  i  )i  i  i  i  )            i  i  i  c                       e Zd Zd Zy)BYTEAN__name__
__module____qualname____visit_name__     V/var/www/html/venv/lib/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.pyr   r   u  s    Nr   r   c                       e Zd Zd Zy)DOUBLE_PRECISIONNr   r   r   r   r   r   y      'Nr   r   c                       e Zd Zd Zy)INETNr   r   r   r   r   r   }      Nr   r   c                       e Zd Zd Zy)CIDRNr   r   r   r   r   r     r   r   r   c                       e Zd Zd Zy)MACADDRNr   r   r   r   r   r     s    Nr   r   c                       e Zd Zd Zy)MACADDR8Nr   r   r   r   r   r     s    Nr   r   c                       e Zd ZdZd Zy)MONEYa  Provide the PostgreSQL MONEY type.

    Depending on driver, result rows using this type may return a
    string value which includes currency symbols.

    For this reason, it may be preferable to provide conversion to a
    numerically-based currency datatype using :class:`_types.TypeDecorator`::

        import re
        import decimal
        from sqlalchemy import TypeDecorator

        class NumericMoney(TypeDecorator):
            impl = MONEY

            def process_result_value(self, value: Any, dialect: Any) -> None:
                if value is not None:
                    # adjust this for the currency and numeric
                    m = re.match(r"\$([\d.]+)", value)
                    if m:
                        value = decimal.Decimal(m.group(1))
                return value

    Alternatively, the conversion may be applied as a CAST using
    the :meth:`_types.TypeDecorator.column_expression` method as follows::

        import decimal
        from sqlalchemy import cast
        from sqlalchemy import TypeDecorator

        class NumericMoney(TypeDecorator):
            impl = MONEY

            def column_expression(self, column: Any):
                return cast(column, Numeric())

    .. versionadded:: 1.2

    Nr   r   r   __doc__r   r   r   r   r   r     s    &P Nr   r   c                       e Zd ZdZd Zy)OIDzCProvide the PostgreSQL OID type.

    .. versionadded:: 0.9.5

    Nr   r   r   r   r   r     s     Nr   r   c                       e Zd ZdZd Zy)REGCLASSzHProvide the PostgreSQL REGCLASS type.

    .. versionadded:: 1.2.7

    Nr   r   r   r   r   r     s      Nr   r   c                   (     e Zd ZdZd Zd fd	Z xZS )	TIMESTAMPz&Provide the PostgreSQL TIMESTAMP type.c                 <    t         t        |   |       || _        y)zConstruct a TIMESTAMP.

        :param timezone: boolean value if timezone present, default False
        :param precision: optional integer precision value

         .. versionadded:: 1.4

        timezoneN)superr   __init__	precisionselfr   r   	__class__s      r   r   zTIMESTAMP.__init__  s     	i'':"r   FNr   r   r   r   r   r   __classcell__r   s   @r   r   r     s    0 N
# 
#r   r   c                   (     e Zd ZdZd Zd fd	Z xZS )TIMEzPostgreSQL TIME type.c                 <    t         t        |   |       || _        y)zConstruct a TIME.

        :param timezone: boolean value if timezone present, default False
        :param precision: optional integer precision value

         .. versionadded:: 1.4

        r   N)r   r   r   r   r   s      r   r   zTIME.__init__  s     	dD"H"5"r   r   r   r   s   @r   r   r     s    N
# 
#r   r   c                   ^    e Zd ZdZd ZdZd
dZed        Ze	d        Z
ddZe	d        Zd	 Zy)INTERVALzPostgreSQL INTERVAL type.TNc                      || _         || _        y)a   Construct an INTERVAL.

        :param precision: optional integer precision value
        :param fields: string fields specifier.  allows storage of fields
         to be limited, such as ``"YEAR"``, ``"MONTH"``, ``"DAY TO HOUR"``,
         etc.

         .. versionadded:: 1.2

        N)r   fields)r   r   r   s      r   r   zINTERVAL.__init__	  s     #r   c                 .    t        |j                        S )Nr   )r   second_precision)clsintervalkws      r   adapt_emulated_to_nativez!INTERVAL.adapt_emulated_to_native  s    (";";<<r   c                 "    t         j                  S N)r   Intervalr   s    r   _type_affinityzINTERVAL._type_affinity  s       r   c                 D    t        j                  d| j                        S )NT)nativer   )r   r   r   )r   allow_nulltypes     r   
as_genericzINTERVAL.as_generic  s      t~~NNr   c                 "    t         j                  S r   )dt	timedeltar   s    r   python_typezINTERVAL.python_type"  s    ||r   c                     | S r   r   )r   opvalues      r   coerce_compared_valuezINTERVAL.coerce_compared_value&  s    r   )NNF)r   r   r   r   r   r   r   classmethodr   propertyr   r   r   r   r   r   r   r   r     s[    #NF = = ! !O  r   r   c                       e Zd Zd ZddZy)BITNc                 J    |s|xs d| _         || _        y || _         || _        y )Nr   )lengthvarying)r   r   r   s      r   r   zBIT.__init__0  s)     +ADK  !DKr   NFr   r   r   r   r   r   r   r   r   r   -  s    Nr   r   c                   P     e Zd ZdZd ZddZ fdZd Zd Zd Z	e
d        Z xZS )	r   az  PostgreSQL UUID type.

    Represents the UUID column type, interpreting
    data either as natively returned by the DBAPI
    or as Python uuid objects.

    The UUID type is currently known to work within the prominent DBAPI
    drivers supported by SQLAlchemy including psycopg2, pg8000 and
    asyncpg. Support for other DBAPI drivers may be incomplete or non-present.

    c                     || _         y)zConstruct a UUID type.


        :param as_uuid=False: if True, values will be interpreted
         as Python uuid objects, converting to/from string via the
         DBAPI.

        Nas_uuid)r   r   s     r   r   zUUID.__init__M  s     r   c                 d    t        |t        j                        r| S t        t        |   ||      S )z@See :meth:`.TypeEngine.coerce_compared_value` for a description.)
isinstancer   string_typesr   r   r   )r   r   r   r   s      r   r   zUUID.coerce_compared_valueX  s.     eT../Kt:2uEEr   c                 &    | j                   rd }|S y )Nc                 4    | t        j                  |       } | S r   )r   	text_typer   s    r   processz$UUID.bind_processor.<locals>.processc  s    $ NN51Er   r   r   dialectr   s      r   bind_processorzUUID.bind_processor`      <<
 Nr   c                 &    | j                   rd }|S y )Nc                      | t        |       } | S r   )_python_UUIDr   s    r   r   z&UUID.result_processor.<locals>.processo  s    $(/Er   r   )r   r   coltyper   s       r   result_processorzUUID.result_processorl  r   r   c                 .    | j                   rd }|S d }|S )Nc                     | d| z  } | S )Nz
'%s'::UUIDr   r   s    r   r   z'UUID.literal_processor.<locals>.process{  s    $(50Er   c                     | d| z  } | S )N'%s'r   r   s    r   r   z'UUID.literal_processor.<locals>.process  s    $"UNEr   r   r   s      r   literal_processorzUUID.literal_processorx  s!    <<
 N
 Nr   c                 2    | j                   rt        S t        S r   )r   r   strr   s    r   r   zUUID.python_type  s    #|||44r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r   r   r   =  s=    
 N	F

$ 5 5r   r   c                       e Zd ZdZd Zy)TSVECTORa  The :class:`_postgresql.TSVECTOR` type implements the PostgreSQL
    text search type TSVECTOR.

    It can be used to do full text queries on natural language
    documents.

    .. versionadded:: 0.9.0

    .. seealso::

        :ref:`postgresql_match`

    Nr   r   r   r   r  r    s      Nr   r  c                        e Zd ZdZdZ fdZed        ZddZddZ	 G d de
      Z G d	 d
e
      Zd ZddZddZddZddZ xZS )ENUMa  PostgreSQL ENUM type.

    This is a subclass of :class:`_types.Enum` which includes
    support for PG's ``CREATE TYPE`` and ``DROP TYPE``.

    When the builtin type :class:`_types.Enum` is used and the
    :paramref:`.Enum.native_enum` flag is left at its default of
    True, the PostgreSQL backend will use a :class:`_postgresql.ENUM`
    type as the implementation, so the special create/drop rules
    will be used.

    The create/drop behavior of ENUM is necessarily intricate, due to the
    awkward relationship the ENUM type has in relationship to the
    parent table, in that it may be "owned" by just a single table, or
    may be shared among many tables.

    When using :class:`_types.Enum` or :class:`_postgresql.ENUM`
    in an "inline" fashion, the ``CREATE TYPE`` and ``DROP TYPE`` is emitted
    corresponding to when the :meth:`_schema.Table.create` and
    :meth:`_schema.Table.drop`
    methods are called::

        table = Table('sometable', metadata,
            Column('some_enum', ENUM('a', 'b', 'c', name='myenum'))
        )

        table.create(engine)  # will emit CREATE ENUM and CREATE TABLE
        table.drop(engine)  # will emit DROP TABLE and DROP ENUM

    To use a common enumerated type between multiple tables, the best
    practice is to declare the :class:`_types.Enum` or
    :class:`_postgresql.ENUM` independently, and associate it with the
    :class:`_schema.MetaData` object itself::

        my_enum = ENUM('a', 'b', 'c', name='myenum', metadata=metadata)

        t1 = Table('sometable_one', metadata,
            Column('some_enum', myenum)
        )

        t2 = Table('sometable_two', metadata,
            Column('some_enum', myenum)
        )

    When this pattern is used, care must still be taken at the level
    of individual table creates.  Emitting CREATE TABLE without also
    specifying ``checkfirst=True`` will still cause issues::

        t1.create(engine) # will fail: no such type 'myenum'

    If we specify ``checkfirst=True``, the individual table-level create
    operation will check for the ``ENUM`` and create if not exists::

        # will check if enum exists, and emit CREATE TYPE if not
        t1.create(engine, checkfirst=True)

    When using a metadata-level ENUM type, the type will always be created
    and dropped if either the metadata-wide create/drop is called::

        metadata.create_all(engine)  # will emit CREATE TYPE
        metadata.drop_all(engine)  # will emit DROP TYPE

    The type can also be created and dropped directly::

        my_enum.create(engine)
        my_enum.drop(engine)

    .. versionchanged:: 1.0.0 The PostgreSQL :class:`_postgresql.ENUM` type
       now behaves more strictly with regards to CREATE/DROP.  A metadata-level
       ENUM type will only be created and dropped at the metadata level,
       not the table level, with the exception of
       ``table.create(checkfirst=True)``.
       The ``table.drop()`` call will now emit a DROP TYPE for a table-level
       enumerated type.

    Tc                     |j                  dd      }|du rt        j                  d       |j                  dd      | _        t	        t
        |   |i | y)a  Construct an :class:`_postgresql.ENUM`.

        Arguments are the same as that of
        :class:`_types.Enum`, but also including
        the following parameters.

        :param create_type: Defaults to True.
         Indicates that ``CREATE TYPE`` should be
         emitted, after optionally checking for the
         presence of the type, when the parent
         table is being created; and additionally
         that ``DROP TYPE`` is called when the table
         is dropped.    When ``False``, no check
         will be performed and no ``CREATE TYPE``
         or ``DROP TYPE`` is emitted, unless
         :meth:`~.postgresql.ENUM.create`
         or :meth:`~.postgresql.ENUM.drop`
         are called directly.
         Setting to ``False`` is helpful
         when invoking a creation scheme to a SQL file
         without access to the actual database -
         the :meth:`~.postgresql.ENUM.create` and
         :meth:`~.postgresql.ENUM.drop` methods can
         be used to emit SQL to a target bind.

        native_enumNFzthe native_enum flag does not apply to the sqlalchemy.dialects.postgresql.ENUM datatype; this type always refers to ENUM.   Use sqlalchemy.types.Enum for non-native enum.create_typeT)popr   warnr  r   r  r   )r   enumsr   r  r   s       r   r   zENUM.__init__  sW    6 ff]D1%II# 66-6dD"E0R0r   c                    |j                  d|j                         |j                  d|j                         |j                  d|j                         |j                  d|j                         |j                  d|j
                         |j                  dd       |j                  d|j                         |j                  d	|j                          | d
i |S )zbProduce a PostgreSQL native :class:`_postgresql.ENUM` from plain
        :class:`.Enum`.

        validate_stringsnamer   inherit_schemametadata_create_eventsFvalues_callableomit_aliasesr   )
setdefaultr  r  r   r  r  r  _omit_aliases)r   implr   s      r   r   zENUM.adapt_emulated_to_native  s     	($*?*?@
fdii(
h,
&(;(;<
j$--0
&.
')=)=>
nd&8&89yRyr   c                 n    |j                   j                  sy|j                  | j                  | |       y)a  Emit ``CREATE TYPE`` for this
        :class:`_postgresql.ENUM`.

        If the underlying dialect does not support
        PostgreSQL CREATE TYPE, no action is taken.

        :param bind: a connectable :class:`_engine.Engine`,
         :class:`_engine.Connection`, or similar object to emit
         SQL.
        :param checkfirst: if ``True``, a query against
         the PG catalog will be first performed to see
         if the type does not exist already before
         creating.

        N
checkfirst)r   supports_native_enum_run_ddl_visitorEnumGeneratorr   bindr  s      r   r5   zENUM.create,  s/      ||00d00$:Nr   c                 n    |j                   j                  sy|j                  | j                  | |       y)a  Emit ``DROP TYPE`` for this
        :class:`_postgresql.ENUM`.

        If the underlying dialect does not support
        PostgreSQL DROP TYPE, no action is taken.

        :param bind: a connectable :class:`_engine.Engine`,
         :class:`_engine.Connection`, or similar object to emit
         SQL.
        :param checkfirst: if ``True``, a query against
         the PG catalog will be first performed to see
         if the type actually exists before dropping.

        Nr  )r   r  r  EnumDropperr  s      r   dropz	ENUM.dropA  s/     ||00d..Lr   c                   ,     e Zd Zd fd	Zd Zd Z xZS )ENUM.EnumGeneratorc                 P    t        t        j                  |   |fi | || _        y r   )r   r  r  r   r  r   r   
connectionr  kwargsr   s        r   r   zENUM.EnumGenerator.__init__V  s$    $$$d4ZJ6J(DOr   c                     | j                   sy| j                  j                  |      }| j                  j                  j	                  | j                  |j
                  |       S NTr   r  r$  schema_for_objectr   has_typer  r   enumeffective_schemas      r   _can_create_enumz#ENUM.EnumGenerator._can_create_enumZ  sX    ??#@@F..773C 8   r   c                 p    | j                  |      sy | j                  j                  t        |             y r   )r.  r$  executeCreateEnumTyper   r,  s     r   
visit_enumzENUM.EnumGenerator.visit_enumd  s*    ((.OO##N4$89r   r   )r   r   r   r   r.  r3  r   r   s   @r   r  r!  U  s    	)		:r   r  c                   ,     e Zd Zd fd	Zd Zd Z xZS )ENUM.EnumDropperc                 P    t        t        j                  |   |fi | || _        y r   )r   r  r  r   r  r#  s        r   r   zENUM.EnumDropper.__init__k  s$    $""D2:HH(DOr   c                     | j                   sy| j                  j                  |      }| j                  j                  j	                  | j                  |j
                  |      S r'  r(  r+  s      r   _can_drop_enumzENUM.EnumDropper._can_drop_enumo  sS    ??#@@F??**333C 4  r   c                 p    | j                  |      sy | j                  j                  t        |             y r   )r8  r$  r0  DropEnumTyper2  s     r   r3  zENUM.EnumDropper.visit_enumy  s*    &&t,OO##L$67r   r   )r   r   r   r   r8  r3  r   r   s   @r   r  r5  j  s    	)		8r   r  c                 $   | j                   syd|v r|d   }d|j                  v r|j                  d   }nt               x}|j                  d<   | j                  | j                  f|v }|j                  | j                  | j                  f       |S y)a  Look in the 'ddl runner' for 'memos', then
        note our name in that collection.

        This to ensure a particular named enum is operated
        upon only once within any kind of create/drop
        sequence without relying upon "checkfirst".

        T_ddl_runner	_pg_enumsF)r  memosetr   r  add)r   r  r   
ddl_runnerpg_enumspresents         r   _check_for_name_in_memoszENUM._check_for_name_in_memos  s     BM*Jjoo-%??;7:=%?:??;7{{DII.(:GLL$++tyy12Nr   c                     |s| j                   s:|j                  dd      s'| j                  ||      s| j                  ||       y y y y N_is_metadata_operationFr  r  )r  getrD  r5   r   targetr  r  r   s        r   _on_table_createzENUM._on_table_create  sL    MM7?//
B?KKTjK9 @ @ "r   c                     | j                   s:|j                  dd      s'| j                  ||      s| j                  ||       y y y y rF  )r  rI  rD  r  rJ  s        r   _on_table_dropzENUM._on_table_drop  sH    FF3U;11*bAII4JI7 B < r   c                 P    | j                  ||      s| j                  ||       y y NrH  )rD  r5   rJ  s        r   _on_metadata_createzENUM._on_metadata_create  s'    ,,Z<KKTjK9 =r   c                 P    | j                  ||      s| j                  ||       y y rP  )rD  r  rJ  s        r   _on_metadata_dropzENUM._on_metadata_drop  s'    ,,Z<II4JI7 =r   )NTr   )r   r   r   r   r  r   r   r   r5   r  r   r  r  rD  rL  rN  rQ  rS  r   r   s   @r   r  r    sh    KZ K$1L  O*M(: :*8g 8*.:8:8r   r  c                       e Zd ZdZd Zy)
_ColonCast
colon_castc                 T    || _         || _        t        j                  |      | _        y r   )typeclauser   
TypeClause
typeclause)r   r   type_s      r   r   z_ColonCast.__init__  s"    	 "--e4r   Nr   r   r   r   rU  rU    s    !N5r   rU  _arrayr   r	   jsonb	int4range	int8rangenumrange	daterangetsrange	tstzrangeintegerbigintsmallintzcharacter varying	characterz"char"r  textnumericfloatrealinetcidr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booleanr   tsvectorc                        e Zd Zd Zd Zd Z	 ddZ	 ddZd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Z fdZd Zd Zd Zd Zd Zd Zd Zd Zej8                  d        Zd Zd Zd Z d Z!d Z" xZ#S ) 
PGCompilerc                 |     |j                   j                  | fi |d |j                  j                  | fi |S )Nz::)rY  _compiler_dispatchr[  r   elementr   s      r   visit_colon_castzPGCompiler.visit_colon_cast  s@    -GNN--d9b91G11$="=
 	
r   c                 .    d | j                   |fi |z  S )Nz	ARRAY[%s])visit_clauselistr  s      r   visit_arrayzPGCompiler.visit_array  s     2T227AbAAAr   c                 |     | j                   |j                  fi |d | j                   |j                  fi |S )N:)r   startstopr  s      r   visit_slicezPGCompiler.visit_slice  s:    DLL-"-DLL,,
 	
r   c                     |s\|j                   j                  t        j                  ur6d|d<    | j                  t        j                  ||j                         fi |S d|d<    | j                  ||sdndfi |S )NT_cast_appliedeager_groupingz -> z ->> rX  r   r   JSONr   r   r0   _generate_generic_binaryr   rv   operatorr  r   s        r   visit_json_getitem_op_binaryz'PGCompiler.visit_json_getitem_op_binary	  s}     **(--?"&B4<< =DDD#,t,,-FW
@B
 	
r   c                     |s\|j                   j                  t        j                  ur6d|d<    | j                  t        j                  ||j                         fi |S d|d<    | j                  ||sdndfi |S )NTr  r  z #> z #>> r  r  s        r   !visit_json_path_getitem_op_binaryz,PGCompiler.visit_json_path_getitem_op_binary	  s}     **(--?"&B4<< =DDD#,t,,-FW
@B
 	
r   c                 ~     | j                   |j                  fi |d | j                   |j                  fi |dS )N[])r   r   r   r   rv   r  r   s       r   visit_getitem_binaryzPGCompiler.visit_getitem_binary!	  s:    DLL++DLL,,
 	
r   c                 |     | j                   |j                  fi |d | j                   |j                  fi |S )Nz
 ORDER BY )r   rK  order_byr  s      r   visit_aggregate_order_byz#PGCompiler.visit_aggregate_order_by'	  s<    DLL.2.DLL))0R0
 	
r   c           	      z   d|j                   v rp| j                  |j                   d   t        j                        }|rA | j                  |j
                  fi |d|d | j                  |j                  fi |dS  | j                  |j
                  fi |d | j                  |j                  fi |dS )Npostgresql_regconfigz @@ to_tsquery(, ))	modifiersrender_literal_valuer   
STRINGTYPEr   r   r   )r   rv   r  r   	regconfigs        r   visit_match_op_binaryz PGCompiler.visit_match_op_binary-	  s    !V%5%5511  !78(:M:MI  DLL33 DLL44  DLL++DLL,,
 	
r   c                    |j                   j                  dd       } | j                  |j                  fi |d | j                  |j                  fi ||r%d| j                  |t        j                        z   z   S dz   S )Nescapez ILIKE  ESCAPE  r  rI  r   r   r   r  r   r  r   rv   r  r   r  s        r   visit_ilike_op_binaryz PGCompiler.visit_ilike_op_binary=	  s    !!%%h5 DLL++DLL,,

  2268;N;NOO	
 	
 
 	
r   c                    |j                   j                  dd       } | j                  |j                  fi |d | j                  |j                  fi ||r%d| j                  |t        j                        z   z   S dz   S )Nr  z NOT ILIKE r  r  r  r  s        r   visit_not_ilike_op_binaryz$PGCompiler.visit_not_ilike_op_binaryI	  s    !!%%h5DLL++DLL,,

  2268;N;NOO	
 	
 
 	
r   c                 N   |j                   d   }| | j                  |d|z  fi |S |dk(  r | j                  |d|z  fi |S  | j                  |j                  fi |d|d| j	                  |t
        j                        d | j                  |j                  fi |dS )	Nflagsz %s iz %s*  z CONCAT('(?', z, ')', r  )r  r  r   r   r  r   r  r   )r   base_oprv   r  r   r  s         r   _regexp_matchzPGCompiler._regexp_matchT	  s      )=0400(,.  C<0400')-/  DLL++%%eX-@-@ADLL,,	
 	
r   c                 *    | j                  d|||      S )N~r  r  s       r   visit_regexp_match_op_binaryz'PGCompiler.visit_regexp_match_op_binarye	  s    !!#vx<<r   c                 *    | j                  d|||      S )Nz!~r  r  s       r    visit_not_regexp_match_op_binaryz+PGCompiler.visit_not_regexp_match_op_binaryh	  s    !!$"==r   c           	           | j                   |j                  fi |} | j                   |j                  fi |}|j                  d   }|	d|d|dS d|d|d| j	                  |t
        j                        dS )Nr  zREGEXP_REPLACE(r  r  )r   r   r   r  r  r   r  )r   rv   r  r   stringpattern_replacer  s          r   visit_regexp_replace_op_binaryz)PGCompiler.visit_regexp_replace_op_binaryk	  s    fkk0R0&$,,v||:r:  )=   ))%1D1DE r   c                 Z     ddj                   fd|xs t               gD              dS )NzSELECT r  c              3      K   | ]B  }d j                   j                  j                  |j                  r
t	               n|      z   D yw)zCAST(NULL AS %s)N)r   type_compilerr   _isnullr    ).0r\  r   s     r   	<genexpr>z2PGCompiler.visit_empty_set_expr.<locals>.<genexpr>	  sE      
 	 #,,,,44!&GIEs   AAz WHERE 1!=1)r   r    )r   element_typess   ` r   visit_empty_set_exprzPGCompiler.visit_empty_set_expr{	  s3    
 II 
 +9wyk 
 	
r   c                     t         t        |   ||      }| j                  j                  r|j                  dd      }|S )N\z\\)r   r  r  r   _backslash_escapesreplace)r   r   r\  r   s      r   r  zPGCompiler.render_literal_value	  s8    j$<UEJ<<**MM$/Er   c                 >    d| j                   j                  |      z  S )Nznextval('%s'))preparerformat_sequence)r   seqr   s      r   visit_sequencezPGCompiler.visit_sequence	  s    !>!>s!CCCr   c                     d}|j                   #|d | j                  |j                   fi |z   z  }|j                  4|j                   |dz  }|d | j                  |j                  fi |z   z  }|S )Nr  z	 
 LIMIT z
 LIMIT ALLz OFFSET )_limit_clauser   _offset_clauser   rb   r   ri  s       r   limit_clausezPGCompiler.limit_clause	  s    +L<4<<0D0D#K#KKKD  ,##+&Jf.C.C!Jr!JJJDr   c                 b    |j                         dk7  rt        j                  d|z        d|z   S )NONLYzUnrecognized hint: %rzONLY )upperr   CompileError)r   sqltextrf   hintiscruds        r   format_from_hint_textz PGCompiler.format_from_hint_text	  s2    ::<6!""#:T#ABB  r   c                     |j                   s|j                  rM|j                  r@ddj                  |j                  D cg c]  } | j                  |fi | c}      z   dz   S yyc c}w )NzDISTINCT ON (r  z) z	DISTINCT r  )	_distinct_distinct_onr   r   )r   rb   r   cols       r   get_select_precolumnsz PGCompiler.get_select_precolumns	  s|     v22""#ii (.':': # )DLL33 	 #s   A'
c                 $    |j                   j                  r|j                   j                  rd}nd}n|j                   j                  rd}nd}|j                   j                  rtt	        j
                         }|j                   j                  D ]&  }|j                  t        j                  |             ( |ddj                   fd|D              z   z  }|j                   j                  r|dz  }|j                   j                  r|d	z  }|S )
Nz FOR KEY SHAREz
 FOR SHAREz FOR NO KEY UPDATEz FOR UPDATEz OF r  c              3   J   K   | ]  } j                   |fd dd  yw)TF)ashint
use_schemaN)r   )r  rf   r   r   s     r   r  z/PGCompiler.for_update_clause.<locals>.<genexpr>	  s0      & UH4EHRH&s    #z NOWAITz SKIP LOCKED)_for_update_argread	key_sharerV   r   
OrderedSetupdatesql_utilsurface_selectables_onlyr   nowaitskip_locked)r   rb   r   tmptablescs   ` `   r   for_update_clausezPGCompiler.for_update_clause	  s    !!&&%%//&"##--&CC!!$$__&F++.. Dh??BCD 6DII &#&   C
 !!((9C!!-->!C
r   c                     t        j                  |      D cg c]   }| j                  |||j                        " }}ddj	                  |      z   S c c}w )N)fallback_label_namez
RETURNING r  )r   _select_iterables_label_returning_column_non_anon_labelr   )r   stmtreturning_colsr  columnss        r   returning_clausezPGCompiler.returning_clause	  sf      11.A	
  ((aQ->-> ) 
 
 dii000
s   %Ac                 l    | j                   |j                  j                  d   fi |} | j                   |j                  j                  d   fi |}t        |j                  j                        dkD  r6 | j                   |j                  j                  d   fi |}d|d|d|dS d|d|dS )Nr   r      z
SUBSTRING(z FROM z FOR r  )r   clauseslen)r   funcr   sr  r   s         r   visit_substring_funczPGCompiler.visit_substring_func	  s    DLL--a07B7T\\11!4;;t||##$q(!T\\$,,"6"6q"9@R@F56vFF ) /077r   c                 B    |j                   *d j                  j                  |j                         z  }|S |j                  Yddj	                   fd|j                  D              z  }|j
                  $|d j                  |j
                  dd      z  z  }|S d}|S )	NzON CONSTRAINT %s(%s)r  c              3      K   | ]M  }t        |t        j                        rj                  j	                  |      nj                  |d d        O yw)Finclude_tabler  N)r   r   r   r  quoter   )r  r  r   s     r   r  z1PGCompiler._on_conflict_target.<locals>.<genexpr>	  sT      -  "!T%6%67 MM''*auOP-s   AA	 WHERE %sFr  r  )constraint_targetr  #truncate_and_render_constraint_nameinferred_target_elementsr   inferred_target_whereclauser   )r   rY  r   target_texts   `   r   _on_conflict_targetzPGCompiler._on_conflict_target	  s    ##/ #--CC,, 0 % ,,8 499 -  88- $ K 11={T\\66"'$ .: .     Kr   c                     | j                   d uxrH | j                  j                  d u xs. t        | j                  j                  t        j
                        S r   )insert_single_values_expr	statement_post_values_clauser   r   OnConflictDoNothingr   s    r   &_is_safe_for_fast_insert_values_helperz1PGCompiler._is_safe_for_fast_insert_values_helper

  sP     --T9 
NN..$6 22C4K4K	
r   c                 8     | j                   |fi |}|rd|z  S y)NzON CONFLICT %s DO NOTHINGzON CONFLICT DO NOTHING)r  )r   on_conflictr   r  s       r   visit_on_conflict_do_nothingz'PGCompiler.visit_on_conflict_do_nothing
  s*    .d..{AbA.<<+r   c           	         |} | j                   |fi |}g }t        |j                        }| j                  d   d   }|j                  j
                  }|D ]!  }	|	j                  }
|
|v r|j                  |
      }n|	|v r|j                  |	      }n=t        j                  |      r#t        j                  d ||	j                        }nQt        |t        j                        r7|j                  j                  r!|j                         }|	j                  |_        | j!                  |j#                         d      }| j$                  j'                  |	j(                        }|j+                  |d|       $ |rt-        j.                  d| j0                  j                  j(                  dd	j3                  d
 |D                     |j5                         D ]  \  }}t        |t,        j6                        r| j$                  j'                  |      n| j!                  |d      }| j!                  t        j8                  t:        j<                  |      d      }|j+                  |d|        d	j3                  |      }|j>                  $|d| j!                  |j>                  dd      z  z  }d|d|S )N
selectabler\  F)r  z = z?Additional column names not matching any column keys in table 'z': r  c              3   &   K   | ]	  }d |z    ywr   Nr   )r  r  s     r   r  z9PGCompiler.visit_on_conflict_do_update.<locals>.<genexpr>R
  s     BavzB   r  Tr  zON CONFLICT z DO UPDATE SET ) r  dictupdate_values_to_setstackrf   r  keyr  r   _is_literalr   BindParameterrX  r   r  _cloner   
self_groupr  r  r  appendr   r  current_executabler   itemsr   expectr   ExpressionElementRoleupdate_whereclause)r   r  r   rY  r  action_set_opsset_parametersinsert_statementcolsr  col_keyr   
value_textkey_textkvaction_texts                    r   visit_on_conflict_do_updatez&PGCompiler.visit_on_conflict_do_update%
  s}   .d..{AbAf99:  ::b>,7%%'' 	FAeeG.(&**73n$&**1-$$U+ ..tU!&&I uh&<&<=

**!LLNE!"EJe&6&6&8UKJ}}**1662H!!x"DE/	F4 II ++1166YYB>BB	 ',,. 
J1 "!T%6%67 MM''*aE: 
 "\\$$U%@%@!D$ * 
 %%8Z&HI
J ii/$$0;))% *6 *  K 5@MMr   c                 P     dd<   ddj                   fd|D              z   S )NTasfromzFROM r  c              3   H   K   | ]  } |j                   fd i  yw	fromhintsNr  r  t
from_hintsr   r   s     r   r  z0PGCompiler.update_from_clause.<locals>.<genexpr>m
  s0      #
 !A  BBrB#
   "r   )r   update_stmt
from_tableextra_fromsrH  r   s   `   ``r   update_from_clausezPGCompiler.update_from_clausei
  s3     8 #
 #
 
 
 	
r   c                 P     dd<   ddj                   fd|D              z   S )z9Render the DELETE .. USING clause specific to PostgreSQL.TrA  zUSING r  c              3   H   K   | ]  } |j                   fd i  ywrC  rE  rF  s     r   r  z6PGCompiler.delete_extra_from_clause.<locals>.<genexpr>w
  s0      $
 !A  BBrB$
rI  rJ  )r   delete_stmtrL  rM  rH  r   s   `   ``r   delete_extra_from_clausez#PGCompiler.delete_extra_from_clauser
  s3     8$)) $
 $
 
 
 	
r   c                    d}|j                   #|d | j                  |j                   fi |z  z  }|j                  K|d | j                  |j                  fi |d|j                  d   rdndd|j                  d   rd	nd
z  }|S )Nr  z
 OFFSET (%s) ROWSz
 FETCH FIRST (r  percentz PERCENTz ROWS 	with_tiesz	WITH TIESr  )r  r   _fetch_clause_fetch_clause_optionsr  s       r   fetch_clausezPGCompiler.fetch_clause|
  s       ,)LDLL%%-)+-  D +V118R8$::9E
2M//<  D r   r   )$r   r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r	  r  r   memoized_propertyr  r  r?  rN  rR  rX  r   r   s   @r   r  r    s    
B
 /4
" /4



 

	

"=> 
D!
(<	18 D 

 
",BNH

r   r  c                   n     e Zd Zd Zd Z fdZ fdZd Zd Zd Z	d Z
d	 Zd
 Zd Zd Z fdZ xZS )PGDDLCompilerc                    | j                   j                  |      }|j                  j                  | j                        }t        |t        j                        r|j                  }|j                  d uxr | j                  j                  }|j                  r||j                  j                  u r| j                  j                  st        |t        j                        s|s|j                   :t        |j                   t"        j$                        r\|j                   j&                  rFt        |t        j(                        r|dz  }nt        |t        j                        r|dz  }nc|dz  }n]|d| j                  j*                  j-                  |j                  || j                         z   z  }| j/                  |      }||d|z   z  }|j0                  !|d| j-                  |j0                        z   z  }|r!|d| j-                  |j                        z   z  }|j2                  s	|s|dz  }|S |j2                  r|r|dz  }|S )	Nz
 BIGSERIALz SMALLSERIALz SERIALr  )type_expressionidentifier_preparerz	 DEFAULT z	 NOT NULLz NULL)r  format_columnrX  dialect_implr   r   r   TypeDecoratorr  identitysupports_identity_columnsprimary_keyrf   _autoincrement_columnsupports_smallserialSmallIntegerr   r   Sequenceoptional
BigIntegerr  r   get_column_default_stringcomputednullable)r   r3   r%  colspec	impl_typehas_identityr   s          r   get_column_specificationz&PGDDLCompiler.get_column_specification
  s   ----f5KK,,T\\:	i!7!78!I OO4' 766 	 &,,<<<11!)X-B-BC &v~~v?// )X%8%89<'Ix'<'<=>)9$sT\\77?? &$(MM @   G
 44V<G";00??&sT\\&//:::GsT\\&//:::G|{"G  __wGr   c                 2    |j                   d   d   }|rdS dS )N
postgresql	not_validz
 NOT VALIDr  )dialect_options)r   r4   rt  s      r   _define_constraint_validityz)PGDDLCompiler._define_constraint_validity
  s$    ..|<[I	(|0b0r   c                    |j                   rt        |j                        d   j                  }t	        |t
        j                        rOt	        |j                  t
        j                        r+|j                  j                  st        j                  d      t        t        | ;  |      }|| j                  |      z  }|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listr  rX  r   r   ARRAY	item_typeEnumr  r   r  r   r[  visit_check_constraintrv  )r   r4   typri  r   s       r   r}  z$PGDDLCompiler.visit_check_constraint
  s    !!z))*1-22C3/s}}hmm<11&&E  ]D@L00<<r   c                 V    t         t        |   |      }|| j                  |      z  }|S r   )r   r[  visit_foreign_key_constraintrv  )r   r4   ri  r   s      r   r  z*PGDDLCompiler.visit_foreign_key_constraint
  s3    ]DF
 	00<<r   c                 R    d| j                   j                  |j                        z  S )NzCOMMENT ON TABLE %s IS NULL)r  format_tabler  )r   r  s     r   visit_drop_table_commentz&PGDDLCompiler.visit_drop_table_comment
  s'    ,t}}/I/ILL0
 
 	
r   c                      |j                   }d j                  j                  |      ddj                   fd|j                  D              dS )NzCREATE TYPE z
 AS ENUM (r  c              3   ~   K   | ]4  }j                   j                  t        j                  |      d        6 yw)Tliteral_bindsN)sql_compilerr   r   literal)r  er   s     r   r  z7PGDDLCompiler.visit_create_enum_type.<locals>.<genexpr>
  s7       !!))#++a.)Ms   :=r  )r  r  format_typer   r	  )r   r5   r\  s   `  r   visit_create_enum_typez$PGDDLCompiler.visit_create_enum_type
  sG     MM%%e,II  
 	
r   c                 V    |j                   }d| j                  j                  |      z  S )NzDROP TYPE %s)r  r  r  )r   r  r\  s      r   visit_drop_enum_typez"PGDDLCompiler.visit_drop_enum_type
  s%    !:!:5!ABBr   c                 d   | j                   }|j                  }| j                  |       d}|j                  r|dz  }|dz  }| j                  j
                  r|j                  d   d   }|r|dz  }|j                  r|dz  }|| j                  |d	      d
|j                  |j                        dz  }|j                  d   d   }|r4|d| j                   j                  |t              j                         z  z  }|j                  d   d   }|ddj                  |j                  D cg c]y  }| j                   j#                  t%        |t&        j(                        s|j+                         n|dd      t-        |d      r |j.                  |v rd||j.                     z   ndz   { c}      z  z  }|j                  d   d   }	|	r|	D 
cg c]7  }
t%        |
t0        j2                        r|j                  j4                  |
   n|
9 }}
|ddj                  |D cg c]  }|j7                  |j8                         c}      z  z  }|j                  d   d   }|r6|ddj                  |j;                         D cg c]  }d|z  	 c}      z  z  }|j                  d   d   }|r|d|j7                  |      z  z  }|j                  d   d   }|Jt=        j>                  t@        jB                  |      }| j                   j#                  |dd      }|d|z   z  }|S c c}w c c}
w c c}w c c}w )NzCREATE zUNIQUE zINDEX rs  concurrentlyCONCURRENTLY zIF NOT EXISTS Finclude_schemaz ON r  rn   z	USING %s opsr  r  Tr  r  r*  r  includez INCLUDE (%s)rs   z
 WITH (%s)z%s = %s
tablespacez TABLESPACE %srq   z WHERE )"r  r  _verify_index_tablerl   r   #_supports_create_index_concurrentlyru  if_not_exists_prepared_index_namer  rf   validate_sql_phrase	IDX_USINGlowerr   expressionsr  r   r   r   ColumnClauser.  hasattrr*  r   r   r  r  r  r1  r   r2  r   DDLExpressionRole)r   r5   r  indexri  r  rn   r  exprincludeclauser  
inclusionsr  
withclausestorage_parametertablespace_namewhereclausewhere_compileds                     r   visit_create_indexz PGDDLCompiler.visit_create_index
  ss   ==  '<<ID<<;; 00>~NL'$$D%%eE%B!!%++.
 	

 %%l3G<--33E9EKKMND
 ##L1%8II !& 1 1  %%--)$
0G0GH )!&+&* .  #4/DHHO s488},
 	
( --l;IF
 )	  c4#4#45 c"J  Odii1;<A'<'  D **<8@
L		 2<1A1A1C- "$55 D  //=lK$x~~o'FFFD++L9'B"#**''K "..665 7 N I..Dq( =s   ,A>L<L#"L(<L-c                     |j                   }d}| j                  j                  r|j                  d   d   }|r|dz  }|j                  r|dz  }|| j                  |d      z  }|S )Nz
DROP INDEX rs  r  r  z
IF EXISTS Tr  )r  r   !_supports_drop_index_concurrentlyru  	if_existsr  )r   r  r  ri  r  s        r   visit_drop_indexzPGDDLCompiler.visit_drop_indexT  so    <<99 00>~NL'>>L D))%)EEr   c                    d}|j                   !|d| j                  j                  |      z  z  }g }|j                  D ]  \  }}}d|d<    | j                  j
                  |fi |t        |d      r4|j                  |j                  v rd|j                  |j                     z   ndz   } |j                  |d|        |d| j                  j                  |j                  t              j                         d	d
j                  |      dz  }|j                  -|d| j                  j                  |j                  d      z  z  }|| j!                  |      z  }|S )Nr  zCONSTRAINT %s Fr  r*  r  z WITH zEXCLUDE USING z (r  r  z WHERE (%s)Tr  )r  r  format_constraint_render_exprsr  r   r  r*  r  r/  r  rn   r  r  r   rq   define_constraint_deferrability)	r   r4   r   ri  r   r  r  r   exclude_elements	            r   visit_exclude_constraintz&PGDDLCompiler.visit_exclude_constraintd  su   ??&$t}}'F'F(  D (66 	BND$"'B7d//77CC4'DHH
,F z~~dhh//O HOOOR@A	B 	MM--  )eg IIh	
 	
 'MD$5$5$=$=   %> %  D 	44Z@@r   c                 ~    g }|j                   d   }|j                  d      }|Ht        |t        t        f      s|f}|j                  ddj                   fd|D              z   dz          |d   r|j                  d|d   z         |d	   d
u r|j                  d       n|d	   du r|j                  d       |d   r7|d   j                  dd      j                         }|j                  d|z         |d   r2|d   }|j                  d j                  j                  |      z         dj                  |      S )Nrs  inheritsz
 INHERITS ( r  c              3   T   K   | ]  }j                   j                  |       ! y wr   )r  r  )r  r  r   s     r   r  z2PGDDLCompiler.post_create_table.<locals>.<genexpr>  s      K$DMM//5Ks   %(z )partition_byz
 PARTITION BY %s	with_oidsTz
 WITH OIDSFz
 WITHOUT OIDS	on_commit_r  z
 ON COMMIT %sr  z
 TABLESPACE %sr  )ru  rI  r   ry  tupler/  r   r  r  r  r  )r   rf   
table_optspg_optsr  on_commit_optionsr  s   `      r   post_create_tablezPGDDLCompiler.post_create_table  sR   
''5;;z*hu6$; ))K(KKL >"2W^5LLM;4'n-[!U*/0; ' 4 < <S# F L L N/2CCD< %l3O"T]]%8%8%II wwz""r   c                     |j                   du rt        j                  d      d| j                  j	                  |j
                  dd      z  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  )	persistedr   r  r  r   r  )r   	generateds     r   visit_computed_columnz#PGDDLCompiler.visit_computed_column  s]    %'""&  143D3D3L3LU$ 4M 4
 
 	
r   c                     d }|j                   j                  2d| j                  j                  |j                   j                        z  }t	        t
        |   |fd|i|S )Nz AS %sprefix)r  	data_typer  r   r   r[  visit_create_sequence)r   r5   r   r  r   s       r   r  z#PGDDLCompiler.visit_create_sequence  sk    >>##/ 2 2 : :((! F ]D?
!
%'
 	
r   )r   r   r   rq  rv  r}  r  r  r  r  r  r  r  r  r  r  r   r   s   @r   r[  r[  
  sN    5n1$

	
C
Xt : #D

	
 	
r   r[  c                        e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z fdZd dZd Zd Zd Zd Zd Zd Zd Z d Z! xZ"S )!PGTypeCompilerc                      y)Nr  r   r   r\  r   s      r   visit_TSVECTORzPGTypeCompiler.visit_TSVECTOR      r   c                      y)Nr   r   r  s      r   
visit_INETzPGTypeCompiler.visit_INET      r   c                      y)Nr   r   r  s      r   
visit_CIDRzPGTypeCompiler.visit_CIDR  r  r   c                      y)Nr   r   r  s      r   visit_MACADDRzPGTypeCompiler.visit_MACADDR      r   c                      y)Nr   r   r  s      r   visit_MACADDR8zPGTypeCompiler.visit_MACADDR8  r  r   c                      y)Nr   r   r  s      r   visit_MONEYzPGTypeCompiler.visit_MONEY      r   c                      y)Nr   r   r  s      r   	visit_OIDzPGTypeCompiler.visit_OID  s    r   c                      y)Nr   r   r  s      r   visit_REGCLASSzPGTypeCompiler.visit_REGCLASS  r  r   c                 >    |j                   sydd|j                   iz  S )Nr   zFLOAT(%(precision)s)r   r   r  s      r   visit_FLOATzPGTypeCompiler.visit_FLOAT  s     )[%//,JJJr   c                      y)NzDOUBLE PRECISIONr   r  s      r   visit_DOUBLE_PRECISIONz%PGTypeCompiler.visit_DOUBLE_PRECISION  s    !r   c                      y)Nr   r   r  s      r   visit_BIGINTzPGTypeCompiler.visit_BIGINT      r   c                      y)NHSTOREr   r  s      r   visit_HSTOREzPGTypeCompiler.visit_HSTORE  r  r   c                      y)Nr  r   r  s      r   
visit_JSONzPGTypeCompiler.visit_JSON  r  r   c                      y)NJSONBr   r  s      r   visit_JSONBzPGTypeCompiler.visit_JSONB  r  r   c                      y)N	INT4RANGEr   r  s      r   visit_INT4RANGEzPGTypeCompiler.visit_INT4RANGE      r   c                      y)N	INT8RANGEr   r  s      r   visit_INT8RANGEzPGTypeCompiler.visit_INT8RANGE  r  r   c                      y)NNUMRANGEr   r  s      r   visit_NUMRANGEzPGTypeCompiler.visit_NUMRANGE  r  r   c                      y)N	DATERANGEr   r  s      r   visit_DATERANGEzPGTypeCompiler.visit_DATERANGE  r  r   c                      y)NTSRANGEr   r  s      r   visit_TSRANGEzPGTypeCompiler.visit_TSRANGE  r  r   c                      y)N	TSTZRANGEr   r  s      r   visit_TSTZRANGEzPGTypeCompiler.visit_TSTZRANGE  r  r   c                 (     | j                   |fi |S r   )visit_TIMESTAMPr  s      r   visit_datetimezPGTypeCompiler.visit_datetime  s    #t##E0R00r   c                     |j                   r| j                  j                  st        t        |   |fi |S  | j                  |fi |S r   )r  r   r  r   r  r3  
visit_ENUM)r   r\  r   r   s      r   r3  zPGTypeCompiler.visit_enum  sE      (I(I9%F2FF"4??5/B//r   c                 T    || j                   j                  }|j                  |      S r   )r   r^  r  )r   r\  r^  r   s       r   r  zPGTypeCompiler.visit_ENUM  s)    &"&,,"B"B"..u55r   c                 t    dt        |dd       d|j                  z  ndd|j                  xr dxs ddz   S )	Nr   r   (%d)r  r  WITHWITHOUT
 TIME ZONEgetattrr   r   r  s      r   r  zPGTypeCompiler.visit_TIMESTAMP	  K     uk40< U__$ ^^&3)|C	
 	
r   c                 t    dt        |dd       d|j                  z  ndd|j                  xr dxs ddz   S )	Nr   r   r  r  r  r  r  r  r  r  s      r   
visit_TIMEzPGTypeCompiler.visit_TIME  r  r   c                     d}|j                   |d|j                   z   z  }|j                  |d|j                  z  z  }|S )Nr   r  z (%d))r   r   )r   r\  r   ri  s       r   visit_INTERVALzPGTypeCompiler.visit_INTERVAL  sF    <<#C%,,&&D??&Geoo--Dr   c                     |j                   r"d}|j                  |d|j                  z  z  }|S d|j                  z  }|S )NzBIT VARYINGr  zBIT(%d))r   r   )r   r\  r   compileds       r   	visit_BITzPGTypeCompiler.visit_BIT!  sG    ==$H||'FU\\11  !5<</Hr   c                      y)Nr   r   r  s      r   
visit_UUIDzPGTypeCompiler.visit_UUID*  r  r   c                 (     | j                   |fi |S r   )visit_BYTEAr  s      r   visit_large_binaryz!PGTypeCompiler.visit_large_binary-  s    t,,,r   c                      y)Nr   r   r  s      r   r  zPGTypeCompiler.visit_BYTEA0  r  r   c                      | j                   |j                  fi |}t        j                  ddd|j                  |j                  ndz  z  |d      S )Nz((?: COLLATE.*)?)$z%s\1[]r   )count)r   r{  resub
dimensions)r   r\  r   r|   s       r   visit_ARRAYzPGTypeCompiler.visit_ARRAY3  s^    U__33vv!+0+;+;+Gu''QP 
 	
r   r   )#r   r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r3  r  r  r  r  r  r  r  r  r%  r   r   s   @r   r  r    s    K"106


-
r   r  c                       e Zd ZeZd ZddZy)PGIdentifierPreparerc                 |    |d   | j                   k(  r)|dd j                  | j                  | j                        }|S )Nr   r   r!  )initial_quoter  escape_to_quoteescape_quote)r   r   s     r   _unquote_identifierz(PGIdentifierPreparer._unquote_identifierH  sB    8t)))!BK''$$d&7&7E r   c                     |j                   st        j                  d      | j                  |j                         }| j	                  |      }| j
                  s|r|| j                  |      dz   |z   }|S )Nz%PostgreSQL ENUM type requires a name..)r  r   r  r  r)  omit_schemaquote_schema)r   r\  r  r  r-  s        r   r  z PGIdentifierPreparer.format_typeO  sr    zz""#JKKzz%**%11%8    ,$$%56<tCDr   N)T)r   r   r   RESERVED_WORDSreserved_wordsr,  r  r   r   r   r'  r'  D  s    #Nr   r'  c                   ,    e Zd ZddZddZddZddZy)PGInspectorNc                     | j                         5 }| j                  j                  |||| j                        cddd       S # 1 sw Y   yxY w)z(Return the OID for the given table name.
info_cacheN)_operation_contextr   get_table_oidr7  )r   
table_namer   conns       r   r9  zPGInspector.get_table_oid`  sK     $$& 	$<<--j&T__ . 	 	 	   )AAc                     |xs | j                   }| j                         5 }| j                  j                  ||      cddd       S # 1 sw Y   yxY w)aK  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.

        .. versionadded:: 1.0.0

        N)default_schema_namer8  r   _load_enumsr   r   r;  s      r   	get_enumszPGInspector.get_enumsh  sK    $ 3433$$& 	:$<<++D&9	: 	: 	:   AAc                     |xs | j                   }| j                         5 }| j                  j                  ||      cddd       S # 1 sw Y   yxY w)a  Return 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``.

        .. versionadded:: 1.0.0

        N)r>  r8  r   _get_foreign_table_namesr@  s      r   get_foreign_table_namesz#PGInspector.get_foreign_table_names~  sO     3433$$& 	G$<<88vF	G 	G 	GrB  c                     | j                         5 }| j                  j                  ||| j                  |      cddd       S # 1 sw Y   yxY w)a  Return all view names in `schema`.

        :param schema: Optional, retrieve names from a non-default schema.
         For special quoting, use :class:`.quoted_name`.

        :param include: specify which types of views to return.  Passed
         as a string value (for a single type) or a tuple (for any number
         of types).  Defaults to ``('plain', 'materialized')``.

         .. versionadded:: 1.1

        )r7  r  N)r8  r   get_view_namesr7  )r   r   r  r;  s       r   rG  zPGInspector.get_view_names  sK     $$& 	$<<..f' / 	 	 	r<  r   Nplainmaterialized)r   r   r   r9  rA  rE  rG  r   r   r   r4  r4  _  s    :,Gr   r4  c                       e Zd ZdZy)r1  create_enum_typeNr   r   r   r   r1  r1    r   r   r1  c                       e Zd ZdZy)r:  drop_enum_typeNr   r   r   r   r:  r:    s    %Nr   r:  c                   *     e Zd Zd Z fdZd Z xZS )PGExecutionContextc                 ^    | j                  d| j                  j                  |      z  |      S )Nzselect nextval('%s'))_execute_scalarr^  r  )r   r  r\  s      r   fire_sequencez PGExecutionContext.fire_sequence  s7    ##&**::3?@ 
 	
r   c                 h   |j                   r||j                  j                  u r|j                  rI|j                  j                  r3| j                  d|j                  j                  z  |j                        S |j                  ,|j                  j                  r|j                  j                  ro	 |j                  }|j                  &| j                   j#                  |j                        }nd }|
d|d|d}nd|d}| j                  ||j                        S t$        t&        | S  |      S # t        $ rr |j                  j                  }|j                  }|ddt        ddt        |      z
        z    }|ddt        ddt        |      z
        z    }|d|d}|x|_        }Y w xY w)	Nz	select %sr      r  _seqzselect nextval('"z"."z"'))rd  rf   re  server_defaulthas_argumentrS  argrX  r   is_sequenceri  _postgresql_seq_nameAttributeErrorr  maxr  r$  r)  r   rQ  get_insert_default)	r   r3   seq_nametabr  r  r-  r   r   s	           r   r_  z%PGExecutionContext.get_insert_default  s   &FLL,N,N"N$$)>)>)K)K ++&"7"7";";;V[[  '**v~~/F/FB%::H <<+'+'H'H($ (,$#/( C 0 9ABC++C=='A&II3 & B ,,++C ++Ca"s1rCH}'>">?Ca"s1rCH}'>">?C*-s3D=AAF/(Bs   5D6 6A8F10F1c                 ,    t         j                  |      S r   )AUTOCOMMIT_REGEXPmatch)r   r  s     r   should_autocommit_textz)PGExecutionContext.should_autocommit_text  s     &&y11r   )r   r   r   rT  r_  re  r   r   s   @r   rQ  rQ    s    
+JZ2r   rQ  c                   "    e Zd ZdZd Zd Zd Zy)"PGReadOnlyConnectionCharacteristicTc                 (    |j                  |d       y r   set_readonlyr   r   
dbapi_conns      r   reset_characteristicz7PGReadOnlyConnectionCharacteristic.reset_characteristic      Z/r   c                 (    |j                  ||       y r   ri  r   r   rl  r   s       r   set_characteristicz5PGReadOnlyConnectionCharacteristic.set_characteristic  rn  r   c                 $    |j                  |      S r   )get_readonlyrk  s      r   get_characteristicz5PGReadOnlyConnectionCharacteristic.get_characteristic  s    ##J//r   Nr   r   r   transactionalrm  rq  rt  r   r   r   rg  rg    s     M000r   rg  c                   "    e Zd ZdZd Zd Zd Zy)$PGDeferrableConnectionCharacteristicTc                 (    |j                  |d       y r   set_deferrablerk  s      r   rm  z9PGDeferrableConnectionCharacteristic.reset_characteristic      z51r   c                 (    |j                  ||       y r   rz  rp  s       r   rq  z7PGDeferrableConnectionCharacteristic.set_characteristic  r|  r   c                 $    |j                  |      S r   )get_deferrablerk  s      r   rt  z7PGDeferrableConnectionCharacteristic.get_characteristic  s    %%j11r   Nru  r   r   r   rx  rx    s     M222r   rx  c            	       n    e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZd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"Z#dZ$dZ%dZ&e'jP                  jR                  Z)e)jU                   e+        e,       d      Z)e-j\                  dddi di ddfe-j^                  ddddddd	fe-j`                  d
dife-jb                  d
difgZ2dZ3dZ4dZ5dZ6	 	 	 d3dZ7 fdZ8d Z9 e:g d      Z;d Z<d Z=d Z>d Z?d Z@d ZAd ZBd ZC	 d4dZD	 d4dZEd ZFd ZGd ZHd5dZId5dZJd5dZKd  ZLeMj                  d5d!       ZOeMj                  d"        ZPeMj                  d5d#       ZQeMj                  d5d$       ZReMj                  	 d6d%       ZSeMj                  d5d&       ZTeMj                  d5d'       ZUeMj                  d5d(       ZVd) ZWeMj                  d5d*       ZXeMj                  	 	 d7d+       ZYd, ZZeMj                  d-        Z[eMj                  	 d5d.       Z\eMj                  d5d/       Z]eMj                  d5d0       Z^d5d1Z_d2 Z` xZaS )8	PGDialectrs  T?   FpyformatN)postgresql_readonlypostgresql_deferrable)rn   r  rq   r  r  rs   r  )ignore_search_pathr  r  r  r  r  rt  )postgresql_ignore_search_pathc                 n    t        j                  j                  | fi | || _        || _        || _        y r   )r   DefaultDialectr   isolation_level_json_deserializer_json_serializer)r   r  json_serializerjson_deserializerr%  s        r   r   zPGDialect.__init__`  s7     	''77
  /"3 /r   c                    t         t        |   |       | j                  dk  rdx| _        | _        | j                  dk\  | _        | j                  si| j                  j                         | _        | j                  j                  t        j                  d        | j                  j                  t        d        | j                  dk\  | _        | j                  dk  rd| _        n)|j                  d      j!                         }|dk(  | _        | j                  dk\  | _        | j                  dk\  | _        | j                  dk\  | _        y )N   r  Fr  r   )	   r  z show standard_conforming_stringsrW   
   )r   r  
initializeserver_version_infofull_returningimplicit_returningr  colspecscopyr  r   r|  r  rf  r  exec_driver_sqlscalarr  r  rc  )r   r$  
std_stringr   s      r   r  zPGDialect.initializep  s-   i)*5##v-<AAD$"9$($<$<$F!(( MM..0DMMMhmmT2MMdD) %)$<$<$F!##f,&+D# $332fh  '1E&9D# $$. 	0 261I1I N
 2
. *.)A)AU)J&r   c                 ,      j                    fd}|S y )Nc                 >    j                  | j                         y r   )set_isolation_levelr  )r;  r   s    r   connectz%PGDialect.on_connect.<locals>.connect  s    ((t/C/CDr   )r  )r   r  s   ` r   
on_connectzPGDialect.on_connect  s    +E Nr   )SERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READc           
      P   |j                  dd      }|| j                  vrAt        j                  d|d| j                  ddj                  | j                              |j                         }|j                  d|z         |j                  d       |j                          y )	Nr  r  zInvalid value 'z2' for isolation_level. Valid isolation levels for z are r  z=SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL %sCOMMIT)	r  _isolation_lookupr   ArgumentErrorr  r   cursorr0  close)r   r$  levelr  s       r   r  zPGDialect.set_isolation_level  s    c3'...## $))TYYt/E/E%FH 
 ""$!#()	
 	x r   c                     |j                         }|j                  d       |j                         d   }|j                          |j	                         S )Nz show transaction isolation levelr   )r  r0  fetchoner  r  )r   r$  r  vals       r   get_isolation_levelzPGDialect.get_isolation_level  sC    ""$9:oo"yy{r   c                     t               r   NotImplementedErrorr   r$  r   s      r   rj  zPGDialect.set_readonly      !##r   c                     t               r   r  r   r$  s     r   rs  zPGDialect.get_readonly  r  r   c                     t               r   r  r  s      r   r{  zPGDialect.set_deferrable  r  r   c                     t               r   r  r  s     r   r  zPGDialect.get_deferrable  r  r   c                 :    | j                  |j                         y r   )do_beginr$  r   r$  xids      r   do_begin_twophasezPGDialect.do_begin_twophase  s    j++,r   c                 ,    |j                  d|z         y )NzPREPARE TRANSACTION '%s')r  r  s      r   do_prepare_twophasezPGDialect.do_prepare_twophase  s    ""#=#CDr   c                     |rT|r|j                  d       |j                  d|z         |j                  d       | j                  |j                         y | j                  |j                         y )NROLLBACKzROLLBACK PREPARED '%s'BEGIN)r  do_rollbackr$  r   r$  r  is_preparedrecovers        r   do_rollback_twophasezPGDialect.do_rollback_twophase  sd     
 **:6&&'?#'EF&&w/Z223Z223r   c                     |rT|r|j                  d       |j                  d|z         |j                  d       | j                  |j                         y | j                  |j                         y )Nr  zCOMMIT PREPARED '%s'r  )r  r  r$  	do_commitr  s        r   do_commit_twophasezPGDialect.do_commit_twophase  s`     **:6&&'='CD&&w/Z223NN:001r   c                 z    |j                  t        j                  d            }|D cg c]  }|d   	 c}S c c}w )Nz!SELECT gid FROM pg_prepared_xactsr   )r0  r   ri  )r   r$  	resultsetrows       r   do_recover_twophasezPGDialect.do_recover_twophase  s9    &&HH89
	 #,,3A,,,s   8c                 @    |j                  d      j                         S )Nzselect current_schema())r  r  r  s     r   _get_default_schema_namez"PGDialect._get_default_schema_name  s    ))*CDKKMMr   c                 *   d}|j                  t        j                  |      j                  t        j                  dt        j                   |j                               t        j                                    }t        |j                               S )Nz=select nspname from pg_namespace where lower(nspname)=:schemar   r#  )r0  r   ri  
bindparams	bindparamr   r   r  r   Unicodeboolfirst)r   r$  r   queryr  s        r   
has_schemazPGDialect.has_schema  sq    N 	 ##HHUO&&NN<6<<>2"**
 FLLN##r   c                 t   | j                  |       |k|j                  t        j                  d      j	                  t        j
                  dt        j                  |      t        j                                    }n|j                  t        j                  d      j	                  t        j
                  dt        j                  |      t        j                        t        j
                  dt        j                  |      t        j                                    }t        |j                               S )Nzselect relname from pg_class c join pg_namespace n on n.oid=c.relnamespace where pg_catalog.pg_table_is_visible(c.oid) and relname=:namer  r#  ztselect relname from pg_class c join pg_namespace n on n.oid=c.relnamespace where n.nspname=:schema and relname=:namer   )_ensure_has_table_connectionr0  r   ri  r  r  r   r   r   r  r  r  )r   r$  r:  r   r  s        r   	has_tablezPGDialect.has_table  s    ))*5>''(
 *MMz2&..F  ''$ *MMz2&..
 MM v.&..F$ FLLN##r   c                    || j                   }|j                  t        j                  d      j	                  t        j
                  dt        j                  |      t        j                        t        j
                  dt        j                  |      t        j                                    }t        |j                               S )NzSELECT relname FROM pg_class c join pg_namespace n on n.oid=c.relnamespace where relkind='S' and n.nspname=:schema and relname=:namer  r#  r   )r>  r0  r   ri  r  r  r   r   r   r  r  r  )r   r$  sequence_namer   r  s        r   has_sequencezPGDialect.has_sequence,  s    >--F##HH6 jNN=1"**
 NN6*"**
& FLLN##r   c                    |d}t        j                  |      }nd}t        j                  |      }|j                  t        j                  dt	        j
                  |      t        j                              }|H|j                  t        j                  dt	        j
                  |      t        j                              }|j                  |      }t        |j                               S )Na  
            SELECT EXISTS (
                SELECT * FROM pg_catalog.pg_type t, pg_catalog.pg_namespace n
                WHERE t.typnamespace = n.oid
                AND t.typname = :typname
                AND n.nspname = :nspname
                )
                z
            SELECT EXISTS (
                SELECT * FROM pg_catalog.pg_type t
                WHERE t.typname = :typname
                AND pg_type_is_visible(t.oid)
                )
                typnamer#  nspname)r   ri  r  r  r   r   r   r  r0  r  r  )r   r$  	type_namer   r  r  s         r   r*  zPGDialect.has_typeD  s    E HHUOEE HHUOE  MM4>>)4H<L<L

 $$t~~f5X=M=ME
 ##E*FMMO$$r   c                    |j                  d      j                         }t        j                  d|      }|st	        d|z        t        |j                  ddd      D cg c]  }|t        |       c}      S c c}w )Nzselect pg_catalog.version()zQ.*(?:PostgreSQL|EnterpriseDB) (\d+)\.?(\d+)?(?:\.(\d+))?(?:\.\d+)?(?:devel|beta)?z,Could not determine version from string '%s'r   r  r   )r  r  r"  rd  AssertionErrorr  rI   int)r   r$  r=  mxs        r   _get_server_version_infoz"PGDialect._get_server_version_infof  s}    &&'DELLNHHC

  >B  aggaA&6H!-c!fHIIHs    A<(A<c                    d}|d}nd}d|z  }t        j                  |      }|t        j                  |      }t        j                  |      j	                  t
        j                        }|j                  t
        j                        }|r4|j	                  t        j                  dt
        j                              }|j                  |t        ||	            }	|	j                         }|t        j                  |      |S )
zFetch the oid for schema.table_name.

        Several reflection methods require the table oid.  The idea for using
        this method is that it can be fetched one time and cached for
        subsequent calls.

        Nzn.nspname = :schemaz%pg_catalog.pg_table_is_visible(c.oid)a	  
            SELECT c.oid
            FROM pg_catalog.pg_class c
            LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
            WHERE (%s)
            AND c.relname = :table_name AND c.relkind in
            ('r', 'v', 'm', 'f', 'p')
        )r:  )ru  r   r#  )r:  r   )r   r   r   ri  r  r   r  r  Integerr  r0  r'  r  r   NoSuchTableError)
r   r$  r:  r   r   	table_oidschema_where_clauser  r  r  s
             r   r9  zPGDialect.get_table_oids  s     	"7"I "" 	 ^^J/
^^F+FHHUO&&(2B2B&CII(**I+S]]88;K;KLMAq$*V"LMHHJ	&&z22r   c                     |j                  t        j                  d      j                  t        j
                              }|D cg c]  \  }| c}S c c}w )NzOSELECT nspname FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' ORDER BY nspname)r  )r0  r   ri  r  r   r  )r   r$  r   resultr  s        r   get_schema_nameszPGDialect.get_schema_names  sO    ##HH# gh..g/
 #)))))s   Ac                     |j                  t        j                  d      j                  t        j
                        t        ||n| j                              }|D cg c]  \  }| c}S c c}w )NzSELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :schema AND c.relkind in ('r', 'p')relnamer   r0  r   ri  r  r   r  r'  r>  r   r$  r   r   r  r  s         r   get_table_nameszPGDialect.get_table_names  sl    ##HHH gh..g/% --
 #)))))    A.c                     |j                  t        j                  d      j                  t        j
                        t        ||n| j                              }|D cg c]  \  }| c}S c c}w )Nz|SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :schema AND c.relkind = 'f'r  r   r  r  s         r   rD  z"PGDialect._get_foreign_table_names  sl    ##HH@ gh..g/% --
 #)))))r  c           	         ddd}	 t        j                  |      D cg c]  }||   	 }}|st        d      |j	                  t        j                  ddj                  d	 |D              z        j                  t        j                  
      t        ||n| j                              }|D 	cg c]  \  }	|	 c}	S c c}w # t        $ r t        d|d      w xY wc c}	w )Nr=  r  rI  zinclude zU unknown, needs to be a sequence containing one or both of 'plain' and 'materialized'zZempty include, needs to be a sequence containing one or both of 'plain' and 'materialized'z~SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :schema AND c.relkind IN (%s)r  c              3   &   K   | ]	  }d |z    ywr%  r   )r  elems     r   r  z+PGDialect.get_view_names.<locals>.<genexpr>  s     =tVd]=r&  r  r   )r   to_listKeyError
ValueErrorr0  r   ri  r   r  r   r  r'  r>  )
r   r$  r   r  r   include_kindr  kindsr  r  s
             r   rG  zPGDialect.get_view_names  s    
 "%c:	.2ll7.CD\!_DED < 
 ##HHB 99=u==?
 gh..g/% --
 #))))3 E 	?FI 	0 *s!   C B?C 1C ?C Cc           
      "   |s| j                   }|j                  t        j                  d      j	                  t        j
                  dt        j                  |      t        j                                    }|D cg c]  }|d   	 c}S c c}w )NzrSELECT relname FROM pg_class c join pg_namespace n on n.oid=c.relnamespace where relkind='S' and n.nspname=:schemar   r#  r   )
r>  r0  r   ri  r  r  r   r   r   r  )r   r$  r   r   r  r  s         r   get_sequence_nameszPGDialect.get_sequence_names  s{    --F##HH$ jNN6*"**
 #))3A)))s   =Bc                     |j                  t        j                  d      j                  t        j
                        t        ||n| j                  |            }|S )NzSELECT pg_get_viewdef(c.oid) view_def FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :schema AND c.relname = :view_name AND c.relkind IN ('v', 'm'))view_def)r   	view_name)r  r   ri  r  r   r  r'  r>  )r   r$  r  r   r   r  s         r   get_view_definitionzPGDialect.get_view_definition  s]    $$HH.
 gx//g0% --#	
 r   c                    | j                  ||||j                  d            }| j                  dk\  rdnd}| j                  dk\  rd}nd}d	|d
|d}t        j                  |      j                  t        j                  dt        j                              j                  t        j                  t        j                        }	|j                  |	t        |            }
|
j                         }| j                  |      }t        d | j                  |d      D              }g }|D ]6  \  }}}}}}}}| j!                  ||||||||||
      }|j#                  |       8 |S )Nr7  r6  )   za.attgenerated as generatedzNULL as generatedr  a                  (SELECT json_build_object(
                    'always', a.attidentity = 'a',
                    'start', s.seqstart,
                    'increment', s.seqincrement,
                    'minvalue', s.seqmin,
                    'maxvalue', s.seqmax,
                    'cache', s.seqcache,
                    'cycle', s.seqcycle)
                FROM pg_catalog.pg_sequence s
                JOIN pg_catalog.pg_class c on s.seqrelid = c."oid"
                WHERE c.relkind = 'S'
                AND a.attidentity != ''
                AND s.seqrelid = pg_catalog.pg_get_serial_sequence(
                    a.attrelid::regclass::text, a.attname
                )::regclass::oid
                ) as identity_options                zNULL as identity_optionsa  
            SELECT a.attname,
              pg_catalog.format_type(a.atttypid, a.atttypmod),
              (
                SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid)
                FROM pg_catalog.pg_attrdef d
                WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum
                AND a.atthasdef
              ) AS DEFAULT,
              a.attnotnull,
              a.attrelid as table_oid,
              pgd.description as comment,
              z,
              a.  
            FROM pg_catalog.pg_attribute a
            LEFT JOIN pg_catalog.pg_description pgd ON (
                pgd.objoid = a.attrelid AND pgd.objsubid = a.attnum)
            WHERE a.attrelid = :table_oid
            AND a.attnum > 0 AND NOT a.attisdropped
            ORDER BY a.attnum
        r  r#  )attnamer   r  c              3   N   K   | ]  }|d    r|d   f|fn|d   |d   f|f  yw)visibler  r   Nr   )r  recs     r   r  z(PGDialect.get_columns.<locals>.<genexpr>W  sH      
  9~ &k^S!x=#f+.45
s   #%*r   )r9  rI  r  r   ri  r  r  r   r  r  r  r0  r'  fetchall_load_domainsr?  _get_column_infor/  )r   r$  r:  r   r   r  r  rb  SQL_COLSr  r  rowsdomainsr	  r  r  r  default_r   commentcolumn_infos                        r   get_columnszPGDialect.get_columns  s    &&
Frvvl7K ' 
	 ''50 *$ 	
 ##u,H& 2H. -
2 HHXZk9I9IJKWX--x7G7GWH 	

 q$";<zz| $$Z0  
 ''
3'?	
 
  	( 	
//K NN;'-	(. r   c                    d }|	d}dx}}d}n$d}t        j                  dd|      } ||      \  }}t        t        j                  |            }| }t        j
                  d|      }|r|j                  d      }t        j
                  d	|      }|r@|j                  d      r/t        t        j                  d
|j                  d                  }nd}i }|dk(  r0|r+|j                  d      \  }}t        |      t        |      f}nd}n|dk(  rd}n|dk(  rd}n|dv rd|d<   |rt        |      |d<   d}n|dv rd|d<   |rt        |      |d<   d}n|dk(  rd|d<   |rt        |      f}nrd}no|j                  d      rPt        j                  d|t         j                        }|rt        |      |d<   |r|j                  d      |d<   d}d}n|rt        |      f}	 || j                  v r| j                  |   }n||v r/||   }t        }|d   |d<   |d   s|d   |d<   t        |d         }nP||v rI||   }|d   } ||      \  }}t        t        j                  |            }|xr |d   }|d    r|s|d    }d }	 |r  ||i |}|rn | j                  d!   |      }nX|r*t        j                  d"|d#       t        j                   }n,t        j                  d$|d%|d#       t        j                   }|	d&vrt#        ||	d'v (      }d }nd }d}|t        j
                  d)|      }|{t%        |j&                  t        j(                        rd}|}d*|j                  d+      vr@|>|j                  d      d,|z  z   d*z   |j                  d+      z   |j                  d-      z   }t#        |||||xs |
d u|.      }|||d/<   |
|
|d0<   |S )1Nc                 R    t        j                  dd|       | j                  d      fS )Nz\[\]$r  r   )r"  r#  endswith)attypes    r   _handle_array_typez6PGDialect._get_column_info.<locals>._handle_array_type  s*     xV,% r   Tzno format_type()Fz\(.*\)r  z\(([\d,]+)\)r   z\((.*)\)\s*,\s*r   rj  ,rw  )5   re  )ry  r{  r   r   )rz  r|  r~  rq  r   r   zinterval (.+)r   r  r  r   labelsr  rm  r   r]  z3PostgreSQL format_type() returned NULL for column ''zDid not recognize type 'z' of column ')Nr      )r     s)r  r  z(nextval\(')([^']+)('.*$)r.  r  z"%s"r   )r  rX  rm  r   autoincrementr  rl  rb  )r"  r#  r  r   quoted_token_parsersearchrI   splitr  
startswithrd  Iischema_namesr  r  r   NULLTYPEr'  
issubclassr   r  )r   r  r  r   r   r  r	  r   r  r  rb  r  no_format_typer  is_arrayenum_or_domain_keyrm  charlenargsr%  precscalefield_matchr   r,  domainrl  r%  rd  schr  s                                  r   r  zPGDialect._get_column_infoz  st   	 !N#55F[H"N VVIr;7F  2&9FH #4#;#;F#CD;))O[9mmA&Gyyk2DJJqM*djjm<=DDY%mmC0eD	3u:.))Dy DJJ!%F:&)'l{#D 
 

 "'F:&)'l{#D}$ $F9Gz*((#3VRTTBK&)'l{##.#4#4Q#7x FDL?D+++,,V4#u,/0!%fvI'+H~F8$T(^,#w. !34)#5f#= %*4+C+CF+K%L" $:z(:)$W %Y/Gt.v.G6$,,X6w?II ''GII@FM ''G
 //9+CH GH II>HE g44h6F6FG$(Mekk!n,
 A!C<)  ++a.)  ++a.	)  '?84+?
 &.K
#&.K
#r   c                 L   | j                  ||||j                  d            }| j                  dk  rd| j                  dd      z  }nd}t	        j
                  |      j                  t        j                        }|j                  |t        |	            }|j                         D 	cg c]  }	|	d
   	 }
}	d}t	        j
                  |      j                  t        j                        }|j                  |t        |	            }|j                         }|
|dS c c}	w )Nr7  r6  )r     aq  
                SELECT a.attname
                FROM
                    pg_class t
                    join pg_index ix on t.oid = ix.indrelid
                    join pg_attribute a
                        on t.oid=a.attrelid AND %s
                 WHERE
                  t.oid = :table_oid and ix.indisprimary = 't'
                ORDER BY a.attnum
            a.attnum	ix.indkeya  
                SELECT a.attname
                FROM pg_attribute a JOIN (
                    SELECT unnest(ix.indkey) attnum,
                           generate_subscripts(ix.indkey, 1) ord
                    FROM pg_index ix
                    WHERE ix.indrelid = :table_oid AND ix.indisprimary
                    ) k ON a.attnum=k.attnum
                WHERE a.attrelid = :table_oid
                ORDER BY k.ord
            )r	  r
  r   z
        SELECT conname
           FROM  pg_catalog.pg_constraint r
           WHERE r.conrelid = :table_oid AND r.contype = 'p'
           ORDER BY 1
        )conname)constrained_columnsr  )r9  rI  r  _pg_index_anyr   ri  r  r   r  r0  r'  r  r  )r   r$  r:  r   r   r  PK_SQLrG  r  rr8  PK_CONS_SQLr  s                r   get_pk_constraintzPGDialect.get_pk_constraint1  s   &&
Frvvl7K ' 
	 ##f,
 $$KF"
F HHV$$X-=-=$>q$";<jjl+!++ HH[!))(2B2B)Cq$";<xxz'+T:: ,s   -D!c                    | j                   }| j                  ||||j                  d            }d}t        j                  d      }	t        j                  |      j                  t        j                  t        j                        }
|j                  |
t        |            }g }|j                         D ]4  \  }}}t        j                  |	|      j                         }|\  }}}}}}}}}}}}}|	|dk(  rdnd	}t        j                  d
|      D cg c]  }|j!                  |       }}|r|| j"                  k7  r|}n |}n|r|j!                  |      }n	|||k(  r|}|j!                  |      }t        j                  d|      D cg c]  }|j!                  |       }}d|fd|fd|fd|fd|ffD ci c]  \  }}||dk7  r|| }}}||||||d}|j%                  |       7 |S c c}w c c}w c c}}w )Nr7  r6  a  
          SELECT r.conname,
                pg_catalog.pg_get_constraintdef(r.oid, true) as condef,
                n.nspname as conschema
          FROM  pg_catalog.pg_constraint r,
                pg_namespace n,
                pg_class c

          WHERE r.conrelid = :table AND
                r.contype = 'f' AND
                c.oid = confrelid AND
                n.oid = c.relnamespace
          ORDER BY 1
        a/  FOREIGN KEY \((.*?)\) REFERENCES (?:(.*?)\.)?(.*?)\((.*?)\)[\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<  condef)rf   
DEFERRABLETFr  z\s*,\sonupdateondeleterL   r<   rd  z	NO ACTION)r  r=  referred_schemareferred_tablereferred_columnsoptions)r^  r9  rI  r"  compiler   ri  r  r   r  r0  r'  r  r'  groupsr(  r,  r>  r/  ) r   r$  r:  r   r  r   r  r  FK_SQLFK_REGEXrG  r  fkeysr<  rD  	conschemar  r=  rH  rI  rJ  r  rd  rF  rG  r<   rL   r  r<  r=  rK  fkey_ds                                    r   get_foreign_keyszPGDialect.get_foreign_keysd  s    ++&&
Frvvl7K ' 
	 ::7	
 HHV$$$$X-=-= % 
 q$Y"78*+**, C	!&GVY		(F+224A  #  %%/<%?TU
 *.AB# ,,Q/# #
 -  8 88&/O&,O  #+">">"O#)(; #)%99.IN )-=>  ,,Q/     ** ),!:.e$
Aq =Q+%5 1
G 
  ':#2"0$4"F LL GC	!H _#. 
s   G2G7<G<c                     | j                   dk  r(ddj                  fdt        dd      D              z  S ddS )	N)r  r   r  z OR c              3   .   K   | ]  }d |fz    yw)z%s[%d] = %sNr   )r  indr  
compare_tos     r   r  z*PGDialect._pg_index_any.<locals>.<genexpr>  s"      (;>S# 66(s   r   r  z = ANY(r  )r  r   range)r   r  rW  s    ``r   r>  zPGDialect._pg_index_any  sK    ##f, FKK (BG2,(    &)*55r   c                   & | j                  ||||j                  d            }| j                  dk  rSd| j                  dk\  rdndd| j                  dk\  rd	nd
d| j                  dk\  rdnd
d| j                  dd      d	}nd| j                  dk\  rdnd
d}t	        j
                  |      j                  t        j                  t        j                        }|j                  |t        |            }t        d       }	d }
|j                         D ]  }|\  }}}}}}}}}}}}|r ||
k7  rt        j                  d|z         |}
5||	v }|	|   }|||d   |<   |rK|j                         }|r||d  r||d  }|d | }ng }|D cg c]  }t!        |j#                                c}|d<   |D cg c]  }t!        |j#                                c}|d<   i }t%        |xs dj                               D ]G  \  }}t!        |j#                               }d} |dz  r| dz  } |d z  s| d!z  } n
|d z  r| d"z  } | sC| ||<   I |r||d#<   ||d$<   |||d%<   |r+t        |D !cg c]  }!|!j                  d&       c}!      |d'<   |r
|d(k7  r||d)<   |s|||d*<    g }"|	j'                         D ]
  \  }#&|#&d$   &d   D $cg c]
  }$&d   |$    c}$d+}%| j                  dk\  r&d   D $cg c]
  }$&d   |$    c}$|%d,<   d%&v r&d%   |%d%<   d#&v r(t        &fd-&d#   j'                         D              |%d.<   d,|%v r|%d,   |%j)                  d/i       d0<   d'&v r&d'   |%j)                  d/i       d1<   d)&v r&d)   |%j)                  d/i       d2<   d*&v r&d*   |%j)                  d/i       d*<   |"j+                  |%        |"S c c}w c c}w c c}!w c c}$w c c}$w )3Nr7  r6  )r     z
              SELECT
                  i.relname as relname,
                  ix.indisunique, ix.indexprs, ix.indpred,
                  a.attname, a.attnum, NULL, ix.indkeyr  z	::varcharr  z,
                  zix.indoption::varcharNULLr  r  zi.reloptionsam  , am.amname,
                  NULL as indnkeyatts
              FROM
                  pg_class t
                        join pg_index ix on t.oid = ix.indrelid
                        join pg_class i on i.oid = ix.indexrelid
                        left outer join
                            pg_attribute a
                            on t.oid = a.attrelid and r:  r;  aw  
                        left outer join
                            pg_am am
                            on i.relam = am.oid
              WHERE
                  t.relkind IN ('r', 'v', 'f', 'm')
                  and t.oid = :table_oid
                  and ix.indisprimary = 'f'
              ORDER BY
                  t.relname,
                  i.relname
            a@  
              SELECT
                  i.relname as relname,
                  ix.indisunique, ix.indexprs,
                  a.attname, a.attnum, c.conrelid, ix.indkey::varchar,
                  ix.indoption::varchar, i.reloptions, am.amname,
                  pg_get_expr(ix.indpred, ix.indrelid),
                  )   r   zix.indnkeyattsa   as indnkeyatts
              FROM
                  pg_class t
                        join pg_index ix on t.oid = ix.indrelid
                        join pg_class i on i.oid = ix.indexrelid
                        left outer join
                            pg_attribute a
                            on t.oid = a.attrelid and a.attnum = ANY(ix.indkey)
                        left outer join
                            pg_constraint c
                            on (ix.indrelid = c.conrelid and
                                ix.indexrelid = c.conindid and
                                c.contype in ('p', 'u', 'x'))
                        left outer join
                            pg_am am
                            on i.relam = am.oid
              WHERE
                  t.relkind IN ('r', 'v', 'f', 'm', 'p')
                  and t.oid = :table_oid
                  and ix.indisprimary = 'f'
              ORDER BY
                  t.relname,
                  i.relname
            )r  r	  r
  c                       t        t              S r   r   r'  r   r   r   <lambda>z'PGDialect.get_indexes.<locals>.<lambda>>      k$&7 r   z;Skipped unsupported reflection of expression-based index %sr8  r*  incr   r   )r=   r  )
nulls_last)nulls_firstsortingrl   duplicates_constraint=rK  btreeamnamepostgresql_where)r  rl   column_namesinclude_columnsc              3   D   K   | ]  \  }}d    d   |      |f  yw)r8  r*  Nr   )r  r  r   idxs      r   r  z(PGDialect.get_indexes.<locals>.<genexpr>  s3      / 5 [UA/7/s    column_sortingru  postgresql_includepostgresql_withpostgresql_using)r9  rI  r  r>  r   ri  r  r   r  r0  r'  r   r  r   r  r(  r  strip	enumerater1  r  r/  )'r   r$  r:  r   r   r  IDX_SQLrG  r  indexessv_idx_namer  idx_namerl   r  r  col_numconrelididx_key
idx_optionrK  rh  filter_definitionindnkeyattshas_idxr  idx_keysinc_keysr<  rd  col_idx	col_flagscol_sortingoptionr  r  r  entryrm  s'                                         @r   get_indexeszPGDialect.get_indexes  s   &&
Frvvl7K ' 
	 ##f,:  $776ArI++v5 ( ++v5  "":{;G$G -N ++w6 !?"GH HHW%%$$h.>.> & 
 q$";<78::< S	BC ! {*II46>? '')GH%E),fg&"==? 8KL#9  (5H'5H!H8@A1AGGIAe8@A1AGGIAe
 *3%2,,.+ 7&GY !$IOO$5 6I"$K 4'#y0 )D 0'?:K$t+'+;;K"+6(7 '.E)$"(h'5=E12'+9@Avc*A(E)$ f/&,E(O$0AE,-gS	Bj   !	!ID#h-9<U DAVQ DE
 ''72 EHJ+OqCKN+O'(&#-145L1M-.C*. /$'	N$8$8$:/ +&' !E) +,   !2B7( C 	N   !2B7% 3 M   !2B7& "S( *+   !2B7& MM% C!	!D ]  BA: B$ !E
 ,Ps    O8 O%O
O
.Oc                 8   | j                  ||||j                  d            }d}t        j                  |      j	                  t
        j                        }|j                  |t        |            }t        d       }	|j                         D ]<  }
|	|
j                     }|
j                  |d<   |
j                  |d   |
j                  <   > |	j                         D cg c]!  \  }}||d   D cg c]
  }|d   |    c}d	# c}}}S c c}w c c}}}w )
Nr7  r6  a  
            SELECT
                cons.conname as name,
                cons.conkey as key,
                a.attnum as col_num,
                a.attname as col_name
            FROM
                pg_catalog.pg_constraint cons
                join pg_attribute a
                  on cons.conrelid = a.attrelid AND
                    a.attnum = ANY(cons.conkey)
            WHERE
                cons.conrelid = :table_oid AND
                cons.contype = 'u'
        )col_namer
  c                       t        t              S r   r^  r   r   r   r_  z2PGDialect.get_unique_constraints.<locals>.<lambda>  r`  r   r*  r8  )r  rj  )r9  rI  r   ri  r  r   r  r0  r'  r   r  r  r*  r  rx  r1  )r   r$  r:  r   r   r  
UNIQUE_SQLrG  r  uniquesr  ucr  r  s                 r   get_unique_constraintsz PGDialect.get_unique_constraints  s    &&
Frvvl7K ' 
	
  HHZ (((2B2B(Cq$";<78::< 	3C"BBuI&)llBvJs{{#	3 $MMO
 
b 2e9+MaBvJqM+MN
 	
+M
s   %D5DDDc                     | j                  ||||j                  d            }d}|j                  t        j                  |      t        |            }d|j                         iS )Nr7  r6  z
            SELECT
                pgd.description as table_comment
            FROM
                pg_catalog.pg_description pgd
            WHERE
                pgd.objsubid = 0 AND
                pgd.objoid = :table_oid
        r
  ri  )r9  rI  r0  r   ri  r'  r  )r   r$  r:  r   r   r  COMMENT_SQLr  s           r   get_table_commentzPGDialect.get_table_comment  sh    &&
Frvvl7K ' 
	 HH[!4)#<
 
##r   c                 6   | j                  ||||j                  d            }d}|j                  t        j                  |      t        |            }g }|D ]  \  }	}
t        j                  d|
t        j                        }|st        j                  d|
z         d}nDt        j                  d	t        j                        j                  d
|j                  d            }|	|d}|r|j                  d      rddi|d<   |j                  |        |S )Nr7  r6  a  
            SELECT
                cons.conname as name,
                pg_get_constraintdef(cons.oid) as src
            FROM
                pg_catalog.pg_constraint cons
            WHERE
                cons.conrelid = :table_oid AND
                cons.contype = 'c'
        r
  z^CHECK *\((.+)\)( NOT VALID)?$)r  z)Could not parse CHECK constraint text: %rr  z^[\s\n]*\((.+)\)[\s\n]*$z\1r   )r  r  r  rt  Tru  )r9  rI  r0  r   ri  r'  r"  rd  DOTALLr   r  rL  r#  rI   r/  )r   r$  r:  r   r   r  	CHECK_SQLr  retr  srcr  r  r  s                 r   get_check_constraintszPGDialect.get_check_constraints  s   &&
Frvvl7K ' 
			 sxx	2D94MN 	ID# 13biiA 		EKL**/ryy#eQWWQZ(  "g6EQWWQZ,7+>'(JJu-	. 
r   c                    |xs | j                   }| j                  si S d}|dk7  r|dz  }|dz  }t        j                  |      j	                  t
        j                  t
        j                        }|dk7  r|j                  |      }|j                  |      }g }i }|j                         D ]  }|j                  |j                  f}	|	|v r"||	   d   j                  |j                         A|j                  |j                  |j                  g dx||	<   }
|j                  |
d   j                  |j                         |j                  |
        |S )	Na  
            SELECT t.typname as "name",
               -- no enum defaults in 8.4 at least
               -- t.typdefault as "default",
               pg_catalog.pg_type_is_visible(t.oid) as "visible",
               n.nspname as "schema",
               e.enumlabel as "label"
            FROM pg_catalog.pg_type t
                 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
                 LEFT JOIN pg_catalog.pg_enum e ON t.oid = e.enumtypid
            WHERE t.typtype = 'e'
        r  zAND n.nspname = :schema z ORDER BY "schema", "name", e.oid)r	  labelr   r!  )r  r   r  r!  )r>  r  r   ri  r  r   r  r  r0  r  r   r  r/  r  r  )r   r$  r   	SQL_ENUMSr  r  r	  enum_by_namer,  r*  enum_recs              r   r?  zPGDialect._load_enums#  sX   3433((I	 S=33I 	77	HHY''$$H,<,< ( 
 S=F+Aq!JJL 	'D;;		*Cl"S!(+224::> !II"kk#|| 	0 S!H ::)X&--djj9X&	' r   c                 B   d}t        j                  |      }|j                  d      j                  |      }i }|j	                         D ]Q  }|}t        j                  d|d         j                  d      }|d   r|d   f}n
|d	   |d   f}||d
   |d   d||<   S |S )Na  
            SELECT t.typname as "name",
               pg_catalog.format_type(t.typbasetype, t.typtypmod) as "attype",
               not t.typnotnull as "nullable",
               t.typdefault as "default",
               pg_catalog.pg_type_is_visible(t.oid) as "visible",
               n.nspname as "schema"
            FROM pg_catalog.pg_type t
               LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
            WHERE t.typtype = 'd'
        T)future_resultz([^\(]+)r  r   r  r  r   rm  r   )r  rm  r   )r   ri  execution_optionsr0  mappingsr"  r'  rI   )	r   r$  SQL_DOMAINSr  r  r  r6  r  r*  s	            r   r  zPGDialect._load_domainsW  s    
 HH[!((t(<DDQGjjl 	FFYY{F8,<=CCAFF
 i f~'h'8 !":.!),GCL	& r   )NNN)TFr   rH  r   )br   r   r   r  supports_statement_cachesupports_altermax_identifier_lengthsupports_sane_rowcountr  supports_native_booleanrf  supports_sequencessequences_optional"preexecute_autoincrement_sequencespostfetch_lastrowidsupports_commentssupports_default_valuessupports_default_metavaluesupports_empty_insertsupports_multivalues_insertrc  default_paramstyler+  r  r  statement_compilerr[  ddl_compilerr  r  r'  r  rQ  execution_ctx_clsr4  	inspectorr  r  r  r   r  connection_characteristicsrk   rg  rx  r   IndexTableCheckConstraintForeignKeyConstraintconstruct_argumentsreflection_optionsr  r  r  r   r  r  r?  r  r  r  rj  rs  r{  r  r  r  r  r  r  r  r  r  r  r*  r  r   cacher9  r  r  rD  rG  r  r  r  r  rB  rS  r>  r  r  r  r  r?  r  r   r   s   @r   r  r    s   D#N!")-&"!%!"& $#!MH# L"M#H*ION 	99  "<!A!A#E#G%I%K	
" LL %"	
 LL&+" $!! 
	
 ""U	
 ''U	
=$L <*.'(,% 	0 "KH 	
 $$$$-E :?4" :?
2-N$ %$N$0 %DJ % %N * * * * * * /H* *B * *$  " j jXun 0; 0;d 
 &+p pd6 S Sj -1#
 #
J $ $( * *X2h%r   r  ){r   collectionsr   datetimer   r"  ro  r   r   r  r   r]  r   r   _hstorer	   _jsonr
   _rangesr   r   r   r   enginer   r   r   r   r   r   r   r   r   r  sql.ddlr   typesr   r   r   r   r   r    r!   r"   r#   r$   r%   rL  r*  r  UNICODErc  r?  r1  _DECIMAL_TYPES_FLOAT_TYPES
_INT_TYPESLargeBinaryr   Floatr   
TypeEnginer   PGInetr   PGCidrr   	PGMacAddrr   
PGMacAddr8r   r   r   r   r   NativeForEmulated_AbstractIntervalr   
PGIntervalr   PGBitPGUuidr  r|  r  CastrU  rz  r   r  JSONPathTyper  r  r  r  r  r  r  r  r  Stringr+  SQLCompilerr  DDLCompilerr[  GenericTypeCompilerr  IdentifierPreparerr'  	Inspectorr4  _CreateDropBaser1  r:  DefaultExecutionContextrQ  ConnectionCharacteristicrg  rx  r  r  r   r   r   <module>r     so  N`. $  	 %          %          #            BJJ:BDDA	BJJ@DD2::  giV %/
H   (x~~ (8  
8  
h!!  	 x""   
*H *Z(

  x""  #"" #&#8== #&%x))8+E+E %P 

(

 
 	O58 O5d 
 x""  &I88%%x}} I8X5 5 NNFLLxMM4MM 2 2MM5::,fll,gnn, EJJ, U[[	,
 "", "",   , "", w, "", w, f, , , ,  hoo!," HOO#,$ D%,& w',( U),* D+,, D-,. D/,0 D1,2 
33,4 35,6 w7,8 9,: U;,< 
3=,> ?,@ (A,B C,D 	E,F $-"W,^[%% [|h
H(( h
V	F
X11 F
R866 6?*&& ?D(V++ (&6)) &8288 82v0,,02,,2z&& zr   