관리-도구
편집 파일: base.cpython-37.pyc
B ��4][� � g @ s� d Z ddlmZ ddlZddlZddlmZ ddlmZ ddlm Z ddlm Z dd lmZ dd lm Z ddl mZ ddl mZ dd l mZ ddl mZ ddl m Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ yddlm Z! W n e"k �rR dZ!Y nX e�#dej$�Z%e�#dej$ej&B �Z'e(dddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dd�d�d�gf�Z)d�Z*d�Z+d�Z,G d�d�� d�ej-�Z.G d�d�� d�ej/�Z0G d�d�� d�ej1�Z2e2Z3G d�d�� d�ej1�Z4e4Z5G d�d�� d�ej1�Z6e6Z7G d�d�� d�ej1�Z8G d�d�� d�ej1�Z9G d�d�� d�ej1�Z:G d�d�� d�ej;�Z;G d�d�� d�ej<�Z<G d�d�� d�ej=ej>�Z?e?Z@G d�d�� d�ej1�ZAeAZBG d�d�� d�ej1�Z e ZCG d�d�� d�ej1�ZDG d�d�� d�ej=ejE�ZFejGe?ejEeFiZHeeeeeejIejIeeeee2e4e eAeAe6e8e9e:e0e;e;e;e<e<ee<e.ee?eDd�� ZJG d�d�� d�ejK�ZLG d�d�� d�ejM�ZNG d�d�� d�ejO�ZPG d�d�� d�ejQ�ZRG d�d�� d�e jS�ZTG d�d�� d�ejU�ZVG d�d�� d�ejU�ZWG d�d�� d�ejX�ZYG d�d�� d�ejZ�Z[dS )�a� .. dialect:: postgresql :name: PostgreSQL .. _postgresql_sequences: Sequences/SERIAL/IDENTITY ------------------------- PostgreSQL supports sequences, and SQLAlchemy uses these as the default means of creating new primary key values for integer-based primary key columns. When creating tables, SQLAlchemy will issue the ``SERIAL`` datatype for integer-based primary key columns, which generates a sequence and server side default corresponding to the column. To specify a specific named sequence to be used for primary key generation, use the :func:`~sqlalchemy.schema.Sequence` construct:: Table('sometable', metadata, Column('id', Integer, Sequence('some_id_seq'), primary_key=True) ) When SQLAlchemy issues a single INSERT statement, to fulfill the contract of having the "last insert identifier" available, a RETURNING clause is added to the INSERT statement which specifies the primary key columns should be returned after the statement completes. The RETURNING functionality only takes place if PostgreSQL 8.2 or later is in use. As a fallback approach, the sequence, whether specified explicitly or implicitly via ``SERIAL``, is executed independently beforehand, the returned value to be used in the subsequent insert. Note that when an :func:`~sqlalchemy.sql.expression.insert()` construct is executed using "executemany" semantics, the "last inserted identifier" functionality does not apply; no RETURNING clause is emitted nor is the sequence pre-executed in this case. To force the usage of RETURNING by default off, specify the flag ``implicit_returning=False`` to :func:`.create_engine`. PostgreSQL 10 IDENTITY columns ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PostgreSQL 10 has a new IDENTITY feature that supersedes the use of SERIAL. Built-in support for rendering of IDENTITY is not available yet, however the following compilation hook may be used to replace occurrences of SERIAL with IDENTITY:: from sqlalchemy.schema import CreateColumn from sqlalchemy.ext.compiler import compiles @compiles(CreateColumn, 'postgresql') def use_identity(element, compiler, **kw): text = compiler.visit_create_column(element, **kw) text = text.replace("SERIAL", "INT GENERATED BY DEFAULT AS IDENTITY") return text Using the above, a table such as:: t = Table( 't', m, Column('id', Integer, primary_key=True), Column('data', String) ) Will generate on the backing database as:: CREATE TABLE t ( id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, data VARCHAR, PRIMARY KEY (id) ) .. _postgresql_isolation_level: Transaction Isolation Level --------------------------- All PostgreSQL dialects support setting of transaction isolation level both via a dialect-specific parameter :paramref:`.create_engine.isolation_level` accepted by :func:`.create_engine`, as well as the :paramref:`.Connection.execution_options.isolation_level` argument as passed to :meth:`.Connection.execution_options`. When using a non-psycopg2 dialect, this feature works by issuing the command ``SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL <level>`` for each new connection. For the special AUTOCOMMIT isolation level, DBAPI-specific techniques are used. To set isolation level using :func:`.create_engine`:: engine = create_engine( "postgresql+pg8000://scott:tiger@localhost/test", isolation_level="READ UNCOMMITTED" ) To set using per-connection execution options:: connection = engine.connect() connection = connection.execution_options( isolation_level="READ COMMITTED" ) Valid values for ``isolation_level`` include: * ``READ COMMITTED`` * ``READ UNCOMMITTED`` * ``REPEATABLE READ`` * ``SERIALIZABLE`` * ``AUTOCOMMIT`` - on psycopg2 / pg8000 only .. seealso:: :ref:`psycopg2_isolation_level` :ref:`pg8000_isolation_level` .. _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:`.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:`.Table` objects will in all cases retain this ``.schema`` attribute as was specified. However, with regards to tables which these :class:`.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 <http://www.postgresql.org/docs/current/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_. By default, the PostgreSQL dialect mimics the behavior encouraged by PostgreSQL's own ``pg_get_constraintdef()`` builtin procedure. This function returns a sample definition for a particular foreign key constraint, omitting the referenced schema name from that definition when the name is also in the PostgreSQL schema search path. The interaction below illustrates this behavior:: test=> CREATE TABLE test_schema.referred(id INTEGER PRIMARY KEY); CREATE TABLE test=> CREATE TABLE referring( test(> id INTEGER PRIMARY KEY, test(> referred_id INTEGER REFERENCES test_schema.referred(id)); CREATE TABLE test=> SET search_path TO public, test_schema; test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n test-> ON n.oid = c.relnamespace test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid test-> WHERE c.relname='referring' AND r.contype = 'f' test-> ; pg_get_constraintdef --------------------------------------------------- FOREIGN KEY (referred_id) REFERENCES referred(id) (1 row) Above, we created a table ``referred`` as a member of the remote schema ``test_schema``, however when we added ``test_schema`` to the PG ``search_path`` and then asked ``pg_get_constraintdef()`` for the ``FOREIGN KEY`` syntax, ``test_schema`` was not included in the output of the function. On the other hand, if we set the search path back to the typical default of ``public``:: test=> SET search_path TO public; SET The same query against ``pg_get_constraintdef()`` now returns the fully schema-qualified name for us:: test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n test-> ON n.oid = c.relnamespace test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid test-> WHERE c.relname='referring' AND r.contype = 'f'; pg_get_constraintdef --------------------------------------------------------------- FOREIGN KEY (referred_id) REFERENCES test_schema.referred(id) (1 row) SQLAlchemy will by default use the return value of ``pg_get_constraintdef()`` in order to determine the remote schema name. That is, if our ``search_path`` were set to include ``test_schema``, and we invoked a table reflection process as follows:: >>> from sqlalchemy import Table, MetaData, create_engine >>> engine = create_engine("postgresql://scott:tiger@localhost/test") >>> with engine.connect() as conn: ... conn.execute("SET search_path TO test_schema, public") ... meta = MetaData() ... referring = Table('referring', meta, ... autoload=True, autoload_with=conn) ... <sqlalchemy.engine.result.ResultProxy object at 0x101612ed0> The above process would deliver to the :attr:`.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:`.Table` as well as :meth:`.MetaData.reflect`:: >>> with engine.connect() as conn: ... conn.execute("SET search_path TO test_schema, public") ... meta = MetaData() ... referring = Table('referring', meta, autoload=True, ... autoload_with=conn, ... postgresql_ignore_search_path=True) ... <sqlalchemy.engine.result.ResultProxy object at 0x1016126d0> 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:`.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:`.Table` and :meth:`.MetaData.reflect`. .. seealso:: `The Schema Search Path <http://www.postgresql.org/docs/9.0/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_ - on the PostgreSQL website. INSERT/UPDATE...RETURNING ------------------------- The dialect supports PG 8.2's ``INSERT..RETURNING``, ``UPDATE..RETURNING`` and ``DELETE..RETURNING`` syntaxes. ``INSERT..RETURNING`` is used by default for single-row INSERT statements in order to fetch newly generated primary key identifiers. To specify an explicit ``RETURNING`` clause, use the :meth:`._UpdateBase.returning` method on a per-statement basis:: # INSERT..RETURNING result = table.insert().returning(table.c.col1, table.c.col2).\ values(name='foo') print result.fetchall() # UPDATE..RETURNING result = table.update().returning(table.c.col1, table.c.col2).\ where(table.c.name=='foo').values(name='bar') print result.fetchall() # DELETE..RETURNING result = table.delete().returning(table.c.col1, table.c.col2).\ where(table.c.name=='foo') print result.fetchall() .. _postgresql_insert_on_conflict: INSERT...ON CONFLICT (Upsert) ------------------------------ Starting with version 9.5, PostgreSQL allows "upserts" (update or insert) of rows into a table via the ``ON CONFLICT`` clause of the ``INSERT`` statement. A candidate row will only be inserted if that row does not violate any unique constraints. In the case of a unique constraint violation, a secondary action can occur which can be either "DO UPDATE", indicating that the data in the target row should be updated, or "DO NOTHING", which indicates to silently skip this row. Conflicts are determined using existing unique constraints and indexes. These constraints may be identified either using their name as stated in DDL, or they may be *inferred* by stating the columns and conditions that comprise the indexes. SQLAlchemy provides ``ON CONFLICT`` support via the PostgreSQL-specific :func:`.postgresql.dml.insert()` function, which provides the generative methods :meth:`~.postgresql.dml.Insert.on_conflict_do_update` and :meth:`~.postgresql.dml.Insert.on_conflict_do_nothing`:: 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'] ) conn.execute(do_nothing_stmt) do_update_stmt = insert_stmt.on_conflict_do_update( constraint='pk_my_table', set_=dict(data='updated value') ) conn.execute(do_update_stmt) Both methods supply the "target" of the conflict using either the named constraint or by column inference: * The :paramref:`.Insert.on_conflict_do_update.index_elements` argument specifies a sequence containing string column names, :class:`.Column` objects, and/or SQL expression elements, which would identify a unique index:: do_update_stmt = insert_stmt.on_conflict_do_update( index_elements=['id'], set_=dict(data='updated value') ) do_update_stmt = insert_stmt.on_conflict_do_update( index_elements=[my_table.c.id], set_=dict(data='updated value') ) * When using :paramref:`.Insert.on_conflict_do_update.index_elements` to infer an index, a partial index can be inferred by also specifying the use the :paramref:`.Insert.on_conflict_do_update.index_where` parameter:: from sqlalchemy.dialects.postgresql import insert 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) ) conn.execute(stmt) * The :paramref:`.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:: do_update_stmt = insert_stmt.on_conflict_do_update( constraint='my_table_idx_1', set_=dict(data='updated value') ) do_update_stmt = insert_stmt.on_conflict_do_update( constraint='my_table_pk', set_=dict(data='updated value') ) * The :paramref:`.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:`.Table` using the :attr:`.Table.primary_key` attribute:: do_update_stmt = insert_stmt.on_conflict_do_update( constraint=my_table.primary_key, set_=dict(data='updated value') ) ``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:`.Insert.on_conflict_do_update.set_` parameter. This parameter accepts a dictionary which consists of direct values for UPDATE:: from sqlalchemy.dialects.postgresql import insert 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') ) conn.execute(do_update_stmt) .. warning:: The :meth:`.Insert.on_conflict_do_update` method does **not** take into account Python-side default UPDATE values or generation functions, e.g. e.g. those specified using :paramref:`.Column.onupdate`. These values will not be exercised for an ON CONFLICT style of UPDATE, unless they are manually specified in the :paramref:`.Insert.on_conflict_do_update.set_` dictionary. In order to refer to the proposed insertion row, the special alias :attr:`~.postgresql.dml.Insert.excluded` is available as an attribute on the :class:`.postgresql.dml.Insert` object; this object is a :class:`.ColumnCollection` which alias contains all columns of the target table:: from sqlalchemy.dialects.postgresql import insert 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) ) conn.execute(do_update_stmt) The :meth:`.Insert.on_conflict_do_update` method also accepts a WHERE clause using the :paramref:`.Insert.on_conflict_do_update.where` parameter, which will limit those rows which receive an UPDATE:: from sqlalchemy.dialects.postgresql import insert 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) ) conn.execute(on_update_stmt) ``ON CONFLICT`` may also 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.dml.Insert.on_conflict_do_nothing` method:: from sqlalchemy.dialects.postgresql import insert stmt = insert(my_table).values(id='some_id', data='inserted value') stmt = stmt.on_conflict_do_nothing(index_elements=['id']) conn.execute(stmt) 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:: from sqlalchemy.dialects.postgresql import insert stmt = insert(my_table).values(id='some_id', data='inserted value') stmt = stmt.on_conflict_do_nothing() conn.execute(stmt) .. versionadded:: 1.1 Added support for PostgreSQL ON CONFLICT clauses .. seealso:: `INSERT .. ON CONFLICT <http://www.postgresql.org/docs/current/static/sql-insert.html#SQL-ON-CONFLICT>`_ - in the PostgreSQL documentation. .. _postgresql_match: Full Text Search ---------------- SQLAlchemy makes available the PostgreSQL ``@@`` operator via the :meth:`.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. .. _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) Operator Classes ^^^^^^^^^^^^^^^^ PostgreSQL allows the specification of an *operator class* for each column of an index (see http://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`` dictionary are the "key" name of the :class:`.Column`, i.e. the name used to access it from the ``.c`` collection of :class:`.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' }) 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 http://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:`.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:`.Inspector`, the :meth:`.Inspector.get_indexes` and the :meth:`.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=True)``, the UNIQUE INDEX is **not** returned in :attr:`.Table.indexes` when it is detected as mirroring a :class:`.UniqueConstraint` in the :attr:`.Table.constraints` collection. .. versionchanged:: 1.0.0 - :class:`.Table` reflection now includes :class:`.UniqueConstraint` objects present in the :attr:`.Table.constraints` collection; the PostgreSQL backend will no longer include a "mirrored" :class:`.Index` construct in :attr:`.Table.indexes` if it is detected as corresponding to a unique constraint. Special Reflection Options -------------------------- The :class:`.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:`.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 <http://www.postgresql.org/docs/current/static/sql-createtable.html>`_ 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. In order to send and receive an ARRAY of ENUM, use the following workaround type, which decorates the :class:`.postgresql.ARRAY` datatype. .. 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, for an ARRAY of JSON/JSONB we need to render the appropriate CAST, however current psycopg2 drivers seem to handle the result for ARRAY of JSON automatically, so the type is simpler:: 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� )�exc)�schema)�sql)�util)�default)� reflection)�compiler)�elements)� expression)�sqltypes)�BIGINT)�BOOLEAN)�CHAR)�DATE)�FLOAT)�INTEGER)�NUMERIC)�REAL)�SMALLINT)�TEXT)�VARCHAR)�UUIDz ^(?:btree|hash|gist|gin|[\w_]+)$zs\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|GRANT|REVOKE|IMPORT FOREIGN SCHEMA|REFRESH MATERIALIZED VIEW|TRUNCATE)�allZanalyseZanalyze�and�any�array�asZascZ asymmetricZboth�case�cast�check�collate�column� constraint�createZcurrent_catalogZcurrent_dateZcurrent_roleZcurrent_timeZcurrent_timestampZcurrent_userr � deferrable�descZdistinctZdo�else�end�except�falseZfetch�forZforeign�fromZgrant�groupZhaving�in� initiallyZ intersectZintoZleading�limit� localtimeZlocaltimestamp�new�not�null�of�off�offset�old�on�only�or�orderZplacingZprimaryZ referencesZ returning�selectZsession_userZsomeZ symmetric�tableZthen�toZtrailing�true�union�unique�user�usingZvariadicZwhen�where�window�withZ authorizationZbetween�binaryZcrossZcurrent_schemaZfreeze�fullZilike�inner�isZisnull�join�leftZlikeZnatural�notnullZouterZoverZoverlaps�rightZsimilar�verbose)i� i� )i� i� i� i� )� � � � i� i� i� c @ s e Zd Zd ZdS )�BYTEAN)�__name__� __module__�__qualname__�__visit_name__� r[ r[ �V/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/dialects/postgresql/base.pyrV 7 s rV c @ s e Zd Zd ZdS )�DOUBLE_PRECISIONN)rW rX rY rZ r[ r[ r[ r\ r] ; s r] c @ s e Zd Zd ZdS )�INETN)rW rX rY rZ r[ r[ r[ r\ r^ ? s r^ c @ s e Zd Zd ZdS )�CIDRN)rW rX rY rZ r[ r[ r[ r\ r_ F s r_ c @ s e Zd Zd ZdS )�MACADDRN)rW rX rY rZ r[ r[ r[ r\ r` M s r` c @ s e Zd ZdZd ZdS )�MONEYzCProvide the PostgreSQL MONEY type. .. versionadded:: 1.2 N)rW rX rY �__doc__rZ r[ r[ r[ r\ ra T s ra c @ s e Zd ZdZd ZdS )�OIDzCProvide the PostgreSQL OID type. .. versionadded:: 0.9.5 N)rW rX rY rb rZ r[ r[ r[ r\ rc _ s rc c @ s e Zd ZdZd ZdS )�REGCLASSzHProvide the PostgreSQL REGCLASS type. .. versionadded:: 1.2.7 N)rW rX rY rb rZ r[ r[ r[ r\ rd j s rd c s e Zd Zd� fdd� Z� ZS )� TIMESTAMPFNc s t t| �j|d� || _d S )N)�timezone)�superre �__init__� precision)�selfrf ri )� __class__r[ r\ rh v s zTIMESTAMP.__init__)FN)rW rX rY rh � __classcell__r[ r[ )rk r\ re u s re c s e Zd Zd� fdd� Z� ZS )�TIMEFNc s t t| �j|d� || _d S )N)rf )rg rm rh ri )rj rf ri )rk r[ r\ rh | s z TIME.__init__)FN)rW rX rY rh rl r[ r[ )rk r\ rm { s rm c @ sF e Zd ZdZd ZdZddd�Zedd� �Ze dd � �Z e d d� �ZdS ) �INTERVALz�PostgreSQL INTERVAL type. The INTERVAL type may not be supported on all DBAPIs. It is known to work on psycopg2 and not pg8000 or zxjdbc. TNc C s || _ || _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)ri �fields)rj ri ro r[ r[ r\ rh � s zINTERVAL.__init__c K s t |jd�S )N)ri )rn Zsecond_precision)�cls�interval�kwr[ r[ r\ �adapt_emulated_to_native� s z!INTERVAL.adapt_emulated_to_nativec C s t jS )N)r �Interval)rj r[ r[ r\ �_type_affinity� s zINTERVAL._type_affinityc C s t jS )N)�dt� timedelta)rj r[ r[ r\ �python_type� s zINTERVAL.python_type)NN)rW rX rY rb rZ Znativerh �classmethodrs �propertyru rx r[ r[ r[ r\ rn � s rn c @ s e Zd Zd Zddd�ZdS )�BITNFc C s |s|p d| _ n|| _ || _d S )N� )�length�varying)rj r} r~ r[ r[ r\ rh � s zBIT.__init__)NF)rW rX rY rZ rh r[ r[ r[ r\ r{ � s r{ c @ s. e Zd ZdZd Zd dd�Zdd� Zdd� Zd S )r a PostgreSQL UUID type. Represents the UUID column type, interpreting data either as natively returned by the DBAPI or as Python uuid objects. The UUID type may not be supported on all DBAPIs. It is known to work on psycopg2 and not pg8000. Fc C s |rt dkrtd��|| _dS )z�Construct a UUID type. :param as_uuid=False: if True, values will be interpreted as Python uuid objects, converting to/from string via the DBAPI. Nz=This version of Python does not support the native UUID type.)�_python_UUID�NotImplementedError�as_uuid)rj r� r[ r[ r\ rh � s z UUID.__init__c C s | j rdd� }|S d S d S )Nc S s | d k rt �| �} | S )N)r � text_type)�valuer[ r[ r\ �process� s z$UUID.bind_processor.<locals>.process)r� )rj �dialectr� r[ r[ r\ �bind_processor� s zUUID.bind_processorc C s | j rdd� }|S d S d S )Nc S s | d k rt | �} | S )N)r )r� r[ r[ r\ r� � s z&UUID.result_processor.<locals>.process)r� )rj r� �coltyper� r[ r[ r\ �result_processor� s zUUID.result_processorN)F)rW rX rY rb rZ rh r� r� r[ r[ r[ r\ r � s r c @ s e Zd ZdZd ZdS )�TSVECTORa The :class:`.postgresql.TSVECTOR` type implements the PostgreSQL text search type TSVECTOR. It can be used to do full text queries on natural language documents. .. versionadded:: 0.9.0 .. seealso:: :ref:`postgresql_match` N)rW rX rY rb rZ r[ r[ r[ r\ r� � s r� c st e Zd ZdZdZ� fdd�Zedd� �Zddd �Zdd d�Z dd � Z ddd�Zddd�Zddd�Z ddd�Z� ZS )�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:`.Table.create` and :meth:`.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:`.MetaData` object itself:: my_enum = ENUM('a', 'b', 'c', name='myenum', metadata=metadata) t1 = Table('sometable_one', metadata, Column('some_enum', myenum) ) t2 = Table('sometable_two', metadata, Column('some_enum', myenum) ) When this pattern is used, care must still be taken at the level of individual table creates. Emitting CREATE TABLE without also specifying ``checkfirst=True`` will still cause issues:: t1.create(engine) # will fail: no such type 'myenum' If we specify ``checkfirst=True``, the individual table-level create operation will check for the ``ENUM`` and create if not exists:: # will check if enum exists, and emit CREATE TYPE if not t1.create(engine, checkfirst=True) When using a metadata-level ENUM type, the type will always be created and dropped if either the metadata-wide create/drop is called:: metadata.create_all(engine) # will emit CREATE TYPE metadata.drop_all(engine) # will emit DROP TYPE The type can also be created and dropped directly:: my_enum.create(engine) my_enum.drop(engine) .. versionchanged:: 1.0.0 The PostgreSQL :class:`.postgresql.ENUM` type now behaves more strictly with regards to CREATE/DROP. A metadata-level ENUM type will only be created and dropped at the metadata level, not the table level, with the exception of ``table.create(checkfirst=True)``. The ``table.drop()`` call will now emit a DROP TYPE for a table-level enumerated type. Tc s$ |� dd�| _tt| �j||� dS )a Construct an :class:`~.postgresql.ENUM`. Arguments are the same as that of :class:`.types.Enum`, but also including the following parameters. :param create_type: Defaults to True. Indicates that ``CREATE TYPE`` should be emitted, after optionally checking for the presence of the type, when the parent table is being created; and additionally that ``DROP TYPE`` is called when the table is dropped. When ``False``, no check will be performed and no ``CREATE TYPE`` or ``DROP TYPE`` is emitted, unless :meth:`~.postgresql.ENUM.create` or :meth:`~.postgresql.ENUM.drop` are called directly. Setting to ``False`` is helpful when invoking a creation scheme to a SQL file without access to the actual database - the :meth:`~.postgresql.ENUM.create` and :meth:`~.postgresql.ENUM.drop` methods can be used to emit SQL to a target bind. �create_typeTN)�popr� rg r� rh )rj �enumsrr )rk r[ r\ rh Y s z ENUM.__init__c K sj |� d|j� |� d|j� |� d|j� |� d|j� |� d|j� |� dd� |� d|j� | f |�S ) zbProduce a PostgreSQL native :class:`.postgresql.ENUM` from plain :class:`.Enum`. �validate_strings�namer �inherit_schema�metadataZ_create_eventsF�values_callable)� setdefaultr� r� r r� r� r� )rp �implrr r[ r[ r\ rs w s zENUM.adapt_emulated_to_nativeNc C s8 |j jsdS |r&|j j|| j| jd�s4|�t| �� dS )a� Emit ``CREATE TYPE`` for this :class:`~.postgresql.ENUM`. If the underlying dialect does not support PostgreSQL CREATE TYPE, no action is taken. :param bind: a connectable :class:`.Engine`, :class:`.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)r )r� �supports_native_enum�has_typer� r �execute�CreateEnumType)rj �bind� checkfirstr[ r[ r\ r% � s zENUM.createc C s8 |j jsdS |r&|j j|| j| jd�r4|�t| �� dS )a� Emit ``DROP TYPE`` for this :class:`~.postgresql.ENUM`. If the underlying dialect does not support PostgreSQL DROP TYPE, no action is taken. :param bind: a connectable :class:`.Engine`, :class:`.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. N)r )r� r� r� r� r r� �DropEnumType)rj r� r� r[ r[ r\ �drop� s z ENUM.dropc C sn | j s dS d|krf|d }d|jkr0|jd }nt� }|jd<