U aocg@s*dZddlmZddlZddlZddlmZddl m Z ddl m Z ddl mZdd l mZd d l mZd d l mZd d l mZd dl mZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZ d dl!m"Z"d dl#m$Z$d dl#m%Z%d dl#m&Z&d dl#m'Z'd dl#m(Z(d dl#m)Z)d dl#m*Z*d d l#m+Z+d d!l#m,Z,d d"l#m-Z-d d#l#m.Z.e/d$ej0Z1e/d%ej0ej2BZ3e4d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddgfZ5dZ6dZ7dZ8Gdddej9Z:Gdddej;Ze>Z?Gdddej=Z@e@ZAGdddej=ZBeBZCGdddej=ZDGdddej=ZEGdddej=ZFGdddejGZGGdddejHZHGdddejIejJZKeKZLGdddej=ZMeMZNGdddej=ZeZOGdddej=ZPGdddejIejQZRejSe jSejTeKejQeRejUjVejVejUejUiZWe jSe jXejUejYejZej[ej\ej]ej^ej_e)e$e,e.e&ej`ej`e-e*e(e+e>e@eeMeMeBeDeEeFe`` 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", execution_options={ "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 Valid values for ``isolation_level`` on most PostgreSQL dialects include: * ``READ COMMITTED`` * ``READ UNCOMMITTED`` * ``REPEATABLE READ`` * ``SERIALIZABLE`` * ``AUTOCOMMIT`` .. seealso:: :ref:`postgresql_readonly_deferrable` :ref:`dbapi_autocommit` :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_alternate_search_path: Setting Alternate Search Paths on Connect ------------------------------------------ The PostgreSQL ``search_path`` variable refers to the list of schema names that will be implicitly referred towards when a particular table or other object is referenced in a SQL statement. As detailed in the next section :ref:`postgresql_schema_reflection`, SQLAlchemy is generally organized around the concept of keeping this variable at its default value of ``public``, however, in order to have it set to any arbitrary name or names when connections are used automatically, the "SET SESSION search_path" command may be invoked for all connections in a pool using the following event handler, as discussed at :ref:`schema_set_default_connections`:: from sqlalchemy import event from sqlalchemy import create_engine engine = create_engine("postgresql+psycopg2://scott:tiger@host/dbname") @event.listens_for(engine, "connect", insert=True) def set_search_path(dbapi_connection, connection_record): existing_autocommit = dbapi_connection.autocommit dbapi_connection.autocommit = True cursor = dbapi_connection.cursor() cursor.execute("SET SESSION search_path='%s'" % schema_name) cursor.close() dbapi_connection.autocommit = existing_autocommit The reason the recipe is complicated by use of the ``.autocommit`` DBAPI attribute is so that when the ``SET SESSION search_path`` directive is invoked, it is invoked outside of the scope of any transaction and therefore will not be reverted when the DBAPI connection has a rollback. .. seealso:: :ref:`schema_set_default_connections` - in the :ref:`metadata_toplevel` documentation .. _postgresql_schema_reflection: Remote-Schema Table Introspection and PostgreSQL search_path ------------------------------------------------------------ **TL;DR;**: keep the ``search_path`` variable set to its default of ``public``, name schemas **other** than ``public`` explicitly within ``Table`` definitions. The PostgreSQL dialect can reflect tables from any schema. The :paramref:`_schema.Table.schema` argument, or alternatively the :paramref:`.MetaData.reflect.schema` argument determines which schema will be searched for the table or tables. The reflected :class:`_schema.Table` objects will in all cases retain this ``.schema`` attribute as was specified. However, with regards to tables which these :class:`_schema.Table` objects refer to via foreign key constraint, a decision must be made as to how the ``.schema`` is represented in those remote tables, in the case where that remote schema name is also a member of the current `PostgreSQL search path `_. By default, the PostgreSQL dialect mimics the behavior encouraged by PostgreSQL's own ``pg_get_constraintdef()`` builtin procedure. This function returns a sample definition for a particular foreign key constraint, omitting the referenced schema name from that definition when the name is also in the PostgreSQL schema search path. The interaction below illustrates this behavior:: test=> CREATE TABLE test_schema.referred(id INTEGER PRIMARY KEY); CREATE TABLE test=> CREATE TABLE referring( test(> id INTEGER PRIMARY KEY, test(> referred_id INTEGER REFERENCES test_schema.referred(id)); CREATE TABLE test=> SET search_path TO public, test_schema; test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n test-> ON n.oid = c.relnamespace test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid test-> WHERE c.relname='referring' AND r.contype = 'f' test-> ; pg_get_constraintdef --------------------------------------------------- FOREIGN KEY (referred_id) REFERENCES referred(id) (1 row) Above, we created a table ``referred`` as a member of the remote schema ``test_schema``, however when we added ``test_schema`` to the PG ``search_path`` and then asked ``pg_get_constraintdef()`` for the ``FOREIGN KEY`` syntax, ``test_schema`` was not included in the output of the function. On the other hand, if we set the search path back to the typical default of ``public``:: test=> SET search_path TO public; SET The same query against ``pg_get_constraintdef()`` now returns the fully schema-qualified name for us:: test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n test-> ON n.oid = c.relnamespace test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid test-> WHERE c.relname='referring' AND r.contype = 'f'; pg_get_constraintdef --------------------------------------------------------------- FOREIGN KEY (referred_id) REFERENCES test_schema.referred(id) (1 row) SQLAlchemy will by default use the return value of ``pg_get_constraintdef()`` in order to determine the remote schema name. That is, if our ``search_path`` were set to include ``test_schema``, and we invoked a table reflection process as follows:: >>> from sqlalchemy import Table, MetaData, create_engine, text >>> engine = create_engine("postgresql://scott:tiger@localhost/test") >>> with engine.connect() as conn: ... conn.execute(text("SET search_path TO test_schema, public")) ... meta = MetaData() ... referring = Table('referring', meta, ... autoload_with=conn) ... The above process would deliver to the :attr:`_schema.MetaData.tables` collection ``referred`` table named **without** the schema:: >>> meta.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")) ... meta = MetaData() ... referring = Table('referring', meta, ... autoload_with=conn, ... postgresql_ignore_search_path=True) ... We will now have ``test_schema.referred`` stored as schema-qualified:: >>> meta.tables['test_schema.referred'].schema 'test_schema' .. sidebar:: Best Practices for PostgreSQL Schema reflection The description of PostgreSQL schema reflection behavior is complex, and is the product of many years of dealing with widely varied use cases and user preferences. But in fact, there's no need to understand any of it if you just stick to the simplest use pattern: leave the ``search_path`` set to its default of ``public`` only, never refer to the name ``public`` as an explicit schema name otherwise, and refer to all other schema names explicitly when building up a :class:`_schema.Table` object. The options described here are only for those users who can't, or prefer not to, stay within these guidelines. Note that **in all cases**, the "default" schema is always reflected as ``None``. The "default" schema on PostgreSQL is that which is returned by the PostgreSQL ``current_schema()`` function. On a typical PostgreSQL installation, this is the name ``public``. So a table that refers to another which is in the ``public`` (i.e. default) schema will always have the ``.schema`` attribute set to ``None``. .. versionadded:: 0.9.2 Added the ``postgresql_ignore_search_path`` dialect-level option accepted by :class:`_schema.Table` and :meth:`_schema.MetaData.reflect`. .. seealso:: `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) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO NOTHING {stop} >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... constraint='pk_my_table', ... set_=dict(data='updated value') ... ) >>> print(do_update_stmt) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT ON CONSTRAINT pk_my_table DO UPDATE SET data = %(param_1)s .. versionadded:: 1.1 .. seealso:: `INSERT .. ON CONFLICT `_ - in the PostgreSQL documentation. Specifying the Target ^^^^^^^^^^^^^^^^^^^^^ Both methods supply the "target" of the conflict using either the named constraint or by column inference: * The :paramref:`_postgresql.Insert.on_conflict_do_update.index_elements` argument specifies a sequence containing string column names, :class:`_schema.Column` objects, and/or SQL expression elements, which would identify a unique index: .. sourcecode:: pycon+sql >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... index_elements=['id'], ... set_=dict(data='updated value') ... ) >>> print(do_update_stmt) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s {stop} >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... index_elements=[my_table.c.id], ... set_=dict(data='updated value') ... ) >>> print(do_update_stmt) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s * When using :paramref:`_postgresql.Insert.on_conflict_do_update.index_elements` to infer an index, a partial index can be inferred by also specifying the use the :paramref:`_postgresql.Insert.on_conflict_do_update.index_where` parameter: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values(user_email='a@b.com', data='inserted data') >>> stmt = stmt.on_conflict_do_update( ... index_elements=[my_table.c.user_email], ... index_where=my_table.c.user_email.like('%@gmail.com'), ... set_=dict(data=stmt.excluded.data) ... ) >>> print(stmt) {opensql}INSERT INTO my_table (data, user_email) VALUES (%(data)s, %(user_email)s) ON CONFLICT (user_email) WHERE user_email LIKE %(user_email_1)s DO UPDATE SET data = excluded.data * The :paramref:`_postgresql.Insert.on_conflict_do_update.constraint` argument is used to specify an index directly rather than inferring it. This can be the name of a UNIQUE constraint, a PRIMARY KEY constraint, or an INDEX: .. sourcecode:: pycon+sql >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... constraint='my_table_idx_1', ... set_=dict(data='updated value') ... ) >>> print(do_update_stmt) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT ON CONSTRAINT my_table_idx_1 DO UPDATE SET data = %(param_1)s {stop} >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... constraint='my_table_pk', ... set_=dict(data='updated value') ... ) >>> print(do_update_stmt) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT ON CONSTRAINT my_table_pk DO UPDATE SET data = %(param_1)s {stop} * The :paramref:`_postgresql.Insert.on_conflict_do_update.constraint` argument may also refer to a SQLAlchemy construct representing a constraint, e.g. :class:`.UniqueConstraint`, :class:`.PrimaryKeyConstraint`, :class:`.Index`, or :class:`.ExcludeConstraint`. In this use, if the constraint has a name, it is used directly. Otherwise, if the constraint is unnamed, then inference will be used, where the expressions and optional WHERE clause of the constraint will be spelled out in the construct. This use is especially convenient to refer to the named or unnamed primary key of a :class:`_schema.Table` using the :attr:`_schema.Table.primary_key` attribute: .. sourcecode:: pycon+sql >>> do_update_stmt = insert_stmt.on_conflict_do_update( ... constraint=my_table.primary_key, ... set_=dict(data='updated value') ... ) >>> print(do_update_stmt) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s The SET Clause ^^^^^^^^^^^^^^^ ``ON CONFLICT...DO UPDATE`` is used to perform an update of the already existing row, using any combination of new values as well as values from the proposed insertion. These values are specified using the :paramref:`_postgresql.Insert.on_conflict_do_update.set_` parameter. This parameter accepts a dictionary which consists of direct values for UPDATE: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values(id='some_id', data='inserted value') >>> do_update_stmt = stmt.on_conflict_do_update( ... index_elements=['id'], ... set_=dict(data='updated value') ... ) >>> print(do_update_stmt) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s .. warning:: The :meth:`_expression.Insert.on_conflict_do_update` method does **not** take into account Python-side default UPDATE values or generation functions, e.g. those specified using :paramref:`_schema.Column.onupdate`. These values will not be exercised for an ON CONFLICT style of UPDATE, unless they are manually specified in the :paramref:`_postgresql.Insert.on_conflict_do_update.set_` dictionary. Updating using the Excluded INSERT Values ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In order to refer to the proposed insertion row, the special alias :attr:`~.postgresql.Insert.excluded` is available as an attribute on the :class:`_postgresql.Insert` object; this object is a :class:`_expression.ColumnCollection` which alias contains all columns of the target table: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values( ... id='some_id', ... data='inserted value', ... author='jlh' ... ) >>> do_update_stmt = stmt.on_conflict_do_update( ... index_elements=['id'], ... set_=dict(data='updated value', author=stmt.excluded.author) ... ) >>> print(do_update_stmt) {opensql}INSERT INTO my_table (id, data, author) VALUES (%(id)s, %(data)s, %(author)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s, author = excluded.author Additional WHERE Criteria ^^^^^^^^^^^^^^^^^^^^^^^^^ The :meth:`_expression.Insert.on_conflict_do_update` method also accepts a WHERE clause using the :paramref:`_postgresql.Insert.on_conflict_do_update.where` parameter, which will limit those rows which receive an UPDATE: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values( ... id='some_id', ... data='inserted value', ... author='jlh' ... ) >>> on_update_stmt = stmt.on_conflict_do_update( ... index_elements=['id'], ... set_=dict(data='updated value', author=stmt.excluded.author), ... where=(my_table.c.status == 2) ... ) >>> print(on_update_stmt) {opensql}INSERT INTO my_table (id, data, author) VALUES (%(id)s, %(data)s, %(author)s) ON CONFLICT (id) DO UPDATE SET data = %(param_1)s, author = excluded.author WHERE my_table.status = %(status_1)s Skipping Rows with DO NOTHING ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``ON CONFLICT`` may be used to skip inserting a row entirely if any conflict with a unique or exclusion constraint occurs; below this is illustrated using the :meth:`~.postgresql.Insert.on_conflict_do_nothing` method: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values(id='some_id', data='inserted value') >>> stmt = stmt.on_conflict_do_nothing(index_elements=['id']) >>> print(stmt) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT (id) DO NOTHING If ``DO NOTHING`` is used without specifying any columns or constraint, it has the effect of skipping the INSERT for any unique or exclusion constraint violation which occurs: .. sourcecode:: pycon+sql >>> stmt = insert(my_table).values(id='some_id', data='inserted value') >>> stmt = stmt.on_conflict_do_nothing() >>> print(stmt) {opensql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s) ON CONFLICT DO NOTHING .. _postgresql_match: Full Text Search ---------------- SQLAlchemy makes available the PostgreSQL ``@@`` operator via the :meth:`_expression.ColumnElement.match` method on any textual column expression. On a PostgreSQL dialect, an expression like the following:: select(sometable.c.text.match("search string")) will emit to the database:: SELECT text @@ to_tsquery('search string') FROM table The PostgreSQL text search functions such as ``to_tsquery()`` and ``to_tsvector()`` are available explicitly using the standard :data:`.func` construct. For example:: select(func.to_tsvector('fat cats ate rats').match('cat & rat')) Emits the equivalent of:: SELECT to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat') The :class:`_postgresql.TSVECTOR` type can provide for explicit CAST:: from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy import select, cast select(cast("some text", TSVECTOR)) produces a statement equivalent to:: SELECT CAST('some text' AS TSVECTOR) AS anon_1 Full Text Searches in PostgreSQL are influenced by a combination of: the PostgreSQL setting of ``default_text_search_config``, the ``regconfig`` used to build the GIN/GiST indexes, and the ``regconfig`` optionally passed in during a query. When performing a Full Text Search against a column that has a GIN or GiST index that is already pre-computed (which is common on full text searches) one may need to explicitly pass in a particular PostgreSQL ``regconfig`` value to ensure the query-planner utilizes the index and does not re-compute the column on demand. In order to provide for this explicit query planning, or to use different search strategies, the ``match`` method accepts a ``postgresql_regconfig`` keyword argument:: select(mytable.c.id).where( mytable.c.title.match('somestring', postgresql_regconfig='english') ) Emits the equivalent of:: SELECT mytable.id FROM mytable WHERE mytable.title @@ to_tsquery('english', 'somestring') One can also specifically pass in a `'regconfig'` value to the ``to_tsvector()`` command as the initial argument:: select(mytable.c.id).where( func.to_tsvector('english', mytable.c.title )\ .match('somestring', postgresql_regconfig='english') ) produces a statement equivalent to:: SELECT mytable.id FROM mytable WHERE to_tsvector('english', mytable.title) @@ to_tsquery('english', 'somestring') It is recommended that you use the ``EXPLAIN ANALYZE...`` tool from PostgreSQL to ensure that you are generating queries with SQLAlchemy that take full advantage of any indexes you may have created for full text search. FROM ONLY ... ------------- The dialect supports PostgreSQL's ONLY keyword for targeting only a particular table in an inheritance hierarchy. This can be used to produce the ``SELECT ... FROM ONLY``, ``UPDATE ONLY ...``, and ``DELETE FROM ONLY ...`` syntaxes. It uses SQLAlchemy's hints mechanism:: # SELECT ... FROM ONLY ... result = table.select().with_hint(table, 'ONLY', 'postgresql') print(result.fetchall()) # UPDATE ONLY ... table.update(values=dict(foo='bar')).with_hint('ONLY', dialect_name='postgresql') # DELETE FROM ONLY ... table.delete().with_hint('ONLY', dialect_name='postgresql') .. _postgresql_indexes: PostgreSQL-Specific Index Options --------------------------------- Several extensions to the :class:`.Index` construct are available, specific to the PostgreSQL dialect. Covering Indexes ^^^^^^^^^^^^^^^^ The ``postgresql_include`` option renders INCLUDE(colname) for the given string names:: Index("my_index", table.c.x, postgresql_include=['y']) would render the index as ``CREATE INDEX my_index ON table (x) INCLUDE (y)`` Note that this feature requires PostgreSQL 11 or later. .. versionadded:: 1.4 .. _postgresql_partial_indexes: Partial Indexes ^^^^^^^^^^^^^^^ Partial indexes add criterion to the index definition so that the index is applied to a subset of rows. These can be specified on :class:`.Index` using the ``postgresql_where`` keyword argument:: Index('my_index', my_table.c.id, postgresql_where=my_table.c.value > 10) .. _postgresql_operator_classes: Operator Classes ^^^^^^^^^^^^^^^^ PostgreSQL allows the specification of an *operator class* for each column of an index (see https://www.postgresql.org/docs/8.3/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/8.3/static/indexes-types.html). These can be specified on :class:`.Index` using the ``postgresql_using`` keyword argument:: Index('my_index', my_table.c.data, postgresql_using='gin') The value passed to the keyword argument will be simply passed through to the underlying CREATE INDEX command, so it *must* be a valid index type for your version of PostgreSQL. .. _postgresql_index_storage: Index Storage Parameters ^^^^^^^^^^^^^^^^^^^^^^^^ PostgreSQL allows storage parameters to be set on indexes. The storage parameters available depend on the index method used by the index. Storage parameters can be specified on :class:`.Index` using the ``postgresql_with`` keyword argument:: Index('my_index', my_table.c.data, postgresql_with={"fillfactor": 50}) .. versionadded:: 1.0.6 PostgreSQL allows to define the tablespace in which to create the index. The tablespace can be specified on :class:`.Index` using the ``postgresql_tablespace`` keyword argument:: Index('my_index', my_table.c.data, postgresql_tablespace='my_tablespace') .. versionadded:: 1.1 Note that the same option is available on :class:`_schema.Table` as well. .. _postgresql_index_concurrently: Indexes with CONCURRENTLY ^^^^^^^^^^^^^^^^^^^^^^^^^ The PostgreSQL index option CONCURRENTLY is supported by passing the flag ``postgresql_concurrently`` to the :class:`.Index` construct:: tbl = Table('testtbl', m, Column('data', Integer)) idx1 = Index('test_idx1', tbl.c.data, postgresql_concurrently=True) The above index construct will render DDL for CREATE INDEX, assuming PostgreSQL 8.2 or higher is detected or for a connection-less dialect, as:: CREATE INDEX CONCURRENTLY test_idx1 ON testtbl (data) For DROP INDEX, assuming PostgreSQL 9.2 or higher is detected or for a connection-less dialect, it will emit:: DROP INDEX CONCURRENTLY test_idx1 .. versionadded:: 1.1 support for CONCURRENTLY on DROP INDEX. The CONCURRENTLY keyword is now only emitted if a high enough version of PostgreSQL is detected on the connection (or for a connection-less dialect). When using CONCURRENTLY, the PostgreSQL database requires that the statement be invoked outside of a transaction block. The Python DBAPI enforces that even for a single statement, a transaction is present, so to use this construct, the DBAPI's "autocommit" mode must be used:: metadata = MetaData() table = Table( "foo", metadata, Column("id", String)) index = Index( "foo_idx", table.c.id, postgresql_concurrently=True) with engine.connect() as conn: with conn.execution_options(isolation_level='AUTOCOMMIT'): table.create(conn) .. seealso:: :ref:`postgresql_isolation_level` .. _postgresql_index_reflection: PostgreSQL Index Reflection --------------------------- The PostgreSQL database creates a UNIQUE INDEX implicitly whenever the UNIQUE CONSTRAINT construct is used. When inspecting a table using :class:`_reflection.Inspector`, the :meth:`_reflection.Inspector.get_indexes` and the :meth:`_reflection.Inspector.get_unique_constraints` will report on these two constructs distinctly; in the case of the index, the key ``duplicates_constraint`` will be present in the index entry if it is detected as mirroring a constraint. When performing reflection using ``Table(..., autoload_with=engine)``, the UNIQUE INDEX is **not** returned in :attr:`_schema.Table.indexes` when it is detected as mirroring a :class:`.UniqueConstraint` in the :attr:`_schema.Table.constraints` collection . .. versionchanged:: 1.0.0 - :class:`_schema.Table` reflection now includes :class:`.UniqueConstraint` objects present in the :attr:`_schema.Table.constraints` collection; the PostgreSQL backend will no longer include a "mirrored" :class:`.Index` construct in :attr:`_schema.Table.indexes` if it is detected as corresponding to a unique constraint. Special Reflection Options -------------------------- The :class:`_reflection.Inspector` used for the PostgreSQL backend is an instance of :class:`.PGInspector`, which offers additional methods:: from sqlalchemy import create_engine, inspect engine = create_engine("postgresql+psycopg2://localhost/test") insp = inspect(engine) # will be a PGInspector print(insp.get_enums()) .. autoclass:: PGInspector :members: .. _postgresql_table_options: PostgreSQL Table Options ------------------------ Several options for CREATE TABLE are supported directly by the PostgreSQL dialect in conjunction with the :class:`_schema.Table` construct: * ``TABLESPACE``:: Table("some_table", metadata, ..., postgresql_tablespace='some_tablespace') The above option is also available on the :class:`.Index` construct. * ``ON COMMIT``:: Table("some_table", metadata, ..., postgresql_on_commit='PRESERVE ROWS') * ``WITH OIDS``:: Table("some_table", metadata, ..., postgresql_with_oids=True) * ``WITHOUT OIDS``:: Table("some_table", metadata, ..., postgresql_with_oids=False) * ``INHERITS``:: Table("some_table", metadata, ..., postgresql_inherits="some_supertable") Table("some_table", metadata, ..., postgresql_inherits=("t1", "t2", ...)) .. versionadded:: 1.0.0 * ``PARTITION BY``:: Table("some_table", metadata, ..., postgresql_partition_by='LIST (part_column)') .. versionadded:: 1.2.6 .. seealso:: `PostgreSQL CREATE TABLE options `_ .. _postgresql_table_valued_overview: Table values, Table and Column valued functions, Row and Tuple objects ----------------------------------------------------------------------- PostgreSQL makes great use of modern SQL forms such as table-valued functions, tables and rows as values. These constructs are commonly used as part of PostgreSQL's support for complex datatypes such as JSON, ARRAY, and other datatypes. SQLAlchemy's SQL expression language has native support for most table-valued and row-valued forms. .. _postgresql_table_valued: Table-Valued Functions ^^^^^^^^^^^^^^^^^^^^^^^ Many PostgreSQL built-in functions are intended to be used in the FROM clause of a SELECT statement, and are capable of returning table rows or sets of table rows. A large portion of PostgreSQL's JSON functions for example such as ``json_array_elements()``, ``json_object_keys()``, ``json_each_text()``, ``json_each()``, ``json_to_record()``, ``json_populate_recordset()`` use such forms. These classes of SQL function calling forms in SQLAlchemy are available using the :meth:`_functions.FunctionElement.table_valued` method in conjunction with :class:`_functions.Function` objects generated from the :data:`_sql.func` namespace. Examples from PostgreSQL's reference documentation follow below: * ``json_each()``:: >>> from sqlalchemy import select, func >>> stmt = select(func.json_each('{"a":"foo", "b":"bar"}').table_valued("key", "value")) >>> print(stmt) SELECT anon_1.key, anon_1.value FROM json_each(:json_each_1) AS anon_1 * ``json_populate_record()``:: >>> from sqlalchemy import select, func, literal_column >>> stmt = select( ... func.json_populate_record( ... literal_column("null::myrowtype"), ... '{"a":1,"b":2}' ... ).table_valued("a", "b", name="x") ... ) >>> print(stmt) SELECT x.a, x.b FROM json_populate_record(null::myrowtype, :json_populate_record_1) AS x * ``json_to_record()`` - this form uses a PostgreSQL specific form of derived columns in the alias, where we may make use of :func:`_sql.column` elements with types to produce them. The :meth:`_functions.FunctionElement.table_valued` method produces a :class:`_sql.TableValuedAlias` construct, and the method :meth:`_sql.TableValuedAlias.render_derived` method sets up the derived columns specification:: >>> from sqlalchemy import select, func, column, Integer, Text >>> stmt = select( ... func.json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}').table_valued( ... column("a", Integer), column("b", Text), column("d", Text), ... ).render_derived(name="x", with_types=True) ... ) >>> print(stmt) SELECT x.a, x.b, x.d FROM json_to_record(:json_to_record_1) AS x(a INTEGER, b TEXT, d TEXT) * ``WITH ORDINALITY`` - part of the SQL standard, ``WITH ORDINALITY`` adds an ordinal counter to the output of a function and is accepted by a limited set of PostgreSQL functions including ``unnest()`` and ``generate_series()``. The :meth:`_functions.FunctionElement.table_valued` method accepts a keyword parameter ``with_ordinality`` for this purpose, which accepts the string name that will be applied to the "ordinality" column:: >>> from sqlalchemy import select, func >>> stmt = select( ... func.generate_series(4, 1, -1).table_valued("value", with_ordinality="ordinality") ... ) >>> print(stmt) SELECT anon_1.value, anon_1.ordinality FROM generate_series(:generate_series_1, :generate_series_2, :generate_series_3) WITH ORDINALITY AS anon_1 .. versionadded:: 1.4.0b2 .. seealso:: :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial` .. _postgresql_column_valued: Column Valued Functions ^^^^^^^^^^^^^^^^^^^^^^^ Similar to the table valued function, a column valued function is present in the FROM clause, but delivers itself to the columns clause as a single scalar value. PostgreSQL functions such as ``json_array_elements()``, ``unnest()`` and ``generate_series()`` may use this form. Column valued functions are available using the :meth:`_functions.FunctionElement.column_valued` method of :class:`_functions.FunctionElement`: * ``json_array_elements()``:: >>> from sqlalchemy import select, func >>> stmt = select(func.json_array_elements('["one", "two"]').column_valued("x")) >>> print(stmt) SELECT x FROM json_array_elements(:json_array_elements_1) AS x * ``unnest()`` - in order to generate a PostgreSQL ARRAY literal, the :func:`_postgresql.array` construct may be used:: >>> from sqlalchemy.dialects.postgresql import array >>> from sqlalchemy import select, func >>> stmt = select(func.unnest(array([1, 2])).column_valued()) >>> print(stmt) SELECT anon_1 FROM unnest(ARRAY[%(param_1)s, %(param_2)s]) AS anon_1 The function can of course be used against an existing table-bound column that's of type :class:`_types.ARRAY`:: >>> from sqlalchemy import table, column, ARRAY, Integer >>> from sqlalchemy import select, func >>> t = table("t", column('value', ARRAY(Integer))) >>> stmt = select(func.unnest(t.c.value).column_valued("unnested_value")) >>> print(stmt) SELECT unnested_value FROM unnest(t.value) AS unnested_value .. seealso:: :ref:`tutorial_functions_column_valued` - in the :ref:`unified_tutorial` Row Types ^^^^^^^^^ Built-in support for rendering a ``ROW`` may be approximated using ``func.ROW`` with the :attr:`_sa.func` namespace, or by using the :func:`_sql.tuple_` construct:: >>> from sqlalchemy import table, column, func, tuple_ >>> t = table("t", column("id"), column("fk")) >>> stmt = t.select().where( ... tuple_(t.c.id, t.c.fk) > (1,2) ... ).where( ... func.ROW(t.c.id, t.c.fk) < func.ROW(3, 7) ... ) >>> print(stmt) SELECT t.id, t.fk FROM t WHERE (t.id, t.fk) > (:param_1, :param_2) AND ROW(t.id, t.fk) < ROW(:ROW_1, :ROW_2) .. seealso:: `PostgreSQL Row Constructors `_ `PostgreSQL Row Constructor Comparison `_ Table Types passed to Functions ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PostgreSQL supports passing a table as an argument to a function, which it refers towards as a "record" type. SQLAlchemy :class:`_sql.FromClause` objects such as :class:`_schema.Table` support this special form using the :meth:`_sql.FromClause.table_valued` method, which is comparable to the :meth:`_functions.FunctionElement.table_valued` method except that the collection of columns is already established by that of the :class:`_sql.FromClause` itself:: >>> from sqlalchemy import table, column, func, select >>> a = table( "a", column("id"), column("x"), column("y")) >>> stmt = select(func.row_to_json(a.table_valued())) >>> print(stmt) SELECT row_to_json(a) AS row_to_json_1 FROM a .. versionadded:: 1.4.0b2 ARRAY Types ----------- The PostgreSQL dialect supports arrays, both as multidimensional column types as well as array literals: * :class:`_postgresql.ARRAY` - ARRAY datatype * :class:`_postgresql.array` - array literal * :func:`_postgresql.array_agg` - ARRAY_AGG SQL function * :class:`_postgresql.aggregate_order_by` - helper for PG's ORDER BY aggregate function syntax. JSON Types ---------- The PostgreSQL dialect supports both JSON and JSONB datatypes, including psycopg2's native support and support for all of PostgreSQL's special operators: * :class:`_postgresql.JSON` * :class:`_postgresql.JSONB` HSTORE Type ----------- The PostgreSQL HSTORE type as well as hstore literals are supported: * :class:`_postgresql.HSTORE` - HSTORE datatype * :class:`_postgresql.hstore` - hstore literal ENUM Types ---------- PostgreSQL has an independently creatable TYPE structure which is used to implement an enumerated type. This approach introduces significant complexity on the SQLAlchemy side in terms of when this type should be CREATED and DROPPED. The type object is also an independently reflectable entity. The following sections should be consulted: * :class:`_postgresql.ENUM` - DDL and typing support for ENUM. * :meth:`.PGInspector.get_enums` - retrieve a listing of current ENUM types * :meth:`.postgresql.ENUM.create` , :meth:`.postgresql.ENUM.drop` - individual CREATE and DROP commands for ENUM. .. _postgresql_array_of_enum: Using ENUM with ARRAY ^^^^^^^^^^^^^^^^^^^^^ The combination of ENUM and ARRAY is not directly supported by backend DBAPIs at this time. Prior to SQLAlchemy 1.3.17, a special workaround was needed in order to allow this combination to work, described below. .. versionchanged:: 1.3.17 The combination of ENUM and ARRAY is now directly handled by SQLAlchemy's implementation without any workarounds needed. .. sourcecode:: python from sqlalchemy import TypeDecorator from sqlalchemy.dialects.postgresql import ARRAY class ArrayOfEnum(TypeDecorator): impl = ARRAY def bind_expression(self, bindvalue): return sa.cast(bindvalue, self) def result_processor(self, dialect, coltype): super_rp = super(ArrayOfEnum, self).result_processor( dialect, coltype) def handle_raw_string(value): inner = re.match(r"^{(.*)}$", value).group(1) return inner.split(",") if inner else [] def process(value): if value is None: return None return super_rp(handle_raw_string(value)) return process E.g.:: Table( 'mydata', metadata, Column('id', Integer, primary_key=True), Column('data', ArrayOfEnum(ENUM('a', 'b, 'c', name='myenum'))) ) This type is not included as a built-in type as it would be incompatible with a DBAPI that suddenly decides to support ARRAY of ENUM directly in a new version. .. _postgresql_array_of_json: Using JSON/JSONB with ARRAY ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Similar to using ENUM, prior to SQLAlchemy 1.3.17, for an ARRAY of JSON/JSONB we need to render the appropriate CAST. Current psycopg2 drivers accommodate the result set correctly without any special steps. .. versionchanged:: 1.3.17 The combination of JSON/JSONB and ARRAY is now directly handled by SQLAlchemy's implementation without any workarounds needed. .. sourcecode:: python class CastingArray(ARRAY): def bind_expression(self, bindvalue): return sa.cast(bindvalue, self) E.g.:: Table( 'mydata', metadata, Column('id', Integer, primary_key=True), Column('data', CastingArray(JSONB)) ) ) defaultdictN)UUID)array)hstore)json)ranges)excschema)sql)util)characteristics)default) reflection) coercions)compiler)elements) expression)roles)sqltypes)DDLBase)BIGINT)BOOLEAN)CHAR)DATE)FLOAT)INTEGER)NUMERIC)REAL)SMALLINT)TEXT)VARCHARz ^(?:btree|hash|gist|gin|[\w_]+)$zs\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|GRANT|REVOKE|IMPORT FOREIGN SCHEMA|REFRESH MATERIALIZED VIEW|TRUNCATE)allZanalyseZanalyzeandanyrasZascZ asymmetricZbothZcasecastcheckZcollatecolumn constraintcreateZcurrent_catalogZ current_dateZ current_role current_timeZcurrent_timestampZ current_userr deferrabledescZdistinctZdoelseendexceptfalsefetchforZforeignfromZgrantgroupZhavingin initiallyZ intersectZintoleadinglimit localtimeZlocaltimestampnewnotnullofoffoffsetoldononlyororderZplacingZprimaryZ referencesZ returningselectZ session_userZsomeZ symmetrictableZthentoZtrailingtrueunionuniqueuserusingZvariadicwhenwhereZwindowwith authorizationZbetweenbinaryZcrossZcurrent_schemafreezefullZilikeinnerisZisnulljoinleftZlikeZnaturalnotnullouterZoveroverlapsrightZsimilarverbose)ii)iiii)iiic@seZdZdZdS)BYTEAN__name__ __module__ __qualname____visit_name__rjrjdC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\dialects\postgresql\base.pyrdsrdc@seZdZdZdS)DOUBLE_PRECISIONNrerjrjrjrkrlsrlc@seZdZdZdS)INETNrerjrjrjrkrmsrmc@seZdZdZdS)CIDRNrerjrjrjrkrnsrnc@seZdZdZdS)MACADDRNrerjrjrjrkrosroc@seZdZdZdZdS)MONEYaProvide the PostgreSQL MONEY type. Depending on driver, result rows using this type may return a string value which includes currency symbols. For this reason, it may be preferable to provide conversion to a numerically-based currency datatype using :class:`_types.TypeDecorator`:: import re import decimal from sqlalchemy import TypeDecorator class NumericMoney(TypeDecorator): impl = MONEY def process_result_value(self, value: Any, dialect: Any) -> None: if value is not None: # adjust this for the currency and numeric m = re.match(r"\$([\d.]+)", value) if m: value = decimal.Decimal(m.group(1)) return value Alternatively, the conversion may be applied as a CAST using the :meth:`_types.TypeDecorator.column_expression` method as follows:: import decimal from sqlalchemy import cast from sqlalchemy import TypeDecorator class NumericMoney(TypeDecorator): impl = MONEY def column_expression(self, column: Any): return cast(column, Numeric()) .. versionadded:: 1.2 Nrfrgrh__doc__rirjrjrjrkrps(rpc@seZdZdZdZdS)OIDzCProvide the PostgreSQL OID type. .. versionadded:: 0.9.5 Nrqrjrjrjrkrs4srsc@seZdZdZdZdS)REGCLASSzHProvide the PostgreSQL REGCLASS type. .. versionadded:: 1.2.7 Nrqrjrjrjrkrt?srtcseZdZdfdd ZZS) TIMESTAMPFNcstt|j|d||_dSN)timezone)superru__init__ precisionselfrwrz __class__rjrkryKszTIMESTAMP.__init__)FNrfrgrhry __classcell__rjrjr}rkruJsrucseZdZdfdd ZZS)TIMEFNcstt|j|d||_dSrv)rxrryrzr{r}rjrkryQsz TIME.__init__)FNrrjrjr}rkrPsrc@sXeZdZdZdZdZdddZeddZe dd Z dd d Z e d dZ ddZ dS)INTERVALzPostgreSQL INTERVAL type.TNcCs||_||_dS)a Construct an INTERVAL. :param precision: optional integer precision value :param fields: string fields specifier. allows storage of fields to be limited, such as ``"YEAR"``, ``"MONTH"``, ``"DAY TO HOUR"``, etc. .. versionadded:: 1.2 N)rzfields)r|rzrrjrjrkry]s zINTERVAL.__init__cKs t|jdS)Nrz)rsecond_precision)clsintervalkwrjrjrkadapt_emulated_to_nativeksz!INTERVAL.adapt_emulated_to_nativecCstjSN)rIntervalr|rjrjrk_type_affinityoszINTERVAL._type_affinityFcCstjd|jdS)NT)nativer)rrrz)r|Zallow_nulltyperjrjrk as_genericsszINTERVAL.as_genericcCstjSr)dt timedeltarrjrjrk python_typevszINTERVAL.python_typecCs|Srrjr|opvaluerjrjrkcoerce_compared_valuezszINTERVAL.coerce_compared_value)NN)F)rfrgrhrrrirry classmethodrpropertyrrrrrjrjrjrkrVs     rc@seZdZdZdddZdS)BITNFcCs |s|p d|_n||_||_dS)Nr)lengthvarying)r|rrrjrjrkrys z BIT.__init__)NF)rfrgrhriryrjrjrjrkrsrcs>eZdZdZdZd ddZfddZddZd d ZZ S) razPostgreSQL UUID type. Represents the UUID column type, interpreting data either as natively returned by the DBAPI or as Python uuid objects. The UUID type is currently known to work within the prominent DBAPI drivers supported by SQLAlchemy including psycopg2, pg8000 and asyncpg. Support for other DBAPI drivers may be incomplete or non-present. FcCs ||_dS)zConstruct a UUID type. :param as_uuid=False: if True, values will be interpreted as Python uuid objects, converting to/from string via the DBAPI. Nas_uuid)r|rrjrjrkrys z UUID.__init__cs&t|tjr|Stt|||SdS)z@See :meth:`.TypeEngine.coerce_compared_value` for a description.N) isinstancer string_typesrxrrrr}rjrkrs zUUID.coerce_compared_valuecCs|jrdd}|SdSdS)NcSs|dk rt|}|Sr)r text_typerrjrjrkprocesss z$UUID.bind_processor..processr)r|dialectrrjrjrkbind_processorszUUID.bind_processorcCs|jrdd}|SdSdS)NcSs|dk rt|}|Sr) _python_UUIDrrjrjrkrsz&UUID.result_processor..processr)r|rcoltyperrjrjrkresult_processorszUUID.result_processor)F) rfrgrhrrriryrrrrrjrjr}rkrs    rc@seZdZdZdZdS)TSVECTORaThe :class:`_postgresql.TSVECTOR` type implements the PostgreSQL text search type TSVECTOR. It can be used to do full text queries on natural language documents. .. versionadded:: 0.9.0 .. seealso:: :ref:`postgresql_match` NrqrjrjrjrkrsrcseZdZdZdZfddZeddZddd Zdd d Z Gd d d e Z Gddde Z ddZ dddZdddZdddZd ddZZS)!ENUMa PostgreSQL ENUM type. This is a subclass of :class:`_types.Enum` which includes support for PG's ``CREATE TYPE`` and ``DROP TYPE``. When the builtin type :class:`_types.Enum` is used and the :paramref:`.Enum.native_enum` flag is left at its default of True, the PostgreSQL backend will use a :class:`_postgresql.ENUM` type as the implementation, so the special create/drop rules will be used. The create/drop behavior of ENUM is necessarily intricate, due to the awkward relationship the ENUM type has in relationship to the parent table, in that it may be "owned" by just a single table, or may be shared among many tables. When using :class:`_types.Enum` or :class:`_postgresql.ENUM` in an "inline" fashion, the ``CREATE TYPE`` and ``DROP TYPE`` is emitted corresponding to when the :meth:`_schema.Table.create` and :meth:`_schema.Table.drop` methods are called:: table = Table('sometable', metadata, Column('some_enum', ENUM('a', 'b', 'c', name='myenum')) ) table.create(engine) # will emit CREATE ENUM and CREATE TABLE table.drop(engine) # will emit DROP TABLE and DROP ENUM To use a common enumerated type between multiple tables, the best practice is to declare the :class:`_types.Enum` or :class:`_postgresql.ENUM` independently, and associate it with the :class:`_schema.MetaData` object itself:: my_enum = ENUM('a', 'b', 'c', name='myenum', metadata=metadata) t1 = Table('sometable_one', metadata, Column('some_enum', myenum) ) t2 = Table('sometable_two', metadata, Column('some_enum', myenum) ) When this pattern is used, care must still be taken at the level of individual table creates. Emitting CREATE TABLE without also specifying ``checkfirst=True`` will still cause issues:: t1.create(engine) # will fail: no such type 'myenum' If we specify ``checkfirst=True``, the individual table-level create operation will check for the ``ENUM`` and create if not exists:: # will check if enum exists, and emit CREATE TYPE if not t1.create(engine, checkfirst=True) When using a metadata-level ENUM type, the type will always be created and dropped if either the metadata-wide create/drop is called:: metadata.create_all(engine) # will emit CREATE TYPE metadata.drop_all(engine) # will emit DROP TYPE The type can also be created and dropped directly:: my_enum.create(engine) my_enum.drop(engine) .. versionchanged:: 1.0.0 The PostgreSQL :class:`_postgresql.ENUM` type now behaves more strictly with regards to CREATE/DROP. A metadata-level ENUM type will only be created and dropped at the metadata level, not the table level, with the exception of ``table.create(checkfirst=True)``. The ``table.drop()`` call will now emit a DROP TYPE for a table-level enumerated type. Tcs$|dd|_tt|j||dS)aConstruct an :class:`_postgresql.ENUM`. Arguments are the same as that of :class:`_types.Enum`, but also including the following parameters. :param create_type: Defaults to True. Indicates that ``CREATE TYPE`` should be emitted, after optionally checking for the presence of the type, when the parent table is being created; and additionally that ``DROP TYPE`` is called when the table is dropped. When ``False``, no check will be performed and no ``CREATE TYPE`` or ``DROP TYPE`` is emitted, unless :meth:`~.postgresql.ENUM.create` or :meth:`~.postgresql.ENUM.drop` are called directly. Setting to ``False`` is helpful when invoking a creation scheme to a SQL file without access to the actual database - the :meth:`~.postgresql.ENUM.create` and :meth:`~.postgresql.ENUM.drop` methods can be used to emit SQL to a target bind. create_typeTN)poprrxrry)r|enumsrr}rjrkry4sz ENUM.__init__cKsx|d|j|d|j|d|j|d|j|d|j|dd|d|j|d |j|f|S) zbProduce a PostgreSQL native :class:`_postgresql.ENUM` from plain :class:`.Enum`. validate_stringsnamer inherit_schemametadataZ_create_eventsFvalues_callableZ omit_aliases) setdefaultrrr rrrZ _omit_aliases)rimplrrjrjrkrRs zENUM.adapt_emulated_to_nativeNcCs"|jjs dS|j|j||ddS)aEmit ``CREATE TYPE`` for this :class:`_postgresql.ENUM`. If the underlying dialect does not support PostgreSQL CREATE TYPE, no action is taken. :param bind: a connectable :class:`_engine.Engine`, :class:`_engine.Connection`, or similar object to emit SQL. :param checkfirst: if ``True``, a query against the PG catalog will be first performed to see if the type does not exist already before creating. N checkfirst)rsupports_native_enum_run_ddl_visitor EnumGeneratorr|bindrrjrjrkr,bsz ENUM.createcCs"|jjs dS|j|j||ddS)aEmit ``DROP TYPE`` for this :class:`_postgresql.ENUM`. If the underlying dialect does not support PostgreSQL DROP TYPE, no action is taken. :param bind: a connectable :class:`_engine.Engine`, :class:`_engine.Connection`, or similar object to emit SQL. :param checkfirst: if ``True``, a query against the PG catalog will be first performed to see if the type actually exists before dropping. Nr)rrr EnumDropperrrjrjrkdropwsz ENUM.dropcs.eZdZdfdd ZddZddZZS) zENUM.EnumGeneratorFc s ttj|j|f|||_dSr)rxrrryrr|r connectionrkwargsr}rjrkryszENUM.EnumGenerator.__init__cCs0|js dS|j|}|jjj|j|j|d SNTr rrschema_for_objectrhas_typerr|enumeffective_schemarjrjrk_can_create_enums z#ENUM.EnumGenerator._can_create_enumcCs"||sdS|jt|dSr)rrexecuteCreateEnumTyper|rrjrjrk visit_enums zENUM.EnumGenerator.visit_enum)F)rfrgrhryrrrrjrjr}rkrs rcs.eZdZdfdd ZddZddZZS) zENUM.EnumDropperFc s ttj|j|f|||_dSr)rxrrryrrr}rjrkryszENUM.EnumDropper.__init__cCs.|js dS|j|}|jjj|j|j|dSrrrrjrjrk_can_drop_enums zENUM.EnumDropper._can_drop_enumcCs"||sdS|jt|dSr)rrr DropEnumTyperrjrjrkrs zENUM.EnumDropper.visit_enum)F)rfrgrhryrrrrjrjr}rkrs rcCsn|js dSd|krf|d}d|jkr0|jd}nt}|jd<|j|jf|k}||j|jf|SdSdS)aLook in the 'ddl runner' for 'memos', then note our name in that collection. This to ensure a particular named enum is operated upon only once within any kind of create/drop sequence without relying upon "checkfirst". TZ _ddl_runnerZ _pg_enumsFN)rmemosetr radd)r|rrZ ddl_runnerZpg_enumsZpresentrjrjrk_check_for_name_in_memoss   zENUM._check_for_name_in_memosFcKs4|s|js0|dds0|||s0|j||ddSNZ_is_metadata_operationFrr)rgetrr,r|targetrrrrjrjrk_on_table_creates  zENUM._on_table_createcKs0|js,|dds,|||s,|j||ddSr)rrrrrrjrjrk_on_table_drops  zENUM._on_table_dropcKs|||s|j||ddSNr)rr,rrjrjrk_on_metadata_creates zENUM._on_metadata_createcKs|||s|j||ddSr)rrrrjrjrk_on_metadata_drops zENUM._on_metadata_drop)NT)NT)F)F)F)F)rfrgrhrr native_enumryrrr,rrrrrrrrrrrjrjr}rkrsM      r)*_arrayrrZjsonbZ int4rangeZ int8rangeZnumrangeZ daterangeZtsrangeZ tstzrangeintegerZbigintZsmallintzcharacter varying characterz"char"rtextnumericfloatrealZinetZcidruuidbit bit varyingZmacaddrZmoneyoidZregclassdouble precision timestamptimestamp with time zonetimestamp without time zonetime with time zonetime without time zonedatetimeZbyteabooleanrZtsvectorcseZdZddZddZd:ddZd;dd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ ddZddZddZfddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9ZZS)< PGCompilercKsd|j|f|S)Nz ARRAY[%s])Zvisit_clauselistr|elementrrjrjrk visit_arrayszPGCompiler.visit_arraycKs$d|j|jf||j|jf|fS)Nz%s:%s)rstartstoprrjrjrk visit_slice!szPGCompiler.visit_sliceFcKsR|s2|jjtjk r2d|d<|jt||jf|Sd|d<|j||sHdndf|S)NT _cast_appliedeager_groupingz -> z ->> typerrJSONrr r(_generate_generic_binaryr|rToperatorrrrjrjrkvisit_json_getitem_op_binary's  z'PGCompiler.visit_json_getitem_op_binarycKsR|s2|jjtjk r2d|d<|jt||jf|Sd|d<|j||sHdndf|S)NTrrz #> z #>> rrrjrjrk!visit_json_path_getitem_op_binary7s  z,PGCompiler.visit_json_path_getitem_op_binarycKs$d|j|jf||j|jf|fS)Nz%s[%s])rrZr^r|rTrrrjrjrkvisit_getitem_binaryFszPGCompiler.visit_getitem_binarycKs$d|j|jf||j|jf|fS)Nz%s ORDER BY %s)rrZorder_byrrjrjrkvisit_aggregate_order_byLsz#PGCompiler.visit_aggregate_order_bycKsld|jkrH||jdtj}|rHd|j|jf|||j|jf|fSd|j|jf||j|jf|fS)NZpostgresql_regconfigz%s @@ to_tsquery(%s, %s)z%s @@ to_tsquery(%s)) modifiersrender_literal_valuer STRINGTYPErrZr^)r|rTrrZ regconfigrjrjrkvisit_match_op_binaryRs z PGCompiler.visit_match_op_binarycKsL|jdd}d|j|jf||j|jf|f|rFd||tjndS)Nescapez %s ILIKE %s ESCAPE rrrrZr^rrrr|rTrrr rjrjrkvisit_ilike_op_binarybsz PGCompiler.visit_ilike_op_binarycKsL|jdd}d|j|jf||j|jf|f|rFd||tjndS)Nr z%s NOT ILIKE %sr r r r rjrjrkvisit_not_ilike_op_binarynsz$PGCompiler.visit_not_ilike_op_binarycCs|jd}|dkr&|j|d|f|St|tjrP|jdkrP|j|d|f|S|j|f|}|j|jf|}|j|jf|}d||||fS)Nflagsz %s iz %s* z%s %s CONCAT('(?', %s, ')', %s)) rrrr BindParameterrrrZr^)r|Zbase_oprTrrrstringpatternrjrjrk _regexp_matchys0 zPGCompiler._regexp_matchcKs|d|||S)N~rrrjrjrkvisit_regexp_match_op_binarysz'PGCompiler.visit_regexp_match_op_binarycKs|d|||S)Nz!~rrrjrjrk visit_not_regexp_match_op_binarysz+PGCompiler.visit_not_regexp_match_op_binarycKs~|j|jf|}|j|jf|}|jd}|dk r@|j|f|}|j|jdf|}|dkrjd|||fSd||||fSdS)Nr replacementzREGEXP_REPLACE(%s, %s, %s)zREGEXP_REPLACE(%s, %s, %s, %s))rrZr^r)r|rTrrrrrrrjrjrkvisit_regexp_replace_op_binarys$ z)PGCompiler.visit_regexp_replace_op_binarycs&ddfdd|ptgDfS)NzSELECT %s WHERE 1!=1, c3s,|]$}djj|jrtn|VqdS)zCAST(NULL AS %s)N)r type_compilerr_isnullr).0type_rrjrk s z2PGCompiler.visit_empty_set_expr..)rYr)r|Z element_typesrjrrkvisit_empty_set_exprs  zPGCompiler.visit_empty_set_exprcs*tt|||}|jjr&|dd}|S)N\z\\)rxrrr_backslash_escapesreplace)r|rr r}rjrkrs zPGCompiler.render_literal_valuecKsd|j|S)Nz nextval('%s'))preparerformat_sequence)r|seqrrjrjrkvisit_sequenceszPGCompiler.visit_sequencecKs^d}|jdk r&|d|j|jf|7}|jdk rZ|jdkrB|d7}|d|j|jf|7}|S)Nr z LIMIT z LIMIT ALLz OFFSET )Z _limit_clauser_offset_clauser|rHrrrjrjrk limit_clauses   zPGCompiler.limit_clausecCs"|dkrtd|d|S)NONLYzUnrecognized hint: %rzONLY )upperr CompileError)r|sqltextrIhintZiscrudrjrjrkformat_from_hint_texts z PGCompiler.format_from_hint_textc sD|js |jr<|jr6ddfdd|jDdSdSndSdS)Nz DISTINCT ON (rcsg|]}j|fqSrjrrcolrr|rjrk sz4PGCompiler.get_select_precolumns..z) z DISTINCT r )Z _distinctZ _distinct_onrY)r|rHrrjr6rkget_select_precolumnss   z PGCompiler.get_select_precolumnsc s|jjr|jjrd}q.d}n|jjr*d}nd}|jjr~t}|jjD]}|t|qF|dd fdd|D7}|jj r|d 7}|jj r|d 7}|S) Nz FOR KEY SHAREz FOR SHAREz FOR NO KEY UPDATEz FOR UPDATEz OF rc3s&|]}j|fdddVqdS)TF)Zashint use_schemaNr3)rrIr6rjrkr!sz/PGCompiler.for_update_clause..z NOWAITz SKIP LOCKED) Z_for_update_argreadZ key_sharer@rZ OrderedSetupdatesql_utilZsurface_selectables_onlyrYZnowaitZ skip_locked)r|rHrtmpZtablescrjr6rkfor_update_clauses&  zPGCompiler.for_update_clausecs(fddt|D}dd|S)Ncsg|]}|qSrj)Z_label_returning_columnrr>r|stmtrjrkr7 sz/PGCompiler.returning_clause..z RETURNING r)rZ_select_iterablesrY)r|rBZreturning_colscolumnsrjrArkreturning_clause s zPGCompiler.returning_clausecKsp|j|jjdf|}|j|jjdf|}t|jjdkr`|j|jjdf|}d|||fSd||fSdS)NrrzSUBSTRING(%s FROM %s FOR %s)zSUBSTRING(%s FROM %s))rZclauseslen)r|funcrsrrrjrjrkvisit_substring_func s zPGCompiler.visit_substring_funcc st|jdk rdj|j}nR|jdk rlddfdd|jD}|jdk rp|dj|jddd7}nd }|S) NzON CONSTRAINT %s(%s)rc3s6|].}t|tjrj|nj|dddVqdS)F include_tabler9N)rrrr&quoterr@rrjrkr!" s z1PGCompiler._on_conflict_target.. WHERE %sFrKr )Zconstraint_targetr&Z#truncate_and_render_constraint_nameZinferred_target_elementsrYZinferred_target_whereclauser)r|clauser target_textrjrrk_on_conflict_target s&     zPGCompiler._on_conflict_targetcKs"|j|f|}|rd|SdSdS)NzON CONFLICT %s DO NOTHINGzON CONFLICT DO NOTHING)rQ)r| on_conflictrrPrjrjrkvisit_on_conflict_do_nothing5 sz'PGCompiler.visit_on_conflict_do_nothingcKs|}|j|f|}g}t|j}|jdd}|jj}|D]} | j} | |krX|| } n| |kr:|| } nq:t | rt j d| | j d} n$t | t j r| j jr| } | j | _ |j| dd} |j| } |d| | fq:|rvtd|jjjdd d |Df|D]\\}}t |tjr:|j|n |j|dd} |jttj|dd} |d| | fqd|}|jdk r|d |j|jd dd 7}d||fS)NZ selectabler F)r9%s = %szFAdditional column names not matching any column keys in table '%s': %srcss|]}d|VqdSz'%s'Nrjr@rjrjrkr!k sz9PGCompiler.visit_on_conflict_do_update..rNTrKzON CONFLICT %s DO UPDATE SET %s) rQdictZupdate_values_to_setstackrIr>keyrrZ _is_literalrrrrrZ_cloner self_groupr&rMappendrwarnZcurrent_executablerrYitemsrexpectrZExpressionElementRoleZupdate_whereclause)r|rRrrOrPZaction_set_opsZset_parametersZinsert_statementcolsr>Zcol_keyrZ value_textZkey_textkvZ action_textrjrjrkvisit_on_conflict_do_update> sd            z&PGCompiler.visit_on_conflict_do_updatec s(dd<ddfdd|DS)NTasfromzFROM rc3s$|]}|jfdiVqdSZ fromhintsNZ_compiler_dispatchrt from_hintsrr|rjrkr! sz0PGCompiler.update_from_clause..rY)r|Z update_stmt from_table extra_fromsrjrrjrirkupdate_from_clause szPGCompiler.update_from_clausec s(dd<ddfdd|DS)z9Render the DELETE .. USING clause specific to PostgreSQL.TrdzUSING rc3s$|]}|jfdiVqdSrerfrgrirjrkr! sz6PGCompiler.delete_extra_from_clause..rk)r|Z delete_stmtrlrmrjrrjrirkdelete_extra_from_clause sz#PGCompiler.delete_extra_from_clausecKsnd}|jdk r&|d|j|jf|7}|jdk rj|d|j|jf||jdrPdnd|jdr`dndf7}|S) Nr z OFFSET (%s) ROWSz FETCH FIRST (%s)%s ROWS %spercentz PERCENTZ with_tiesz WITH TIESr-)r*rZ _fetch_clauseZ_fetch_clause_optionsr+rjrjrk fetch_clause s   zPGCompiler.fetch_clause)F)F) rfrgrhrrrrrrrrrrrrrr"rr)r,r2r8r?rDrIrQrSrcrnrorqrrjrjr}rkrs<        " D  rcspeZdZddZfddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ fddZ ZS) PGDDLCompilercKsh|j|}|j|j}t|tjr,|j}|j dk o<|jj }|j r||j j kr|jjsdt|tjs|s|jdkst|jtjr|jjrt|tjr|d7}qt|tjr|d7}q|d7}n>|d|jjj|j||jd7}||}|dk r|d|7}|jdk r|d||j7}|r6|d||j 7}|jsN|sN|d7}n|jrd|rd|d7}|S) Nz BIGSERIALz SMALLSERIALz SERIAL )Ztype_expressionidentifier_preparerz DEFAULT z NOT NULLz NULL)r&Z format_columnrZ dialect_implrrrZ TypeDecoratorridentitysupports_identity_columns primary_keyrI_autoincrement_columnsupports_smallserialZ SmallIntegerrr SequenceoptionalZ BigIntegerrrZget_column_default_stringcomputednullable)r|r*rZcolspecZ impl_typeZ has_identityrrjrjrkget_column_specification sZ                   z&PGDDLCompiler.get_column_specificationcsR|jrBt|jdj}t|tjrBt|jtjrB|jj sBt dt t ||S)NrzPostgreSQL dialect cannot produce the CHECK constraint for ARRAY of non-native ENUM; please specify create_constraint=False on this Enum datatype.)Z _type_boundlistrCrrrARRAY item_typeEnumrr r/rxrrvisit_check_constraint)r|r+typr}rjrkr s  z$PGDDLCompiler.visit_check_constraintcCsd|j|jS)NzCOMMENT ON TABLE %s IS NULL)r& format_tabler)r|rrjrjrkvisit_drop_table_comment sz&PGDDLCompiler.visit_drop_table_commentcs0|j}dj|dfdd|jDfS)NzCREATE TYPE %s AS ENUM (%s)rc3s$|]}jjt|ddVqdS)T literal_bindsN) sql_compilerrr literal)rerrjrkr! sz7PGDDLCompiler.visit_create_enum_type..)rr& format_typerYr)r|r,r rjrrkvisit_create_enum_type s z$PGDDLCompiler.visit_create_enum_typecCs|j}d|j|S)Nz DROP TYPE %s)rr&r)r|rr rjrjrkvisit_drop_enum_type sz"PGDDLCompiler.visit_drop_enum_typec sj|jd}jr(|d7}|d7}jjrRjdd}|rR|d7}|jr`|d7}|djd d  j f7}jdd }|r|d j |t  7}jdd |ddfddjD7}jdd}|r&fdd|D}|ddfdd|D7}jdd}|rZ|dddd|D7}jdd}|r|d|7}jdd} | dk rttj| } jj| d dd} |d| 7}|S)NzCREATE zUNIQUE zINDEX postgresql concurrently CONCURRENTLY zIF NOT EXISTS z %s ON %s FZinclude_schemarOz USING %s opsrJrcsXg|]P}jjt|tjs"|n|dddt|drN|jkrNd|jndqS)FTrLrrZrsr )rrrrZ ColumnClauser[hasattrrZ)rexpr)rr|rjrkr7& s   z4PGDDLCompiler.visit_create_index..includecs(g|] }t|tjr jj|n|qSrj)rrrrIr>r4)indexrjrkr7: s z INCLUDE (%s)csg|]}|jqSrj)rMrr@r&rjrkr7A srRz WITH (%s)cSsg|] }d|qS)rVrj)rZstorage_parameterrjrjrkr7H s tablespacez TABLESPACE %srQTrz WHERE )r&rZ_verify_index_tablerMr#_supports_create_index_concurrentlydialect_optionsZ if_not_exists_prepared_index_namerrIvalidate_sql_phrase IDX_USINGlowerrYZ expressionsr^rMrr_rZDDLExpressionRolerr) r|r,rrrOZ includeclauseZ inclusionsZ withclausetablespace_nameZ whereclauseZwhere_compiledrj)rrr&r|rkvisit_create_index s        z PGDDLCompiler.visit_create_indexcCsP|j}d}|jjr,|jdd}|r,|d7}|jr:|d7}||j|dd7}|S)Nz DROP INDEX rrrz IF EXISTS Tr)rr!_supports_drop_index_concurrentlyrZ if_existsr)r|rrrrrjrjrkvisit_drop_index` szPGDDLCompiler.visit_drop_indexc Ksd}|jdk r"|d|j|7}g}|jD]^\}}}d|d<|jj|f|t|drr|j|jkrrd|j|jnd}| d||fq,|d|j |j t  d |f7}|jdk r|d |jj|jd d 7}|||7}|S) Nr zCONSTRAINT %s FrLrZrsz %s WITH %szEXCLUDE USING %s (%s)rz WHERE (%s)Tr)rr&Zformat_constraintZ _render_exprsrrrrZrr\rrOrrrYrQZdefine_constraint_deferrability) r|r+rrrrrrZexclude_elementrjrjrkvisit_exclude_constraintp s<      z&PGDDLCompiler.visit_exclude_constraintcsg}|jd}|d}|dk rZt|ttfs4|f}|ddfdd|Dd|drt|d |d|d d kr|d n|d d kr|d|dr|ddd}|d||dr|d}|dj |d|S)Nrinheritsz INHERITS ( rc3s|]}j|VqdSr)r&rMrrrrjrkr! sz2PGDDLCompiler.post_create_table..z ) partition_byz PARTITION BY %s with_oidsTz WITH OIDSFz WITHOUT OIDS on_commit_rsz ON COMMIT %srz TABLESPACE %sr ) rrrrtupler\rYr%r.r&rM)r|rIZ table_optsZpg_optsrZon_commit_optionsrrjrrkpost_create_table s8      zPGDDLCompiler.post_create_tablecCs,|jdkrtdd|jj|jdddS)NFzPostrgreSQL computed columns do not support 'virtual' persistence; set the 'persisted' flag to None or True for PostgreSQL support.zGENERATED ALWAYS AS (%s) STOREDTr) persistedr r/rrr0)r| generatedrjrjrkvisit_computed_column s z#PGDDLCompiler.visit_computed_columnc s@d}|jjdk r$d|j|jj}tt|j|fd|i|S)Nz AS %sprefix)rZ data_typerrrxrrvisit_create_sequence)r|r,rrr}rjrkr s  z#PGDDLCompiler.visit_create_sequence)rfrgrhr~rrrrrrrrrrrrjrjr}rkrr s7  Z" rrcseZdZddZddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zfd)d*Zd>d,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9Zd:d;Zddd Z?d!d"Z@d#d$ZAd]d%d&ZBd^d'd(ZCd)d*ZDd+d,ZEd-d.ZFd_d/d0ZGd`d1d2ZHdad3d4ZId5d6ZJeKjLdbd7d8ZMeKjLd9d:ZNeKjLdcd;d<ZOeKjLddd=d>ZPeKjLded@dAZQeKjLdfdBdCZReKjLdgdDdEZSeKjLdhdFdGZTdHdIZUeKjLdidJdKZVeKjLdjdLdMZWdNdOZXeKjLdPdQZYeKjLdkdRdSZZeKjLdldTdUZ[eKjLdmdVdWZ\dndXdYZ]dZd[Z^Z_S)o PGDialectrT?FZpyformatN)Zpostgresql_readonlyZpostgresql_deferrable)rOrrQrrrRr)Zignore_search_pathrrrrr)postgresql_ignore_search_pathcKs&tjj|f|||_||_||_dSr)rDefaultDialectryisolation_levelZ_json_deserializerZ_json_serializer)r|rZjson_serializerZjson_deserializerrrjrjrkry] szPGDialect.__init__cstt|||jdkr&d|_|_|jdk|_|jsb|j|_|j t j d|j t d|jdk|_ |jdkrd|_n|d}|dk|_|jdk|_|jdk|_|jdk|_dS)NrEFrr ) rEz show standard_conforming_stringsrA )rxr initializeserver_version_infofull_returningimplicit_returningrcolspecscopyrrrrryr$exec_driver_sqlscalarrrrv)r|rZ std_stringr}rjrkrm s&        zPGDialect.initializecs"jdk rfdd}|SdSdS)Ncs|jdSr)set_isolation_levelr)rrrjrkconnect sz%PGDialect.on_connect..connect)r)r|r(rjrrk on_connect s  zPGDialect.on_connectZ SERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READcCs`|dd}||jkr4td||jd|jf|}|d||d|dS)NrrszLInvalid value '%s' for isolation_level. Valid isolation levels for %s are %srz=SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL %sZCOMMIT) r%_isolation_lookupr ArgumentErrorrrYcursorrclose)r|rlevelr,rjrjrkr' s   zPGDialect.set_isolation_levelcCs.|}|d|d}||S)Nz show transaction isolation levelr)r,rZfetchoner-r.)r|rr,valrjrjrkget_isolation_level s   zPGDialect.get_isolation_levelcCs tdSrNotImplementedErrorr|rrrjrjrkr szPGDialect.set_readonlycCs tdSrr1r|rrjrjrkr  szPGDialect.get_readonlycCs tdSrr1r3rjrjrkr szPGDialect.set_deferrablecCs tdSrr1r4rjrjrkr szPGDialect.get_deferrablecCs||jdSr)Zdo_beginrr|rxidrjrjrkdo_begin_twophase szPGDialect.do_begin_twophasecCs|d|dS)NzPREPARE TRANSACTION '%s')r%r5rjrjrkdo_prepare_twophase szPGDialect.do_prepare_twophasecCsH|r8|r|d|d||d||jn ||jdS)NROLLBACKzROLLBACK PREPARED '%s'BEGIN)r% do_rollbackrr|rr6Z is_preparedZrecoverrjrjrkdo_rollback_twophase s  zPGDialect.do_rollback_twophasecCsH|r8|r|d|d||d||jn ||jdS)Nr9zCOMMIT PREPARED '%s'r:)r%r;rZ do_commitr<rjrjrkdo_commit_twophase s  zPGDialect.do_commit_twophasecCs|td}dd|DS)Nz!SELECT gid FROM pg_prepared_xactscSsg|] }|dqSrrjrrowrjrjrkr7 sz1PGDialect.do_recover_twophase..)rr r)r|rZ resultsetrjrjrkdo_recover_twophase szPGDialect.do_recover_twophasecCs|dS)Nzselect current_schema())r%r&r4rjrjrk_get_default_schema_name sz"PGDialect._get_default_schema_namec Cs>d}|t|tjdt|tj d}t | S)Nz=select nspname from pg_namespace where lower(nspname)=:schemar rU) rr r bindparams bindparamrrrrUnicodeboolfirst)r|rr queryr,rjrjrk has_schema s   zPGDialect.has_schemac Cs|||dkr>|tdtjdt|tj d}n@|tdtjdt|tj dtjdt|tj d}t | S)Nzselect relname from pg_class c join pg_namespace n on n.oid=c.relnamespace where pg_catalog.pg_table_is_visible(c.oid) and relname=:namerrUztselect relname from pg_class c join pg_namespace n on n.oid=c.relnamespace where n.nspname=:schema and relname=:namer ) Z_ensure_has_table_connectionrr rrDrErrrrFrGrH)r|rrr r,rjrjrk has_table s< zPGDialect.has_tablec CsZ|dkr|j}|tdtjdt|tj dtjdt|tj d}t | S)NzSELECT relname FROM pg_class c join pg_namespace n on n.oid=c.relnamespace where relkind='S' and n.nspname=:schema and relname=:namerrUr ) rrr rrDrErrrrFrGrH)r|rZ sequence_namer r,rjrjrk has_sequence) s&zPGDialect.has_sequencecCs|dk rd}t|}nd}t|}|tjdt|tjd}|dk rj|tjdt|tjd}||}t | S)Na  SELECT EXISTS ( SELECT * FROM pg_catalog.pg_type t, pg_catalog.pg_namespace n WHERE t.typnamespace = n.oid AND t.typname = :typname AND n.nspname = :nspname ) z SELECT EXISTS ( SELECT * FROM pg_catalog.pg_type t WHERE t.typname = :typname AND pg_type_is_visible(t.oid) ) ZtypnamerUnspname) r rrDrErrrrFrrGr&)r|rZ type_namer rIr,rjrjrkrA s,   zPGDialect.has_typecCsF|d}td|}|s*td|tdd|dddDS) Nzselect version()zQ.*(?:PostgreSQL|EnterpriseDB) (\d+)\.?(\d+)?(?:\.(\d+))?(?:\.\d+)?(?:devel|beta)?z,Could not determine version from string '%s'cSsg|]}|dk rt|qSr)intrxrjrjrkr7n sz6PGDialect._get_server_version_info..rrEr )r%r&rrAssertionErrorrr7)r|rrbmrjrjrk_get_server_version_infoc sz"PGDialect._get_server_version_infoc Ksd}|dk rd}nd}d|}t|}|dk r:t|}t|jtjd}|jtjd}|rv|tj dtjd}| |t ||d } | }|dkrt ||S) zFetch the oid for schema.table_name. Several reflection methods require the table oid. The idea for using this method is that it can be fetched one time and cached for subsequent calls. Nzn.nspname = :schemaz%pg_catalog.pg_table_is_visible(c.oid)a  SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE (%s) AND c.relname = :table_name AND c.relkind in ('r', 'v', 'm', 'f', 'p') )r)rr rU)rr )rrr rrDrrFrCIntegerrErrXr&r ZNoSuchTableError) r|rrr r table_oidZschema_where_clauserIrHr>rjrjrkrp s(    zPGDialect.get_table_oidcKs(|tdjtjd}dd|DS)NzOSELECT nspname FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' ORDER BY nspname)rMcSsg|] \}|qSrjrjrrjrjrkr7 sz.PGDialect.get_schema_names..)rr rrCrrF)r|rrresultrjrjrkget_schema_names szPGDialect.get_schema_namescKs>|tdjtjdt|dk r$|n|jd}dd|DS)NzSELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :schema AND c.relkind in ('r', 'p')relnamer cSsg|] \}|qSrjrjrrjrjrkr7 sz-PGDialect.get_table_names..rr rrCrrFrXrr|rr rrVrjrjrkget_table_names s zPGDialect.get_table_namescKs>|tdjtjdt|dk r$|n|jd}dd|DS)Nz|SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :schema AND c.relkind = 'f'rXr cSsg|] \}|qSrjrjrrjrjrkr7 sz6PGDialect._get_foreign_table_names..rZr[rjrjrkr s z"PGDialect._get_foreign_table_namesrc sdddzfddt|D}Wn"tk rHtd|fYnX|sVtd|tdd d d |Djt j d t |dk r|n|j d }dd|DS)NrbrRrcsg|] }|qSrjrjrrZ include_kindrjrkr7 sz,PGDialect.get_view_names..z_include %r unknown, needs to be a sequence containing one or both of 'plain' and 'materialized'zZempty include, needs to be a sequence containing one or both of 'plain' and 'materialized'z~SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :schema AND c.relkind IN (%s)rcss|]}d|VqdSrWrj)relemrjrjrkr! sz+PGDialect.get_view_names..rXr cSsg|] \}|qSrjrjrrjrjrkr7 s) rZto_listKeyError ValueErrorrr rrYrCrrFrXr)r|rr rrkindsrVrjr^rkr s8   zPGDialect.get_view_namesc KsB|s |j}|tdtjdt|tj d}dd|DS)NzrSELECT relname FROM pg_class c join pg_namespace n on n.oid=c.relnamespace where relkind='S' and n.nspname=:schemar rUcSsg|] }|dqSr?rjr@rjrjrkr7 sz0PGDialect.get_sequence_names..) rrr rrDrErrrrF)r|rr rr,rjrjrkget_sequence_names s zPGDialect.get_sequence_namescKs6|tdjtjdt|dk r$|n|j|d}|S)NzSELECT pg_get_viewdef(c.oid) view_def FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = :schema AND c.relname = :view_name AND c.relkind IN ('v', 'm'))view_def)r view_name)r&r rrCrrFrXr)r|rrer rrdrjrjrkget_view_definition szPGDialect.get_view_definitionc Ks|j||||dd}|jdkr&dnd}|jdkr:d}nd}d ||f}t|tjd tjd j tj tj d } | | t |d } | } ||} t dd|j|ddD} g}| D]:\}}}}}}}}|||||| | |||| }||q|S)Nrr) za.attgenerated as generatedzNULL as generatedra (SELECT json_build_object( 'always', a.attidentity = 'a', 'start', s.seqstart, 'increment', s.seqincrement, 'minvalue', s.seqmin, 'maxvalue', s.seqmax, 'cache', s.seqcache, 'cycle', s.seqcycle) FROM pg_catalog.pg_sequence s JOIN pg_catalog.pg_class c on s.seqrelid = c."oid" WHERE c.relkind = 'S' AND a.attidentity != '' AND s.seqrelid = pg_catalog.pg_get_serial_sequence( a.attrelid::regclass::text, a.attname )::regclass::oid ) as identity_options zNULL as identity_optionsa SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), ( SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef ) AS DEFAULT, a.attnotnull, a.attrelid as table_oid, pgd.description as comment, %s, %s FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_description pgd ON ( pgd.objoid = a.attrelid AND pgd.objsubid = a.attnum) WHERE a.attrelid = :table_oid AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum rUrU)attnamerrUcss8|]0}|dr|df|fn|d|df|fVqdS)visiblerr Nrj)rZrecrjrjrkr!Tsz(PGDialect.get_columns..*r )rrr r rrDrErrTrCrFrrXfetchall _load_domainsr_get_column_infor\)r|rrr rrUrruZSQL_COLSrHr>rowsdomainsrrCrrZdefault_r[comment column_inforjrjrk get_columns sp      zPGDialect.get_columnsc Csdd} tdd|} | | \} } tt| }| }td|}|rP|d}td|}|r|drttd|d}nd }i}| d kr|r|d \}}t|t|f}nd }n| d krd }n| dkrd }n| dkrd|d<|rt||d<d }n| dkr(d|d<|r"t||d<d }n| dkrRd|d<|rLt|f}nd }n\| drt d| tj }|rt||d<|r|d|d<d} d }n|rt|f}| |j kr|j | }qn||kr||}t }|d|d<|ds|d|d<t|d}qnh||krt||}|d} | | \} } tt| }|oT|d}|d r|s|d }qnd}qq|r|||}| r|j d!|}ntd"| |ftj}| d#krt|| d$kd%}d}nd}d}|dk rbtd&|}|dk rbt|jtjrd}|}d'|d(krb|dk rb|dd)|d'|d(|d*}t|||||px| dk |d+}|dk r||d,<| dk r| |d-<|S).NcSstdd||dfS)Nz\[\]$r r)rrendswith)attyperjrjrk_handle_array_types z6PGDialect._get_column_info.._handle_array_typez\(.*\)r z \(([\d,]+)\)rz\((.*)\)\s*,\s*rjr,r)5r)rrTrwrz)rrrFrrrz interval (.+)rrrjr labelsrur}rrz*Did not recognize type '%s' of column '%s')Nr )rHs)r0rz(nextval\(')([^']+)('.*$)rrEz"%s"r )rrr}r autoincrementrqr|ru)rrrrZquoted_token_parsersearchr7splitrN startswithrI ischema_namesrr]rZNULLTYPErX issubclassrrT)r|rrrr[rprr rqrrurvruZis_arrayZenum_or_domain_keyr}ZcharlenargsrprecZscaleZ field_matchrrdomainr|r}rZschrrrjrjrkrnws                                zPGDialect._get_column_infoc Ks|j||||dd}|jdkr4d|dd}nd}t|jtjd}| |t |d }d d | D} d } t| jtjd }| |t |d }| } | | dS)Nrr)raq SELECT a.attname FROM pg_class t join pg_index ix on t.oid = ix.indrelid join pg_attribute a on t.oid=a.attrelid AND %s WHERE t.oid = :table_oid and ix.indisprimary = 't' ORDER BY a.attnum a.attnum ix.indkeya SELECT a.attname FROM pg_attribute a JOIN ( SELECT unnest(ix.indkey) attnum, generate_subscripts(ix.indkey, 1) ord FROM pg_index ix WHERE ix.indrelid = :table_oid AND ix.indisprimary ) k ON a.attnum=k.attnum WHERE a.attrelid = :table_oid ORDER BY k.ord )rhricSsg|] }|dqSr?rj)rrrjrjrkr7Fsz/PGDialect.get_pk_constraint..z SELECT conname FROM pg_catalog.pg_constraint r WHERE r.conrelid = :table_oid AND r.contype = 'p' ORDER BY 1 )conname)constrained_columnsr) rrr  _pg_index_anyr rrCrrFrrXrlr&) r|rrr rrUZPK_SQLrhr>r`Z PK_CONS_SQLrrjrjrkget_pk_constraint!s,   zPGDialect.get_pk_constraintc s|j|j||||dd}d}td}t|jtj tj d} | | t |d} g} | D]\} } }t || }|\ }}}}}}}}}}}}}|dk r|dkrdnd }fd d td |D}|r||jkr|}n|}n(|r|}n|dk r||kr|}|}fd d td|D}ddd|fd|fd|fd|fd|ffD}| |||||d}| |qb| S)Nrra SELECT r.conname, pg_catalog.pg_get_constraintdef(r.oid, true) as condef, n.nspname as conschema FROM pg_catalog.pg_constraint r, pg_namespace n, pg_class c WHERE r.conrelid = :table AND r.contype = 'f' AND c.oid = confrelid AND n.oid = c.relnamespace ORDER BY 1 a/FOREIGN KEY \((.*?)\) REFERENCES (?:(.*?)\.)?(.*?)\((.*?)\)[\s]?(MATCH (FULL|PARTIAL|SIMPLE)+)?[\s]?(ON UPDATE (CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?[\s]?(ON DELETE (CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?[\s]?(DEFERRABLE|NOT DEFERRABLE)?[\s]?(INITIALLY (DEFERRED|IMMEDIATE)+)?)rcondef)rIZ DEFERRABLETFcsg|]}|qSrjrrOrrjrkr7sz.PGDialect.get_foreign_keys..rwcsg|]}|qSrjrrOrrjrkr7sz\s*,\scSs&i|]\}}|dk r|dkr||qS)Nz NO ACTIONrj)rrarbrjrjrk s z.PGDialect.get_foreign_keys..onupdateondeleter9r.r)rrreferred_schemareferred_tablereferred_columnsoptions)rtrrrcompiler rrCrrFrrXrlr~groupsrrrr\)r|rrr rrrUZFK_SQLZFK_REGEXrhr>ZfkeysrrZ conschemarRrrrrrrrrr.r9rZfkey_drjrrkget_foreign_keysTs           zPGDialect.get_foreign_keyscs>|jdkr.ddfddtddDSdfSdS) N)rrrJz OR c3s|]}d|fVqdS)z %s[%d] = %sNrj)rindr5 compare_torjrkr!sz*PGDialect._pg_index_any..rrz %s = ANY(%s))r rYrange)r|r5rrjrrkrs   zPGDialect._pg_index_anyc# sx|j||||dd}|jdkrfd|jdkr2dnd|jdkrBdnd |jd krRd nd |d d f}nd|jdkrvdnd f}t|jtjtjd}| |t |d}t dd} d} | D]} | \ } } }}}}}}}}}}|r| | krt d| | } q| | k}| | }|dk r*||d|<|s|}|rd||drd||d}|d|}ng}dd|D|d<dd|D|d<i}t|pdD]`\}}t|}d}|d@r|d7}|d@s|d 7}n|d@r|d!7}|r|||<q|r||d"<| |d#<|dk r,| |d$<|rHt d%d|D|d&<|r`|d'kr`||d(<|r||d)<qg} | D]\}!|!d#fd*ddDd+}"|jdkrʇfd,ddD|"d-<d$krd$|"d$<d"kr t fd.d/d"D|"d0<d&kr*d&|"d1id2<d(krHd(|"d1id3<d)krfd)|"d1id)<| |"qz| S)4Nrr)ra SELECT i.relname as relname, ix.indisunique, ix.indexprs, ix.indpred, a.attname, a.attnum, NULL, ix.indkey%s, %s, %s, am.amname, NULL as indnkeyatts FROM pg_class t join pg_index ix on t.oid = ix.indrelid join pg_class i on i.oid = ix.indexrelid left outer join pg_attribute a on t.oid = a.attrelid and %s left outer join pg_am am on i.relam = am.oid WHERE t.relkind IN ('r', 'v', 'f', 'm') and t.oid = :table_oid and ix.indisprimary = 'f' ORDER BY t.relname, i.relname rz ::varcharr zix.indoption::varcharNULLrz i.reloptionsrra/ SELECT i.relname as relname, ix.indisunique, ix.indexprs, a.attname, a.attnum, c.conrelid, ix.indkey::varchar, ix.indoption::varchar, i.reloptions, am.amname, pg_get_expr(ix.indpred, ix.indrelid), %s as indnkeyatts FROM pg_class t join pg_index ix on t.oid = ix.indrelid join pg_class i on i.oid = ix.indexrelid left outer join pg_attribute a on t.oid = a.attrelid and a.attnum = ANY(ix.indkey) left outer join pg_constraint c on (ix.indrelid = c.conrelid and ix.indexrelid = c.conindid and c.contype in ('p', 'u', 'x')) left outer join pg_am am on i.relam = am.oid WHERE t.relkind IN ('r', 'v', 'f', 'm', 'p') and t.oid = :table_oid and ix.indisprimary = 'f' ORDER BY t.relname, i.relname ) rzix.indnkeyatts)rYrhricSsttSrrrXrjrjrjrk.z'PGDialect.get_indexes..z;Skipped unsupported reflection of expression-based index %sr`cSsg|]}t|qSrjrNstriprrarjrjrkr7[sz)PGDialect.get_indexes..rZcSsg|]}t|qSrjrrrjrjrkr7\sincrjr)r/rE)Z nulls_last)Z nulls_firstsortingrMZduplicates_constraintcSsg|]}|dqS)=)r)roptionrjrjrkr7ysrZbtreeamnameZpostgresql_wherecsg|]}d|qSr`rjr]idxrjrkr7s)rrM column_namescsg|]}d|qSrrjr]rrjrkr7sZinclude_columnsc3s*|]"\}}dd||fVqdS)r`rZNrj)rrrrrjrkr!sz(PGDialect.get_indexes..Zcolumn_sortingrZpostgresql_withZpostgresql_using)rrr rr rrCrrFrrXrrlrr]r enumeraterNrr^rr\)#r|rrr rrUZIDX_SQLrhr>ZindexesZ sv_idx_namerAZidx_namerMrr5col_numZconrelidZidx_keyZ idx_optionrrZfilter_definitionZ indnkeyattsZhas_idxrZidx_keysZinc_keysrZcol_idxZ col_flagsZ col_sortingrVrentryrjrrk get_indexess  & $                           zPGDialect.get_indexesc Ks|j||||dd}d}t|jtjd}||t|d}t dd} | D](} | | j } | j | d<| j | d | j<qVd d | DS) Nrra SELECT cons.conname as name, cons.conkey as key, a.attnum as col_num, a.attname as col_name FROM pg_catalog.pg_constraint cons join pg_attribute a on cons.conrelid = a.attrelid AND a.attnum = ANY(cons.conkey) WHERE cons.conrelid = :table_oid AND cons.contype = 'u' )col_namericSsttSrrrjrjrjrkrrz2PGDialect.get_unique_constraints..rZr`cs,g|]$\}|fdddDdqS)csg|]}d|qSrrjr]ucrjrkr7sz?PGDialect.get_unique_constraints...rZ)rrrjrrjrrkr7sz4PGDialect.get_unique_constraints..)rrr rrCrrFrrXrrlrrZrrr^) r|rrr rrUZ UNIQUE_SQLrhr>ZuniquesrArrjrjrkget_unique_constraintss"    z PGDialect.get_unique_constraintscKs@|j||||dd}d}|t|t|d}d|iS)Nrrz SELECT pgd.description as table_comment FROM pg_catalog.pg_description pgd WHERE pgd.objsubid = 0 AND pgd.objoid = :table_oid rir)rrrr rrXr&)r|rrr rrUZ COMMENT_SQLr>rjrjrkget_table_comments zPGDialect.get_table_commentcKs|j||||dd}d}|t|t|d}g}|D]~\} } tjd| tjd} | snt d| d} ntj d tjd d | d } | | d } | r| d rddi| d<|| q<|S)Nrra SELECT cons.conname as name, pg_get_constraintdef(cons.oid) as src FROM pg_catalog.pg_constraint cons WHERE cons.conrelid = :table_oid AND cons.contype = 'c' riz^CHECK *\((.+)\)( NOT VALID)?$)rz)Could not parse CHECK constraint text: %rr z^[\s\n]*\((.+)\)[\s\n]*$z\1r)rr0rEZ not_validTr)rrrr rrXrrDOTALLrr]rrr7r\)r|rrr rrUZ CHECK_SQLr>retrsrcrRr0rrjrjrkget_check_constraintss<     zPGDialect.get_check_constraintsc Cs|p|j}|jsiSd}|dkr(|d7}|d7}t|jtjtjd}|dkr\|j|d}||}g}i}| D]n}|j |j f} | |kr|| d |j qv|j |j |jgd|| <} |j dk r| d |j | | qv|S) Na SELECT t.typname as "name", -- no enum defaults in 8.4 at least -- t.typdefault as "default", pg_catalog.pg_type_is_visible(t.oid) as "visible", n.nspname as "schema", e.enumlabel as "label" FROM pg_catalog.pg_type t LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace LEFT JOIN pg_catalog.pg_enum e ON t.oid = e.enumtypid WHERE t.typtype = 'e' rkzAND n.nspname = :schema z ORDER BY "schema", "name", e.oid)rhlabelr rz)rr rjrz)rrr rrCrrFrDrrlr rr\rrj) r|rr Z SQL_ENUMSrHr>rZ enum_by_namerrZZenum_recrjrjrkr s:         zPGDialect._load_enumsc Csd}t|}|jdd|}i}|D]Z}|}td|dd}|dr^|df}n|d |df}||d |d d ||<q,|S) Na SELECT t.typname as "name", pg_catalog.format_type(t.typbasetype, t.typtypmod) as "attype", not t.typnotnull as "nullable", t.typdefault as "default", pg_catalog.pg_type_is_visible(t.oid) as "visible", n.nspname as "schema" FROM pg_catalog.pg_type t LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE t.typtype = 'd' T)Z future_resultz([^\(]+)rurrjrr r}r)rur}r)r rZexecution_optionsrZmappingsrr~r7) r|rZ SQL_DOMAINSrHr>rprrurZrjrjrkrmAs    zPGDialect._load_domains)NNN)TF)TF)N)N)N)N)N)N)Nr)N)N)N)N)NF)N)N)N)N)`rfrgrhrZsupports_statement_cacheZsupports_alterZmax_identifier_lengthZsupports_sane_rowcountrZsupports_native_booleanryZsupports_sequencesZsequences_optionalZ"preexecute_autoincrement_sequencesZpostfetch_lastrowidZsupports_commentsZsupports_default_valuesZsupports_default_metavalueZsupports_empty_insertZsupports_multivalues_insertrvZdefault_paramstylerr#rZstatement_compilerrrZ ddl_compilerrrrr&rZexecution_ctx_clsrZ inspectorrr"r!rrZconnection_characteristicsrLrrr ZIndexZTableZconstruct_argumentsZreflection_optionsr$rrryrr)rr*r'r0rr rrr7r8r=r>rBrCrJrKrLrrSrcacherrWr\rrrcrfrsrnrrrrrrrrrmrrjrjr}rkr s     $     '  "  '    !   l+ 2 r P %  , 4r)vrr collectionsrdatetimerrrrrr rrrZ_hstorer_jsonr_rangesr r r rZenginerrrrrrrrrr<Zsql.ddlrtypesrrrrrrrr r!r"r#rrrUNICODErrrZ_DECIMAL_TYPESZ _FLOAT_TYPESZ _INT_TYPESZ LargeBinaryrdZFloatrlZ TypeEnginermZPGInetrnZPGCidrroZ PGMacAddrrprsrtrurZNativeForEmulatedZ_AbstractIntervalrZ PGIntervalrZPGBitZPGUuidrrrrrrZ JSONPathTyper#rrrrrrrrStringrZ SQLCompilerrZ DDLCompilerrrZGenericTypeCompilerrZIdentifierPreparerrZ InspectorrZ_CreateDropBaserrZDefaultExecutionContextrZConnectionCharacteristicrrrrrjrjrjrksO                                 k-  ( < . B;