configurations, the :ref:`horizontal_sharding_toplevel` extension may
be used. See the example at :ref:`examples_sharding`.
-
-.. versionadded:: 1.1
-
.. _sql_caching:
sqlalchemy.exc.CompileError: Can't emit DROP CONSTRAINT for constraint
ForeignKeyConstraint(...); it has no name
-.. versionchanged:: 1.0.0 - The DDL system invoked by
- :meth:`_schema.MetaData.create_all`
- and :meth:`_schema.MetaData.drop_all` will now automatically resolve mutually
- dependent foreign keys between tables declared by
- :class:`_schema.ForeignKeyConstraint` and :class:`_schema.ForeignKey` objects, without
- the need to explicitly set the :paramref:`_schema.ForeignKeyConstraint.use_alter`
- flag.
-
-.. versionchanged:: 1.0.0 - The :paramref:`_schema.ForeignKeyConstraint.use_alter`
- flag can be used with an un-named constraint; only the DROP operation
- will emit a specific error when actually called upon.
-
.. seealso::
:ref:`constraint_naming_conventions`
structure of the expression will determine which column is noted as
"column zero".
-.. versionadded:: 1.0.0 The :class:`.CheckConstraint` object now supports
- the ``column_0_name`` naming convention token.
-
.. _naming_schematypes:
Configuring Naming for Boolean, Enum, and other schema types
CONSTRAINT ck_foo_flag CHECK (flag IN (0, 1))
)
-.. versionchanged:: 1.0 Constraint naming conventions that don't include
- ``%(constraint_name)s`` again work with :class:`.SchemaType` constraints.
-
Constraints API
---------------
Above, the presence of ``**kw`` tells :func:`.listens_for` that
arguments should be passed to the function by name, rather than positionally.
-.. versionadded:: 0.9.0 Added optional ``named`` argument dispatch to
- event calling.
-
Targets
-------
""" """
# do something before mappings are configured
-.. versionadded:: 0.9.3
-
-
.. _declarative_metadata:
``metadata``
"Writer.magazine_id == Article.magazine_id)",
)
-.. versionchanged:: 1.0.0 the ORM will attempt to warn when a column is used
- as the synchronization target from more than one relationship
- simultaneously.
-
-
Non-relational Comparisons / Materialized Path
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FROM element
WHERE element.path LIKE ('/foo/bar2' || '/%') ORDER BY element.path
-.. versionadded:: 0.9.5 Support has been added to allow a single-column
- comparison to itself within a primaryjoin condition, as well as for
- primaryjoin conditions that use :meth:`.ColumnOperators.like` as the comparison
- operator.
-
.. _self_referential_many_to_many:
Self-Referential Many-to-Many Relationship
signal to the ORM that we'd like ``None`` to be passed into the type whenever
present, even though no special type-level behaviors are assigned to it.
-.. versionadded:: 1.1 added the :meth:`.TypeEngine.evaluates_none` method
- in order to indicate that a "None" value should be treated as significant.
-
.. _orm_server_defaults:
Fetching Server-Generated Defaults
Another use case for events is to track the lifecycle of objects. This
refers to the states first introduced at :ref:`session_object_states`.
-.. versionadded:: 1.1 added a system of events that intercept all possible
- state transitions of an object within the :class:`.Session`.
-
All the states above can be tracked fully with events. Each event
represents a distinct state transition, meaning, the starting state
and the destination state are both part of what are tracked. With the
the session's transaction is rolled back, a deleted object moves
*back* to the persistent state.
- .. versionchanged:: 1.1 The 'deleted' state is a newly added session
- object state distinct from the 'persistent' state.
-
* **Detached** - an instance which corresponds, or previously corresponded,
to a record in the database, but is not currently in any session.
The detached object will contain a database identity marker, however
when absolutely necessary and only on backends that support :term:`RETURNING`,
currently PostgreSQL, Oracle, MariaDB 10.5, SQLite 3.35, and SQL Server.
-.. versionadded:: 0.9.0
-
- Support for server side version identifier tracking.
Programmatic or Conditional Version Counters
--------------------------------------------
# will leave version_uuid unchanged
u1.name = "u3"
session.commit()
-
-.. versionadded:: 0.9.0
-
- Support for programmatic and conditional version identifier tracking.
-
queued up, here it is. The author recommends "table_per_related"
or "table_per_association" instead of this approach.
-.. versionadded:: 0.8.3
-
"""
from sqlalchemy import and_
from sqlalchemy import Column
will always remain fixed and always output exactly that
type.
-.. versionadded:: 1.0.0
-
.. _multipart_schema_names:
Multipart Schema Names
it is available using the ``legacy_schema_aliasing`` argument to
:func:`_sa.create_engine` as illustrated above.
-.. versionchanged:: 1.1 the ``legacy_schema_aliasing`` flag introduced
- in version 1.0.5 to allow disabling of legacy mode for schemas now
- defaults to False.
-
.. deprecated:: 1.4
The ``legacy_schema_aliasing`` flag is now
CREATE TABLE my_table (x INTEGER NOT NULL, y INTEGER NOT NULL,
PRIMARY KEY NONCLUSTERED (x, y))
-.. versionchanged:: 1.1 the ``mssql_clustered`` option now defaults
- to None, rather than False. ``mssql_clustered=False`` now explicitly
- renders the NONCLUSTERED clause, whereas None omits the CLUSTERED
- clause entirely, allowing SQL Server defaults to take effect.
-
-
MSSQL-Specific Index Options
-----------------------------
either ``VARBINARY(max)`` or IMAGE is rendered, as well as the SQL
Server ``FILESTREAM`` option.
- .. versionadded:: 1.0.0
-
.. seealso::
:ref:`mssql_large_type_deprecation`
additional arguments, such as "CONTENT", "DOCUMENT",
"xml_schema_collection".
- .. versionadded:: 1.1.11
-
"""
__visit_name__ = "XML"
underlying CREATE INDEX, so it *must* be a valid index prefix for your MySQL
storage engine.
-.. versionadded:: 1.1.5
-
.. seealso::
`CREATE INDEX <https://dev.mysql.com/doc/refman/5.0/en/create-index.html>`_ - MySQL documentation
d TIMESTAMP NOT NULL
)
-.. versionchanged:: 1.0.0 - SQLAlchemy now renders NULL or NOT NULL in all
- cases for TIMESTAMP columns, to accommodate
- ``explicit_defaults_for_timestamp``. Prior to this version, it will
- not render "NOT NULL" for a TIMESTAMP column that is ``nullable=False``.
-
""" # noqa
from array import array as _array
essential that the list of set values is expressed in the
**exact same order** as exists on the MySQL database.
- .. versionadded:: 1.0.0
-
"""
self.retrieve_as_bitwise = kw.pop("retrieve_as_bitwise", False)
self.values = tuple(values)
datatype, by adapting the operations to render the ``JSON_EXTRACT``
function at the database level.
- .. versionadded:: 1.1
-
"""
pass
"oracle+cx_oracle://scott:tiger@xe",
exclude_tablespaces=["SYSAUX", "SOME_TABLESPACE"])
-.. versionadded:: 1.1
-
DateTime Compatibility
----------------------
is reflected and the type is reported as ``DATE``, the time-supporting
:class:`_oracle.DATE` type is used.
-.. versionchanged:: 0.9.4 Added :class:`_oracle.DATE` to subclass
- :class:`.DateTime`. This is a change as previous versions
- would reflect a ``DATE`` column as :class:`_types.DATE`, which subclasses
- :class:`.Date`. The only significance here is for schemes that are
- examining the type of column for use in special Python translations or
- for migrating schemas to other database backends.
-
.. _oracle_table_options:
Oracle Table Options
"some_table", metadata, ...,
prefixes=['GLOBAL TEMPORARY'], oracle_on_commit='PRESERVE ROWS')
-.. versionadded:: 1.0.0
-
* ``COMPRESS``::
Table('mytable', metadata, Column('data', String(32)),
The ``oracle_compress`` parameter accepts either an integer compression
level, or ``True`` to use the default compression level.
-.. versionadded:: 1.0.0
-
.. _oracle_index_options:
Oracle Specific Index Options
Bitmap indexes cannot be unique and cannot be compressed. SQLAlchemy will not
check for such limitations, only the database will.
-.. versionadded:: 1.0.0
-
Index compression
~~~~~~~~~~~~~~~~~
number of prefix columns to compress, or ``True`` to use the default (all
columns for non-unique indexes, all but the last column for unique indexes).
-.. versionadded:: 1.0.0
-
""" # noqa
from __future__ import annotations
:class:`_types.DateTime`; this is to suit the fact that the Oracle
``DATE`` type supports a time value.
- .. versionadded:: 0.9.4
-
"""
__visit_name__ = "DATE"
class ARRAY(sqltypes.ARRAY):
-
"""PostgreSQL ARRAY type.
- .. versionchanged:: 1.1 The :class:`_postgresql.ARRAY` type is now
- a subclass of the core :class:`_types.ARRAY` type.
-
The :class:`_postgresql.ARRAY` type is constructed in the same way
as the core :class:`_types.ARRAY` type; a member type is required, and a
number of dimensions is recommended if the type is to be used for more
a value of one will be added to all index values before passing
to the database.
- .. versionadded:: 0.9.5
-
-
"""
if isinstance(item_type, ARRAY):
raise ValueError(
{printsql}INSERT INTO my_table (id, data) VALUES (%(id)s, %(data)s)
ON CONFLICT ON CONSTRAINT pk_my_table DO UPDATE SET data = %(param_1)s
-.. versionadded:: 1.1
-
.. seealso::
`INSERT .. ON CONFLICT
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:
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
: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
--------------------------
Table("some_table", metadata, ..., postgresql_inherits=("t1", "t2", ...))
- .. versionadded:: 1.0.0
-
* ``PARTITION BY``::
Table("some_table", metadata, ...,
(typically 'public') is used. May also be set to ``'*'`` to
indicate load enums for all schemas.
- .. versionadded:: 1.0.0
-
"""
with self._operation_context() as conn:
return self.dialect._load_enums(
except that the list is limited to those tables that report a
``relkind`` value of ``f``.
- .. versionadded:: 1.0.0
-
"""
with self._operation_context() as conn:
return self.dialect._get_foreign_table_names(
The :class:`_postgresql.Insert` object is created using the
:func:`sqlalchemy.dialects.postgresql.insert` function.
- .. versionadded:: 1.1
-
"""
stringify_dialect = "postgresql"
not meeting the ``WHERE`` condition will not be updated
(effectively a ``DO NOTHING`` for those rows).
- .. versionadded:: 1.1
-
.. seealso::
Additional WHERE criterion that can be used to infer a
conditional target index.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`postgresql_insert_on_conflict`
SELECT string_agg(a, ',' ORDER BY a) FROM table;
- .. versionadded:: 1.1
-
.. versionchanged:: 1.2.13 - the ORDER BY argument may be multiple terms
.. seealso::
the plain :class:`_types.ARRAY`, unless an explicit ``type_``
is passed.
- .. versionadded:: 1.1
-
"""
kw["_default_array_type"] = ARRAY
return functions.func.array_agg(*arg, **kw)
:param text_type: the type that should be used for indexed values.
Defaults to :class:`_types.Text`.
- .. versionadded:: 1.1.0
-
"""
if text_type is not None:
self.text_type = text_type
data_table.c.data[('key_1', 'key_2', 5, ..., 'key_n')].astext == 'some value'
- .. versionchanged:: 1.1 The :meth:`_expression.ColumnElement.cast`
- operator on
- JSON objects now requires that the :attr:`.JSON.Comparator.astext`
- modifier be called explicitly, if the cast works only from a textual
- string.
-
Index operations return an expression object whose type defaults to
:class:`_types.JSON` by default,
so that further JSON-oriented instructions
:class:`_postgresql.JSONB`
- .. versionchanged:: 1.1 :class:`_postgresql.JSON` is now a PostgreSQL-
- specific specialization of the new :class:`_types.JSON` type.
-
""" # noqa
astext_type = sqltypes.Text()
from sqlalchemy import null
conn.execute(table.insert(), data=null())
- .. versionchanged:: 0.9.8 - Added ``none_as_null``, and :func:`.null`
- is now supported in order to persist a NULL value.
-
.. seealso::
:attr:`_types.JSON.NULL`
:attr:`.JSON.Comparator.astext`
accessor on indexed attributes. Defaults to :class:`_types.Text`.
- .. versionadded:: 1.1
-
"""
super().__init__(none_as_null=none_as_null)
if astext_type is not None:
in the same way that ``psycopg2.extras.register_default_json`` is used
to register these handlers with the json type.
- .. versionadded:: 0.9.7
-
.. seealso::
:class:`_types.JSON`
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.
-
"""
native_enum = True
layer. This makes it suitable for use in e.g. PyPy. Documentation
is as per ``psycopg2``.
-.. versionadded:: 1.0.0
-
.. seealso::
:mod:`sqlalchemy.dialects.postgresql.psycopg2`
class OID(sqltypes.TypeEngine[int]):
- """Provide the PostgreSQL OID type.
-
- .. versionadded:: 0.9.5
-
- """
+ """Provide the PostgreSQL OID type."""
__visit_name__ = "OID"
It can be used to do full text queries on natural language
documents.
- .. versionadded:: 0.9.0
-
.. seealso::
:ref:`postgresql_match`
``REAL``, ``FLOA`` or ``DOUB``.
* Otherwise, the :class:`_types.NUMERIC` type is used.
-.. versionadded:: 0.9.3 Support for SQLite type affinity rules when reflecting
- columns.
-
-
.. _sqlite_partial_index:
Partial Indexes
CREATE INDEX test_idx1 ON testtbl (data)
WHERE data > 5 AND data < 10
-.. versionadded:: 0.9.9
-
.. _sqlite_dotted_column_names:
Dotted Column Names
the SQLite driver up until version **3.10.0** of SQLite has a bug which
requires that SQLAlchemy filter out these dots in result sets.
-.. versionchanged:: 1.1
-
- The following SQLite issue has been resolved as of version 3.10.0
- of SQLite. SQLAlchemy as of **1.1** automatically disables its internal
- workarounds based on detection of this version.
-
The bug, entirely outside of SQLAlchemy, can be illustrated thusly::
import sqlite3
the type will generate its DDL as DATE_CHAR, DATETIME_CHAR,
TIME_CHAR.
- .. versionadded:: 1.0.0
-
"""
spec = self._storage_format % {
"year": 0,
are compiled into strings; the resulting schema name will be
converted based on presence in the map of the original name.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`schema_translating`
which returns the dialect-level setting without performing a SQL
query.
- .. versionadded:: 0.9.9
-
.. seealso::
:attr:`_engine.Connection.default_isolation_level`
ahead of time from the first connection procured by the dialect,
so SQL query is not invoked when this accessor is called.
- .. versionadded:: 0.9.9
-
.. seealso::
:meth:`_engine.Connection.get_isolation_level`
This method is **not public**, but is documented in order to clarify
the "autoclose" process used.
- .. versionadded:: 1.0.0
-
.. seealso::
:meth:`_engine.CursorResult.close`
if :meth:`.ValuesBase.return_defaults` was not used or if the
backend does not support RETURNING.
- .. versionadded:: 0.9.0
-
.. seealso::
:meth:`.ValuesBase.return_defaults`
can still be used for new requests in which case
it re-acquires connection resources.
- .. versionadded:: 1.0.5
-
"""
def begin(self, conn: Connection) -> None:
:meth:`_events.ConnectionEvents.after_execute`
-
- .. versionadded:: 0.9.4
-
"""
_target_class_doc = "SomeEngine"
def receive_do_connect(dialect, conn_rec, cargs, cparams):
return psycopg2.connect(*cargs, **cparams)
-
- .. versionadded:: 1.0.3
-
.. seealso::
:ref:`custom_dbapi_args`
here is so that third-party dialects that haven't yet implemented this
feature continue to function in the old way.
- .. versionadded:: 0.9.2
-
.. seealso::
:class:`.DialectKWArgs` - implementing base class which consumes
This is an internal dialect method. Applications should use
:meth:`.Inspector.get_check_constraints`.
- .. versionadded:: 1.1.0
-
"""
raise NotImplementedError()
By default this just returns the cls.
- .. versionadded:: 1.0.3
-
"""
return cls
events to the engine or its components. In particular, it allows
a dialect-wrapping class to apply dialect-level events.
- .. versionadded:: 1.0.3
-
"""
def get_driver_connection(self, connection: DBAPIConnection) -> Any:
changes can be made to the engine, most typically involving setup of
events (e.g. those defined in :ref:`core_event_toplevel`).
- .. versionadded:: 1.1
-
""" # noqa: E501
def __init__(self, url: URL, kwargs: Dict[str, Any]):
the invalidation of other connections in the pool is to be performed
based on other conditions, or even on a per-connection basis.
- .. versionadded:: 1.0.3
-
"""
is_pre_ping: bool
foreign key constraint names that would require a separate CREATE
step after-the-fact, based on dependencies between tables.
- .. versionadded:: 1.0.-
-
:param schema: schema name to query, if not the default schema.
:param \**kw: Additional keyword argument to pass to the dialect
specific implementation. See the documentation of the dialect
specific implementation. See the documentation of the dialect
in use for more information.
- .. versionadded:: 1.0.0
-
"""
with self._operation_context() as conn:
specific implementation. See the documentation of the dialect
in use for more information.
- .. versionadded:: 1.0.0
-
"""
with self._operation_context() as conn:
return self.dialect.get_temp_view_names(
:return: a list of dictionaries, each representing the
definition of a check constraints.
- .. versionadded:: 1.1.0
-
.. seealso:: :meth:`Inspector.get_multi_check_constraints`
"""
events at high scale, use a mutable structure that is handled
from inside of a single listener.
- .. versionchanged:: 1.0.0 - a ``collections.deque()`` object is now
- used as the container for the list of events, which explicitly
- disallows collection mutation while the collection is being
- iterated.
-
.. seealso::
:func:`.listen`
"""Raised when an object is passed to .execute() that can't be
executed as SQL.
- .. versionadded:: 1.1
-
"""
def __init__(self, target: Any):
ahead of time from the first connection procured by the dialect,
so SQL query is not invoked when this accessor is called.
- .. versionadded:: 0.9.9
-
.. seealso::
:meth:`_engine.Connection.get_isolation_level`
flag is set to ``True`` in the set of relationship keyword arguments.
Note that not all backends support reflection of ON DELETE.
- .. versionadded:: 1.0.0 - automap will detect non-nullable foreign key
- constraints when producing a one-to-many relationship and establish
- a default cascade of ``all, delete-orphan`` if so; additionally,
- if the constraint specifies
- :paramref:`_schema.ForeignKeyConstraint.ondelete`
- of ``CASCADE`` for non-nullable or ``SET NULL`` for nullable columns,
- the ``passive_deletes=True`` option is also added.
-
5. The names of the relationships are determined using the
:paramref:`.AutomapBase.prepare.name_for_scalar_relationship` and
:paramref:`.AutomapBase.prepare.name_for_collection_relationship`
Note this uses a subquery to ensure an accurate count regardless
of the structure of the original statement.
- .. versionadded:: 1.1.6
-
"""
col = func.count(literal_column("*"))
Equivalent to :meth:`_query.Query.scalar`.
- .. versionadded:: 1.1.6
-
"""
try:
ret = self.one()
Equivalent to :meth:`_query.Query.one_or_none`.
- .. versionadded:: 1.0.9
-
"""
return self._iter().one_or_none()
:class:`_types.Indexable` typed column. In simple cases, it can be
treated as a :class:`_schema.Column` - mapped attribute.
-
-.. versionadded:: 1.1
-
Synopsis
========
attribute that corresponds to an :class:`_types.Indexable`
column.
- .. versionadded:: 1.1
-
.. seealso::
:mod:`sqlalchemy.ext.indexable`
of attribute names that have been refreshed; the list is compared
against this set to determine if action needs to be taken.
- .. versionadded:: 1.0.5
-
"""
return {attribute.key}
coercion to the values placed in the dictionary so that they too are
"mutable", and emit events up to their parent structure.
- .. versionadded:: 1.1
-
.. seealso::
:class:`.MutableDict`
coercion to the values placed in the dictionary so that they too are
"mutable", and emit events up to their parent structure.
- .. versionadded:: 1.1
-
.. seealso::
:class:`.MutableDict`
in some cases can enable complex :func:`_orm.relationship` SQL
conditions to be used.
- .. versionadded:: 0.9.2 :paramref:`_orm.relationship.secondary`
- works
- more effectively when referring to a :class:`_expression.Join`
- instance.
-
:param active_history=False:
When ``True``, indicates that the "previous" value for a
many-to-one reference should be loaded when replaced, if
reducing performance of the innermost subquery beyond that of what
duplicate innermost rows may be causing.
- .. versionchanged:: 0.9.0 -
- :paramref:`_orm.relationship.distinct_target_key` now defaults to
- ``None``, so that the feature enables itself automatically for
- those cases where the innermost query targets a non-unique
- key.
-
.. seealso::
:ref:`loading_toplevel` - includes an introduction to subquery
remain associated with the attached :class:`.Session`, however
additional SELECT statements should be blocked.
- .. versionadded:: 1.1
-
* ``write_only`` - the attribute will be configured with a special
"virtual collection" that may receive
:meth:`_orm.WriteOnlyCollection.add` and
:param info: Optional data dictionary which will be populated into the
:attr:`.InspectionAttr.info` attribute of this object.
- .. versionadded:: 1.0.0
-
:param comparator_factory: A subclass of :class:`.PropComparator`
that will provide custom comparison behavior at the SQL expression
level.
:func:`.composite`
functions.
- .. versionchanged:: 1.0.0 :attr:`.MapperProperty.info` is also
- available on extension types via the
- :attr:`.InspectionAttrInfo.info` attribute, so that it can apply
- to a wider variety of ORM and extension constructs.
-
.. seealso::
:attr:`.QueryableAttribute.info`
:meth:`.SessionEvents.pending_to_persistent` and
:meth:`.MapperEvents.after_insert` are better choices.
- .. versionadded:: 1.0.5
-
:param target: the mapped instance. If
the event is configured with ``raw=True``, this will
instead be the :class:`.InstanceState` state-management
@event.listens_for(Mapper, "before_configured")
def go():
- # ...
+ ...
Contrast this event to :meth:`.MapperEvents.after_configured`,
which is invoked after the series of mappers has been configured,
@event.listens_for(mapper, "before_configured", once=True)
def go():
- # ...
-
-
- .. versionadded:: 0.9.3
+ ...
.. seealso::
:param instance: the ORM-mapped instance being operated upon.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
:param instance: the ORM-mapped instance being operated upon.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
:param instance: the ORM-mapped instance being operated upon.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
:param instance: the ORM-mapped instance being operated upon.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
:param instance: the ORM-mapped instance being operated upon.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
:param instance: the ORM-mapped instance being operated upon.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
the :meth:`.SessionEvents.persistent_to_deleted` event is therefore
invoked at the end of a flush.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
:meth:`.Session.rollback`. The event is not called under
any other circumstances.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
events are called, as well as if the object is individually
expunged from its deleted state via :meth:`.Session.expunge`.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
to the detached state because it was marked as deleted and flushed.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_lifecycle_events`
from its original value by backref handlers in order to control
chained event propagation.
- .. versionchanged:: 0.9.0 the ``initiator`` argument is now
- passed as a :class:`.attributes.Event` object, and may be
- modified by backref handlers within a chain of backref-linked
- events.
:param key: When the event is established using the
:paramref:`.AttributeEvents.include_key` parameter set to
True, this will be the key used in the operation, such as
from its original value by backref handlers in order to control
chained event propagation.
- .. versionchanged:: 0.9.0 the ``initiator`` argument is now
- passed as a :class:`.attributes.Event` object, and may be
- modified by backref handlers within a chain of backref-linked
- events.
-
:return: if the event was registered with ``retval=True``,
the given value, or a new effective value, should be returned.
returned by the previous listener that specifies ``retval=True``
as the ``value`` argument of the next listener.
- .. versionadded:: 1.1
-
:param target: the object instance receiving the event.
If the listener is registered with ``raw=True``, this will
be the :class:`.InstanceState` object.
:param collection_adapter: the :class:`.CollectionAdapter` that will
mediate internal access to the collection.
- .. versionadded:: 1.0.0 :meth:`.AttributeEvents.init_collection`
- and :meth:`.AttributeEvents.dispose_collection` events.
-
.. seealso::
:class:`.AttributeEvents` - background on listener options such
contents before the dispose intact; previously, the collection
would be empty.
- .. versionadded:: 1.0.0 the :meth:`.AttributeEvents.init_collection`
- and :meth:`.AttributeEvents.dispose_collection` events.
-
.. seealso::
:class:`.AttributeEvents` - background on listener options such
:func:`.column_property`, :func:`_orm.relationship`, or :func:`.composite`
functions.
- .. versionchanged:: 1.0.0 :attr:`.InspectionAttr.info` moved
- from :class:`.MapperProperty` so that it can apply to a wider
- variety of ORM and extension constructs.
-
.. seealso::
:attr:`.QueryableAttribute.info`
:func:`.composite`
functions.
- .. versionchanged:: 1.0.0 :attr:`.MapperProperty.info` is also
- available on extension types via the
- :attr:`.InspectionAttrInfo.info` attribute, so that it can apply
- to a wider variety of ORM and extension constructs.
-
.. seealso::
:attr:`.QueryableAttribute.info`
those rows automatically. The warning may be changed to an
exception in a future release.
- .. versionadded:: 0.9.4 - added
- :paramref:`.mapper.confirm_deleted_rows` as well as conditional
- matched row checking on delete.
-
:param eager_defaults: if True, the ORM will immediately fetch the
value of server-generated default values after an INSERT or UPDATE,
rather than leaving them as expired to be fetched on next access.
:ref:`orm_server_defaults`
- .. versionchanged:: 0.9.0 The ``eager_defaults`` option can now
- make use of :term:`RETURNING` for backends which support it.
-
.. versionchanged:: 2.0.0 RETURNING now works with multiple rows
INSERTed at once using the
:ref:`insertmanyvalues <engine_insertmanyvalues>` feature, which
to specify passive_deletes without this taking effect for
all subclass mappers.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`passive_deletes` - description of similar feature as
Please see :ref:`server_side_version_counter` for a discussion
of important points when using this option.
- .. versionadded:: 0.9.0 ``version_id_generator`` supports
- server-side version number generation.
-
.. seealso::
:ref:`custom_version_counter`
:func:`.validates` usage where only one validator should emit per
attribute operation.
- .. versionadded:: 0.9.0
-
.. seealso::
:ref:`simple_validators` - usage examples for :func:`.validates`
:param full=False: render FULL OUTER JOIN; implies ``isouter``.
- .. versionadded:: 1.1
-
"""
join_target = coercions.expect(
:class:`.AliasedClass` objects, :class:`.Mapper` objects
as well as core :class:`.FromClause` elements like subqueries.
- .. versionchanged:: 0.9
- This method no longer applies the given FROM object
- to be the selectable from which matching entities
- select from; the :meth:`.select_entity_from` method
- now accomplishes this. See that method for a description
- of this behavior.
-
.. seealso::
:meth:`~.Query.join`
results in an execution of the
underlying query.
- .. versionadded:: 1.0.9
-
- Added :meth:`_query.Query.one_or_none`
-
.. seealso::
:meth:`_query.Query.first`
See :ref:`unitofwork_merging` for a detailed discussion of merging.
- .. versionchanged:: 1.1 - :meth:`.Session.merge` will now reconcile
- pending objects with overlapping primary keys in the same way
- as persistent. See :ref:`change_3601` for discussion.
-
:param instance: Instance to be merged.
:param load: Boolean, when False, :meth:`.merge` switches into
a "high performance" mode which causes it to forego emitting history
:attr:`.SessionTransaction.nested` attribute is ``True``, then
this is a SAVEPOINT, and if ``False``, indicates this a subtransaction.
- .. versionadded:: 1.0.16 - use ._parent for previous versions
-
"""
return self._parent
See :ref:`unitofwork_merging` for a detailed discussion of merging.
- .. versionchanged:: 1.1 - :meth:`.Session.merge` will now reconcile
- pending objects with overlapping primary keys in the same way
- as persistent. See :ref:`change_3601` for discussion.
-
:param instance: Instance to be merged.
:param load: Boolean, when False, :meth:`.merge` switches into
a "high performance" mode which causes it to forego emitting history
or via transaction commit and enters the "detached" state,
this flag will continue to report True.
- .. versionadded:: 1.1 - added a local method form of
- :func:`.orm.util.was_deleted`.
-
.. seealso::
:attr:`.InstanceState.deleted` - refers to the "deleted" state
be within the :attr:`.Session.identity_map` of its parent
:class:`.Session`.
- .. versionchanged:: 1.1 The :attr:`.InstanceState.persistent`
- accessor no longer returns True for an object that was
- "deleted" within a flush; use the :attr:`.InstanceState.deleted`
- accessor to detect this state. This allows the "persistent"
- state to guarantee membership in the identity map.
-
.. seealso::
:ref:`session_object_states`
:func:`.attributes.get_history` - underlying function
- .. versionadded:: 0.9.0
-
"""
return self.state.get_history(self.key, PASSIVE_OFF ^ INIT_OK)
correctness of results, these joins are always INNER and are
therefore right-nested if linked to an OUTER join.
- .. versionchanged:: 1.0.0 ``innerjoin=True`` now implies
- ``innerjoin="nested"``, whereas in 0.9 it implied
- ``innerjoin="unnested"``. In order to achieve the pre-1.0
- "unnested" inner join behavior, use the value
- ``innerjoin="unnested"``. See :ref:`migration_3008`.
-
.. note::
The joins produced by :func:`_orm.joinedload` are **anonymously
This function is part of the :class:`_orm.Load` interface and supports
both method-chained and standalone operation.
-
- .. versionadded:: 1.1
-
.. seealso::
:ref:`loading_toplevel`
make use of :func:`_sa.create_engine` should not use this parameter
as it is handled by the engine creation strategy.
- .. versionadded:: 1.1 - ``dialect`` is now a public parameter
- to the :class:`_pool.Pool`.
-
:param pre_ping: if True, the pool will emit a "ping" (typically
"SELECT 1", but is dialect-specific) on the connection
upon checkout, to test if the connection is alive or not. If not,
:param exception: the exception object corresponding to the reason
for this invalidation, if any. May be ``None``.
- .. versionadded:: 0.9.2 Added support for connection invalidation
- listening.
-
.. seealso::
:ref:`pool_connection_invalidation`
is checked in. It does not actively close the dbapi_connection
at the point at which it is called.
- .. versionadded:: 1.0.3
-
:param dbapi_connection: a DBAPI connection.
The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute.
associated with the pool. To intercept close events for detached
connections use :meth:`.close_detached`.
- .. versionadded:: 1.1
-
:param dbapi_connection: a DBAPI connection.
The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute.
This event is emitted after the detach occurs. The connection
is no longer associated with the given connection record.
- .. versionadded:: 1.1
-
:param dbapi_connection: a DBAPI connection.
The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute.
the connection is already closed. If the close operation fails,
the connection is discarded.
- .. versionadded:: 1.1
-
:param dbapi_connection: a DBAPI connection.
The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute.
:param symmetric: if True, will render " BETWEEN SYMMETRIC ". Note
that not all databases support this syntax.
- .. versionadded:: 0.9.5
-
.. seealso::
:meth:`_expression.ColumnElement.between`
as well as the bound-value handling and result-row-handling behavior
of the type.
- .. versionchanged:: 0.9.0 :func:`.cast` now applies the given type
- to the expression such that it takes effect on the bound-value,
- e.g. the Python-to-database direction, in addition to the
- result handling, e.g. database-to-Python, direction.
-
An alternative to :func:`.cast` is the :func:`.type_coerce` function.
This function performs the second task of associating an expression
with a specific type, but does not render the ``CAST`` expression
:class:`_schema.MetaData`, DDL, or events, unlike its
:class:`_schema.Table` counterpart.
- .. versionchanged:: 1.0.0 :func:`_expression.column` can now
- be imported from the plain ``sqlalchemy`` namespace like any
- other SQL element.
-
:param text: the text of the element.
:param type: :class:`_types.TypeEngine` object which can associate
>>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
{printsql}SELECT x FROM t WHERE false{stop}
- .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature
- better integrated behavior within conjunctions and on dialects
- that don't support true/false constants.
-
.. seealso::
:func:`.true`
This function is also available from the :data:`~.expression.func`
construct itself via the :meth:`.FunctionElement.filter` method.
- .. versionadded:: 1.0.0
-
.. seealso::
:ref:`tutorial_functions_within_group` - in the
func.row_number().over(order_by='x', range_=(1, 3))
- .. versionadded:: 1.1 support for RANGE / ROWS within a window
-
-
:param element: a :class:`.FunctionElement`, :class:`.WithinGroup`,
or other compatible construct.
:param partition_by: a column element or string, or a list
tuple value which can contain integer values or ``None``,
and will render a RANGE BETWEEN PRECEDING / FOLLOWING clause.
- .. versionadded:: 1.1
-
:param rows: optional rows clause for the window. This is a tuple
value which can contain integer values or None, and will render
a ROWS BETWEEN PRECEDING / FOLLOWING clause.
- .. versionadded:: 1.1
-
This function is also available from the :data:`~.expression.func`
construct itself via the :meth:`.FunctionElement.over` method.
>>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
{printsql}SELECT x FROM t WHERE false{stop}
- .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature
- better integrated behavior within conjunctions and on dialects
- that don't support true/false constants.
-
.. seealso::
:func:`.false`
:param \*order_by: one or more column elements that will be used
as the ORDER BY clause of the WITHIN GROUP construct.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`tutorial_functions_within_group` - in the
:param full: if True, render a FULL OUTER JOIN, instead of JOIN.
- .. versionadded:: 1.1
-
.. seealso::
:meth:`_expression.FromClause.join` - method form,
only supported by a small number of backends, currently more recent
PostgreSQL versions.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`tutorial_lateral_correlation` - overview of usage.
:class:`_schema.Table` object.
It may be used to construct lightweight table constructs.
- .. versionchanged:: 1.0.0 :func:`_expression.table` can now
- be imported from the plain ``sqlalchemy`` namespace like any
- other SQL element.
-
-
:param name: Name of the table.
:param columns: A collection of :func:`_expression.column` constructs.
people AS alias TABLESAMPLE bernoulli(:bernoulli_1)
REPEATABLE (random())
- .. versionadded:: 1.1
-
:param sampling: a ``float`` percentage between 0 and 100 or
:class:`_functions.Function`.
:param default: default value of the parameter.
- .. versionadded:: 0.9.4
-
"""
construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
form ``<dialect>_<kwarg>`` where the value will be assembled
into the list of options.
- .. versionadded:: 0.9.2
-
- .. versionchanged:: 0.9.4 The :attr:`.DialectKWArgs.dialect_kwargs`
- collection is now writable.
-
.. seealso::
:attr:`.DialectKWArgs.dialect_options` - nested dictionary form
:param schema_translate_map: dictionary of schema names to be
translated when forming the resultant SQL
- .. versionadded:: 1.1
-
.. seealso::
:ref:`schema_translating`
inline within the CREATE construct; if omitted, all foreign key
constraints that do not specify use_alter=True are included.
- .. versionadded:: 1.0.0
-
:param if_not_exists: if True, an IF NOT EXISTS operator will be
applied to the construct.
:param extra_dependencies: a sequence of 2-tuples of tables which will
also be considered as dependent on each other.
- .. versionadded:: 1.0.0
-
.. seealso::
:func:`.sort_tables`
the traditional Core method of multiple parameter set
invocation for INSERTs and other statements.
- .. versionchanged:: 1.0.0 an INSERT that uses a multiple-VALUES
- clause, even a list of length one,
- implies that the :paramref:`_expression.Insert.inline`
- flag is set to
- True, indicating that the statement will not attempt to fetch
- the "last inserted primary key" or other defaults. The
- statement deals with an arbitrary number of rows, so the
- :attr:`_engine.CursorResult.inserted_primary_key`
- accessor does not
- apply.
-
- .. versionchanged:: 1.0.0 A multiple-VALUES INSERT now supports
- columns with Python side default values and callables in the
- same way as that of an "executemany" style of invocation; the
- callable is invoked for each row. See :ref:`bug_3288`
- for other details.
-
The UPDATE construct also supports rendering the SET parameters
in a specific order. For this feature refer to the
:meth:`_expression.Update.ordered_values` method.
will only be invoked **once** for the whole statement, and **not
per row**.
- .. versionadded:: 1.0.0 - :meth:`_expression.Insert.from_select`
- now renders
- Python-side and SQL expression column defaults into the
- SELECT statement for columns otherwise not included in the
- list of column names.
-
- .. versionchanged:: 1.0.0 an INSERT that uses FROM SELECT
- implies that the :paramref:`_expression.insert.inline`
- flag is set to
- True, indicating that the statement will not attempt to fetch
- the "last inserted primary key" or other defaults. The statement
- deals with an arbitrary number of rows, so the
- :attr:`_engine.CursorResult.inserted_primary_key`
- accessor does not apply.
-
"""
if self._values:
print(s.compile(compile_kwargs={"literal_binds": True}))
- .. versionadded:: 0.9.0
-
.. seealso::
:ref:`faq_sql_expression_string`
:func:`_expression.type_coerce`
- .. versionadded:: 1.0.7
-
"""
return Cast(self, type_)
query = session.query(User).from_statement(stmt).options(
contains_eager(User.addresses))
- .. versionadded:: 1.1 the :meth:`_expression.TextClause.columns`
- method now
- offers positional column targeting in the result set when
- the column expressions are passed purely positionally.
-
The :meth:`_expression.TextClause.columns` method provides a direct
route to calling :meth:`_expression.FromClause.subquery` as well as
:meth:`_expression.SelectBase.cte`
:class:`.TypeCoerce` supplies the :func:`_expression.type_coerce`
function; see that function for usage details.
- .. versionchanged:: 1.1 The :func:`.type_coerce` function now produces
- a persistent :class:`.TypeCoerce` wrapper object rather than
- translating the given object in place.
-
.. seealso::
:func:`_expression.type_coerce`
func.count(1).filter(True)
- .. versionadded:: 1.0.0
-
.. seealso::
:meth:`.FunctionElement.filter`
passing the name exactly as ``"some_table"`` without converting to
upper case.
- .. versionadded:: 0.9.0
-
.. versionchanged:: 1.2 The :class:`.quoted_name` construct is now
importable from ``sqlalchemy.sql``, in addition to the previous
location of ``sqlalchemy.sql.elements``.
name here is final, and the name will render as ``"ck_t_x5"`` and not
``"ck_t_ck_t_x5"``
- .. versionadded:: 0.9.4
-
.. seealso::
:ref:`constraint_naming_conventions`
See :func:`_expression.within_group` for a full description.
- .. versionadded:: 1.1
-
-
.. seealso::
:ref:`tutorial_functions_within_group` -
from sqlalchemy import funcfilter
funcfilter(func.count(1), True)
- .. versionadded:: 1.0.0
-
.. seealso::
:ref:`tutorial_functions_within_group` -
stmt = select(func.array_agg(table.c.values)[2:5])
- .. versionadded:: 1.1
-
.. seealso::
:func:`_postgresql.array_agg` - PostgreSQL-specific version that
The return type of this function is the same as the sort expression.
- .. versionadded:: 1.1
-
"""
inherit_cache = True
or if the arguments are an array, an :class:`_types.ARRAY` of the sort
expression's type.
- .. versionadded:: 1.1
-
"""
array_for_multi_clause = True
or if the arguments are an array, an :class:`_types.ARRAY` of the sort
expression's type.
- .. versionadded:: 1.1
-
"""
array_for_multi_clause = True
The return type of this function is :class:`.Integer`.
- .. versionadded:: 1.1
-
"""
type = sqltypes.Integer()
The return type of this function is :class:`.Integer`.
- .. versionadded:: 1.1
-
"""
type = sqltypes.Integer()
The return type of this function is :class:`.Numeric`.
- .. versionadded:: 1.1
-
"""
type: sqltypes.Numeric[decimal.Decimal] = sqltypes.Numeric()
The return type of this function is :class:`.Numeric`.
- .. versionadded:: 1.1
-
"""
type: sqltypes.Numeric[decimal.Decimal] = sqltypes.Numeric()
Renders "a IS DISTINCT FROM b" on most platforms;
on some such as SQLite may render "a IS NOT b".
- .. versionadded:: 1.1
-
"""
return self.operate(is_distinct_from, other)
renamed from ``isnot_distinct_from()`` in previous releases.
The previous name remains available for backwards compatibility.
- .. versionadded:: 1.1
-
"""
return self.operate(is_not_distinct_from, other)
:meth:`_types.ARRAY.Comparator.any` method, which a different
calling syntax and usage pattern.
- .. versionadded:: 1.1
-
"""
return self.operate(any_op)
:meth:`_types.ARRAY.Comparator.all` method, which a different
calling syntax and usage pattern.
-
- .. versionadded:: 1.1
-
"""
return self.operate(all_op)
:paramref:`.Sequence.schema`
- .. versionadded:: 1.0.14
-
"""
NULL_UNSPECIFIED = 3
:class:`_schema.MetaData`,
specify the special symbol :attr:`.BLANK_SCHEMA`.
- .. versionadded:: 1.0.14 Added the :attr:`.BLANK_SCHEMA` symbol to
- allow a :class:`_schema.Table`
- to have a blank schema name even when the
- parent :class:`_schema.MetaData` specifies
- :paramref:`_schema.MetaData.schema`.
-
The quoting rules for the schema name are the same as those for the
``name`` parameter, in that quoting is applied for reserved words or
case-sensitive names; to enable unconditional quoting for the schema
new_table = table.to_metadata(m2, schema="alt_schema",
referred_schema_fn=referred_schema_fn)
- .. versionadded:: 0.9.2
-
:param name: optional string name indicating the target table name.
If not specified or None, the table name is retained. This allows
a :class:`_schema.Table` to be copied to the same
:class:`_schema.MetaData` target
with a new name.
- .. versionadded:: 1.0.0
-
"""
if name is None:
name = self.name
well, at the moment that the foreign key is resolved against that
remote :class:`_schema.Column` object.
- .. versionchanged:: 0.9.0
- Support for propagation of type to a :class:`_schema.Column`
- from its
- :class:`_schema.ForeignKey` object has been improved and should be
- more reliable and timely.
-
:param \*args: Additional positional arguments include various
:class:`.SchemaItem` derived constructs which will be applied
as options to the column. These include instances of
datatype of INTEGER in order to disable auto increment semantics
for that column.
- .. versionchanged:: 1.1 The autoincrement flag now defaults to
- ``"auto"`` which indicates autoincrement semantics by default
- for single-column integer primary keys only; for composite
- (multi-column) primary keys, autoincrement is never implicitly
- enabled; as always, ``autoincrement=True`` will allow for
- at most one of those columns to be an "autoincrement" column.
- ``autoincrement=True`` may also be set on a
- :class:`_schema.Column`
- that has an explicit client-side or server-side default,
- subject to limitations of the backend database and dialect.
-
The setting *only* has an effect for columns which are:
* Integer derived (i.e. INT, SMALLINT, BIGINT).
:param info: Optional data dictionary which will be populated into the
:attr:`.SchemaItem.info` attribute of this object.
- .. versionadded:: 1.0.0
-
:param comment: Optional string that will render an SQL comment on
foreign key constraint creation.
an individual dialect at :ref:`dialect_toplevel` for detail on
documented arguments.
- .. versionadded:: 0.9.2
-
"""
self._colspec = coercions.expect(roles.DDLReferredColumnRole, column)
minvalue of 1 and -2^63-1 for ascending and descending sequences,
respectively.
- .. versionadded:: 1.0.7
-
:param maxvalue: the maximum value of the sequence. This
value is used when the CREATE SEQUENCE command is emitted to
the database as the value of the "MAXVALUE" clause. If ``None``,
maxvalue of 2^63-1 and -1 for ascending and descending sequences,
respectively.
- .. versionadded:: 1.0.7
-
:param nominvalue: no minimum value of the sequence. This
value is used when the CREATE SEQUENCE command is emitted to
the database as the value of the "NO MINVALUE" clause. If ``None``,
minvalue of 1 and -2^63-1 for ascending and descending sequences,
respectively.
- .. versionadded:: 1.0.7
-
:param nomaxvalue: no maximum value of the sequence. This
value is used when the CREATE SEQUENCE command is emitted to
the database as the value of the "NO MAXVALUE" clause. If ``None``,
maxvalue of 2^63-1 and -1 for ascending and descending sequences,
respectively.
- .. versionadded:: 1.0.7
-
:param cycle: allows the sequence to wrap around when the maxvalue
or minvalue has been reached by an ascending or descending sequence
respectively. This value is used when the CREATE SEQUENCE command
after the sequence has reached its maximum value will return an
error.
- .. versionadded:: 1.0.7
-
:param schema: optional schema name for the sequence, if located
in a schema other than the default. The rules for selecting the
schema name when a :class:`_schema.MetaData`
sequence which are calculated in advance. Renders the CACHE keyword
understood by Oracle and PostgreSQL.
- .. versionadded:: 1.1.12
-
:param order: optional boolean value; if ``True``, renders the
ORDER keyword, understood by Oracle, indicating the sequence is
definitively ordered. May be necessary to provide deterministic
ordering using Oracle RAC.
- .. versionadded:: 1.1.12
-
:param data_type: The type to be returned by the sequence, for
dialects that allow us to choose between INTEGER, BIGINT, etc.
(e.g., mssql).
:param info: Optional data dictionary which will be populated into the
:attr:`.SchemaItem.info` attribute of this object.
- .. versionadded:: 1.0.0
-
:param comment: Optional string that will render an SQL comment on
foreign key constraint creation.
:param info: Optional data dictionary which will be populated into the
:attr:`.SchemaItem.info` attribute of this object.
- .. versionadded:: 1.0.0
-
"""
self.sqltext = coercions.expect(roles.DDLExpressionRole, sqltext)
methods will perform this resolution
automatically, so the flag is normally not needed.
- .. versionchanged:: 1.0.0 Automatic resolution of foreign key
- cycles has been added, removing the need to use the
- :paramref:`_schema.ForeignKeyConstraint.use_alter` in typical use
- cases.
-
.. seealso::
:ref:`use_alter`
:param info: Optional data dictionary which will be populated into the
:attr:`.SchemaItem.info` attribute of this object.
- .. versionadded:: 1.0.0
-
:param comment: Optional string that will render an SQL comment on
foreign key constraint creation.
the documentation regarding an individual dialect at
:ref:`dialect_toplevel` for detail on documented arguments.
- .. versionadded:: 0.9.2
-
"""
Constraint.__init__(
if the constraint and/or parent table is not yet associated with
a metadata collection that contains the referred table.
- .. versionadded:: 1.0.0
-
"""
return self.elements[0].column.table
or if the constraint has been initialized with :class:`_schema.Column`
objects, is the string ``.key`` of each element.
- .. versionadded:: 1.0.0
-
"""
if hasattr(self, "parent"):
return self._columns.keys()
marked as ``primary_key=True`` are ignored. This behavior is intended to
be backwards compatible with previous behavior.
- .. versionchanged:: 0.9.2 Using a mixture of columns within a
- :class:`.PrimaryKeyConstraint` in addition to columns marked as
- ``primary_key=True`` now emits a warning if the lists don't match.
- The ultimate behavior of ignoring those columns marked with the flag
- only is currently maintained for backwards compatibility; this warning
- may raise an exception in a future release.
-
For the use case where specific options are to be specified on the
:class:`.PrimaryKeyConstraint`, but the usual style of using
``primary_key=True`` flags is still desirable, an empty
mssql_clustered=True)
)
- .. versionadded:: 0.9.2 an empty :class:`.PrimaryKeyConstraint` may now
- be specified for the purposes of establishing keyword arguments with
- the constraint, independently of the specification of "primary key"
- columns within the :class:`_schema.Table` itself; columns marked as
- ``primary_key=True`` will be gathered into the empty constraint's
- column collection.
-
"""
__visit_name__ = "primary_key_constraint"
Index("some_index", text("lower(name)"))
)
- .. versionadded:: 0.9.5 the :func:`_expression.text`
- construct may be used to
- specify :class:`.Index` expressions, provided the :class:`.Index`
- is explicitly associated with the :class:`_schema.Table`.
-
-
.. seealso::
:ref:`schema_indexes` - General information on :class:`.Index`.
:param info=None: Optional data dictionary which will be populated
into the :attr:`.SchemaItem.info` attribute of this object.
- .. versionadded:: 1.0.0
-
:param \**dialect_kw: Additional keyword arguments not mentioned above
are dialect specific, and passed in the form
``<dialectname>_<argname>``. See the documentation regarding an
:param info: Optional data dictionary which will be populated into the
:attr:`.SchemaItem.info` attribute of this object.
- .. versionadded:: 1.0.0
-
:param naming_convention: a dictionary referring to values which
will establish default naming conventions for :class:`.Constraint`
and :class:`.Index` objects, for those objects which are not given
:param extend_existing: Passed along to each :class:`_schema.Table` as
:paramref:`_schema.Table.extend_existing`.
- .. versionadded:: 0.9.1
-
:param autoload_replace: Passed along to each :class:`_schema.Table`
as
:paramref:`_schema.Table.autoload_replace`.
- .. versionadded:: 0.9.1
-
:param resolve_fks: if True, reflect :class:`_schema.Table`
objects linked
to :class:`_schema.ForeignKey` objects located in each
individual dialect at :ref:`dialect_toplevel` for detail on
documented arguments.
- .. versionadded:: 0.9.2 - Added
- :paramref:`.MetaData.reflect.**dialect_kwargs` to support
- dialect-level reflection options for all :class:`_schema.Table`
- objects reflected.
-
"""
with inspection.inspect(bind)._inspection_context() as insp:
The return value is the :class:`_expression.Lateral` construct also
provided by the top-level :func:`_expression.lateral` function.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`tutorial_lateral_correlation` - overview of usage.
directives such as isolation levels, file directives, fetch directives,
etc.
- .. versionadded:: 1.0.0
-
.. seealso::
:meth:`_expression.Select.with_hint`
:param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER
JOIN. Implies :paramref:`.FromClause.join.isouter`.
- .. versionadded:: 1.1
-
.. seealso::
:func:`_expression.join` - standalone function
:param full: if True, render a FULL OUTER JOIN, instead of
LEFT OUTER JOIN.
- .. versionadded:: 1.1
-
.. seealso::
:meth:`_expression.FromClause.join`
construct also
provided by the top-level :func:`_expression.tablesample` function.
- .. versionadded:: 1.1
-
.. seealso::
:func:`_expression.tablesample` - usage guidelines and parameters
While LATERAL is part of the SQL standard, currently only more recent
PostgreSQL versions provide support for this keyword.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`tutorial_lateral_correlation` - overview of usage.
method
available on all :class:`_expression.FromClause` subclasses.
- .. versionadded:: 1.1
-
.. seealso::
:func:`_expression.tablesample`
class HasCTE(roles.HasCTERole, SelectsRows):
- """Mixin that declares a class to include CTE support.
-
- .. versionadded:: 1.1
-
- """
+ """Mixin that declares a class to include CTE support."""
_has_ctes_traverse_internals: _TraverseInternalsType = [
("_independent_ctes", InternalTraversal.dp_clauseelement_list),
when combined with RETURNING, as well as a consumer of
CTE rows.
- .. versionchanged:: 1.1 Added support for UPDATE/INSERT/DELETE as
- CTE, CTEs added to UPDATE/INSERT/DELETE.
-
SQLAlchemy detects :class:`_expression.CTE` objects, which are treated
similarly to :class:`_expression.Alias` objects, as special elements
to be delivered to the FROM clause of the statement as well
The return value is the :class:`_expression.Lateral` construct also
provided by the top-level :func:`_expression.lateral` function.
- .. versionadded:: 1.1
-
.. seealso::
:ref:`tutorial_lateral_correlation` - overview of usage.
The :meth:`_sql.GenerativeSelect.limit` method will replace
any clause applied with :meth:`_sql.GenerativeSelect.fetch`.
- .. versionchanged:: 1.0.0 - :meth:`_expression.Select.limit` can now
- accept arbitrary SQL expressions as well as integer values.
-
:param limit: an integer LIMIT parameter, or a SQL expression
that provides an integer result. Pass ``None`` to reset it.
support ``OFFSET`` will attempt to provide similar
functionality.
-
- .. versionchanged:: 1.0.0 - :meth:`_expression.Select.offset` can now
- accept arbitrary SQL expressions as well as integer values.
-
:param offset: an integer OFFSET parameter, or a SQL expression
that provides an integer result. Pass ``None`` to reset it.
"""A mixin that marks a type as supporting indexing operations,
such as array or JSON structures.
-
- .. versionadded:: 1.1.0
-
-
"""
class Comparator(TypeEngine.Comparator[_T]):
MySQL float types, which do include "scale", will use "scale"
as the default for decimal_return_scale, if not otherwise specified.
- .. versionadded:: 0.9.0
-
""" # noqa: E501
self.precision = precision
self.asdecimal = asdecimal
impacts usage of LIKE expressions with enumerated values (an unusual
use case).
- .. versionchanged:: 1.1 the :class:`.Enum` type now provides in-Python
- validation of input values as well as on data being returned by
- the database.
-
The source of enumerated values may be a list of string values, or
alternatively a PEP-435-compliant enumerated class. For the purposes
of the :class:`.Enum` datatype, this class need only provide a
values to be persisted. For a simple enumeration that uses string values,
a callable such as ``lambda x: [e.value for e in x]`` is sufficient.
- .. versionadded:: 1.1 - support for PEP-435-style enumerated
- classes.
-
-
.. seealso::
:ref:`orm_declarative_mapped_column_enums` - background on using
:param \*enums: either exactly one PEP-435 compliant enumerated type
or one or more string labels.
- .. versionadded:: 1.1 a PEP-435 style enumerated class may be
- passed.
-
:param create_constraint: defaults to False. When creating a
non-native enumerated type, also build a CHECK constraint on the
database against the valid values.
for validity against the list of enumerated values. Unrecognized
values will result in a ``LookupError`` being raised.
- .. versionadded:: 1.1.0b2
-
:param values_callable: A callable which will be passed the PEP-435
compliant enumerated type, which should then return a list of string
values to be persisted. This allows for alternate usages such as
:class:`sqlalchemy.dialects.sqlite.JSON`
- .. versionadded:: 1.1
-
-
"""
__visit_name__ = "JSON"
Alternatively, assigning a new array value to an ORM element that
replaces the old one will always trigger a change event.
- .. versionadded:: 1.1.0
-
.. seealso::
:class:`sqlalchemy.dialects.postgresql.ARRAY`
The type allows dialects to inject result-processing functionality
if needed, and on MySQL will return floating-point values.
- .. versionadded:: 1.0.0
-
"""
:meth:`.TypeEngine.evaluates_none`
- .. versionadded:: 1.1
-
-
"""
_variant_mapping: util.immutabledict[
``None``
still means "no default".
- .. versionadded:: 1.1
-
.. seealso::
:ref:`session_forcing_null` - in the ORM documentation
:param conn_type: the type object reflected from the backend.
- .. versionadded:: 1.0.3
-
"""
return None
introspection is used to check for this in order to support legacy
forms of this function.
- .. versionadded:: 1.0.0 the owning expression is passed to
- the ``get_col_spec()`` method via the keyword argument
- ``type_expression``, if it receives ``**kw`` in its signature.
-
The :attr:`.UserDefinedType.cache_ok` class-level flag indicates if this
custom :class:`.UserDefinedType` is safe to be used as part of a cache key.
This flag defaults to ``None`` which will initially generate a warning