gս  dZddlmZddlmZddlmZddlZddlm Z ddlm Z ddlm Z dd lm Z dd lm Z dd lmZdd lmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlm Z d dlm!Z!d dlm"Z"d dlm#Z#d dlm$Z$d dl%m&Z&d dl%m'Z'd dl%m(Z(d dl%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%m0Z0d d'l%m1Z1d d(l%m2Z2d d)l%m3Z3d d*l%m4Z4d d+l%m5Z5d d,l%m6Z6d d-l%m7Z7d d.l%m8Z8d d/l%m9Z9d d0l%m:Z:d d1l%m;Z;d d2l%mZ>d5d6lm?Z?d5d7lm@Z@d5d8lmAZAd5d9lmBZBd5d:lmCZCd5d;lDmEZEd5dlDmHZHd5d?lDmIZId5d@lDmJZJd5dAlDmKZKd5dBlLmMZMd5dClBmNZNd5dDlBmOZOd5dElBmPZPd5dFlBmQZQd5dGlBmRZRd5dHlBmSZSd5dIlBmTZTd5d:lBmCZUd5dJlVmWZWd5dKlXmYZYd5dLl%mZZZd5dMl%m[Z[d5dNl%m\Z\d5dOl%m]Z]d5dPl%m^Z^d5dQl%m_Z_d5dRl%m`Z`d5dSl%maZad5dTl%mbZbd5dUl%mcZcd5dVl%mdZdd5dWl%meZed5dXl%mfZfd5dYlgmhZhejdZejZkhd[ZleTjejeTje.eTje#eTjjejeTjejeTje9iZtid\ejd]ed^ejd_ejd`ejdaejdbejdcejddejdeejdfejdgejdhejdiejdjejdkejdle`idmeZdnecdoefdpe\dqeTjdreTjdseddteadue_dvebdwe-dxe+dye,dzeed{e)d|e)d}e/id~e0de1de2de:de^de=de=de=de<de<de]de<de*de[de.de>ZGddePjZGddePj ZGddePjZGddePjZGddehZGddehZGddeZGddeZGddeJj ZGddeFj$ZGddeEj(ZGddeEj(ZGddeFj.Zy)a .. dialect:: postgresql :name: PostgreSQL :normal_support: 9.6+ :best_effort: 9+ .. _postgresql_sequences: Sequences/SERIAL/IDENTITY ------------------------- PostgreSQL supports sequences, and SQLAlchemy uses these as the default means of creating new primary key values for integer-based primary key columns. When creating tables, SQLAlchemy will issue the ``SERIAL`` datatype for integer-based primary key columns, which generates a sequence and server side default corresponding to the column. To specify a specific named sequence to be used for primary key generation, use the :func:`~sqlalchemy.schema.Sequence` construct:: Table( "sometable", metadata, Column( "id", Integer, Sequence("some_id_seq", start=1), primary_key=True ), ) When SQLAlchemy issues a single INSERT statement, to fulfill the contract of having the "last insert identifier" available, a RETURNING clause is added to the INSERT statement which specifies the primary key columns should be returned after the statement completes. The RETURNING functionality only takes place if PostgreSQL 8.2 or later is in use. As a fallback approach, the sequence, whether specified explicitly or implicitly via ``SERIAL``, is executed independently beforehand, the returned value to be used in the subsequent insert. Note that when an :func:`~sqlalchemy.sql.expression.insert()` construct is executed using "executemany" semantics, the "last inserted identifier" functionality does not apply; no RETURNING clause is emitted nor is the sequence pre-executed in this case. PostgreSQL 10 and above IDENTITY columns ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PostgreSQL 10 and above have a new IDENTITY feature that supersedes the use of SERIAL. The :class:`_schema.Identity` construct in a :class:`_schema.Column` can be used to control its behavior:: from sqlalchemy import Table, Column, MetaData, Integer, Computed metadata = MetaData() data = Table( "data", metadata, Column( "id", Integer, Identity(start=42, cycle=True), primary_key=True ), Column("data", String), ) The CREATE TABLE for the above :class:`_schema.Table` object would be: .. sourcecode:: sql CREATE TABLE data ( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 42 CYCLE), data VARCHAR, PRIMARY KEY (id) ) .. versionchanged:: 1.4 Added :class:`_schema.Identity` construct in a :class:`_schema.Column` to specify the option of an autoincrementing column. .. note:: Previous versions of SQLAlchemy did not have built-in support for rendering of IDENTITY, and could use the following compilation hook to replace occurrences of SERIAL with IDENTITY:: from sqlalchemy.schema import CreateColumn from sqlalchemy.ext.compiler import compiles @compiles(CreateColumn, "postgresql") def use_identity(element, compiler, **kw): text = compiler.visit_create_column(element, **kw) text = text.replace("SERIAL", "INT GENERATED BY DEFAULT AS IDENTITY") return text Using the above, a table such as:: t = Table( "t", m, Column("id", Integer, primary_key=True), Column("data", String) ) Will generate on the backing database as: .. sourcecode:: sql CREATE TABLE t ( id INT GENERATED BY DEFAULT AS IDENTITY, data VARCHAR, PRIMARY KEY (id) ) .. _postgresql_ss_cursors: Server Side Cursors ------------------- Server-side cursor support is available for the psycopg2, asyncpg dialects and may also be available in others. Server side cursors are enabled on a per-statement basis by using the :paramref:`.Connection.execution_options.stream_results` connection execution option:: with engine.connect() as conn: result = conn.execution_options(stream_results=True).execute( text("select * from table") ) Note that some kinds of SQL statements may not be supported with server side cursors; generally, only SQL statements that return rows should be used with this option. .. deprecated:: 1.4 The dialect-level server_side_cursors flag is deprecated and will be removed in a future release. Please use the :paramref:`_engine.Connection.stream_results` execution option for unbuffered cursor support. .. seealso:: :ref:`engine_stream_results` .. _postgresql_isolation_level: Transaction Isolation Level --------------------------- Most SQLAlchemy dialects support setting of transaction isolation level using the :paramref:`_sa.create_engine.isolation_level` parameter at the :func:`_sa.create_engine` level, and at the :class:`_engine.Connection` level via the :paramref:`.Connection.execution_options.isolation_level` parameter. For PostgreSQL dialects, this feature works either by making use of the DBAPI-specific features, such as psycopg2's isolation level flags which will embed the isolation level setting inline with the ``"BEGIN"`` statement, or for DBAPIs with no direct support by emitting ``SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL `` ahead of the ``"BEGIN"`` statement emitted by the DBAPI. For the special AUTOCOMMIT isolation level, DBAPI-specific techniques are used which is typically an ``.autocommit`` flag on the DBAPI connection object. To set isolation level using :func:`_sa.create_engine`:: engine = create_engine( "postgresql+pg8000://scott:tiger@localhost/test", isolation_level="REPEATABLE READ", ) To set using per-connection execution options:: with engine.connect() as conn: conn = conn.execution_options(isolation_level="REPEATABLE READ") with conn.begin(): ... # work with transaction There are also more options for isolation level configurations, such as "sub-engine" objects linked to a main :class:`_engine.Engine` which each apply different isolation level settings. See the discussion at :ref:`dbapi_autocommit` for background. Valid values for ``isolation_level`` on most PostgreSQL dialects include: * ``READ COMMITTED`` * ``READ UNCOMMITTED`` * ``REPEATABLE READ`` * ``SERIALIZABLE`` * ``AUTOCOMMIT`` .. seealso:: :ref:`dbapi_autocommit` :ref:`postgresql_readonly_deferrable` :ref:`psycopg2_isolation_level` :ref:`pg8000_isolation_level` .. _postgresql_readonly_deferrable: Setting READ ONLY / DEFERRABLE ------------------------------ Most PostgreSQL dialects support setting the "READ ONLY" and "DEFERRABLE" characteristics of the transaction, which is in addition to the isolation level setting. These two attributes can be established either in conjunction with or independently of the isolation level by passing the ``postgresql_readonly`` and ``postgresql_deferrable`` flags with :meth:`_engine.Connection.execution_options`. The example below illustrates passing the ``"SERIALIZABLE"`` isolation level at the same time as setting "READ ONLY" and "DEFERRABLE":: with engine.connect() as conn: conn = conn.execution_options( isolation_level="SERIALIZABLE", postgresql_readonly=True, postgresql_deferrable=True, ) with conn.begin(): ... # work with transaction Note that some DBAPIs such as asyncpg only support "readonly" with SERIALIZABLE isolation. .. versionadded:: 1.4 added support for the ``postgresql_readonly`` and ``postgresql_deferrable`` execution options. .. _postgresql_reset_on_return: Temporary Table / Resource Reset for Connection Pooling ------------------------------------------------------- The :class:`.QueuePool` connection pool implementation used by the SQLAlchemy :class:`.Engine` object includes :ref:`reset on return ` behavior that will invoke the DBAPI ``.rollback()`` method when connections are returned to the pool. While this rollback will clear out the immediate state used by the previous transaction, it does not cover a wider range of session-level state, including temporary tables as well as other server state such as prepared statement handles and statement caches. The PostgreSQL database includes a variety of commands which may be used to reset this state, including ``DISCARD``, ``RESET``, ``DEALLOCATE``, and ``UNLISTEN``. To install one or more of these commands as the means of performing reset-on-return, the :meth:`.PoolEvents.reset` event hook may be used, as demonstrated in the example below. The implementation will end transactions in progress as well as discard temporary tables using the ``CLOSE``, ``RESET`` and ``DISCARD`` commands; see the PostgreSQL documentation for background on what each of these statements do. The :paramref:`_sa.create_engine.pool_reset_on_return` parameter is set to ``None`` so that the custom scheme can replace the default behavior completely. The custom hook implementation calls ``.rollback()`` in any case, as it's usually important that the DBAPI's own tracking of commit/rollback will remain consistent with the state of the transaction:: from sqlalchemy import create_engine from sqlalchemy import event postgresql_engine = create_engine( "postgresql+pyscopg2://scott:tiger@hostname/dbname", # disable default reset-on-return scheme pool_reset_on_return=None, ) @event.listens_for(postgresql_engine, "reset") def _reset_postgresql(dbapi_connection, connection_record, reset_state): if not reset_state.terminate_only: dbapi_connection.execute("CLOSE ALL") dbapi_connection.execute("RESET ALL") dbapi_connection.execute("DISCARD TEMP") # so that the DBAPI itself knows that the connection has been # reset dbapi_connection.rollback() .. versionchanged:: 2.0.0b3 Added additional state arguments to the :meth:`.PoolEvents.reset` event and additionally ensured the event is invoked for all "reset" occurrences, so that it's appropriate as a place for custom "reset" handlers. Previous schemes which use the :meth:`.PoolEvents.checkin` handler remain usable as well. .. seealso:: :ref:`pool_reset_on_return` - in the :ref:`pooling_toplevel` documentation .. _postgresql_alternate_search_path: Setting Alternate Search Paths on Connect ------------------------------------------ The PostgreSQL ``search_path`` variable refers to the list of schema names that will be implicitly referenced when a particular table or other object is referenced in a SQL statement. As detailed in the next section :ref:`postgresql_schema_reflection`, SQLAlchemy is generally organized around the concept of keeping this variable at its default value of ``public``, however, in order to have it set to any arbitrary name or names when connections are used automatically, the "SET SESSION search_path" command may be invoked for all connections in a pool using the following event handler, as discussed at :ref:`schema_set_default_connections`:: from sqlalchemy import event from sqlalchemy import create_engine engine = create_engine("postgresql+psycopg2://scott:tiger@host/dbname") @event.listens_for(engine, "connect", insert=True) def set_search_path(dbapi_connection, connection_record): existing_autocommit = dbapi_connection.autocommit dbapi_connection.autocommit = True cursor = dbapi_connection.cursor() cursor.execute("SET SESSION search_path='%s'" % schema_name) cursor.close() dbapi_connection.autocommit = existing_autocommit The reason the recipe is complicated by use of the ``.autocommit`` DBAPI attribute is so that when the ``SET SESSION search_path`` directive is invoked, it is invoked outside of the scope of any transaction and therefore will not be reverted when the DBAPI connection has a rollback. .. seealso:: :ref:`schema_set_default_connections` - in the :ref:`metadata_toplevel` documentation .. _postgresql_schema_reflection: Remote-Schema Table Introspection and PostgreSQL search_path ------------------------------------------------------------ .. admonition:: Section Best Practices Summarized keep the ``search_path`` variable set to its default of ``public``, without any other schema names. Ensure the username used to connect **does not** match remote schemas, or ensure the ``"$user"`` token is **removed** from ``search_path``. For other schema names, name these explicitly within :class:`_schema.Table` definitions. Alternatively, the ``postgresql_ignore_search_path`` option will cause all reflected :class:`_schema.Table` objects to have a :attr:`_schema.Table.schema` attribute set up. The PostgreSQL dialect can reflect tables from any schema, as outlined in :ref:`metadata_reflection_schemas`. In all cases, the first thing SQLAlchemy does when reflecting tables is to **determine the default schema for the current database connection**. It does this using the PostgreSQL ``current_schema()`` function, illustated below using a PostgreSQL client session (i.e. using the ``psql`` tool): .. sourcecode:: sql test=> select current_schema(); current_schema ---------------- public (1 row) Above we see that on a plain install of PostgreSQL, the default schema name is the name ``public``. However, if your database username **matches the name of a schema**, PostgreSQL's default is to then **use that name as the default schema**. Below, we log in using the username ``scott``. When we create a schema named ``scott``, **it implicitly changes the default schema**: .. sourcecode:: sql test=> select current_schema(); current_schema ---------------- public (1 row) test=> create schema scott; CREATE SCHEMA test=> select current_schema(); current_schema ---------------- scott (1 row) The behavior of ``current_schema()`` is derived from the `PostgreSQL search path `_ variable ``search_path``, which in modern PostgreSQL versions defaults to this: .. sourcecode:: sql test=> show search_path; search_path ----------------- "$user", public (1 row) Where above, the ``"$user"`` variable will inject the current username as the default schema, if one exists. Otherwise, ``public`` is used. When a :class:`_schema.Table` object is reflected, if it is present in the schema indicated by the ``current_schema()`` function, **the schema name assigned to the ".schema" attribute of the Table is the Python "None" value**. Otherwise, the ".schema" attribute will be assigned the string name of that schema. With regards to tables which these :class:`_schema.Table` objects refer to via foreign key constraint, a decision must be made as to how the ``.schema`` is represented in those remote tables, in the case where that remote schema name is also a member of the current ``search_path``. By default, the PostgreSQL dialect mimics the behavior encouraged by PostgreSQL's own ``pg_get_constraintdef()`` builtin procedure. This function returns a sample definition for a particular foreign key constraint, omitting the referenced schema name from that definition when the name is also in the PostgreSQL schema search path. The interaction below illustrates this behavior: .. sourcecode:: sql test=> CREATE TABLE test_schema.referred(id INTEGER PRIMARY KEY); CREATE TABLE test=> CREATE TABLE referring( test(> id INTEGER PRIMARY KEY, test(> referred_id INTEGER REFERENCES test_schema.referred(id)); CREATE TABLE test=> SET search_path TO public, test_schema; test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n test-> ON n.oid = c.relnamespace test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid test-> WHERE c.relname='referring' AND r.contype = 'f' test-> ; pg_get_constraintdef --------------------------------------------------- FOREIGN KEY (referred_id) REFERENCES referred(id) (1 row) Above, we created a table ``referred`` as a member of the remote schema ``test_schema``, however when we added ``test_schema`` to the PG ``search_path`` and then asked ``pg_get_constraintdef()`` for the ``FOREIGN KEY`` syntax, ``test_schema`` was not included in the output of the function. On the other hand, if we set the search path back to the typical default of ``public``: .. sourcecode:: sql test=> SET search_path TO public; SET The same query against ``pg_get_constraintdef()`` now returns the fully schema-qualified name for us: .. sourcecode:: sql test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n test-> ON n.oid = c.relnamespace test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid test-> WHERE c.relname='referring' AND r.contype = 'f'; pg_get_constraintdef --------------------------------------------------------------- FOREIGN KEY (referred_id) REFERENCES test_schema.referred(id) (1 row) SQLAlchemy will by default use the return value of ``pg_get_constraintdef()`` in order to determine the remote schema name. That is, if our ``search_path`` were set to include ``test_schema``, and we invoked a table reflection process as follows:: >>> from sqlalchemy import Table, MetaData, create_engine, text >>> engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test") >>> with engine.connect() as conn: ... conn.execute(text("SET search_path TO test_schema, public")) ... metadata_obj = MetaData() ... referring = Table("referring", metadata_obj, autoload_with=conn) 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, ... ) We will now have ``test_schema.referred`` stored as schema-qualified:: >>> metadata_obj.tables["test_schema.referred"].schema 'test_schema' .. sidebar:: Best Practices for PostgreSQL Schema reflection The description of PostgreSQL schema reflection behavior is complex, and is the product of many years of dealing with widely varied use cases and user preferences. But in fact, there's no need to understand any of it if you just stick to the simplest use pattern: leave the ``search_path`` set to its default of ``public`` only, never refer to the name ``public`` as an explicit schema name otherwise, and refer to all other schema names explicitly when building up a :class:`_schema.Table` object. The options described here are only for those users who can't, or prefer not to, stay within these guidelines. .. seealso:: :ref:`reflection_schema_qualified_interaction` - discussion of the issue from a backend-agnostic perspective `The Schema Search Path `_ - on the PostgreSQL website. INSERT/UPDATE...RETURNING ------------------------- The dialect supports PG 8.2's ``INSERT..RETURNING``, ``UPDATE..RETURNING`` and ``DELETE..RETURNING`` syntaxes. ``INSERT..RETURNING`` is used by default for single-row INSERT statements in order to fetch newly generated primary key identifiers. To specify an explicit ``RETURNING`` clause, use the :meth:`._UpdateBase.returning` method on a per-statement basis:: # INSERT..RETURNING result = ( table.insert().returning(table.c.col1, table.c.col2).values(name="foo") ) print(result.fetchall()) # UPDATE..RETURNING result = ( table.update() .returning(table.c.col1, table.c.col2) .where(table.c.name == "foo") .values(name="bar") ) print(result.fetchall()) # DELETE..RETURNING result = ( table.delete() .returning(table.c.col1, table.c.col2) .where(table.c.name == "foo") ) print(result.fetchall()) .. _postgresql_insert_on_conflict: INSERT...ON CONFLICT (Upsert) ------------------------------ Starting with version 9.5, PostgreSQL allows "upserts" (update or insert) of rows into a table via the ``ON CONFLICT`` clause of the ``INSERT`` statement. A candidate row will only be inserted if that row does not violate any unique constraints. In the case of a unique constraint violation, a secondary action can occur which can be either "DO UPDATE", indicating that the data in the target row should be updated, or "DO NOTHING", which indicates to silently skip this row. Conflicts are determined using existing unique constraints and indexes. These constraints may be identified either using their name as stated in DDL, or they may be inferred by stating the columns and conditions that comprise the indexes. SQLAlchemy provides ``ON CONFLICT`` support via the PostgreSQL-specific :func:`_postgresql.insert()` function, which provides the generative methods :meth:`_postgresql.Insert.on_conflict_do_update` and :meth:`~.postgresql.Insert.on_conflict_do_nothing`: .. sourcecode:: pycon+sql >>> from sqlalchemy.dialects.postgresql import insert >>> insert_stmt = insert(my_table).values( ... id="some_existing_id", data="inserted value" ... ) >>> do_nothing_stmt = insert_stmt.on_conflict_do_nothing(index_elements=["id"]) >>> print(do_nothing_stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO NOTHING {stop} >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... constraint="pk_my_table", set_=dict(data="updated value") ... ) >>> print(do_update_stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT ON CONSTRAINT pk_my_table DO UPDATE SET data = %(param_1)s .. seealso:: `INSERT .. ON CONFLICT `_ - in the PostgreSQL documentation. Specifying the Target ^^^^^^^^^^^^^^^^^^^^^ Both methods supply the "target" of the conflict using either the named constraint or by column inference: * The :paramref:`_postgresql.Insert.on_conflict_do_update.index_elements` argument specifies a sequence containing string column names, :class:`_schema.Column` objects, and/or SQL expression elements, which would identify a unique index: .. sourcecode:: pycon+sql >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... index_elements=["id"], set_=dict(data="updated value") ... ) >>> print(do_update_stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s {stop} >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... index_elements=[my_table.c.id], set_=dict(data="updated value") ... ) >>> print(do_update_stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s * When using :paramref:`_postgresql.Insert.on_conflict_do_update.index_elements` to infer an index, a partial index can be inferred by also specifying the use the :paramref:`_postgresql.Insert.on_conflict_do_update.index_where` parameter: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values(user_email="a@b.com", data="inserted data") >>> stmt = stmt.on_conflict_do_update( ... index_elements=[my_table.c.user_email], ... index_where=my_table.c.user_email.like("%@gmail.com"), ... set_=dict(data=stmt.excluded.data), ... ) >>> print(stmt) {printsql}INSERT INTO my_table (data, user_email) VALUES (%(data)s, %(user_email)s) ON CONFLICT (user_email) WHERE user_email LIKE %(user_email_1)s DO UPDATE SET data = excluded.data * The :paramref:`_postgresql.Insert.on_conflict_do_update.constraint` argument is used to specify an index directly rather than inferring it. This can be the name of a UNIQUE constraint, a PRIMARY KEY constraint, or an INDEX: .. sourcecode:: pycon+sql >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... constraint="my_table_idx_1", set_=dict(data="updated value") ... ) >>> print(do_update_stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT ON CONSTRAINT my_table_idx_1 DO UPDATE SET data = %(param_1)s {stop} >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... constraint="my_table_pk", set_=dict(data="updated value") ... ) >>> print(do_update_stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT ON CONSTRAINT my_table_pk DO UPDATE SET data = %(param_1)s {stop} * The :paramref:`_postgresql.Insert.on_conflict_do_update.constraint` argument may also refer to a SQLAlchemy construct representing a constraint, e.g. :class:`.UniqueConstraint`, :class:`.PrimaryKeyConstraint`, :class:`.Index`, or :class:`.ExcludeConstraint`. In this use, if the constraint has a name, it is used directly. Otherwise, if the constraint is unnamed, then inference will be used, where the expressions and optional WHERE clause of the constraint will be spelled out in the construct. This use is especially convenient to refer to the named or unnamed primary key of a :class:`_schema.Table` using the :attr:`_schema.Table.primary_key` attribute: .. sourcecode:: pycon+sql >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... constraint=my_table.primary_key, set_=dict(data="updated value") ... ) >>> print(do_update_stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s The SET Clause ^^^^^^^^^^^^^^^ ``ON CONFLICT...DO UPDATE`` is used to perform an update of the already existing row, using any combination of new values as well as values from the proposed insertion. These values are specified using the :paramref:`_postgresql.Insert.on_conflict_do_update.set_` parameter. This parameter accepts a dictionary which consists of direct values for UPDATE: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values(id="some_id", data="inserted value") >>> do_update_stmt = stmt.on_conflict_do_update( ... index_elements=["id"], set_=dict(data="updated value") ... ) >>> print(do_update_stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s .. warning:: The :meth:`_expression.Insert.on_conflict_do_update` method does **not** take into account Python-side default UPDATE values or generation functions, e.g. those specified using :paramref:`_schema.Column.onupdate`. These values will not be exercised for an ON CONFLICT style of UPDATE, unless they are manually specified in the :paramref:`_postgresql.Insert.on_conflict_do_update.set_` dictionary. Updating using the Excluded INSERT Values ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In order to refer to the proposed insertion row, the special alias :attr:`~.postgresql.Insert.excluded` is available as an attribute on the :class:`_postgresql.Insert` object; this object is a :class:`_expression.ColumnCollection` which alias contains all columns of the target table: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values( ... id="some_id", data="inserted value", author="jlh" ... ) >>> do_update_stmt = stmt.on_conflict_do_update( ... index_elements=["id"], ... set_=dict(data="updated value", author=stmt.excluded.author), ... ) >>> print(do_update_stmt) {printsql}INSERT INTO my_table (id, data, author) VALUES (%(id)s, %(data)s, %(author)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s, author = excluded.author Additional WHERE Criteria ^^^^^^^^^^^^^^^^^^^^^^^^^ The :meth:`_expression.Insert.on_conflict_do_update` method also accepts a WHERE clause using the :paramref:`_postgresql.Insert.on_conflict_do_update.where` parameter, which will limit those rows which receive an UPDATE: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values( ... id="some_id", data="inserted value", author="jlh" ... ) >>> on_update_stmt = stmt.on_conflict_do_update( ... index_elements=["id"], ... set_=dict(data="updated value", author=stmt.excluded.author), ... where=(my_table.c.status == 2), ... ) >>> print(on_update_stmt) {printsql}INSERT INTO my_table (id, data, author) VALUES (%(id)s, %(data)s, %(author)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s, author = excluded.author WHERE my_table.status = %(status_1)s Skipping Rows with DO NOTHING ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``ON CONFLICT`` may be used to skip inserting a row entirely if any conflict with a unique or exclusion constraint occurs; below this is illustrated using the :meth:`~.postgresql.Insert.on_conflict_do_nothing` method: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values(id="some_id", data="inserted value") >>> stmt = stmt.on_conflict_do_nothing(index_elements=["id"]) >>> print(stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO NOTHING If ``DO NOTHING`` is used without specifying any columns or constraint, it has the effect of skipping the INSERT for any unique or exclusion constraint violation which occurs: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values(id="some_id", data="inserted value") >>> stmt = stmt.on_conflict_do_nothing() >>> print(stmt) {printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT DO NOTHING .. _postgresql_match: Full Text Search ---------------- PostgreSQL's full text search system is available through the use of the :data:`.func` namespace, combined with the use of custom operators via the :meth:`.Operators.bool_op` method. For simple cases with some degree of cross-backend compatibility, the :meth:`.Operators.match` operator may also be used. .. _postgresql_simple_match: Simple plain text matching with ``match()`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The :meth:`.Operators.match` operator provides for cross-compatible simple text matching. For the PostgreSQL backend, it's hardcoded to generate an expression using the ``@@`` operator in conjunction with the ``plainto_tsquery()`` PostgreSQL function. On the PostgreSQL dialect, an expression like the following:: select(sometable.c.text.match("search string")) would emit to the database: .. sourcecode:: sql SELECT text @@ plainto_tsquery('search string') FROM table Above, passing a plain string to :meth:`.Operators.match` will automatically make use of ``plainto_tsquery()`` to specify the type of tsquery. This establishes basic database cross-compatibility for :meth:`.Operators.match` with other backends. .. versionchanged:: 2.0 The default tsquery generation function used by the PostgreSQL dialect with :meth:`.Operators.match` is ``plainto_tsquery()``. To render exactly what was rendered in 1.4, use the following form:: from sqlalchemy import func select(sometable.c.text.bool_op("@@")(func.to_tsquery("search string"))) Which would emit: .. sourcecode:: sql SELECT text @@ to_tsquery('search string') FROM table Using PostgreSQL full text functions and operators directly ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Text search operations beyond the simple use of :meth:`.Operators.match` may make use of the :data:`.func` namespace to generate PostgreSQL full-text functions, in combination with :meth:`.Operators.bool_op` to generate any boolean operator. For example, the query:: select(func.to_tsquery("cat").bool_op("@>")(func.to_tsquery("cat & rat"))) would generate: .. sourcecode:: sql SELECT to_tsquery('cat') @> to_tsquery('cat & rat') The :class:`_postgresql.TSVECTOR` type can provide for explicit CAST:: from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy import select, cast select(cast("some text", TSVECTOR)) produces a statement equivalent to: .. sourcecode:: sql SELECT CAST('some text' AS TSVECTOR) AS anon_1 The ``func`` namespace is augmented by the PostgreSQL dialect to set up correct argument and return types for most full text search functions. These functions are used automatically by the :attr:`_sql.func` namespace assuming the ``sqlalchemy.dialects.postgresql`` package has been imported, or :func:`_sa.create_engine` has been invoked using a ``postgresql`` dialect. These functions are documented at: * :class:`_postgresql.to_tsvector` * :class:`_postgresql.to_tsquery` * :class:`_postgresql.plainto_tsquery` * :class:`_postgresql.phraseto_tsquery` * :class:`_postgresql.websearch_to_tsquery` * :class:`_postgresql.ts_headline` Specifying the "regconfig" with ``match()`` or custom operators ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PostgreSQL's ``plainto_tsquery()`` function accepts an optional "regconfig" argument that is used to instruct PostgreSQL to use a particular pre-computed GIN or GiST index in order to perform the search. When using :meth:`.Operators.match`, this additional parameter may be specified using the ``postgresql_regconfig`` parameter, such as:: select(mytable.c.id).where( mytable.c.title.match("somestring", postgresql_regconfig="english") ) Which would emit: .. sourcecode:: sql SELECT mytable.id FROM mytable WHERE mytable.title @@ plainto_tsquery('english', 'somestring') When using other PostgreSQL search functions with :data:`.func`, the "regconfig" parameter may be passed directly as the initial argument:: select(mytable.c.id).where( func.to_tsvector("english", mytable.c.title).bool_op("@@")( func.to_tsquery("english", "somestring") ) ) produces a statement equivalent to: .. sourcecode:: sql SELECT mytable.id FROM mytable WHERE to_tsvector('english', mytable.title) @@ to_tsquery('english', 'somestring') It is recommended that you use the ``EXPLAIN ANALYZE...`` tool from PostgreSQL to ensure that you are generating queries with SQLAlchemy that take full advantage of any indexes you may have created for full text search. .. seealso:: `Full Text Search `_ - in the PostgreSQL documentation FROM ONLY ... ------------- The dialect supports PostgreSQL's ONLY keyword for targeting only a particular table in an inheritance hierarchy. This can be used to produce the ``SELECT ... FROM ONLY``, ``UPDATE ONLY ...``, and ``DELETE FROM ONLY ...`` syntaxes. It uses SQLAlchemy's hints mechanism:: # SELECT ... FROM ONLY ... result = table.select().with_hint(table, "ONLY", "postgresql") print(result.fetchall()) # UPDATE ONLY ... table.update(values=dict(foo="bar")).with_hint( "ONLY", dialect_name="postgresql" ) # DELETE FROM ONLY ... table.delete().with_hint("ONLY", dialect_name="postgresql") .. _postgresql_indexes: PostgreSQL-Specific Index Options --------------------------------- Several extensions to the :class:`.Index` construct are available, specific to the PostgreSQL dialect. Covering Indexes ^^^^^^^^^^^^^^^^ The ``postgresql_include`` option renders INCLUDE(colname) for the given string names:: Index("my_index", table.c.x, postgresql_include=["y"]) would render the index as ``CREATE INDEX my_index ON table (x) INCLUDE (y)`` Note that this feature requires PostgreSQL 11 or later. .. versionadded:: 1.4 .. _postgresql_partial_indexes: Partial Indexes ^^^^^^^^^^^^^^^ Partial indexes add criterion to the index definition so that the index is applied to a subset of rows. These can be specified on :class:`.Index` using the ``postgresql_where`` keyword argument:: Index("my_index", my_table.c.id, postgresql_where=my_table.c.value > 10) .. _postgresql_operator_classes: Operator Classes ^^^^^^^^^^^^^^^^ PostgreSQL allows the specification of an *operator class* for each column of an index (see https://www.postgresql.org/docs/current/interactive/indexes-opclass.html). The :class:`.Index` construct allows these to be specified via the ``postgresql_ops`` keyword argument:: Index( "my_index", my_table.c.id, my_table.c.data, postgresql_ops={"data": "text_pattern_ops", "id": "int4_ops"}, ) Note that the keys in the ``postgresql_ops`` dictionaries are the "key" name of the :class:`_schema.Column`, i.e. the name used to access it from the ``.c`` collection of :class:`_schema.Table`, which can be configured to be different than the actual name of the column as expressed in the database. If ``postgresql_ops`` is to be used against a complex SQL expression such as a function call, then to apply to the column it must be given a label that is identified in the dictionary by name, e.g.:: Index( "my_index", my_table.c.id, func.lower(my_table.c.data).label("data_lower"), postgresql_ops={"data_lower": "text_pattern_ops", "id": "int4_ops"}, ) Operator classes are also supported by the :class:`_postgresql.ExcludeConstraint` construct using the :paramref:`_postgresql.ExcludeConstraint.ops` parameter. See that parameter for details. .. versionadded:: 1.3.21 added support for operator classes with :class:`_postgresql.ExcludeConstraint`. Index Types ^^^^^^^^^^^ PostgreSQL provides several index types: B-Tree, Hash, GiST, and GIN, as well as the ability for users to create their own (see https://www.postgresql.org/docs/current/static/indexes-types.html). These can be specified on :class:`.Index` using the ``postgresql_using`` keyword argument:: Index("my_index", my_table.c.data, postgresql_using="gin") The value passed to the keyword argument will be simply passed through to the underlying CREATE INDEX command, so it *must* be a valid index type for your version of PostgreSQL. .. _postgresql_index_storage: Index Storage Parameters ^^^^^^^^^^^^^^^^^^^^^^^^ PostgreSQL allows storage parameters to be set on indexes. The storage parameters available depend on the index method used by the index. Storage parameters can be specified on :class:`.Index` using the ``postgresql_with`` keyword argument:: Index("my_index", my_table.c.data, postgresql_with={"fillfactor": 50}) PostgreSQL allows to define the tablespace in which to create the index. The tablespace can be specified on :class:`.Index` using the ``postgresql_tablespace`` keyword argument:: Index("my_index", my_table.c.data, postgresql_tablespace="my_tablespace") Note that the same option is available on :class:`_schema.Table` as well. .. _postgresql_index_concurrently: Indexes with CONCURRENTLY ^^^^^^^^^^^^^^^^^^^^^^^^^ The PostgreSQL index option CONCURRENTLY is supported by passing the flag ``postgresql_concurrently`` to the :class:`.Index` construct:: tbl = Table("testtbl", m, Column("data", Integer)) idx1 = Index("test_idx1", tbl.c.data, postgresql_concurrently=True) The above index construct will render DDL for CREATE INDEX, assuming PostgreSQL 8.2 or higher is detected or for a connection-less dialect, as: .. sourcecode:: sql CREATE INDEX CONCURRENTLY test_idx1 ON testtbl (data) For DROP INDEX, assuming PostgreSQL 9.2 or higher is detected or for a connection-less dialect, it will emit: .. sourcecode:: sql DROP INDEX CONCURRENTLY test_idx1 When using CONCURRENTLY, the PostgreSQL database requires that the statement be invoked outside of a transaction block. The Python DBAPI enforces that even for a single statement, a transaction is present, so to use this construct, the DBAPI's "autocommit" mode must be used:: metadata = MetaData() table = Table("foo", metadata, Column("id", String)) index = Index("foo_idx", table.c.id, postgresql_concurrently=True) with engine.connect() as conn: with conn.execution_options(isolation_level="AUTOCOMMIT"): table.create(conn) .. seealso:: :ref:`postgresql_isolation_level` .. _postgresql_index_reflection: PostgreSQL Index Reflection --------------------------- The PostgreSQL database creates a UNIQUE INDEX implicitly whenever the UNIQUE CONSTRAINT construct is used. When inspecting a table using :class:`_reflection.Inspector`, the :meth:`_reflection.Inspector.get_indexes` and the :meth:`_reflection.Inspector.get_unique_constraints` will report on these two constructs distinctly; in the case of the index, the key ``duplicates_constraint`` will be present in the index entry if it is detected as mirroring a constraint. When performing reflection using ``Table(..., autoload_with=engine)``, the UNIQUE INDEX is **not** returned in :attr:`_schema.Table.indexes` when it is detected as mirroring a :class:`.UniqueConstraint` in the :attr:`_schema.Table.constraints` collection . Special Reflection Options -------------------------- The :class:`_reflection.Inspector` used for the PostgreSQL backend is an instance of :class:`.PGInspector`, which offers additional methods:: from sqlalchemy import create_engine, inspect engine = create_engine("postgresql+psycopg2://localhost/test") insp = inspect(engine) # will be a PGInspector print(insp.get_enums()) .. autoclass:: PGInspector :members: .. _postgresql_table_options: PostgreSQL Table Options ------------------------ Several options for CREATE TABLE are supported directly by the PostgreSQL dialect in conjunction with the :class:`_schema.Table` construct: * ``INHERITS``:: Table("some_table", metadata, ..., postgresql_inherits="some_supertable") Table("some_table", metadata, ..., postgresql_inherits=("t1", "t2", ...)) * ``ON COMMIT``:: Table("some_table", metadata, ..., postgresql_on_commit="PRESERVE ROWS") * ``PARTITION BY``:: Table( "some_table", metadata, ..., postgresql_partition_by="LIST (part_column)", ) .. versionadded:: 1.2.6 * ``TABLESPACE``:: Table("some_table", metadata, ..., postgresql_tablespace="some_tablespace") The above option is also available on the :class:`.Index` construct. * ``USING``:: Table("some_table", metadata, ..., postgresql_using="heap") .. versionadded:: 2.0.26 * ``WITH OIDS``:: Table("some_table", metadata, ..., postgresql_with_oids=True) * ``WITHOUT OIDS``:: Table("some_table", metadata, ..., postgresql_with_oids=False) .. seealso:: `PostgreSQL CREATE TABLE options `_ - 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 `_ 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 `_ - in the PostgreSQL documentation. .. _postgresql_table_valued_overview: Table values, Table and Column valued functions, Row and Tuple objects ----------------------------------------------------------------------- PostgreSQL makes great use of modern SQL forms such as table-valued functions, tables and rows as values. These constructs are commonly used as part of PostgreSQL's support for complex datatypes such as JSON, ARRAY, and other datatypes. SQLAlchemy's SQL expression language has native support for most table-valued and row-valued forms. .. _postgresql_table_valued: Table-Valued Functions ^^^^^^^^^^^^^^^^^^^^^^^ Many PostgreSQL built-in functions are intended to be used in the FROM clause of a SELECT statement, and are capable of returning table rows or sets of table rows. A large portion of PostgreSQL's JSON functions for example such as ``json_array_elements()``, ``json_object_keys()``, ``json_each_text()``, ``json_each()``, ``json_to_record()``, ``json_populate_recordset()`` use such forms. These classes of SQL function calling forms in SQLAlchemy are available using the :meth:`_functions.FunctionElement.table_valued` method in conjunction with :class:`_functions.Function` objects generated from the :data:`_sql.func` namespace. Examples from PostgreSQL's reference documentation follow below: * ``json_each()``: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, func >>> stmt = select( ... func.json_each('{"a":"foo", "b":"bar"}').table_valued("key", "value") ... ) >>> print(stmt) {printsql}SELECT anon_1.key, anon_1.value FROM json_each(:json_each_1) AS anon_1 * ``json_populate_record()``: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, func, literal_column >>> stmt = select( ... func.json_populate_record( ... literal_column("null::myrowtype"), '{"a":1,"b":2}' ... ).table_valued("a", "b", name="x") ... ) >>> print(stmt) {printsql}SELECT x.a, x.b FROM json_populate_record(null::myrowtype, :json_populate_record_1) AS x * ``json_to_record()`` - this form uses a PostgreSQL specific form of derived columns in the alias, where we may make use of :func:`_sql.column` elements with types to produce them. The :meth:`_functions.FunctionElement.table_valued` method produces a :class:`_sql.TableValuedAlias` construct, and the method :meth:`_sql.TableValuedAlias.render_derived` method sets up the derived columns specification: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, func, column, Integer, Text >>> stmt = select( ... func.json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}') ... .table_valued( ... column("a", Integer), ... column("b", Text), ... column("d", Text), ... ) ... .render_derived(name="x", with_types=True) ... ) >>> print(stmt) {printsql}SELECT x.a, x.b, x.d FROM json_to_record(:json_to_record_1) AS x(a INTEGER, b TEXT, d TEXT) * ``WITH ORDINALITY`` - part of the SQL standard, ``WITH ORDINALITY`` adds an ordinal counter to the output of a function and is accepted by a limited set of PostgreSQL functions including ``unnest()`` and ``generate_series()``. The :meth:`_functions.FunctionElement.table_valued` method accepts a keyword parameter ``with_ordinality`` for this purpose, which accepts the string name that will be applied to the "ordinality" column: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, func >>> stmt = select( ... func.generate_series(4, 1, -1) ... .table_valued("value", with_ordinality="ordinality") ... .render_derived() ... ) >>> print(stmt) {printsql}SELECT anon_1.value, anon_1.ordinality FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) WITH ORDINALITY AS anon_1(value, ordinality) .. versionadded:: 1.4.0b2 .. seealso:: :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial` .. _postgresql_column_valued: Column Valued Functions ^^^^^^^^^^^^^^^^^^^^^^^ Similar to the table valued function, a column valued function is present in the FROM clause, but delivers itself to the columns clause as a single scalar value. PostgreSQL functions such as ``json_array_elements()``, ``unnest()`` and ``generate_series()`` may use this form. Column valued functions are available using the :meth:`_functions.FunctionElement.column_valued` method of :class:`_functions.FunctionElement`: * ``json_array_elements()``: .. sourcecode:: pycon+sql >>> from sqlalchemy import select, func >>> stmt = select( ... func.json_array_elements('["one", "two"]').column_valued("x") ... ) >>> print(stmt) {printsql}SELECT x FROM json_array_elements(:json_array_elements_1) AS x * ``unnest()`` - in order to generate a PostgreSQL ARRAY literal, the :func:`_postgresql.array` construct may be used: .. sourcecode:: pycon+sql >>> from sqlalchemy.dialects.postgresql import array >>> from sqlalchemy import select, func >>> stmt = select(func.unnest(array([1, 2])).column_valued()) >>> print(stmt) {printsql}SELECT anon_1 FROM unnest(ARRAY[%(param_1)s, %(param_2)s]) AS anon_1 The function can of course be used against an existing table-bound column that's of type :class:`_types.ARRAY`: .. sourcecode:: pycon+sql >>> from sqlalchemy import table, column, ARRAY, Integer >>> from sqlalchemy import select, func >>> t = table("t", column("value", ARRAY(Integer))) >>> stmt = select(func.unnest(t.c.value).column_valued("unnested_value")) >>> print(stmt) {printsql}SELECT unnested_value FROM unnest(t.value) AS unnested_value .. seealso:: :ref:`tutorial_functions_column_valued` - in the :ref:`unified_tutorial` Row Types ^^^^^^^^^ Built-in support for rendering a ``ROW`` may be approximated using ``func.ROW`` with the :attr:`_sa.func` namespace, or by using the :func:`_sql.tuple_` construct: .. sourcecode:: pycon+sql >>> from sqlalchemy import table, column, func, tuple_ >>> t = table("t", column("id"), column("fk")) >>> stmt = ( ... t.select() ... .where(tuple_(t.c.id, t.c.fk) > (1, 2)) ... .where(func.ROW(t.c.id, t.c.fk) < func.ROW(3, 7)) ... ) >>> print(stmt) {printsql}SELECT t.id, t.fk FROM t WHERE (t.id, t.fk) > (:param_1, :param_2) AND ROW(t.id, t.fk) < ROW(:ROW_1, :ROW_2) .. seealso:: `PostgreSQL Row Constructors `_ `PostgreSQL Row Constructor Comparison `_ Table Types passed to Functions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PostgreSQL supports passing a table as an argument to a function, which is known as a "record" type. SQLAlchemy :class:`_sql.FromClause` objects such as :class:`_schema.Table` support this special form using the :meth:`_sql.FromClause.table_valued` method, which is comparable to the :meth:`_functions.FunctionElement.table_valued` method except that the collection of columns is already established by that of the :class:`_sql.FromClause` itself: .. sourcecode:: pycon+sql >>> from sqlalchemy import table, column, func, select >>> a = table("a", column("id"), column("x"), column("y")) >>> stmt = select(func.row_to_json(a.table_valued())) >>> print(stmt) {printsql}SELECT row_to_json(a) AS row_to_json_1 FROM a .. versionadded:: 1.4.0b2 ) annotations) defaultdict) lru_cacheN)Any)cast)List)Optional)Tuple) TYPE_CHECKING)Union)arraylib)json) pg_catalog)ranges) _regconfig_fn)aggregate_order_by)HSTORE)CreateDomainType)CreateEnumType)DOMAIN)DropDomainType) DropEnumType)ENUM) NamedType)_DECIMAL_TYPES) _FLOAT_TYPES) _INT_TYPES)BIT)BYTEA)CIDR)CITEXT)INET)INTERVAL)MACADDR)MACADDR8)MONEY)OID)PGBit)PGCidr)PGInet) PGInterval) PGMacAddr) PGMacAddr8)PGUuid)REGCLASS) REGCONFIG)TIME) TIMESTAMP)TSVECTOR)exc)schema)select)sql)util)characteristics)default) interfaces) ObjectKind) ObjectScope) reflection)URL)ReflectionDefaults) bindparam) coercions)compiler)elements) expression)roles)sqltypes)InsertmanyvaluesSentinelOpts)InternalTraversal)BIGINT)BOOLEAN)CHAR)DATE)DOUBLE_PRECISION)FLOAT)INTEGER)NUMERIC)REAL)SMALLINT)TEXT)UUID)VARCHAR) TypedDictz ^(?:btree|hash|gist|gin|[\w_]+)$>fasdoinisofonortoallandanyascendfornewnotoffoldbothcaserdescelsefromfullintojoinleftlikenullonlyoversomethentrueuserwhenwitharraycheckcrossfalsefetchgrantgroupilikeinnerlimitorderouterrighttableunionusingwherebinarycolumncreateexceptfreezehavingisnulloffsetr8uniquewindowanalyseanalyzebetweencollater<foreignleadingnaturalnotnullplacingprimarysimilarverbosedistinctoverlapstrailingvariadic initially intersect localtime returning symmetric asymmetric constraint deferrable references current_date current_role current_time current_user session_user authorizationcurrent_schemalocaltimestampcurrent_catalogcurrent_timestamp_arrayhstorerjsonb int4range int8rangenumrange daterangetsrange tstzrangeint4multirangeint8multirange nummultirangedatemultirange tsmultirangetstzmultirangeintegerbigintsmallintzcharacter varying characterz"char"nametextnumericfloatrealinetcidrcitextuuidbit bit varyingmacaddrmacaddr8moneyoidregclassdouble precision timestamptimestamp with time zonetimestamp without time zonetime with time zonetime without time zonedatetimebyteabooleanintervaltsvectorceZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d'd Z d'd ZdZdZdZdZdZdZdZdZdZdZdZfdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(xZ)S)( PGCompilerc (|j|fi|SN_assert_pg_ts_extselfelementkws T/opt/hc_python/lib64/python3.12/site-packages/sqlalchemy/dialects/postgresql/base.pyvisit_to_tsvector_funcz!PGCompiler.visit_to_tsvector_func%t%%g444c (|j|fi|Srrrs rvisit_to_tsquery_funcz PGCompiler.visit_to_tsquery_funcrrc (|j|fi|Srrrs rvisit_plainto_tsquery_funcz%PGCompiler.visit_plainto_tsquery_funcrrc (|j|fi|Srrrs rvisit_phraseto_tsquery_funcz&PGCompiler.visit_phraseto_tsquery_funcrrc (|j|fi|Srrrs rvisit_websearch_to_tsquery_funcz*PGCompiler.visit_websearch_to_tsquery_funcrrc (|j|fi|Srrrs rvisit_ts_headline_funcz!PGCompiler.visit_ts_headline_funcrrc t|ts0tjd|jd|jd|j|j |fi|S)NzCan't compile "z()" full text search function construct that does not originate from the "sqlalchemy.dialects.postgresql" package. Please ensure "import sqlalchemy.dialects.postgresql" is called before constructing "sqlalchemy.func.zD()" to ensure registration of the correct argument and return types.) isinstancerr6 CompileErrorrfunction_argspecrs rrzPGCompiler._assert_pg_ts_extso'=1"""7<<.1$ %,LL>2< = ,, 5 5 5g D DEFFrc|jtjur|jrtj}|d|j j j||jS)Nz::)identifier_preparer) _type_affinityrIStringlength STRINGTYPEdialecttype_compiler_instanceprocesspreparer)rtype_ dbapi_typesqltexts rrender_bind_castzPGCompiler.render_bind_castse  $ $ 7J z ->> typer rIJSONrr9rrrrr!r$rs rvisit_json_getitem_op_binaryz'PGCompiler.visit_json_getitem_op_binary s} **(--?"&B 4<< =DD D# ,t,, -FW @B  rc |s\|jjtjur6d|d<|jt j ||jfi|Sd|d<|j||sdndfi|S)NTr$r%z #> z #>> r&r)s r!visit_json_path_getitem_op_binaryz,PGCompiler.visit_json_path_getitem_op_binarys} **(--?"&B 4<< =DD D# ,t,, -FW @B  rc ~|j|jfi|d|j|jfi|dS)N[])rrtrr s rvisit_getitem_binaryzPGCompiler.visit_getitem_binary)s: DLL + + DLL , ,  rc ||j|jfi|d|j|jfi|S)Nz ORDER BY )rtargetorder_byrs rvisit_aggregate_order_byz#PGCompiler.visit_aggregate_order_by/s< DLL .2 . DLL)) 0R 0  rc zd|jvrp|j|jdtj}|rA|j|j fi|d|d|j|j fi|dS|j|j fi|d|j|j fi|dS)Npostgresql_regconfigz @@ plainto_tsquery(, )) modifiersrender_literal_valuerIr rrtr)rrr!r regconfigs rvisit_match_op_binaryz PGCompiler.visit_match_op_binary5s !V%5%5 511  !78(:M:MI DLL33 DLL44 DLL + + DLL , ,  rc <|jj|fi|Sr)r_compiler_dispatchrs r$visit_ilike_case_insensitive_operandz/PGCompiler.visit_ilike_case_insensitive_operandEs1w11$="==rc |jjdd}|j|jfi|d|j|jfi||%d|j |t jzzSdzS)Nescapez ILIKE  ESCAPE r9getrrtrr:rIr rrr!rrAs rvisit_ilike_op_binaryz PGCompiler.visit_ilike_op_binaryHs!!%%h5 DLL + + DLL , , ! 2268;N;NO O      rc |jjdd}|j|jfi|d|j|jfi||%d|j |t jzzSdzS)NrAz NOT ILIKE rBrCrDrFs rvisit_not_ilike_op_binaryz$PGCompiler.visit_not_ilike_op_binaryTs!!%%h5 DLL + + DLL , , ! 2268;N;NO O      rc N|jd}||j|d|zfi|S|dk(r|j|d|zfi|S|j|jfi|d|d|j |t j d|j|jfi|dS) Nflagsz %s iz %s*  z CONCAT('(?', z, ')', r8)r9rrrtr:rIr r)rbase_oprr!rrKs r _regexp_matchzPGCompiler._regexp_match_s  ) =0400(,.  C<0400')-/  DLL + +   % %eX-@-@ A DLL , ,   rc *|jd|||S)N~rOr s rvisit_regexp_match_op_binaryz'PGCompiler.visit_regexp_match_op_binaryps!!#vx<z2PGCompiler.visit_empty_set_expr..sG :E #,,55==!&GIE:sAA z WHERE 1!=1)rsrR)r element_typesrs` rvisit_empty_set_exprzPGCompiler.visit_empty_set_exprs6 II +9wyk9    rcxt|||}|jjr|j dd}|S)N\z\\)superr:r_backslash_escapesreplace)rvaluer __class__s rr:zPGCompiler.render_literal_values6,UE: << * *MM$/E rc *d|j|zS)Nz string_agg%s)r)rfnrs rvisit_aggregate_strings_funcz'PGCompiler.visit_aggregate_strings_funcs 5 5b 999rc >d|jj|zS)Nz nextval('%s'))rformat_sequence)rseqrs rvisit_sequencezPGCompiler.visit_sequences!>!>s!CCCrc d}|j#|d|j|jfi|zz }|j4|j|dz }|d|j|jfi|zz }|S)NrCz LIMIT z LIMIT ALLz OFFSET ) _limit_clauser_offset_clauserr8rrs r limit_clausezPGCompiler.limit_clauses    + L<4<<0D0D#K#KK KD  ,##+& Jf.C.C!Jr!JJ JD rcb|jdk7rtjd|zd|zS)NONLYzUnrecognized hint: %rzONLY )upperr6r)rrrhintiscruds rformat_from_hint_textz PGCompiler.format_from_hint_texts2 ::<6 !""#:T#AB B  rc |js |jrM|jr@ddj|jDcgc]}|j|fi|c}zdzSyycc}w)Nz DISTINCT ON (r7z) z DISTINCT rC) _distinct _distinct_onrsr)rr8rcols rget_select_precolumnsz PGCompiler.get_select_precolumnss   v22""#ii(.':':':)DLL33': #sA' c `|jjr|jjrd}nd}n|jjrd}nd}|jjrt j }|jjD]&}|j tj|(t|j dd|dd jfd |Dzz }|jjr|d z }|jjr|d z }|S) Nz FOR KEY SHAREz FOR SHAREz FOR NO KEY UPDATEz FOR UPDATETF)ashint use_schemaz OF r7c3DK|]}j|fiywr)r)r]rof_kwrs rr^z/PGCompiler.for_update_clause..s%&:@  U,e,&s z NOWAITz SKIP LOCKED) _for_update_argread key_sharer^r: OrderedSetupdatesql_utilsurface_selectables_onlydictrsnowait skip_locked)rr8rtmptablescrs` @rfor_update_clausezPGCompiler.for_update_clauses   ! ! & &%%//&"  # # - -&CC  ! ! $ $__&F++.. h??BC/HE LLL 7 6DII&:@& C  ! ! ( ( 9 C  ! ! - - > !C rc l|j|jjdfi|}|j|jjdfi|}t|jjdkDr6|j|jjdfi|}d|d|d|dSd|d|dS)Nrr z SUBSTRING(z FROM z FOR r8)rclauseslen)rfuncrsrr s rvisit_substring_funczPGCompiler.visit_substring_funcs DLL--a0 7B 7 T\\11!4;; t||## $q (!T\\$,,"6"6q"9@R@F56vF F )/07 7rc B|j*djj|jz}|S|jYddj fd|jDz}|j $|dj |j ddzz }|Sd}|S) NzON CONSTRAINT %s(%s)r7c3K|]C}t|trjj|nj |ddEyw)F include_tablerN)rstrrquoter)r]rrs rr^z1PGCompiler._on_conflict_target..sP- 9A"!S)MM''*auOP9sA A  WHERE %sFrrC)constraint_targetr#truncate_and_render_constraint_nameinferred_target_elementsrsinferred_target_whereclauser)rclauser target_texts` r_on_conflict_targetzPGCompiler._on_conflict_targets  # # /#--CC,, 0% , , 8 499-  88 -$K11={T\\66"'$.:.  Krc 8|j|fi|}|rd|zSy)NzON CONFLICT %s DO NOTHINGzON CONFLICT DO NOTHING)r)r on_conflictrrs rvisit_on_conflict_do_nothingz'PGCompiler.visit_on_conflict_do_nothing s*.d..{AbA .< <+rc n|}|j|fi|}g}t|j}|jdd}|jj }|D]!} | j } | |vr|j| } n| |vr|j| } n=tj| r#tjd| | j} nQt| tjr7| jjr!| j} | j| _ |j!| j#d} |j$j'| j(} |j+| d| $|rt-j.d|j0jj(dd j3d |D|j5D]\}}t|t6r|j$j'|n|j!|d} |j!tj8t:j<|d} |j+| d| d j3|}|j>$|d |j!|j>d d zz }d|d|S)N selectablerF)rz = z?Additional column names not matching any column keys in table 'z': r7c3&K|] }d|z yw)z'%s'N)r]rs rr^z9PGCompiler.visit_on_conflict_do_update..AsB>avz>srTrz ON CONFLICT z DO UPDATE SET ) rrupdate_values_to_setstackrrkeypoprD _is_literalrF BindParameterr'rr\_cloner self_grouprrrappendr:warncurrent_executablersitemsrexpectrHExpressionElementRoleupdate_whereclause)rrrrraction_set_opsset_parametersinsert_statementcolsrcol_keyrf value_textkey_textkv action_texts rvisit_on_conflict_do_updatez&PGCompiler.visit_on_conflict_do_updatesk.d..{AbA f99: ::b>,7%%''AeeG.(&**73n$&**1-$$U+ ..tU!&&Iuh&<&<= **!LLNE!"EJe&6&6&8UKJ}}**1662H  ! !x"D E38  II++1166YYB>BB  ',,.1"!S)MM''*aE: "\\$$U%@%@!D$* %%8Z&HI/ii/  $ $ 0 ;))%*6* K5@MMrc Pdd<ddjfd|DzS)NTasfromzFROM r7c3HK|]}|jfdiyw fromhintsNr>r]t from_hintsrrs rr^z0PGCompiler.update_from_clause..\s0#   !A  B Br B "rs)r update_stmt from_table extra_fromsrrs` ``rupdate_from_clausezPGCompiler.update_from_clauseXs38 #  #    rc Pdd<ddjfd|DzS)z9Render the DELETE .. USING clause specific to PostgreSQL.TrzUSING r7c3HK|]}|jfdiywrrrs rr^z6PGCompiler.delete_extra_from_clause..fs0$   !A  B Br B rr)r delete_stmtrrrrs` ``rdelete_extra_from_clausez#PGCompiler.delete_extra_from_clauseas38 $))$  $    rc d}|j#|d|j|jfi|zz }|jK|d|j|jfi|d|jdrdndd|jdrd nd z }|S) NrCz OFFSET (%s) ROWSz FETCH FIRST (r8percentz PERCENTz ROWS with_tiesz WITH TIESru)rqr _fetch_clause_fetch_clause_optionsrrs r fetch_clausezPGCompiler.fetch_clauseks  , )LDLL%%-)+- D    +  V118R8$::9E 2M33K@   D rF)*__name__ __module__ __qualname__rrrrrrrrrrr"r*r,r0r4r<r?rGrIrOrSrUrYr`r:rjrnrsryr~rrrrrrrr __classcell__rgs@rrrs555555G*  B B/4 "/4     >     "=>  :D! (:8B,CNJ  rrceZdZdZdZfdZfdZdZdZdZ dZ d Z d Z d Z d Zd ZdZfdZdZdZdZxZS) PGDDLCompilerc |jj|}|jj|j}t |t jr |j}|jduxr|jj}|jr||jjur|jjst |t js|s|j :t |j t"j$r\|j j&rFt |t j(r|dz }nt |t jr|dz }nc|dz }n]|d|jj*j-|j||jzz }|j/|}||d|zz }|j0!|d|j-|j0zz }|r!|d|j-|jzz }|j2s |s|dz }|S|j2r|r|dz }|S) Nz BIGSERIALz SMALLSERIALz SERIALrM)type_expressionr z DEFAULT z NOT NULLz NULL)r format_columnr' dialect_implrrrI TypeDecoratorimplidentitysupports_identity_columns primary_keyr_autoincrement_columnsupports_smallserial SmallIntegerr<r7Sequenceoptional BigIntegerrrget_column_default_stringcomputednullable)rrkwargscolspec impl_type has_identityr<s rget_column_specificationz&PGDDLCompiler.get_column_specifications----f5KK,,T\\: i!7!7 8!I OO4 ' 7 66    &,,<<< 11!)X-B-BC &v~~v?//)X%8%89<'Ix'<'<=>)9$ sT\\@@HH &$(MMI G 44V.s7$A!!))#++a.)M$s:=r8)rr format_typersenums)rrrrs` rvisit_create_enum_typez$PGDDLCompiler.visit_create_enum_typesG MM % %e , II   rc V|j}d|jj|zS)Nz DROP TYPE %srrr)rdroprrs rvisit_drop_enum_typez"PGDDLCompiler.visit_drop_enum_types% !:!:5!ABBrc |j}g}|j7|jd|jj |j|j /|j |j }|jd||j9|jj|j}|jd||jr|jd|j=|jj|jdd}|jd|d d |jj|d |jj|jd d j!|S) NzCOLLATE zDEFAULT z CONSTRAINT zNOT NULLFTrrzCHECK (r8zCREATE DOMAIN z AS rM)r collationrrrr<render_default_stringconstraint_namernot_nullrrrr type_compiler data_typers)rrrdomainoptionsr<rrs rvisit_create_domain_typez&PGDDLCompiler.visit_create_domain_typesa    ' NNXdmm&9&9&:J:J&K%LM N >> %00@G NNXgY/ 0  ! ! -==DD&&D NN[/ 0 ?? NN: & << #%%-- E.E NNWUG1- .T]]66v>?t!!))&*:*:;j@|}|j j#|dd}|d |zz }|Scc} wcc} wcc} wcc}w)!NzCREATE zUNIQUE zINDEX r concurrently CONCURRENTLY zIF NOT EXISTS Finclude_schema ON rMrz USING %s opsrr7Tr%rrCincludez INCLUDE (%s)nulls_not_distinctz NULLS NOT DISTINCTz NULLS DISTINCTr~z WITH (%s)z%s = %s tablespacez TABLESPACE %srz WHERE )!rr_verify_index_tablerr#_supports_create_index_concurrentlyr if_not_exists_prepared_index_name format_tablervalidate_sql_phrase IDX_USINGlowerrs expressionsrrrrG ColumnClauserhasattrrrrrrrrDrrHDDLExpressionRole)rrrrindexrr2rr7expr includeclauser} inclusionsrr9 withclausestorage_parametertablespace_name whereclausewhere_compileds rvisit_create_indexz PGDDLCompiler.visit_create_index s==   ' << I D  << ; ; 00>~NL'    $ $D  % %eE % B  ! !%++ .   %%l3G<  --33E9EKKMN D ##L1%8  II !& 1 1!2%%--$.dJ4K4K#L!OO-!%&+&*.#4/DHHOs488}, !2   ,--l;IF )(C'1c&: c"C(  Odii1;<A'<' D#22<@    % ) )D 5 ( % %D**<8@  L 2<1A1A1C1C-"$551C D // =lK  $x~~o'FF FD++L9'B  "#**''K"..6657N I. .D A, =s,A>L9 2L>"M  M c N|jdd}|durd}|S|durd}|Sd}|S)Nrr9TzNULLS NOT DISTINCT FzNULLS DISTINCT rCr)rrrr9nulls_not_distinct_params r!define_unique_constraint_distinctz/PGDDLCompiler.define_unique_constraint_distinctf sY'77 E    %'< $ ('  5 ('8 $('(* $''rc |j}d}|jjr|jdd}|r|dz }|jr|dz }||j |dz }|S)Nz DROP INDEX rr2r3z IF EXISTS Tr4)rr!_supports_drop_index_concurrentlyr if_existsr>)rr"rrGrr2s rvisit_drop_indexzPGDDLCompiler.visit_drop_indexr so  << 9 9 00>~NL' >> L D ))%)EE rc d}|j!|d|jj|zz }g}d|d<d|d<|jD]}\}}}|jj |fi|t |dr4|j|jvrd|j|jzndz}|j|d ||d |jj|jtjd d j|d z }|j-|d|jj |jdzz }||j!|z }|S)NrCzCONSTRAINT %s FrTrrrMz WITH zEXCLUDE USING z (r7r8z WHERE (%s)r)rrformat_constraint _render_exprsrrrErr7rr@rrArBrsrdefine_constraint_deferrability) rrrrrFrHropexclude_elements rvisit_exclude_constraintz&PGDDLCompiler.visit_exclude_constraint sx ?? & $t}}'F'F( D#?"?(66ND$7d//77CC4'DHH ,Fz~~dhh//O HOOOR@ A7 MM - -  ) eg  IIh        ' MD$5$5$=$=  %>% D 44Z@@ rcg}|jd}|jd}|Ht|ttfs|f}|j ddj fd|Dzdz|dr|j d|dz|d r|j d |d z|d d ur|j d n|d dur|j d|dr7|djddj}|j d|z|dr2|d}|j djj|zdj |S)Nrinheritsz INHERITS ( r7c3TK|]}jj|!ywr)rr)r]rrs rr^z2PGDDLCompiler.post_create_table.. s!K($DMM//5(s%(z ) partition_byz PARTITION BY %srz USING %s with_oidsTz WITH OIDSFz WITHOUT OIDS on_commit_rMz ON COMMIT %sr:z TABLESPACE %srC) rrErr tuplerrsrervrr)rr table_optspg_optsr`on_commit_optionsrMs` rpost_create_tablezPGDDLCompiler.post_create_table sr '' 5;;z*  hu 6$;    ))K(KKL  > "   2W^5LL M 7    mgg.>> ? ; 4 '   n - [ !U *   / 0 ;  ' 4 < > # # / 2 2 : :((!Fw,VIFIbIIrc|j}|jtjd|d|jtjd|dy)Nz%Can't emit COMMENT ON for constraint z: it has no namez: it has no associated table)rrr6rr)r ddl_instancers r_can_comment_on_constraintz(PGDDLCompiler._can_comment_on_constraint st!)) ?? """7 ~F!!     #""7 ~F--  $rc Z|j|d|jj|jd|jj |jj d|j j|jjtjS)NCOMMENT ON CONSTRAINT r6z IS ) rtrrYrr?rrr:commentrIr )rrrs rvisit_set_constraint_commentz*PGDDLCompiler.visit_set_constraint_comment sv ''/ MM + +FNN ; MM & &v~~';'; <    2 2&&(9   rc |j|d|jj|jd|jj |jj dS)Nrvr6z IS NULL)rtrrYrr?r)rr"rs rvisit_drop_constraint_commentz+PGDDLCompiler.visit_drop_constraint_comment sL ''- MM + +DLL 9 MM & &t||'9'9 :  r)rrrrr rrrr#r.r0rPrSrWr^rjrnrqrtrxrzrrs@rrrsd4l1$  C  8BaF ( <##J  J   rrc4eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"fd!Z#d/d"Z$d/d#Z%d$Z&d%Z'd&Z(d'Z)fd(Z*d)Z+d*Z,d+Z-d,Z.d-Z/d.Z0xZ1S)0PGTypeCompilerc y)Nr4rrrrs rvisit_TSVECTORzPGTypeCompiler.visit_TSVECTOR rc y)NTSQUERYrr~s r visit_TSQUERYzPGTypeCompiler.visit_TSQUERY rc y)Nr#rr~s r visit_INETzPGTypeCompiler.visit_INET rc y)Nr!rr~s r visit_CIDRzPGTypeCompiler.visit_CIDR rrc y)Nr"rr~s r visit_CITEXTzPGTypeCompiler.visit_CITEXT rc y)Nr%rr~s r visit_MACADDRzPGTypeCompiler.visit_MACADDR rrc y)Nr&rr~s rvisit_MACADDR8zPGTypeCompiler.visit_MACADDR8 rrc y)Nr'rr~s r visit_MONEYzPGTypeCompiler.visit_MONEY rc y)Nr(rr~s r visit_OIDzPGTypeCompiler.visit_OID rc y)Nr1rr~s rvisit_REGCONFIGzPGTypeCompiler.visit_REGCONFIG rc y)Nr0rr~s rvisit_REGCLASSzPGTypeCompiler.visit_REGCLASS rrc >|jsydd|jizS)NrQzFLOAT(%(precision)s) precision)rr~s r visit_FLOATzPGTypeCompiler.visit_FLOAT s )[%//,JJ Jrc 0|jtfi|Sr)visit_DOUBLE_PRECISIONr'r~s r visit_doublezPGTypeCompiler.visit_double! s*t**46266rc y)NrLrr~s r visit_BIGINTzPGTypeCompiler.visit_BIGINT$ rrc y)Nrrr~s r visit_HSTOREzPGTypeCompiler.visit_HSTORE' rrc y)Nr(rr~s r visit_JSONzPGTypeCompiler.visit_JSON* rrc y)NJSONBrr~s r visit_JSONBzPGTypeCompiler.visit_JSONB- rrc y)NINT4MULTIRANGErr~s rvisit_INT4MULTIRANGEz#PGTypeCompiler.visit_INT4MULTIRANGE0 rc y)NINT8MULTIRANGErr~s rvisit_INT8MULTIRANGEz#PGTypeCompiler.visit_INT8MULTIRANGE3 rrc y)N NUMMULTIRANGErr~s rvisit_NUMMULTIRANGEz"PGTypeCompiler.visit_NUMMULTIRANGE6 src y)NDATEMULTIRANGErr~s rvisit_DATEMULTIRANGEz#PGTypeCompiler.visit_DATEMULTIRANGE9 rrc y)N TSMULTIRANGErr~s rvisit_TSMULTIRANGEz!PGTypeCompiler.visit_TSMULTIRANGE< src y)NTSTZMULTIRANGErr~s rvisit_TSTZMULTIRANGEz#PGTypeCompiler.visit_TSTZMULTIRANGE? rrc y)N INT4RANGErr~s rvisit_INT4RANGEzPGTypeCompiler.visit_INT4RANGEB rrc y)N INT8RANGErr~s rvisit_INT8RANGEzPGTypeCompiler.visit_INT8RANGEE rrc y)NNUMRANGErr~s rvisit_NUMRANGEzPGTypeCompiler.visit_NUMRANGEH rrc y)N DATERANGErr~s rvisit_DATERANGEzPGTypeCompiler.visit_DATERANGEK rrc y)NTSRANGErr~s r visit_TSRANGEzPGTypeCompiler.visit_TSRANGEN rrc y)N TSTZRANGErr~s rvisit_TSTZRANGEzPGTypeCompiler.visit_TSTZRANGEQ rrc y)NINTrr~s rvisit_json_int_indexz#PGTypeCompiler.visit_json_int_indexT rrc y)NrVrr~s rvisit_json_str_indexz#PGTypeCompiler.visit_json_str_indexW rrc (|j|fi|Sr)visit_TIMESTAMPr~s rvisit_datetimezPGTypeCompiler.visit_datetimeZ s#t##E0R00rc |jr|jjst||fi|S|j |fi|Sr)rrsupports_native_enumrc visit_enum visit_ENUMrrrrgs rrzPGTypeCompiler.visit_enum] sC   (I(I7%e2r2 2"4??5/B/ /rc T||jj}|j|Srrr rrrr rs rrzPGTypeCompiler.visit_ENUMc )  &"&,,"B"B "..u55rc T||jj}|j|Srrrs r visit_DOMAINzPGTypeCompiler.visit_DOMAINh rrc tdt|ddd|jzndd|jxrdxsddzS) Nr3r(%d)rCrMWITHWITHOUT TIME ZONEgetattrrtimezoner~s rrzPGTypeCompiler.visit_TIMESTAMPm K5+t4@(^^ & 3)| C   rc tdt|ddd|jzndd|jxrdxsddzS) Nr2rrrCrMrrrrr~s r visit_TIMEzPGTypeCompiler.visit_TIMEw rrc d}|j|d|jzz }|j|d|jzz }|S)Nr$rMz (%d))fieldsr)rrrrs rvisit_INTERVALzPGTypeCompiler.visit_INTERVAL sF << # C%,,& &D ?? & Geoo- -D rc |jr"d}|j|d|jzz }|Sd|jz}|S)Nz BIT VARYINGrzBIT(%d))varyingr )rrrcompileds r visit_BITzPGTypeCompiler.visit_BIT sG ==$H||'FU\\11!5<</Hrc b|jr|j|fi|St| |fi|Sr) native_uuid visit_UUIDrc visit_uuidrs rrzPGTypeCompiler.visit_uuid s7   "4??5/B/ /7%e2r2 2rc y)NrWrr~s rrzPGTypeCompiler.visit_UUID rrc (|j|fi|Sr) visit_BYTEAr~s rvisit_large_binaryz!PGTypeCompiler.visit_large_binary st,,,rc y)Nr rr~s rrzPGTypeCompiler.visit_BYTEA rrc |j|jfi|}tjddd|j |jndzz|dS)Nz((?: COLLATE.*)?)$z%s\1z[]r )count)rrresub dimensions)rrrrs r visit_ARRAYzPGTypeCompiler.visit_ARRAY s^ U__33vv !+0+;+;+Gu''QP   rc (|j|fi|Sr)visit_JSONPATHr~s rvisit_json_pathzPGTypeCompiler.visit_json_path s"t""5/B//rc y)NJSONPATHrr~s rrzPGTypeCompiler.visit_JSONPATH rrr)2rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrs@rr|r| sK 7    10 6 6   3 -  0rr|ceZdZeZdZddZy)PGIdentifierPreparerc||d|jk(r)|ddj|j|j}|S)Nrr r) initial_quotereescape_to_quote escape_quote)rrfs r_unquote_identifierz(PGIdentifierPreparer._unquote_identifier sB 8t)) )!BK''$$d&7&7E rc|js-tjd|jjd|j |j}|j |}|js|r||j|d|}|S)Nz PostgreSQL z type requires a name..) rr6rrgrrschema_for_object omit_schema quote_schema)rrrreffective_schemas rrz PGIdentifierPreparer.format_type szz""eoo6677MN zz%**%11%8   ,''(89:!D6BD rN)T)rrrRESERVED_WORDSreserved_wordsrrrrrr r  s#Nrr c4eZdZUdZded< ded< ded<y)ReflectedNamedTypez"Represents a reflected named type.rrr7boolvisibleNrrr__doc____annotations__rrrrr s, I K! M?rrc(eZdZUdZded< ded<y)ReflectedDomainConstraintz2Represents a reflect check constraint of a domain.rrrNrrrrr r  s< I! J$rr cLeZdZUdZded< ded< ded< ded < ded <y ) ReflectedDomainRepresents a reflected enum.rr'rr Optional[str]r<zList[ReflectedDomainConstraint] constraintsr&Nrrrrr"r" s8& IDN5 10'rr"ceZdZUdZded<y) ReflectedEnumr# List[str]labelsNrrrrr'r' s& +rr'cveZdZUded< d d dZ d d dZd d dZ d d dZ d ddZy) PGInspector PGDialectrNc|j5}|jj||||jcdddS#1swYyxYw)aQReturn the OID for the given table name. :param table_name: string name of the table. For special quoting, use :class:`.quoted_name`. :param schema: string schema name; if omitted, uses the default schema of the database connection. For special quoting, use :class:`.quoted_name`.  info_cacheN)_operation_contextr get_table_oidr/)r table_namer7conns rr1zPGInspector.get_table_oid sB $ $ &$<<--j&T__.' & & )AA c|j5}|jj|||jcdddS#1swYyxYw)aReturn a list of DOMAIN objects. Each member is a dictionary containing these fields: * name - name of the domain * schema - the schema name for the domain. * visible - boolean, whether or not this domain is visible in the default search path. * type - the type defined by this domain. * nullable - Indicates if this domain can be ``NULL``. * default - The default value of the domain or ``None`` if the domain has no default. * constraints - A list of dict wit the constraint defined by this domain. Each element constaints two keys: ``name`` of the constraint and ``check`` with the constraint text. :param schema: schema name. If None, the default schema (typically 'public') is used. May also be set to ``'*'`` to indicate load domains for all schemas. .. versionadded:: 2.0 r.N)r0r _load_domainsr/rr7r3s r get_domainszPGInspector.get_domains s@4 $ $ &$<<--f.' & & (AA c|j5}|jj|||jcdddS#1swYyxYw)a.Return a list of ENUM objects. Each member is a dictionary containing these fields: * name - name of the enum * schema - the schema name for the enum. * visible - boolean, whether or not this enum is visible in the default search path. * labels - a list of string labels that apply to the enum. :param schema: schema name. If None, the default schema (typically 'public') is used. May also be set to ``'*'`` to indicate load enums for all schemas. r.N)r0r _load_enumsr/r7s r get_enumszPGInspector.get_enums6 s@  $ $ &$<<++f,' & &r9c|j5}|jj|||jcdddS#1swYyxYw)zReturn a list of FOREIGN TABLE names. Behavior is similar to that of :meth:`_reflection.Inspector.get_table_names`, except that the list is limited to those tables that report a ``relkind`` value of ``f``. r.N)r0r_get_foreign_table_namesr/r7s rget_foreign_table_namesz#PGInspector.get_foreign_table_namesK s@ $ $ &$<<88f9' & &r9c |j5}|jj||||jcdddS#1swYyxYw)aJReturn if the database has the specified type in the provided schema. :param type_name: the type to check. :param schema: schema name. If None, the default schema (typically 'public') is used. May also be set to ``'*'`` to check in all schemas. .. versionadded:: 2.0 r.N)r0rhas_typer/)r type_namer7rr3s rrAzPGInspector.has_type[ sB $ $ &$<<((iDOO)' & &r4r)r2rr7r$returnint)r7r$rCzList[ReflectedDomain])r7r$rCzList[ReflectedEnum])r7r$rCr()rBrr7r$rrrCr) rrrrr1r8r<r?rArrrr+r+ s 8<'4 ('+# >,'+# "7;&3BE rr+c$eZdZdZfdZxZS)PGExecutionContextc^|jd|jj|z|S)Nzselect nextval('%s'))_execute_scalarr rl)rrmrs r fire_sequencez PGExecutionContext.fire_sequencep s7##&**::3?@    rc `|jr||jjur|jrI|jjr3|j d|jj z|jS|j,|jjr|jjro |j}|j&|j j#|j}nd}| d|d|d}nd|d}|j ||jSt$|M|S#t$rr|jj}|j}|ddtddt|z z}|ddtddt|z z}|d|d}|x|_ }YwxYw) Nz select %srre_seqzselect nextval('"z"."z"'))rrrserver_default has_argumentrHargr'r< is_sequencer_postgresql_seq_nameAttributeErrorrmaxr connectionrrcget_insert_default) rrseq_nametabr}rrr6rgs rrUz%PGExecutionContext.get_insert_defaulty s   &FLL,N,N"N$$)>)>)K)K++&"7"7";";;V[['**v~~/F/F B%::H<<+'+'H'H ($(,$#/( C0 9ABC++C==w)&113&B ,,++C ++Ca"s1rCH}'>">?Ca"s1rCH}'>">?C*-s3D=AAF/( Bs5 D22A8F-,F-)rrrrIrUrrs@rrFrFo s *2*2rrFc"eZdZdZdZdZdZy)"PGReadOnlyConnectionCharacteristicTc(|j|dyNF set_readonlyrr dbapi_conns rreset_characteristicz7PGReadOnlyConnectionCharacteristic.reset_characteristic Z/rc(|j||yrr\rrr_rfs rset_characteristicz5PGReadOnlyConnectionCharacteristic.set_characteristic rarc$|j|Sr) get_readonlyr^s rget_characteristicz5PGReadOnlyConnectionCharacteristic.get_characteristic s##J//rNrrr transactionalr`rdrgrrrrYrY sM000rrYc"eZdZdZdZdZdZy)$PGDeferrableConnectionCharacteristicTc(|j|dyr[set_deferrabler^s rr`z9PGDeferrableConnectionCharacteristic.reset_characteristic z51rc(|j||yrrmrcs rrdz7PGDeferrableConnectionCharacteristic.set_characteristic rorc$|j|Sr)get_deferrabler^s rrgz7PGDeferrableConnectionCharacteristic.get_characteristic s%%j11rNrhrrrrkrk sM222rrkc eZdZdZdZdZdZdZejjZ dZ dZ dZdZdZdZdZdZdZdZej.ej0zej2zZdZdZdZdZdZdZ dZ!dZ"e#Z#e$Z$e%Z&e'Z(e)Z*e+Z,e-Z.e/Z0dZ1dZ2dZ3dZ4dZ5e6jnjpZ8e8jse:e;dZ8ee|jfd2e|jfd?e|jfd@Ze\dAZdBZeWjd]dCZdDZeWj d`dEZe\dFZejdGZ dadHZeWjd]dIZejdJZdKZeWj d]dLZdMZeWjd]dNZe\dOZdPZeWjd]dQZe\dRZdSZdTZe\dUZeWjd]dVZe\dWZeWjd]dXZdYZxZS)br,rT?Fpyformat)postgresql_readonlypostgresql_deferrableN)rr8rr7r2r~r:r9)ignore_search_pathr:rbrcrdr`rrr9)postgresql_ignore_search_pathc ntjj|fi|||_||_||_yr)r<DefaultDialect__init___native_inet_types_json_deserializer_json_serializer)rnative_inet_typesjson_serializerjson_deserializerrs rr|zPGDialect.__init__8 s5 ''77"3"3 /rct|||jdk\|_|j ||jdk\|_|jdk\|_y)N) r )rc initializeserver_version_infor_set_backslash_escapesrUr)rrTrgs rrzPGDialect.initializeE sa :&%)$<$<$F! ##J/151I1IN 2 .*.)A)AU)J&rcy)N) SERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READr)rr_s rget_isolation_level_valuesz$PGDialect.get_isolation_level_valuesS s rc|j}|jd||jd|jy)Nz;SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL COMMIT)cursorexecuteclose)rdbapi_connectionlevelrs rset_isolation_levelzPGDialect.set_isolation_level] sB!((* $g '  x  rc|j}|jd|jd}|j|j S)Nz show transaction isolation levelr)rrfetchonerrv)rrrvals rget_isolation_levelzPGDialect.get_isolation_levelf sC!((*9:oo" yy{rctrNotImplementedErrorrrTrfs rr]zPGDialect.set_readonlym !##rctrrrrTs rrfzPGDialect.get_readonlyp rrctrrrs rrnzPGDialect.set_deferrables rrctrrrs rrrzPGDialect.get_deferrablev rrcLd}d}d}d|jvr:t|jdttfr@d}t |jdDcgc]}d|vr|j dn|dfc}\}}nt|jdt rt|jdj d}d|jvrt|dk(rwd|dvrptjd |d}|rUd}|jdd \}}tr$t|t sJt|t sJ|f}td |r|fnd }d|jvr|rtjd t|jdttfr|jd}nDt|jdt r't|jdj d}d} |r td|D} | r\|st| dkDs7|rJ| rHt|t| k7r1t|dkDst| dkDrtjd|| td|D} || fScc}w#t$rtjd|dwxYw)NFhostTr,portr rz ^([a-zA-Z0-9\-\.]*)(?:\:(\d*))?$rzTuple[Optional[str], ...]rzzCan't mix 'multihost' formats together; use "host=h1,h2,h3&port=p1,p2,p3" or "host=h1:p1&host=h2:p2&host=h3:p3" separatelyc3:K|]}|r t|ndywr)rD)r]xs rr^z6PGDialect._split_multihost_from_url.. sGYc!ft3Ysz%Received non-integer port arguments: z%number of hosts and ports don't matchc3 K|]}dywrr)r]res rr^z6PGDialect._split_multihost_from_url.. s2EqdEs )queryrr rfzipsplitrrrmatchrr rr6 ArgumentError ValueError) rurlhosts ports_strintegrated_multihosttokenhost_port_matchhpportss r_split_multihost_from_urlz#PGDialect._split_multihost_from_urly s6:AE $ SYY #))F+dE];'+$#&&)YYv%6%6E-05L C(udmK%6$ yCIIf-s3cii/55c:;#))+E auQx ')hh;U1X'O'/3,.44Q:1(#-a#55#5#-a#55#5!"$(7!%  SYY #''D #))F+dE];IIf- CIIf-s3!#))F"3"9"9#">? 59  GYGG 3u:>J#e*,Z!^s5zA~##$KL L  }2E22e|Kb '';I;G s I;1J#J#c:|j|jyr)do_beginrTrrTxids rdo_begin_twophasezPGDialect.do_begin_twophase s j++,rc,|jd|zy)NzPREPARE TRANSACTION '%s')exec_driver_sqlrs rdo_prepare_twophasezPGDialect.do_prepare_twophase s""#=#CDrc|rT|r|jd|jd|z|jd|j|jy|j|jy)NROLLBACKzROLLBACK PREPARED '%s'BEGIN)r do_rollbackrTrrTr is_preparedrecovers rdo_rollback_twophasezPGDialect.do_rollback_twophase sd  **:6  & &'?#'E F  & &w /   Z22 3   Z22 3rc|rT|r|jd|jd|z|jd|j|jy|j|jy)NrzCOMMIT PREPARED '%s'r)rrrT do_commitrs rdo_commit_twophasezPGDialect.do_commit_twophase s` **:6  & &'='C D  & &w /   Z22 3 NN:00 1rcf|jtjdjS)Nz!SELECT gid FROM pg_prepared_xacts)scalarsr9rrbrs rdo_recover_twophasezPGDialect.do_recover_twophase s)!! HH8 9 #% rc@|jdjS)Nzselect current_schema())rscalarrs r_get_default_schema_namez"PGDialect._get_default_schema_name s))*CDKKMMrc ttjjjj tjjj|k(}t |j|Sr)r8r pg_namespacernspnamerrr)rrTr7rrs r has_schemazPGDialect.has_schema s[z..00889??  # # % % - - 7 J%%e,--rc|tj}|jtjtjjj |jj k(}|tjur)|j|jjdk7}n:|tjur(|j|jjdk(}|`|jtj|jj tjjjdk7}|S|jtjjj|k(}|S)Nrr)rpg_classrsrrr relnamespacer?DEFAULTrrelpersistence TEMPORARYpg_table_is_visibler)rrr7scopepg_class_tables r_pg_class_filter_scope_schemaz'PGDialect._pg_class_filter_scope_schema s(  !'00N  # #  # # % % ) )^-=-=-J-J J  K'' 'KK 0 0 ? ?3 FGE k++ +KK 0 0 ? ?3 FGE >KK..~/?/?/C/CD''))11\AE KK 7 7 9 9 A AV KLE rc|tj}|jjt j t j|k(Sr)rrrrelkindr9any_rr)rrelkindsrs r_pg_class_relkind_conditionz%PGDialect._pg_class_relkind_condition s>  !'00N''388FLL4J+KKKrcVttjjjj tjjjt dk(|jtj}|j||tjS)Nr2r) r8rrrrelnamerrCrRELKINDS_ALL_TABLE_LIKErr?ANY)rr7rs r_has_table_queryzPGDialect._has_table_query sz**,,445;;    ! ! ) )Y|-D D  , ,22   11 62  rc |j||j|}t|j|d|iS)Nr2)_ensure_has_table_connectionrrr)rrTr2r7rrs r has_tablezPGDialect.has_table* s= ))*5%%f-J%%elJ-GHIIrc ttjjjj tjjj dk(tjjj|k(}|j||tj}t|j|S)NSr) r8rrrrrrrr?rrr)rrT sequence_namer7rrs r has_sequencezPGDialect.has_sequence0 sz**,,445;;    ! ! ) )S 0    ! ! ) )] : 22 63 J%%e,--rc ttjjjj tj tj jjtjjjk(jtjjj|k(}|m|jtjtjjjtj jjdk7}n;|dk7r6|jtj jj|k(}t|j|SNr*)r8rpg_typertypnamersrr typnamespacerpg_type_is_visiblerrr)rrTrBr7rrs rrAzPGDialect.has_type; s :%%''// 0 T''''))--%%''445 U:%%''//9< =  >KK--j.@.@.B.B.F.FG''))11\AE s]KK 7 7 9 9 A AV KLEJ%%e,--rc|jdj}tjd|}|st d|zt |j dddDcgc]}|t|c}Scc}w)Nzselect pg_catalog.version()zQ.*(?:PostgreSQL|EnterpriseDB) (\d+)\.?(\d+)?(?:\.(\d+))?(?:\.\d+)?(?:devel|beta)?z,Could not determine version from string '%s'r rr5)rrrrAssertionErrorrfrrD)rrTrmrs r_get_server_version_infoz"PGDialect._get_server_version_infoQ s  & &'D E L L N HH C    >B aggaA&6H&6!-c!f&6HIIHs A<( A<c ttjjjj tjjj |k(|jtj}|j||tj}|j|}|"tj|r |d|||S)z$Fetch the oid for schema.table_name.rr)r8rrrrrrrrrr?rrr6NoSuchTableError)rrTr2r7rr table_oids rr1zPGDialect.get_table_oid^ sz**,,00177    ! ! ) )Z 7  , ,22   22 63 %%e,  &&,26(!J<( 8B rc |ttjjjj tjjjj djtjjj}|j|jS)Nzpg_%) r8rrrrrnot_liker3rrb)rrTrrs rget_schema_nameszPGDialect.get_schema_namesq s :**,,44 5 U:**,,44==fE F Xj--//77 8  !!%(,,..rcttjjjj |j |}|j|||}|j|jSNr) r8rrrrrrrrrb)rrTr7rrrs r_get_relnames_for_relkindsz$PGDialect._get_relnames_for_relkindsz sjz**,,445;;  , ,X 6 225&2N!!%(,,..rc d|j||tjtjSr)rrRELKINDS_TABLE_NO_FOREIGNr?rrrTr7rs rget_table_nameszPGDialect.get_table_names s2..    0 0%% /  rc d|j|dtjtjS)N)r7rr)rrrr?r)rrTrs rget_temp_table_nameszPGDialect.get_temp_table_names s2.. 99'' /  rc H|j||dtjS)N)frrrr?rrs rr>z"PGDialect._get_foreign_table_names '.. {/  rc d|j||tjtjSr)rr RELKINDS_VIEWr?rrs rget_view_nameszPGDialect.get_view_names s2..    $ $%% /  rc d|j||tjtjSr)rrRELKINDS_MAT_VIEWr?rrs rget_materialized_view_namesz%PGDialect.get_materialized_view_names s2..    ( (%% /  rc d|j||tjtjSr)rrrr?rrs rget_temp_view_nameszPGDialect.get_temp_view_names s4..    $ $'' /  rc H|j||dtjS)N)rrrrs rget_sequence_nameszPGDialect.get_sequence_names rrc 4ttjtjjj j tjjtjjj|k(|jtjtjz}|j||tj}|j|}|"t!j"|r |d|||S)Nrr)r8rpg_get_viewdefrrr select_fromrrrrrrr?rrr6r)rrT view_namer7rrress rget_view_definitionzPGDialect.get_view_definition s :,,Z-@-@-B-B-F-FG H [,, - U##%%--:00,,z/K/KK 22 63 & ;&&+16(!I;' 7@ Jrc t|||fS#t$r%tj|r |d|d|dwxYw)Nr)rKeyErrorr6r)rdatarr7s r_value_or_raisezPGDialect._value_or_raise s_ :vuo. . &&'-6(!E7# 38  s .Ac|rdd|ifSdifS)NT filter_namesFr)rr&s r_prepare_filter_nameszPGDialect._prepare_filter_names s .,77 7"9 rkindc,|tjurtjSd}tj|vr|tj z }tj |vr|tjz }tj|vr|tjz }|S)Nr) r>rrrTABLERELKINDS_TABLEVIEWrMATERIALIZED_VIEWr)rr(rs r_kind_to_relkindszPGDialect._kind_to_relkinds s| :>> !55 5   t #  11 1H ??d "  00 0H  ' '4 /  44 4Hrc |j|f||gtjtjd|}|j |||SN)r7r&rr()get_multi_columnsr?rr>r$rrTr2r7rr#s r get_columnszPGDialect.get_columns S%t%%  $//    ##D*f==rc|jdk\r3tjjjj dn"t jj d}|jdk\rtt jjdtjjjdk(dtjjjdtjjjdtjjjd tjjj d tjjj"d tjjj$t'j( j+tjj-tjjjd k7tjjj.t j0t j0tj2t j0t j0tjjj4t6t8tjjj:t6t<k(j?tjjAj d}n#t jj d}ttjBtjDjjFtjDjjHj+tjDj-tjDjjHtjjj4k(tjDjjJtjjjLk(tjjjNj?tjjAj d}|jQ|}ttjjj:j dtjRtjjjTtjjjVj d|tjjjXj dtjZjj\j dtj^jj`j d||j+tjZjctjt jdtjZjjftjjj4k(tjjjLdkDtjjjhjctj^t jdtj^jjjtjjj4k(tj^jjltjjjLk(j-|jo|jqtjZjj\tjjjL} |js| ||} |rK| j-tjZjj\jutwd} | S)N) rmralwaysar incrementminvaluemaxvaluecachecyclerrCidentity_optionsr<rrr)r2rwrrr&) X##%%--z/F/F/H/H/O/OK R225&2N KK##%%--11)N2KLE rc |j|\}}|j||||} |j| |j} |j |d|j dD cic]} | ds | d| dfn| df| } } t d|j|d|j dD} |j| | | |}|jScc} w)Nrr/)r7r/rr7rc3NK|]}|dr|df|fn |d|df|fyw)rrr7Nr)r]recs rr^z.PGDialect.get_multi_columns..sJ  y>f+%8}c&k2C89s#%) r'rdrmappingsr6rErr;_get_columns_infor)rrTr7r&rr(rrcparamsrrowsddomainsrr s rr1zPGDialect.get_multi_columns{s$(#=#=l#K &##F, Y/I#J/'&D's0NN,+N,c 0tt}|D]}|dtj|||df<&|||df}|j |d||d|dz}|d} |d} |d} |d } t |t r+| s|j |j} | xr |j } |d } | d vrt| | d v }d} nd}d }| tjd| }|yt|jtjrd}d|j!dvr@|>|j!dd|zzdz|j!dz|j!dz} | || | |xs| du|dd}|||d<| | |d<|j#||S)Nrr2rz column '%s'rqr<rmr)r>)NrC)rs)rrlFz(nextval\(')([^']+)('.*$)Trrr z"%s"r5rw)rr'rr< autoincrementrwrr)rr rBr r}rrr<r)rrrv issubclassr rIIntegerrr)rrkrmrr7r row_dict table_colscoltyper<rrmrrrrr column_infos rrizPGDialect._get_columns_info1s#d#H'&..0,!789 &(<*@!ABJ(('!.&1A!A )Gy)GF#D -I#J//H'6*2")//#|ddddfH| ryycc} ww)Nur )rrrnullsnotdistinct)rr rrrrrE)rrTrr7r&rr(r table_oidsbatchesrbatchrr result_by_oidrrr(rwr tablenamefor_oidrs r_reflect_constraintzPGDialect._reflect_constraints_*T))  eT =? z"sN AdOE GAdO''&&y1(-.1!A$.7CF (-M>D:T?GUc"))?GU;?E #(Y'++C4r$r2s rget_pk_constraintzPGDialect.get_pk_constraint#sS+t++  $//    ##D*f==rc n|j|d|||fi|}tjfd|DS)Nrc3XK|]!\}}}}}|f| |gn|||dnf#yw)N)constrained_columnsrrwr)r]r2rpk_namerwrer<r7s rr^z4PGDialect.get_multi_pk_constraint..9sY :@5 D'7A$* 6:\rt '#* ! :@s'*)rrB pk_constraint) rrTr7r&rr(rrr<s ` @rrz!PGDialect.get_multi_pk_constraint/sN*)) V\5$ BD  %22 :@  rc |j|f||g|tjtjd|}|j |||S)N)r7r&ryrr()get_multi_foreign_keysr?rr>r$)rrTr2r7ryrr#s rget_foreign_keyszPGDialect.get_foreign_keysIsX+t**  $*G//   ##D*f==rc tjjd}tjjd}|j |}t tjj jtjj jtjtjj jjdtjtjj jdfd|j jtj j j"j%tjj'tjtj(tjj jtjj j*k(tjj j,dk(j'||j jtjj j.k(j'||j j0|j jk(j'tj tj j j2tjj jk(j5tjj jtjj jj7|j9|}|j;|||}|rK|j7tjj jj=t?d}|S)Ncls_refnsp_refTelse_r r&) rraliasrr.r8rrrrr9rmris_notpg_get_constraintdefrr[r\rr]r^rr confrelidrr`r3rrrrbrC) rr7rcrr( pg_class_refpg_namespace_refrrs r_foreing_key_queryzPGDialect._foreing_key_query]s!**00; %2288C))$/ ##%%--((**22"002266==dC"77&4466::D !""**))++77 "[,, - Y((''))--!//11::;,,..66#=Y""j&>&>&@&@&J&JJY ++/?/A/A/E/EEY))))++22++--112 X##%%--((**22U433H= >Y \225&%H KK##%%--11)N2KLE rc Dd}tjd|d|d|dS)Nz(?:"[^"]+"|[A-Za-z0-9_]+?)z%FOREIGN KEY \((.*?)\) REFERENCES (?:(z)\.)?(z)\(((?:a(?: *, *)?)+)\)[\s]?(MATCH (FULL|PARTIAL|SIMPLE)+)?[\s]?(ON UPDATE (CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?[\s]?(ON DELETE (CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?[\s]?(DEFERRABLE|NOT DEFERRABLE)?[\s]?(INITIALLY (DEFERRED|IMMEDIATE)+)?)rcompile)rqtokens r_fk_regex_patternzPGDialect._fk_regex_patterns=.zz %hfVHGF8D7 7  rc |j}|j|\} } |j|| ||} |j| | } |j} t t }tj}| D]M\}}}}}| ||||f<|||f}tj| |j}|\ }}}}}}}}}}}}} | |dk(rdnd}tjd|D!cgc]}!|j|!}}!|r||jk7r|}n |}n|r|j|}n |||k(r|}|j|}tjd|D!cgc]}!|j|!}}!d|fd|fd| fd |fd |ffD"#cic]\}"}#|#|#d k7r|"|#}$}"}#||||||$|d }%|j|%P|j!Scc}!wcc}!wcc}#}"w) N DEFERRABLETFrnz\s*,\sonupdateondeleterrrz NO ACTION)rrreferred_schemareferred_tablereferred_columnsr-rw)r r'rrrrr rB foreign_keysrrvgroupsrrdefault_schema_namerr)&rrTr7r&rr(ryrrrcrjrrFK_REGEXfkeysr<r2rcondef conschemarw table_fksrrrrrrerrrrrrrrr-fkey_ds& rrz PGDialect.get_multi_foreign_keyss++#'#=#=l#K &''0@%N##E62))D!$11?E ;JG.5ivz*+vz23I (F+224A  # %%/<%?TU *.AB#BA,,Q/B # - 8 88&/O&,O #+">">"O#)(;#)%99.IN)-=> >A,,Q/>   ** ),!:.e$  DAq=Q+%51   ':#2"0$4""F   V $U@FV{{}a#.  s+G"GGc |j|f||gtjtjd|}|j |||Sr0)get_multi_indexesr?rr>r$r2s r get_indexeszPGDialect.get_indexes r4rctjjd}ttjj j tjj jtjjtjj jjdtjjtjj jdjdjtjj jtjj jj!t#dj%d}t|j j |j j|j j&tj(|j j*dk(tj,|j j |j j&dzdftj.j j0j3t4 jd |j j*dk(jd j7|j9tj.tj:tj.j j*|j j*k(tj.j j<|j jk(j|j jj!t#dj%d }t|j j tjj?|j jtjjAtC|j jD|j j&jd tjjAtC|j jF|j j&jdjI|j j j%d}|jJdk\r%tjj jL}n#tjNjd}|jJdk\r%tjj jP}n#tjRjd}ttjj j|j jTjdtjj jVtjXj jZj]djdtjj j^|j j`tjbj jdtj(tjj jfj]dtjhtjj jftjj jfd jd|||j jj|j jl j7tjjtjj jj!t#dtjj jjo|tjj j |j jpk(jotjb|j jrtjbj jpk(j9|tjj j |j j k(j9tjXtj:tjj jtjXj jZk(tjj j tjXj jtk(tjXj jvtjxt{j|dk(jtjj j|j jTS)Ncls_idxrVr rridxrTrris_expridx_attrrFelements_is_expridx_cols) r indnkeyattsrr relname_indexhas_constraintfilter_definition)rrr)@rrrr8rrrindrelidr9rrindkeyrArr indisprimaryrbrCrrrmrVpg_get_indexdefr?rNrrVrr]r^rMrrrrrrrrrvrrr indisuniquerrr indoption reloptionspg_amamnameindpredrQrFrrsrrelamrrrrrr3)rpg_class_indexidx_sqrcols_sqrr9s r _index_queryzPGDialect._index_querys#,,229= ##%%00##%%.. 3 3 5 5 < <=CCHM,,''))00!%,  U$$&&333##%%..229V3DEXe_ " ##!! 1,"22"HH//1A4%1133;;@@F % "A%,,Y7% ([ Y''++--44G++--66&((:K:KKU688$$((6):; < Xj !? F  $$ WYY//0""&wyy'8'8'))--H% #""&wyy'8'8'))--H%*+ Xgii** + Xj !   # #w .$--//;;K((***=9K  # #u ,!+!4!4!6!6!J!J !$!2!23H!I  ##%%..  ((..?##%%11((**33::4@FF$##%%//  ++  ""))"++--55<?  Xj))++44n6F6F6N6N Oq9 rc |j|||||fi|}tt}tj} t|} | r$| dd} g| dd|j |j d| D cgc]} | d c} ij} tt}| D]}||dj|| D]\}}||vr | |||f<||D]}|d}|||f}|d}|d}|d}|r4t||kDr&||d}|d|}|d|}td ||dDsJ|}|}g}||d d }t|r,t||Dcgc] \}}|rdn| c}}|d <||d <n||d <i}t|dD]1\}} d}!| dzr|!dz }!| dzs|!dz }!n | dzr|!dz }!|!s*|!|||<3|r||d<|dr||d<i}"|dr/t|dD#cgc]}#|#jddc}#|"d<|d}$|$dk7r|d|"d<|dr|d|"d<|j d k\r ||d!<||"d"<|d#r|d#|"d$<|"r|"|d%<|j|| r$|j#Scc} wcc}}wcc}#w)&NrrrrrrFrrc3"K|]}|  ywrr)r]rs rr^z.PGDialect.get_multi_indexes..s#+M!(K+Ms r)rr column_namesrCrrr )rnr) nulls_last) nulls_firstcolumn_sortingrduplicates_constraintr=postgresql_withrbtreepostgresql_usingrpostgresql_where)rinclude_columnspostgresql_includerpostgresql_nulls_not_distinctr)rrr rBindexesrrrhrrrbrdr enumeraterrrr)%rrTr7r&rr(rrrr<rrrrrrrr2row index_name table_indexes all_elementsall_elements_is_exprrinc_cols idx_elementsidx_elements_is_exprrGrHrsorting col_index col_flags col_sortingroptionrs% rrzPGDialect.get_multi_indexess*T))  eT =? d#$,,z"AdOE GAdO''!!F5,A5aQqT5,A#Bhj (-M"hz23::8D#$)Zm+5 (4/ +/? ? &?JGL$;<1L29./+,9C56&(O<(=A/2,.?.?F!' S! 4.?>(9:!]F(>A(m(:;./>A/?(:;//584</0@H(<=01KN1L(GH'3B/0!((/.$)f}}]-B^1@s* I9 I> J c |j|f||gtjtjd|}|j |||Sr0)get_multi_unique_constraintsr?rr>r$r2s rget_unique_constraintsz PGDialect.get_unique_constraints#sU1t00  $//    ##D*f==rc "|j|d||||fi|}tt}tj} |D]D\} } } } }| | ||| f<| | | d}|r|dr d|di|d<||| fj |F|j S)Nr)rrrwrrr)rrr rBunique_constraintsrr)rrTr7r&rr(rruniquesr<r2rcon_namerwr-uc_dicts rr.z&PGDialect.get_multi_unique_constraints1s*)) V\5$ BD  d#$77r$r2s rget_table_commentzPGDialect.get_table_commentXsU+t++   L //    ##D*f==rc |j|}ttjjj tj jjjtjjtj tjtjjjtj jjk(tj jjdk(tj jjtj j#dt$k(j'|j)|}|j+|||}|rK|j'tjjj j-t/d}|S)Nrzpg_catalog.pg_classr&)r.r8rrrrr[r\rr]r9r^rr`raclassoidrrr0rrrrbrCrr7rcrr(rrs r_comment_queryzPGDialect._comment_queryds[))$/ ##%%--))++77 [,, - Y))''))--!002299:--//88A=--//88xx}}%:HEF  U433H= >! $225&%H KK##%%--11)N2KLE rc  |j|\}}|j|||} |j| |} tj fd| DS)Nc3FK|]\}}|f|d|infyw)Nrr)r]rrwr<r7s rr^z4PGDialect.get_multi_table_comment..s; #)w%,%8!gi #)s!)r'r<rrB table_comment) rrTr7r&rr(rrcrjrrr<s ` @rr7z!PGDialect.get_multi_table_commentsc$(#=#=l#K &##F,r$r2s rget_check_constraintszPGDialect.get_check_constraintssU/t//   L //    ##D*f==rc |j|}ttjjj tj jjtjtj jjjdtjtj jjdfdtjjjjtjj!tj tj"tjjjtj jj$k(tj jj&dk(j!tjtjjj(tj jjk(j+tjjj tj jjj-|j/|}|j1|||}|rK|j-tjjj j3t5d}|S)NTrrr&)r.r8rrrrrrr9rmrrrr[r\rr]r^rrr`r3rrrrbrCr;s r_check_constraint_queryz!PGDialect._check_constraint_querys))$/ ##%%--((**22"002266==dC"77&4466::D ))++77  [,, - Y((''))--!//11::;,,..66#=Y))))++22++--112 X##%%--((**22U433H= >G J225&%H KK##%%--11)N2KLE rc |j|\}}|j||||} |j| |} tt} t j } | D]\} }}}|| | | || f<tjd|tj}|stjd|zd}nDtjdtjjd|jd}|||d}|r7i}d |jvrd |d <d |jvrd |d <|r||d<| || fj!|| j#S)Nz,^CHECK *\((.+)\)( NO INHERIT)?( NOT VALID)?$)rKz)Could not parse CHECK constraint text: %rrCz^[\s\n]*\((.+)\)[\s\n]*$z\1r )rrrwrTrz NO INHERIT no_inheritr)r'rDrrr rBcheck_constraintsrrDOTALLr:rrrrrrr)rrTr7r&rr(rrcrjrrrGr<r2 check_namesrcrwrrentryr[s rrAz%PGDialect.get_multi_check_constraintss{$(#=#=l#K &,, $eT ##E62'-$664: 0J C!ck:A)!6:"67?iiA  EKL**/ryy#eQWWQZ(#""E 188:-&*B{O AHHJ.'+B|$/1E+, vz2 3 : :5 AQ5;R!&&((rc\|n|jtjtjjj tj jjdk7}|S|dk7r6|jtj jj|k(}|Sr)rrrrrrrr)rrr7s r_pg_type_filter_schemaz PGDialect._pg_type_filter_schemas >KK--j.@.@.B.B.F.FG''))11\AE s]KK 7 7 9 9 A AV KLE rc 6ttjjjt j jttjjjjttjjjjdjtjjjjd}ttj jj"jdtj$tj jj&jdtj(jj*jd|jj,jdj/tj(tj(jj&tj jj0k(j3|tj jj&|jjk(j5tj jj6dk(j9tj(jj*tj jj"}|j;||S)Nr)lbl_aggrrr7r)r8rpg_enumr enumtypidr9rrr enumlabelrrV enumsortorderrArrrrrrrrr)rsrr]rtyptyper3rM)rr7 lbl_agg_sqrs r _enum_queryzPGDialect._enum_query s" ""$$..""&#**,,66;;DA"**,,:: %/ Xj((**44 5 Xi  " ""$$,,226:--j.@.@.B.B.F.FGMM''))1177A ##))(3  T''''))--%%''445 YJ..0044 8N8NNU:%%''//36 7 X''))11:3E3E3G3G3O3O% .**5&99rc |jsgS|j|j|}g}|D]!\}}}}|j||||gn|d#|S)N)rr7rr))rrrVr) rrTr7rrrrrr)s rr;zPGDialect._load_enums7sm((I##D$4$4V$<=-3 )D'66 LL $&$*Nb  .4 rc  ttjjjt j jtjtjjjdjdt j jtjjjjtjdjtjjjdk7jtjjjj!d}ttj"jj$jdtj&tj"jj(tj"jj*jdtj"jj,jdtj"jj.jd tj0tj"jjjd tj2jj4jd |jj6|jj8tj:jj< j?tj2tj2jjtj"jj@k(jCtj:tj"jjDtj:jjk(jC|tj"jj|jjk(jtj"jjFd k(jItj2jj4tj"jj$}|jK||S) NTcondefsconnamesrdomain_constraintsrrrr<rr7rl)&r8rrrcontypidr9rrrrrArrrVrrrrrr typbasetype typtypmod typnotnull typdefaultrrrrYrZ pg_collationcollnamersrr] typcollationrTr3rM)rr7rrs r _domain_queryzPGDialect._domain_queryJsO ((**33""33"002266% """,,..66;;DA% # U:++--66!; < Xj..0099 : X* +# * ""$$,,226:&&&&((44&&((22%/$$&&11188D""$$//55i@--j.@.@.B.B.F.FGMM''))1177A  !!''))22  T''''))--%%''445 Y''""$$11**,,001 Y""$$((FHH,=,==U:%%''//36 7 X''))11:3E3E3G3G3O3OA H**5&99rc |j|j|}g}|jD]}tjd|dj d}g}|drat t|d|dd} | D]>\} } | jjds&| d d } |j| | d @|d |d |d||d|d||dd} |j| |S)Nz([^\(]+)rr rZrYc |dS)Nrr)rs rz)PGDialect._load_domains..s!A$r)rrr)rrrr7rrr<rb)rr7rr'rr<r%r&) rrdrhrrvrsortedrcasefoldr{r)rrTr7rrrmr,rr%sorted_constraintsrdef_r domain_recs rr6zPGDialect._load_domainss##D$6$6v$>?)+oo'FYY{F8,<=CCAFF;=Kj!&,z*F9,=>&&"#5JD$}}11': $Qr #**D5+IJ #5v *!),":.!),*#J/ +J NN: &9(<rcV|jdj}|dk(|_y)Nz show standard_conforming_stringsrj)rrrd)rrT std_strings rrz PGDialect._set_backslash_escapess0 // . &( #-"5r)NNN)rrArCzUUnion[Tuple[None, None], Tuple[Tuple[Optional[str], ...], Tuple[Optional[int], ...]]])TFr)r(r>rCzTuple[str, ...]) rr$rmzdict[str, ReflectedDomain]rzdict[str, ReflectedEnum]rrrrCzsqltypes.TypeEngine[Any]r[r)rrrrsupports_statement_cachesupports_altermax_identifier_lengthsupports_sane_rowcountr= BindTyping RENDER_CASTS bind_typingrsupports_native_booleansupports_native_uuidrsupports_sequencessequences_optional"preexecute_autoincrement_sequencespostfetch_lastrowiduse_insertmanyvaluesreturns_native_bytesrJANY_AUTOINCREMENTUSE_INSERT_FROM_SELECTRENDER_SELECT_COL_CASTS"insertmanyvalues_implicit_sentinelsupports_commentssupports_constraint_commentssupports_default_valuessupports_default_metavaluesupports_empty_insertsupports_multivalues_insertrdefault_paramstylerycolspecsrstatement_compilerr ddl_compilerr|type_compiler_clsr rrFexecution_ctx_clsr+ inspectorupdate_returningdelete_returninginsert_returningupdate_returning_multifromdelete_returning_multifromr<r{connection_characteristicsrrYrkr7IndexTableCheckConstraintForeignKeyConstraintUniqueConstraintconstruct_argumentsreflection_optionsrdr<rUr|rrrrr]rfrnrrrrrrrrrr@r<rrrrrrrrArr1rrr r r>rrrrr r$r'r.r3rdr1rrrurwrxr}rir flexi_cacherK dp_stringdp_string_list dp_plain_objrrrrrrrr:memoized_propertyrrrrrr/r.r8r<r7rBrDrArMrVr;rdr6rrrs@rr,r, s# D#N!''44K")-& %66 & = = > & > > ?' #' "!%!"& $#!MH# L&#H*I!%!% 99" >[BB!+ ; 7(bjj4!+O!<O"O,O( O  O " ObQf[  Z $../ *99: "//0 #001    [Z Z x$ > 4 &+ >>&[77r   0',_B > > I I VB-1 > >%N > >[6  > >[,,\4)l [(:(:T$[9:9:v""H6rr,)r __future__r collectionsr functoolsrrtypingrrrr r r r rCrrr_jsonrr_rangesextrrrr named_typesrrrrrrrtypesrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r6r7r8r9r:enginer;r<r=r>r?r@rAengine.reflectionrBrCrDrErFrGrHrIr sql.compilerrJ sql.visitorsrKrLrMrNrOrPrQrRrSrTrUrVrWrX util.typingrYrIrArrIntervalrr( JSONPathTyperUuidrrrrrrrrrrrrrrr ry SQLCompilerr DDLCompilerrGenericTypeCompilerr|IdentifierPreparerr rr r"r' Inspectorr+DefaultExecutionContextrFConnectionCharacteristicrYrkr{r,rrrrsJ{z-##   #=9)95%/!!#'%'!!##+)+#'))'% ! 3#8-%!$ BJJ:BDD A gT NNFLL x MM4 MM MM5:: MM6  3 fll3 f3 EJJ3 U[[ 3 "" 3 "" 3  3""3w3""3g,,3g,,3W**3g,,3G((3 g,,!3"w#3$ f%3&'3()3*+3, hoo-3. HOO/30 D132w334 U536 D738 D93: D;3< f=3> D?3@ 3A3B3C3DwE3FG3H UI3J 3K3LM3N(O3PQ3R S3T"9U3V4W3XdY3Z D[3\ D]3^ U_3`wa3bc3de3 ls%%sl u H((u p {X11{|8668@@% %(((&,&,k*&&k\428842n 0,, 0 2,, 2m6&&m6r