L i5  dZddlmZddlmZddlmZddlZddlm Z ddlm Z ddlm Z dd lm Z dd lm Z dd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddl&m'Z'ddl&m(Z(ddl&m)Z)dd l&m*Z*dd!l&m+Z+dd"l&m,Z,dd#l&m-Z-dd$l&m.Z.dd%l&m/Z/dd&l&m0Z0dd'l&m1Z1dd(l&m2Z2dd)l&m3Z3dd*l&m4Z4dd+l&m5Z5dd,l&m6Z6dd-l&m7Z7dd.l&m8Z8dd/l&m9Z9dd0l&m:Z:dd1l&m;Z;dd2l&mZ>dd5l&m?Z?d6d7lm@Z@d6d8lmAZAd6d9lmBZBd6d:lmCZCd6d;lmDZDd6dlEmHZHd6d?lEmIZId6d@lEmJZJd6dAlEmKZKd6dBlEmLZLd6dClMmNZNd6dDlCmOZOd6dElCmPZPd6dFlCmQZQd6dGlCmRZRd6dHlCmSZSd6dIlCmTZTd6dJlCmUZUd6d;lCmDZVd6dKlWmXZXd6dLlYmZZZd6dMl&m[Z[d6dNl&m\Z\d6dOl&m]Z]d6dPl&m^Z^d6dQl&m_Z_d6dRl&m`Z`d6dSl&maZad6dTl&mbZbd6dUl&mcZcd6dVl&mdZdd6dWl&meZed6dXl&mfZfd6dYl&mgZgd6dZlhmiZiejd[ejZlhd\ZmeUjejeUje/eUje$eUjjejeUjejeUje:iZuid]ejd^ed_ejd`ejdaejdbejdcejddejdeejdfejdgejdhejdiejdjejdkejdlejdmeaidne[doeddpegdqe]dreUjdseUjdteeduebdve`dwecdxe.dye,dze-d{efd|e*d}e*d~e0ide1de2de3de;de_de>de>de>de=de=de^de=de+de\de/de?ZGddeQj ZGddeQjZGddeQjZGddeQjZGddeiZGddeiZGddeZGddeZGddeKj"ZGddeGj&ZGddeFj*ZGddeFj*ZGddeGj0Zy)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+psycopg2://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. .. _postgresql_covering_indexes: 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. .. seealso:: :ref:`postgresql_constraint_options` .. 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. * ``INCLUDE``: This option adds one or more columns as a "payload" to the unique index created automatically by PostgreSQL for the constraint. For example, the following table definition:: Table( "mytable", metadata, Column("id", Integer, nullable=False), Column("value", Integer, nullable=False), UniqueConstraint("id", postgresql_include=["value"]), ) would produce the DDL statement .. sourcecode:: sql CREATE TABLE mytable ( id INTEGER NOT NULL, value INTEGER NOT NULL, UNIQUE (id) INCLUDE (value) ) Note that this feature requires PostgreSQL 11 or later. .. versionadded:: 2.0.41 .. seealso:: :ref:`postgresql_covering_indexes` .. seealso:: `PostgreSQL CREATE TABLE options `_ - in the PostgreSQL documentation. * Column list with foreign key ``ON DELETE SET`` actions: This applies to :class:`.ForeignKey` and :class:`.ForeignKeyConstraint`, the :paramref:`.ForeignKey.ondelete` parameter will accept on the PostgreSQL backend only a string list of column names inside parenthesis, following the ``SET NULL`` or ``SET DEFAULT`` phrases, which will limit the set of columns that are subject to the action:: fktable = Table( "fktable", metadata, Column("tid", Integer), Column("id", Integer), Column("fk_id_del_set_null", Integer), ForeignKeyConstraint( columns=["tid", "fk_id_del_set_null"], refcolumns=[pktable.c.tid, pktable.c.id], ondelete="SET NULL (fk_id_del_set_null)", ), ) .. versionadded:: 2.0.40 .. _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)Dict)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_]+)$>fasdoinisofonortoallandanyascendfornewnotoffoldbothcaserdescelsefromfullintojoinleftlikenullonlyoversomethentrueuserwhenwitharraycheckcrossfalsefetchgrantgroupilikeinnerlimitorderouterrighttableunionusingwherebinarycolumncreateexceptfreezehavingisnulloffsetr9uniquewindowanalyseanalyzebetweencollater=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 i/mnt/ssd/data/python-lab/Trading/venv/lib/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.) isinstancerr7 CompileErrorrfunction_argspecrs rrzPGCompiler._assert_pg_ts_ext!so'=1"""7<<.1$ %,LL>2< = ,, 5 5 5g D DEFFrc|jtjur|jrtj}|d|j j j||jS)Nz::)identifier_preparer) _type_affinityrJStringlength STRINGTYPEdialecttype_compiler_instanceprocesspreparer)rtype_ dbapi_typesqltexts rrender_bind_castzPGCompiler.render_bind_cast6se  $ $ 7J|j|jfi|d|j|jfi|dS|j||sdndfi|S)NT _cast_appliedeager_grouping[]z -> z ->> )rr rJJSONrr:rrru_jsonJSONBr_supports_jsonb_subscriptingrr%rrr'r*rs rvisit_json_getitem_op_binaryz'PGCompiler.visit_json_getitem_op_binaryOs **(--?"&B 4<< =DD D# 6;;++U[[9 99  V[[/B/ V\\0R0 1400mDF rc |s\|jjtjur6d|d<|jt j ||jfi|Sd|d<|j||sdndfi|S)NTr*r+z #> z #>> )rr rJr.rr:rr%r2s r!visit_json_path_getitem_op_binaryz,PGCompiler.visit_json_path_getitem_op_binaryms} **(--?"&B 4<< =DD D# ,t,, -FW @B  rc ~|j|jfi|d|j|jfi|dS)Nr,r-)rrurr&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_bys< 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_valuerJrrrur)rrr'r regconfigs rvisit_match_op_binaryz PGCompiler.visit_match_op_binarys !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_operands1w11$="==rc |jjdd}|j|jfi|d|j|jfi||%d|j |t jzzSdzS)Nescapez ILIKE  ESCAPE r@getrrurrArJrrrr'rrHs rvisit_ilike_op_binaryz PGCompiler.visit_ilike_op_binarys!!%%h5 DLL + + DLL , , ! 2268;N;NO O      rc |jjdd}|j|jfi|d|j|jfi||%d|j |t jzzSdzS)NrHz NOT ILIKE rIrJrKrMs rvisit_not_ilike_op_binaryz$PGCompiler.visit_not_ilike_op_binarys!!%%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, ')', r?)r@r%rrurArJrr)rbase_oprr'rrRs r _regexp_matchzPGCompiler._regexp_matchs  ) =0400(,.  C<0400')-/  DLL + +   % %eX-@-@ A DLL , ,   rc *|jd|||S)N~rVr&s rvisit_regexp_match_op_binaryz'PGCompiler.visit_regexp_match_op_binarys!!#vx<r?)rrurr@rArJr)rrr'rstringpattern_replacerRs rvisit_regexp_replace_op_binaryz)PGCompiler.visit_regexp_replace_op_binarysfkk0R0&$,,v||:r:  ) =  ))%1D1DE rc Zddjfd|xs tgDdS)NzSELECT r>c3K|]B}djjj|jr t n|zDyw)zCAST(NULL AS %s)N)rrrrrS).0rrs r z2PGCompiler.visit_empty_set_expr..sE  #,,55==!&GIEsAA z WHERE 1!=1)rtrS)r element_typesrs` rvisit_empty_set_exprzPGCompiler.visit_empty_set_exprs3 II +9wyk    rcxt|||}|jjr|j dd}|S)N\z\\)superrAr_backslash_escapesreplace)rvaluer __class__s rrAzPGCompiler.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)NrJz LIMIT z LIMIT ALLz OFFSET ) _limit_clauser_offset_clauserr9rrs r limit_clausezPGCompiler.limit_clauses    + L<4<<0D0D#K#KK KD  ,##+& Jf.C.C!Jr!JJ JD rcb|jdk7rtjd|zd|zS)NONLYzUnrecognized hint: %rzONLY )upperr7r)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 (r>z) z DISTINCT rJ) _distinct _distinct_onrtr)rr9rcols 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 r>c3DK|]}j|fiywr)r)rcrof_kwrs rrdz/PGCompiler.for_update_clause..)s&&16  U,e,&s z NOWAITz SKIP LOCKED) _for_update_argread key_sharer_r; OrderedSetupdatesql_utilsurface_selectables_onlydictrtnowait skip_locked)rr9rtmptablescrs` @rfor_update_clausezPGCompiler.for_update_clauses  ! ! & &%%//&"  # # - -&CC  ! ! $ $__&F++.. D h??BC DHE LLL 7 6DII&:@& C  ! ! ( ( 9 C  ! ! - - > !C rc l|j|jjdfi|}|j|jjdfi|}t|jjdkDr6|j|jjdfi|}d|d|d|dSd|d|dS)Nrrz SUBSTRING(z FROM z FOR r?)rrlen)rfuncrsr!r s rvisit_substring_funczPGCompiler.visit_substring_func4s 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)r>c3K|]C}t|trjj|nj |ddEyw)F include_tablerN)rstrrquoter)rcrrs rrdz1PGCompiler._on_conflict_target..KsN- "!S)MM''*auOP-sA A  WHERE %sFrrJ)constraint_targetr#truncate_and_render_constraint_nameinferred_target_elementsrtinferred_target_whereclauser)rclauser target_texts` r_on_conflict_targetzPGCompiler._on_conflict_target=s  # # /#--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': r>c3&K|] }d|z yw)z'%s'N)rcrs rrdz9PGCompiler.visit_on_conflict_do_update..sBavzBsrTrz ON CONFLICT z DO UPDATE SET ) rrupdate_values_to_setstackrrkeypoprE _is_literalrG BindParameterrrr_cloner self_grouprrrappendr;warncurrent_executablertitemsrexpectrIExpressionElementRoleupdate_whereclause)rrrrraction_set_opsset_parametersinsert_statementcolsrcol_keyrl value_textkey_textkv action_texts rvisit_on_conflict_do_updatez&PGCompiler.visit_on_conflict_do_updatefsy.d..{AbA f99: ::b>,7%%'' FAeeG.(&**73n$&**1-$$U+ ..tU!&&Iuh&<&<= **!LLNE!"EJe&6&6&8UKJ}}**1662H  ! !x"D E3 F8  II++1166YYB>BB  ',,. J1"!S)MM''*aE: "\\$$U%@%@!D$* %%8Z&HI Jii/  $ $ 0 ;))%*6* K5@MMrc Pdd<ddjfd|DzS)NTasfromzFROM r>c3HK|]}|jfdiyw fromhintsNrErct from_hintsrrs rrdz0PGCompiler.update_from_clause..s0#  !A  B Br B# "rt)r update_stmt from_table extra_fromsrrs` ``rupdate_from_clausezPGCompiler.update_from_clauses38 #  #    rc Pdd<ddjfd|DzS)z9Render the DELETE .. USING clause specific to PostgreSQL.TrzUSING r>c3HK|]}|jfdiywrrrs rrdz6PGCompiler.delete_extra_from_clause..s0$  !A  B Br B$ rr)r delete_stmtrrrrs` ``rdelete_extra_from_clausez#PGCompiler.delete_extra_from_clauses38 $))$  $    rc d}|j#|d|j|jfi|zz }|jK|d|j|jfi|d|jdrdndd|jdrd nd z }|S) NrJz OFFSET (%s) ROWSz FETCH FIRST (r?percentz PERCENTz ROWS with_tiesz WITH TIESr{)rwr _fetch_clause_fetch_clause_optionsrxs r fetch_clausezPGCompiler.fetch_clauses  , )LDLL%%-)+- D    +  V118R8$::9E 2M33K@   D rF)*__name__ __module__ __qualname__rrrrrrrrrr#r(r3r5r7r;rCrFrNrPrVrZr\r`rfrArprtryrrrrrrrrrr __classcell__rms@rrrs555555G*  B  B/4>/4     >     "=>  :D! (:8B,CNJ  rrceZdZdZdZdZfdZfdZfdZfdZ e jdZ d Z d Zd Zd Zd ZdZdZdZdZdZdZfdZdZdZdZxZS) 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 SERIALrT)type_expressionr z DEFAULT z NOT NULLz NULL)r format_columnr dialect_implrrrJ TypeDecoratorimplidentitysupports_identity_columns primary_keyr_autoincrement_columnsupports_smallserial SmallIntegerr=r8Sequenceoptional 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) r rrrrrtrrr)robj includeclauser inclusionsrs r_define_includezPGDDLCompiler._define_include s++L9)D % !+3 4CIIKK # =  2< =QT]]  ( ="    >s 2B,B c ||jrt|jdj}t |t j rOt |jt jr+|jjstjdt|5|}||j|z }|S)NrzPostgreSQL dialect cannot produce the CHECK constraint for ARRAY of non-native ENUM; please specify create_constraint=False on this Enum datatype.) _type_boundlistcolumnsrrrJARRAYrEnum native_enumr7rrivisit_check_constraintr)rrrtyprrms rrz$PGDDLCompiler.visit_check_constraint s  ! !z))*1-22C3/s}}hmm< 11&&E w-j9 00<< rc Nt||}||j|z }|Sr)rivisit_foreign_key_constraintrrrrrrms rrz*PGDDLCompiler.visit_foreign_key_constraint- s,w3J? 00<< rc Nt||}||j|z }|Sr)rivisit_primary_key_constraintrr s rr"z*PGDDLCompiler.visit_primary_key_constraint2 s,w3J? $$Z00 rc Nt||}||j|z }|Sr)rivisit_unique_constraintrr s rr$z%PGDDLCompiler.visit_unique_constraint7 s,w.z: $$Z00 rcJtjdtjS)NzC^(?:RESTRICT|CASCADE|SET (?:NULL|DEFAULT)(?:\s*\(.+\))?|NO ACTION)$)rerI)rs r_fk_ondelete_patternz"PGDDLCompiler._fk_ondelete_pattern< szz  DD  rchd|jj|j|jzS)Nz ON DELETE %s)rvalidate_sql_phraseondeleter()rrs r"define_constraint_ondelete_cascadez0PGDDLCompiler.define_constraint_ondelete_cascadeD s1!B!B   !:!:"   rc |j}djj|ddjfd|jDdS)Nz CREATE TYPE z AS ENUM (r>c3~K|]4}jjtj|d6yw)T literal_bindsN) sql_compilerrr:literal)rcers rrdz7PGDDLCompiler.visit_create_enum_type..N s7!!))#++a.)Ms:=r?)rr format_typertenums)rrrrs` rvisit_create_enum_typez$PGDDLCompiler.visit_create_enum_typeI sG MM % %e , II   rc V|j}d|jj|zS)Nz DROP TYPE %srrr4)rdroprrs rvisit_drop_enum_typez"PGDDLCompiler.visit_drop_enum_typeT s% !:!: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 NULLFTrr0zCHECK (r?zCREATE DOMAIN z AS rT)r collationrrrr=render_default_stringconstraint_namernot_nullrr1rr4 type_compiler data_typert)rrrdomainoptionsr=rrs rvisit_create_domain_typez&PGDDLCompiler.visit_create_domain_typeY sa    ' NNXdmm&9&9&:J:J&K%LM N >> %00@G NNXgY/ 0  ! ! -==DD&&D NN[/ 0 ?? NN: & << #%%-- E.E NNWUG1- .T]]66v>?t!!))&*:*:;Tr<rrJnulls_not_distinctz NULLS NOT DISTINCTz NULLS DISTINCTrz WITH (%s)z%s = %s tablespacez TABLESPACE %srz WHERE )rr_verify_index_tablerr#_supports_create_index_concurrentlyr  if_not_exists_prepared_index_name format_tablerr* IDX_USINGlowerrt expressionsr1rrrH ColumnClauserhasattrrrrrrErrIDDLExpressionRole)rrrrindexrrIrrNexprrO withclausestorage_parametertablespace_name whereclausewhere_compileds rvisit_create_indexz PGDDLCompiler.visit_create_indexy s'==   ' << I D  << ; ; 00>~NL'    $ $D  % %eE % B  ! !%++ .   %%l3G<  --33E9EKKMN D ##L1%8  II !& 1 1%%--$.dJ4K4K#L!OO-!%&+&*.#4/DHHOs488},    , $$U++"22<@    % ) )D 5 ( % %D**<8@  L 2<1A1A1C-"$55 D // =lK  $x~~o'FF FD++L9'B  "#**''K"..6657N I. .D qDs ,A>K ! K c N|jdd}|durd}|S|durd}|Sd}|S)Nr rOTzNULLS NOT DISTINCT FzNULLS DISTINCT rJr )rrrrOnulls_not_distinct_params r!define_unique_constraint_distinctz/PGDDLCompiler.define_unique_constraint_distinct sY'77 E    %'< $ ('  5 ('8 $('(* $''rc |j}d}|jjr|jdd}|r|dz }|jr|dz }||j |dz }|S)Nz DROP INDEX r rIrJz IF EXISTS TrK)rr!_supports_drop_index_concurrentlyr  if_existsrT)rr9rr\rrIs rvisit_drop_indexzPGDDLCompiler.visit_drop_index 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)NrJzCONSTRAINT %s FrTr0rrTz WITH zEXCLUDE USING z (r>r?z WHERE (%s)r/)rrformat_constraint _render_exprsr1rrZrrNrr*rrVrWrtrdefine_constraint_deferrability) rrrrrGr]ropexclude_elements rvisit_exclude_constraintz&PGDDLCompiler.visit_exclude_constraint s ?? & $t}}'F'F( D#?"?(66 BND$7d//77CC4'DHH ,Fz~~dhh//O HOOOR@ A B 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)Nr inheritsz INHERITS ( r>c3TK|]}jj|!ywr)rr)rcrrs rrdz2PGDDLCompiler.post_create_table.. s K$DMM//5Ks%(z ) partition_byz PARTITION BY %srz USING %s with_oidsTz WITH OIDSFz WITHOUT OIDS on_commit_rTz ON COMMIT %srPz TABLESPACE %srJ) r rLrrtuplerrtrkr|rr)rr table_optspg_optsrson_commit_optionsr`s` 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)rrr7rr)r ddl_instancers r_can_comment_on_constraintz(PGDDLCompiler._can_comment_on_constraintH st!)) ?? """7 ~F!!     #""7 ~F--  $rc Z|j|d|jj|jd|jj |jj d|j j|jjtjS)NCOMMENT ON CONSTRAINT rMz IS ) rrrlrrUrr1rAcommentrJr )rrrs rvisit_set_constraint_commentz*PGDDLCompiler.visit_set_constraint_commentU sv ''/ MM + +FNN ; MM & &v~~';'; <    2 2&&(9   rc |j|d|jj|jd|jj |jj dS)NrrMz IS NULL)rrrlrrUr)rr9rs rvisit_drop_constraint_commentz+PGDDLCompiler.visit_drop_constraint_comment_ sL ''- MM + +DLL 9 MM & &t||'9'9 :  r)rrrrrrrrr"r$r;memoized_propertyr(r,r6r:rErGrcrfrjrqr}rrrrrrrs@rrrs4l1  $        C  8BYv ( <##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)Nr5rrrrs rvisit_TSVECTORzPGTypeCompiler.visit_TSVECTORh rc y)NTSQUERYrrs r visit_TSQUERYzPGTypeCompiler.visit_TSQUERYk rc y)Nr$rrs r visit_INETzPGTypeCompiler.visit_INETn rc y)Nr"rrs r visit_CIDRzPGTypeCompiler.visit_CIDRq rrc y)Nr#rrs r visit_CITEXTzPGTypeCompiler.visit_CITEXTt rc y)Nr&rrs r visit_MACADDRzPGTypeCompiler.visit_MACADDRw rrc y)Nr'rrs rvisit_MACADDR8zPGTypeCompiler.visit_MACADDR8z rrc y)Nr(rrs r visit_MONEYzPGTypeCompiler.visit_MONEY} rc y)Nr)rrs r visit_OIDzPGTypeCompiler.visit_OID rc y)Nr2rrs rvisit_REGCONFIGzPGTypeCompiler.visit_REGCONFIG rc y)Nr1rrs rvisit_REGCLASSzPGTypeCompiler.visit_REGCLASS rrc >|jsydd|jizS)NrRzFLOAT(%(precision)s) precision)rrs r visit_FLOATzPGTypeCompiler.visit_FLOAT s )[%//,JJ Jrc 0|jtfi|Sr)visit_DOUBLE_PRECISIONrrs r visit_doublezPGTypeCompiler.visit_double s*t**46266rc y)NrMrrs r visit_BIGINTzPGTypeCompiler.visit_BIGINT rrc y)Nrrrs r visit_HSTOREzPGTypeCompiler.visit_HSTORE rrc y)Nr.rrs r visit_JSONzPGTypeCompiler.visit_JSON rrc y)Nr0rrs r visit_JSONBzPGTypeCompiler.visit_JSONB rrc y)NINT4MULTIRANGErrs rvisit_INT4MULTIRANGEz#PGTypeCompiler.visit_INT4MULTIRANGE rc y)NINT8MULTIRANGErrs rvisit_INT8MULTIRANGEz#PGTypeCompiler.visit_INT8MULTIRANGE rrc y)N NUMMULTIRANGErrs rvisit_NUMMULTIRANGEz"PGTypeCompiler.visit_NUMMULTIRANGE src y)NDATEMULTIRANGErrs rvisit_DATEMULTIRANGEz#PGTypeCompiler.visit_DATEMULTIRANGE rrc y)N TSMULTIRANGErrs rvisit_TSMULTIRANGEz!PGTypeCompiler.visit_TSMULTIRANGE src y)NTSTZMULTIRANGErrs rvisit_TSTZMULTIRANGEz#PGTypeCompiler.visit_TSTZMULTIRANGE rrc y)N INT4RANGErrs rvisit_INT4RANGEzPGTypeCompiler.visit_INT4RANGE rrc y)N INT8RANGErrs rvisit_INT8RANGEzPGTypeCompiler.visit_INT8RANGE rrc y)NNUMRANGErrs rvisit_NUMRANGEzPGTypeCompiler.visit_NUMRANGE rrc y)N DATERANGErrs rvisit_DATERANGEzPGTypeCompiler.visit_DATERANGE rrc y)NTSRANGErrs r visit_TSRANGEzPGTypeCompiler.visit_TSRANGE rrc y)N TSTZRANGErrs rvisit_TSTZRANGEzPGTypeCompiler.visit_TSTZRANGE rrc y)NINTrrs rvisit_json_int_indexz#PGTypeCompiler.visit_json_int_index rrc y)NrWrrs rvisit_json_str_indexz#PGTypeCompiler.visit_json_str_index rrc (|j|fi|Sr)visit_TIMESTAMPrs rvisit_datetimezPGTypeCompiler.visit_datetime s#t##E0R00rc |jr|jjst||fi|S|j |fi|Sr)rrsupports_native_enumri visit_enum visit_ENUMrrrrms rrzPGTypeCompiler.visit_enum sC   (I(I7%e2r2 2"4??5/B/ /rc T||jj}|j|Srrr r4rrr rs rrzPGTypeCompiler.visit_ENUM )  &"&,,"B"B "..u55rc T||jj}|j|Srrrs r visit_DOMAINzPGTypeCompiler.visit_DOMAIN rrc tdt|ddd|jzndd|jxrdxsddzS) Nr4r(%d)rJrTWITHWITHOUT TIME ZONEgetattrrtimezoners rrzPGTypeCompiler.visit_TIMESTAMP K5+t4@(^^ & 3)| C   rc tdt|ddd|jzndd|jxrdxsddzS) Nr3rrrJrTrrrrrs r visit_TIMEzPGTypeCompiler.visit_TIME rrc d}|j|d|jzz }|j|d|jzz }|S)Nr%rTz (%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_UUIDri visit_uuidrs rr zPGTypeCompiler.visit_uuid s7   "4??5/B/ /7%e2r2 2rc y)NrXrrs rr zPGTypeCompiler.visit_UUID rrc (|j|fi|Sr) visit_BYTEArs rvisit_large_binaryz!PGTypeCompiler.visit_large_binary st,,,rc y)Nr!rrs rrzPGTypeCompiler.visit_BYTEA rrc |j|jfi|}tjddd|j |jndzz|dS)Nz((?: COLLATE.*)?)$z%s\1z[]r)count)rrr&sub dimensions)rrrrs r visit_ARRAYzPGTypeCompiler.visit_ARRAY s^ U__33vv !+0+;+;+Gu''QP   rc (|j|fi|Sr)visit_JSONPATHrs rvisit_json_pathzPGTypeCompiler.visit_json_path s"t""5/B//rc y)NJSONPATHrrs rrzPGTypeCompiler.visit_JSONPATH! rrr)2rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr r rrrrrrrs@rrrg sK 7    10 6 6   3 -  0rrceZdZeZdZddZy)PGIdentifierPreparerc||d|jk(r)|ddj|j|j}|S)Nrrr) initial_quoterkescape_to_quote escape_quote)rrls 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..) rr7rrmrrschema_for_object omit_schema quote_schema)rrrreffective_schemas rr4z PGIdentifierPreparer.format_type/ szz""eoo6677MN zz%**%11%8   ,''(89:!D6BD rN)T)rrrRESERVED_WORDSreserved_wordsr!r4rrrrr% s#Nrrc4eZdZUdZded< ded< ded<y)ReflectedNamedTypez"Represents a reflected named type.rrr8boolvisibleNrrr__doc____annotations__rrrr+r+A s, I K! M?rr+c(eZdZUdZded< ded<y)ReflectedDomainConstraintz2Represents a reflect check constraint of a domain.rrrNr.rrrr2r2L s< I! J$rr2cLeZdZUdZded< ded< ded< ded < ded <y ) ReflectedDomainRepresents a reflected enum.rrr,r Optional[str]r=zList[ReflectedDomainConstraint] constraintsr=Nr.rrrr4r4U s8& IDN5 10'rr4ceZdZUdZded<y) ReflectedEnumr5 List[str]labelsNr.rrrr9r9h s& +rr9cveZdZUded< 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_oidrA)r table_namer8conns rrCzPGInspector.get_table_oidr sK $ $ & $<<--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)rBr _load_domainsrArr8rEs r get_domainszPGInspector.get_domains sI4 $ $ & $<<--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)rBr _load_enumsrArIs r get_enumszPGInspector.get_enums sI  $ $ & $<<++f,   rKc|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)rBr_get_foreign_table_namesrArIs rget_foreign_table_namesz#PGInspector.get_foreign_table_names sI $ $ & $<<88f9   rKc |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)rBrhas_typerA)r type_namer8rrEs rrSzPGInspector.has_type sK $ $ & $<<((iDOO)   rFr)rDrr8r6returnint)r8r6rUzList[ReflectedDomain])r8r6rUzList[ReflectedEnum])r8r6rUr:)rTrr8r6rrrUr,) rrrr0rCrJrNrQrSrrrr=r=o s 8<'4 ('+# >,'+# "7;&3BE rr=c$eZdZdZfdZxZS)PGExecutionContextc^|jd|jj|z|S)Nzselect nextval('%s'))_execute_scalarr rr)rrsrs r fire_sequencez PGExecutionContext.fire_sequence 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 %srrx_seqzselect nextval('"z"."z"'))rrrserver_default has_argumentrZargrr= is_sequencer_postgresql_seq_nameAttributeErrorrmaxr connectionr$riget_insert_default) rrseq_nametabrrr'r7rms rrgz%PGExecutionContext.get_insert_default 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-)rrrr[rgrrs@rrXrX s *2*2rrXc"eZdZdZdZdZdZy)"PGReadOnlyConnectionCharacteristicTc(|j|dyNF set_readonlyrr dbapi_conns rreset_characteristicz7PGReadOnlyConnectionCharacteristic.reset_characteristic Z/rc(|j||yrrnrrrqrls rset_characteristicz5PGReadOnlyConnectionCharacteristic.set_characteristic rsrc$|j|Sr) get_readonlyrps rget_characteristicz5PGReadOnlyConnectionCharacteristic.get_characteristic s##J//rNrrr transactionalrrrvryrrrrkrk sM000rrkc"eZdZdZdZdZdZy)$PGDeferrableConnectionCharacteristicTc(|j|dyrmset_deferrablerps rrrz9PGDeferrableConnectionCharacteristic.reset_characteristic( z51rc(|j||yrrrus rrvz7PGDeferrableConnectionCharacteristic.set_characteristic+ rrc$|j|Sr)get_deferrablerps rryz7PGDeferrableConnectionCharacteristic.get_characteristic. s%%j11rNrzrrrr}r}# sM222rr}c * 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~jfd?e~jfd3e~jfd@e~jfdAZejdBZdCZeYjd^dDZdEZeYj dadFZe^dGZejdHZ dbdIZeYjd^dJZejdKZdLZeYj d^dMZdNZeYjd^dOZe^dPZdQZeYjd^dRZe^dSZdTZdUZe^dVZeYjd^dWZe^dXZeYjd^dYZdZZxZS)cr>r T?Fpyformat)postgresql_readonlypostgresql_deferrableN)rrrrNrIrrPrO)ignore_search_pathrPrurvrwrsrr r)rrO)postgresql_ignore_search_pathc ntjj|fi|||_||_||_yr)r=DefaultDialect__init___native_inet_types_json_deserializer_json_serializer)rnative_inet_typesjson_serializerjson_deserializerrs rrzPGDialect.__init__ s5 ''77"3"3 /rct|||jdk\|_|j ||jdk\|_|jdk\|_|jdk\|_y)N) r ))ri initializeserver_version_infor_set_backslash_escapesrhrr1)rrfrms rrzPGDialect.initialize st :&%)$<$<$F! ##J/151I1IN 2 .*.)A)AU)J&,0,D,D,M)rcy)N) SERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READr)rrqs rget_isolation_level_valuesz$PGDialect.get_isolation_level_values 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)rrfetchonerr|)rrrvals rget_isolation_levelzPGDialect.get_isolation_level sC!((*9:oo" yy{rctrNotImplementedErrorrrfrls rrozPGDialect.set_readonly !##rctrrrrfs rrxzPGDialect.get_readonly rrctrrrs rrzPGDialect.set_deferrable rrctrrrs rrzPGDialect.get_deferrable 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 ,portrrz ^([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)rV)rcxs rrdz6PGDialect._split_multihost_from_url... sGc!ft3Gsz%Received non-integer port arguments: z%number of hosts and ports don't matchc3 K|]}dywrr)rcrxs rrdz6PGDialect._split_multihost_from_url..A s2qd2s )queryrrryzipsplitrrr&matchrr rr7 ArgumentError ValueError) rurlhosts ports_strintegrated_multihosttokenhost_port_matchhpportss r_split_multihost_from_urlz#PGDialect._split_multihost_from_url s6:AE $ SYY #))F+dE];'+$#&&)YYv%6!-05L C(udmK$ 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_beginrfrrfxids rdo_begin_twophasezPGDialect.do_begin_twophaseE s j++,rc,|jd|zy)NzPREPARE TRANSACTION '%s')exec_driver_sqlrs rdo_prepare_twophasezPGDialect.do_prepare_twophaseH s""#=#CDrc|rT|r|jd|jd|z|jd|j|jy|j|jy)NROLLBACKzROLLBACK PREPARED '%s'BEGIN)r do_rollbackrfrrfr is_preparedrecovers rdo_rollback_twophasezPGDialect.do_rollback_twophaseK sd  **:6  & &'?#'E F  & &w /   Z22 3   Z22 3rc|rT|r|jd|jd|z|jd|j|jy|j|jy)NrzCOMMIT PREPARED '%s'r)rrrf 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)scalarsr:rrcrs rdo_recover_twophasezPGDialect.do_recover_twophaseg s)!! HH8 9 #% rc@|jdjS)Nzselect current_schema())rscalarrs r_get_default_schema_namez"PGDialect._get_default_schema_namel s))*CDKKMMrc ttjjjj tjjj|k(}t |j|Sr)r9r pg_namespacernspnamerr,r)rrfr8rrs r has_schemazPGDialect.has_schemao 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_classrtrrr relnamespacer@DEFAULTrrelpersistence TEMPORARYpg_table_is_visibler)rrr8scopepg_class_tables r_pg_class_filter_scope_schemaz'PGDialect._pg_class_filter_scope_schemav 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)rrrrelkindr:any_rr)rrelkindsrs r_pg_class_relkind_conditionz%PGDialect._pg_class_relkind_condition s>  !'00N''388FLL4J+KKKrcVttjjjj tjjjt dk(|jtj}|j||tjS)NrDr) r9rrrrelnamerrDrRELKINDS_ALL_TABLE_LIKErr@ANY)rr8rs r_has_table_queryzPGDialect._has_table_query sz**,,445;;    ! ! ) )Y|-D D  , ,22   11 62  rc |j||j|}t|j|d|iS)NrD)_ensure_has_table_connectionrr,r)rrfrDr8rrs r has_tablezPGDialect.has_table s= ))*5%%f-J%%elJ-GHIIrc ttjjjj tjjj dk(tjjj|k(}|j||tj}t|j|S)NSr) r9rrrrrrrr@rr,r)rrf sequence_namer8rrs r has_sequencezPGDialect.has_sequence 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*)r9rpg_typertypnamertrr typnamespacerpg_type_is_visiblerr,r)rrfrTr8rrs rrSzPGDialect.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'rrr6)rrr&rAssertionErrorryrrV)rrfrmrs r_get_server_version_infoz"PGDialect._get_server_version_info s}  & &'D E L L N HH C    >B aggaA&6H!-c!fHIIHs A<( A<c ttjjjj tjjj |k(|jtj}|j||tj}|j|}|"tj|r |d|||S)z$Fetch the oid for schema.table_name.rr#)r9rrrrrrrrrr@rrr7NoSuchTableError)rrfrDr8rr table_oids rrCzPGDialect.get_table_oid sz**,,00177    ! ! ) )Z 7  , ,22   22 63 %%e,  &&,26(!J<( 8B rc |ttjjjj tjjjj djtjjj}|j|jS)Nzpg_%) r9rrrrrnot_liker:rrc)rrfrrs rget_schema_nameszPGDialect.get_schema_names s :**,,44 5 U:**,,44==fE F Xj--//77 8  !!%(,,..rcttjjjj |j |}|j|||}|j|jSNr) r9rrrrrrrrrc)rrfr8rrrs r_get_relnames_for_relkindsz$PGDialect._get_relnames_for_relkinds sjz**,,445;;  , ,X 6 225&2N!!%(,,..rc d|j||tjtjSr)rrRELKINDS_TABLE_NO_FOREIGNr@rrrfr8rs rget_table_nameszPGDialect.get_table_names s2..    0 0%% /  rc d|j|dtjtjS)N)r8rr)rrrr@r)rrfrs rget_temp_table_nameszPGDialect.get_temp_table_namess2.. 99'' /  rc H|j||dtjS)N)frrrr@rrs rrPz"PGDialect._get_foreign_table_names '.. {/  rc d|j||tjtjSr)rr RELKINDS_VIEWr@rrs rget_view_nameszPGDialect.get_view_namess2..    $ $%% /  rc d|j||tjtjSr)rrRELKINDS_MAT_VIEWr@rrs rget_materialized_view_namesz%PGDialect.get_materialized_view_namess2..    ( (%% /  rc d|j||tjtjSr)rrr%r@rrs rget_temp_view_nameszPGDialect.get_temp_view_names#s4..    $ $'' /  rc H|j||dtjS)N)rr!r"rs rget_sequence_nameszPGDialect.get_sequence_names.r#rc 4ttjtjjj j tjjtjjj|k(|jtjtjz}|j||tj}|j|}|"t!j"|r |d|||S)Nrr#)r9rpg_get_viewdefrrr select_fromrrrr%r(rr@rrr7r)rrf view_namer8rrress rget_view_definitionzPGDialect.get_view_definition4s :,,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#)rKeyErrorr7r)rdatarr8s r_value_or_raisezPGDialect._value_or_raiseKs_ :vuo. . &&'-6(!E7# 38  s .Ac|rdd|ifSdifS)NT filter_namesFr)rr9s r_prepare_filter_nameszPGDialect._prepare_filter_namesSs .,77 7"9 rkindc,|tjurtjSd}tj|vr|tj z }tj |vr|tjz }tj|vr|tjz }|S)Nr) r?rrrTABLERELKINDS_TABLEVIEWr%MATERIALIZED_VIEWr()rr;rs r_kind_to_relkindszPGDialect._kind_to_relkindsYs| :>> !55 5   t #  11 1H ??d "  00 0H  ' '4 /  44 4Hrc |j|f||gtjtjd|}|j |||SN)r8r9rr;)get_multi_columnsr@rr?r7rrfrDr8rr6s r get_columnszPGDialect.get_columnseS%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) rralwaysar! incrementminvaluemaxvaluecachecyclerrJidentity_optionsr=rr4r@rDrrrr9) 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)NrrA)r8rAr-r8rc3NK|]}|dr|df|fn |d|df|fyw)r-rr8Nr)rcrecs rrdz.PGDialect.get_multi_columns..sH  y>f+%8}c&k2C89  s#%) r:rwrmappingsrHrLrrM_get_columns_infor)rrfr8r9rr;rrvparamsrrowsddomainsr5rs rrDzPGDialect.get_multi_columnss$(#=#=l#K &##F, Y/I#J/'&D's&NN"!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)NrrDr4z column '%s'rr=rr@rQ)NrJ)rs)rrFz(nextval\(')([^']+)('.*$)Tr#rrz"%s"r6r)rrrr= autoincrementrrr)rrrCrrrrr=r@rr&r issubclassr rJIntegerrr)rr~rr5r8rrow_dict table_colscoltyper=rrrrrrr column_infos rr|zPGDialect._get_columns_infos*d#M +H'&..0,!789 &(<*@!ABJ(('!.&1A!A )Gy)GF#D -I#J//H'6*2")//#|jj|jjtj@jjBjEtj@j)|tjFtj@jjH|jjHk(tj@jjJ|jjk(j5|jjj;t9d j=d }t|jjtjjMtO|jjBjQtR|jj>j d |jjtjjU|jj&j d tjjU|jjj dtjjW|jjj djY|jj|jjj[|jj|jjS)N r indnkeyattsindnullsnotdistinctrirordcontypeoidsconattrrro).rrpg_indexrrindnattsrTrr:rr9 pg_constraintconrelidconnamerunnestindkeygenerate_subscriptsrnrortconindid indexrelidrprsrrrrDrusubqueryrrRrar0rqrir` array_aggrrrWminbool_andgroup_byr:)rrrcon_sqattr_sqs r_constraint_queryzPGDialect._constraint_querys^  # #w .$--//;;K$--//88>>}MK  # #u ,","5"5"7"7"K"K "%))+"3"34I"J  ((**33((**22 3 3 5 5 < <=CCHM,,''))00!%,#))++77 T##((**33&&((334 Y))))++22++--112 U((**22i 6JJ((**3377 &8IJXe_; B !!  $$ $$,,''))11 [00 1 T++--44G++--66&((:K:KKU!!%%i&78Xf 7 >  """"' ))..t4giimm %- !! WYY22399-H WYY22399-H!!'))"?"?@FF)  Xgii(('))*;*; < Xgii(('))*;*; <% rc+dK|j|||||fi|}t|} |dk(} | r| dd} g| dd|j|j| D cgc]} | d c} |dj } t t}| D]}||dj || D]\}}|j|d}|r^|D]X}|d}|d}t||kDr ||d}|d|}ng}|}i}|jd k\r||d <| r|d |d <|||d |d|fZx|ddddf| ryycc} ww)Nur )rrrrrrrpostgresql_includerpostgresql_nulls_not_distinctrro) rrrrr{rrrLrr)rrfrr8r9rr;r table_oidsbatches is_uniquebatchrr result_by_oidrr tablenamefor_oidrowall_colsrinc_colscst_colsoptss r_reflect_constraintzPGDialect._reflect_constraintws*T))  eT =? z"sN AdOE GAdO''&&(-.1!A$.7Chj  (-M" Ehz23::8D E#( <Y'++C4&#&v;&)-&8 x=;6'/ '=H'/ '=H')H'/H!33u<9AD!56$DG 5ED!@A&$ N . %4$T4t;;; < /sAD0 D+ C D0)D0c |j|f||gtjtjd|}|j |||SrC)get_multi_pk_constraintr@rr?r7rEs rget_pk_constraintzPGDialect.get_pk_constraintsS+t++  $//    ##D*f==rc x |j|d|||fi|}tjd  fd|DS)Nrc |||d}|r||d<|S)N)constrained_columnsrrr r)pk_namerrrinfos r pk_constraintz8PGDialect.get_multi_pk_constraint..pk_constraints''+"D *.&'Krc3ZK|]"\}}}}}|f| ||||nf$ywrr) rcrDrrrrr=rr8s rrdz4PGDialect.get_multi_pk_constraint..sL  9 D'7D$*"'4$?     s(+)rrCr) rrfr8r9rr;rrr=rs ` @@rrz!PGDialect.get_multi_pk_constraintsS*)) V\5$ BD  %22   =C  rc |j|f||g|tjtjd|}|j |||S)N)r8r9rrr;)get_multi_foreign_keysr@rr?r7)rrfrDr8rrr6s rget_foreign_keyszPGDialect.get_foreign_keyssX+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 r9) rraliasrrAr9rrrrr:rnris_notpg_get_constraintdefrrnror0rprqrr confrelidrrsr:rrrrurD) rr8rvrr; pg_class_refpg_namespace_refrrs r_foreing_key_queryzPGDialect._foreing_key_querys!**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|DEFAULT)(?:\s\(.+\))?)+)?[\s]?(DEFERRABLE|NOT DEFERRABLE)?[\s]?(INITIALLY (DEFERRED|IMMEDIATE)+)?)r&r)rqtokens r_fk_regex_patternzPGDialect._fk_regex_pattern(s=.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 DEFERRABLETFrz\s*,\sonupdater+rrrz NO ACTION)rrreferred_schemareferred_tablereferred_columnsrDr)r r:rrrrrrC foreign_keysr&rgroupsrr!default_schema_namerr)&rrfr8r9rr;rrrrvr}rrFK_REGEXfkeysr=rDrcondef conschemar table_fksrrrrrrxrrr+rrrrrrDfkey_ds& rrz PGDialect.get_multi_foreign_keys;s++#'#=#=l#K &''0@%N##E62))D!$11?EJ % ;JG.5ivz*+vz23I (F+224A  # %%/<%?TU *.AB#,,Q/# # - 8 88&/O&,O #+">">"O#)(;#)%99.IN)-=> ,,Q/    ** ),!:.e$  Aq=Q+%51 G  ':#2"0$4""F   V $UJ %V{{}a#.  s+G"GGc |j|f||gtjtjd|}|j |||SrC)get_multi_indexesr@rr?r7rEs r get_indexeszPGDialect.get_indexesrGrcttjjjtjjj t jjtjjjjdt jjtjjjjdt jjtjjjdjdjtjjjtjjj jt!dj#d}t|jj|jj |jj$t j&|jj(dk(tj*|jj|jj$dzdftj,jj.j1t2 jd |jj(dk(jd tj4jj6tj4jj8j;|j=tj,t j>tj,jj(|jj(k(tj,jj@|jj k(j=tj4tj4jjB|jjDk(j|jj jt!dj#d }t|jjt jjG|jj t jjItK|jjL|jj$jd t jjItK|jjN|jj$jdt jjItK|jj6|jj$jdt jjItK|jj8|jj$jdjQ|jjj#d}|jRdk\r%tjjjT}n3tjjjVjd}|jRdk\r%tjjjX}n#t jZjd}ttjjj tj\jj^tjjj`tjbjjdjgdjdtjjjhtj\jjjtjljjnt j&tjjjpjgdtjrtjjjptjjj fd jd|||jjt|jjv|jjx|jjzj;tjjtjjj jt!dtjjjj}tj\tjjjtj\jjBk(j}tjltj\jj~tjljjBk(j=|tjjj|jjk(j=tjbt j>tjjj tjbjjdk(tjjjtjbjjk(tjbjjt jtjdk(jtjjj tj\jj^S)Nri att_opclassrrridxrTrris_expridx_attrrGelements_is_exprelements_opclasselements_opdefaultidx_colsrrrrhas_constraintfilter_definition)rrr)Fr9rrrrindrelidr:rrrrTindclassrr indisprimaryrurDrrrnripg_get_indexdefrRrarrW pg_opclassopcname opcdefaultr0rprqr`rrrrrrrrrrrrrrr indisuniquerrr indoption reloptionspg_amamnameindpredrdrGrrrrtrelamrrrrrr:)ridx_sqrcols_sqrrOs r _index_queryzPGDialect._index_querys ##%%00##%%.. 3 3 5 5 < <=CCHM 3 3 5 5 > >?EE!,,''))00!%, U$$&&333##%%..229V3DEXe_! ( ##!! 1,"22"HH//1A4%1133;;@@F % "A%,,Y7%%''//%%''22) ,[ Y''++--44G++--66&((:K:KKY%%%%''++vxx/C/CCU688$$((6):; < Xj !K R  $$ WYY//0""&wyy'8'8'))--H% #""&wyy'8'8'))--H%*+""&wyy'8'8'))--H%*+""&wyy';';WYY]]K%,-  Xgii** + Xj !% *  # #w .$--//;;K$--//88>>}MK  # #u ,!+!4!4!6!6!J!J !$!2!23H!I  ##%%..##%%--##%%11((**33::4@FF$##%%//##%%00  ""))"++--55<?  X##%%.. 0C0C0E0E0M0Mu= rc |j|||||fi|}tt}tj} t|} | ro| dd} g| dd|j |j d| D cgc]} | d c} ij} tt}| D]}||dj|| D]\}}||vr | |||f<||D]}|d}|||f}|d}|d}|d}|d }|d }t||kDr1||d}|d|}|d|}td ||dDsJ|d|}|d|}n |}|}g}|}|}||d d }t|r,t||D !cgc] \} }!|!rdn|  c}!} |d<||d<n||d<i}"t|s)t|||D#$%cic] \}#}$}%|%s|#|$ c}%}$}#|"d<i}&t|dD]1\}'}(d})|(dzr|)dz })|(dzs|)dz })n |(dzr|)dz })|)s*|)|&||'<3|&r|&|d<|dr||d<|dr/t|dD*cgc]}*|*jddc}*|"d<|d}+|+dk7r|d|"d <|d!r|d!|"d"<|j d#k\r ||d$<||"d%<|d&r|d&|"d'<|"r|"|d(<|j|| ro|j#Scc} wcc}!} wcc}%}$}#wcc}*w))NrrrrrrGrrrrc3"K|]}|  ywrr)rcrs rrdz.PGDialect.get_multi_indexes..s# '!(K#s r!)rr column_namesrXpostgresql_opsr"rr)ror) nulls_last) nulls_firstcolumn_sortingrduplicates_constraintr#=postgresql_withr%btreepostgresql_usingrpostgresql_whererinclude_columnsrrrr )rrrrCindexesrr*r{rrrcrer enumeraterrrr),rrfr8r9rr;rrr9r=rrrrrrrrDr index_name table_indexes all_elementsall_elements_is_exprall_elements_opclassall_elements_opdefaultrr idx_elementsidx_elements_is_expridx_elements_opclassidx_elements_opdefaultr\r]rr ropclass is_defaultsorting col_index col_flags col_sortingoptionr%s, rr zPGDialect.get_multi_indexesJsl*T))  eT =? d#$,,z"AdOE GAdO''!!F5,AaQqT,A#Bhj (-M" Ehz23::8D E$)| 0Zm+5A , 4 6>== 9gz $. !'M=(89!G09#k:J0K K, 9&( %t+'94K$-$4 + > (4/ +/? ? &?JGL$;< K29./+,9C56<(=A/2,.?$*!' S! 4>(9:!]F(>A(m(:;./>A/?(:;//584</0@H(<=01KN1L(GH'3B/0!((/ku0| 0R}}I-Br1=>s* K ,K ,K *K c |j|f||gtjtjd|}|j |||SrC)get_multi_unique_constraintsr@rr?r7rEs rget_unique_constraintsz PGDialect.get_unique_constraintssU1t00  $//    ##D*f==rc |j|d||||fi|}tt}tj} |D]:\} } } } }| | ||| f<| | | d}|r||d<||| fj |<|j S)Nr)r-rrr )rrrrCunique_constraintsrr)rrfr8r9rr;rruniquesr=rDrcon_namerrDuc_dicts rrMz&PGDialect.get_multi_unique_constraintss*)) V\5$ BD  d#$77! $225&%H KK##%%--11)N2KLE rc  |j|\}}|j|||} |j| |} tj fd| DS)Nc3FK|]\}}|f|d|infyw)Nrr)rcrrr=r8s rrdz4PGDialect.get_multi_table_comment..As9 w%,%8!gi  s!)r:r[rrC table_comment) rrfr8r9rr;rrvr}rrr=s ` @rrVz!PGDialect.get_multi_table_comment9sc$(#=#=l#K &##F,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)?$)rRz)Could not parse CHECK constraint text: %rrJz^[\s\n]*\((.+)\)[\s\n]*$z\1r)rrrr Tr z NO INHERIT no_inheritr )r:rcrrrrCcheck_constraintsr&rDOTALLr;rrrrrrr)rrfr8r9rr;rrvr}rrrfr=rD check_namesrcrrrentryr\s rr`z%PGDialect.get_multi_check_constraintss$(#=#=l#K &,, $eT ##E62'-$664:( B 0J C!ck:A)!6:"67?iiA  EKL**/ryy#eQWWQZ(#""E 188:-&*B{O AHHJ.'+B|$/1E+, vz2 3 : :5 AQ( BR!&&((rc\|n|jtjtjjj tj jjdk7}|S|dk7r6|jtj jj|k(}|Sr)rrr rrrrr)rrr8s 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_aggrr-r8r3)r9rpg_enumr enumtypidr:rrr enumlabelrrW enumsortorderrTrrrr r rrrr;rtr rprtyptyper:rl)rr8 lbl_agg_sqrs r _enum_queryzPGDialect._enum_querys" ""$$..""&#**,,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)rr8r-r;)rrrur) rrfr8rrr5rr-r;s rrMzPGDialect._load_enumssr((I##D$4$4V$<=-3  )D'66 LL $&$*Nb    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=r-r8r)&r9rrrcontypidr:rrrrrTrrrWrrrrr r4 typbasetype typtypmod typnotnull typdefaultr rrrxry pg_collationcollnamertr rp typcollationrsr:rl)rr8rrs r _domain_queryzPGDialect._domain_querysO ((**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([^\(]+)rrryrxc |dS)Nrr)rs rz)PGDialect._load_domains..Ms !A$r)rrr)rrrr8r-rr=r)rr8r-rrr=r7r=) rrr{r&rrsortedrcasefoldrr)rrfr8rrrrCrr7sorted_constraintsrdef_r domain_recs rrHzPGDialect._load_domains?s'##D$6$6v$>?)+oo' 'FYY{F8,<=CCAFF;=Kj!&,z*F9,=>&&"#5KJD$}}11': $Qr #**D5+IJ Kv *!),":.!),*#J/ +J NN: &9 '<rcV|jdj}|dk(|_y)Nz show standard_conforming_stringsrk)rrrj)rrf std_strings rrz PGDialect._set_backslash_escapesds0 // . &( #-"5r)NNN)rrBrUzUUnion[Tuple[None, None], Tuple[Tuple[Optional[str], ...], Tuple[Optional[int], ...]]])TFr)r;r?rUzTuple[str, ...]) r4r6rzDict[str, ReflectedDomain]r5zDict[str, ReflectedEnum]rrrUzsqltypes.TypeEngine[Any]rmr)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_bytesrKANY_AUTOINCREMENTUSE_INSERT_FROM_SELECTRENDER_SELECT_COL_CASTS"insertmanyvalues_implicit_sentinelsupports_commentssupports_constraint_commentssupports_default_valuessupports_default_metavaluesupports_empty_insertsupports_multivalues_insertrdefault_paramstylercolspecsrstatement_compilerr ddl_compilerrtype_compiler_clsrrrXexecution_ctx_clsr= inspectorupdate_returningdelete_returninginsert_returningupdate_returning_multifromdelete_returning_multifromr=rconnection_characteristicsrrkr}r8IndexTableCheckConstraintForeignKeyConstraintPrimaryKeyConstraintUniqueConstraintconstruct_argumentsreflection_optionsrjrRrhr1rrrrrrorxrrrrrrrrrrArOrrrrrrrrSrrCrrrrrPr&r)r+r-r3r7r:rArFrwrDr&rrrrrr|r flexi_cacherL dp_stringdp_string_list dp_plain_objrr;rrrrrrrrrrr*r rNrMrWr[rVrarcr`rlrurMrrHrrrs@rr>r>2 sI D#N!''44K")-& %66 & = = > & > > ?' #' "!%!"& $#!MH# L&#H*I!%!% 99" >[BB!+ ; 7(bjj4!+O!<O"O,O( O  O " ObQf[  Z $../ *99: "//0 #001     \ \ |4 > B &+ >>&[77r   2',_B > > _ _ BUn-1 > > D > >[6  > >[,,\4)l [(:(:T$[9:9:v""H6rr>)r/ __future__r collectionsr functoolsrr&typingrrrr r r r r rJrrrr/rr_rangesextrrrr named_typesrrrrrrrtypesrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r7r8r9r:r;enginer<r=r>r?r@rArBengine.reflectionrCrDrErFrGrHrIrJr sql.compilerrK sql.visitorsrLrMrNrOrPrQrRrSrTrUrVrWrXrY util.typingrZrr'rVr(rIntervalrr. JSONPathTyperUuidrr0rrrrrrrrrrrrr r SQLCompilerr DDLCompilerrGenericTypeCompilerrIdentifierPreparerrr+r2r4r9 Inspectorr=DefaultExecutionContextrXConnectionCharacteristicrkr}rr>rrrrsM||/##   #=9)95%/!!#'%'!!##+)+#'))'% ! 3#8-%!$ BJJ:BDD A gV 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 lC%%CLP H((P f {X11{|8668@@% %(((&,&,k*&&k\428842n 0,, 0 2,, 2x 6&&x 6r