`The Importance of Naming Constraints <https://alembic.sqlalchemy.org/en/latest/naming.html>`_ - in the Alembic documentation.
-
-.. versionadded:: 1.3.0 added multi-column naming tokens such as ``%(column_0_N_name)s``.
- Generated names that go beyond the character limit for the target database will be
- deterministically truncated.
-
.. _naming_check_constraints:
Naming CHECK Constraints
the individual VALUES clause is isolated from the full parameter dictionary
and returned alone.
-.. versionadded:: 1.2
-
- Added :meth:`.DefaultExecutionContext.get_current_parameters` method,
- which improves upon the still-present
- :attr:`.DefaultExecutionContext.current_parameters` attribute
- by offering the service of organizing multiple VALUES clauses
- into individual parameter dictionaries.
-
.. _defaults_client_invoked_sql:
Client-Invoked SQL Expressions
Computed Columns (GENERATED ALWAYS AS)
--------------------------------------
-.. versionadded:: 1.3.11
-
The :class:`.Computed` construct allows a :class:`_schema.Column` to be declared in
DDL as a "GENERATED ALWAYS AS" column, that is, one which has a value that is
computed by the database server. The construct accepts a SQL expression
Note that the flag only applies to :class:`.QueuePool` use.
-.. versionadded:: 1.3
-
.. seealso::
:ref:`pool_disconnects`
VARCHAR2,
)
-.. versionadded:: 1.2.19 Added :class:`_types.NCHAR` to the list of datatypes
- exported by the Oracle dialect.
-
Types which are specific to Oracle Database, or have Oracle-specific
construction arguments, are as follows:
DBAPIs at this time. Prior to SQLAlchemy 1.3.17, a special workaround
was needed in order to allow this combination to work, described below.
-.. versionchanged:: 1.3.17 The combination of ENUM and ARRAY is now directly
- handled by SQLAlchemy's implementation without any workarounds needed.
-
.. sourcecode:: python
from sqlalchemy import TypeDecorator
we need to render the appropriate CAST. Current psycopg2 drivers accommodate
the result set correctly without any special steps.
-.. versionchanged:: 1.3.17 The combination of JSON/JSONB and ARRAY is now
- directly handled by SQLAlchemy's implementation without any workarounds
- needed.
-
.. sourcecode:: python
class CastingArray(ARRAY):
on the "one" side of a one-to-many relationship so that it deletes objects
in the "many" side, and not the other way around.
-.. versionchanged:: 1.3.18 The text of the "delete-orphan" error message
- when used on a many-to-one or many-to-many relationship has been updated
- to be more descriptive.
-
-
.. seealso::
:ref:`unitofwork_cascades`
ping: 1
...
-.. versionadded: 1.4 the above recipe makes use of 1.4-specific behaviors and will
+.. versionadded:: 1.4 the above recipe makes use of 1.4-specific behaviors and will
not work as given on previous SQLAlchemy versions.
The above recipe is tested for SQLAlchemy 1.4.
inspected and "unrolled" into explicit JOIN criteria for best use, especially
when chaining association proxies together.
-
-.. versionchanged:: 1.3 Association proxy features distinct querying modes
- based on the type of target. See :ref:`change_4351`.
-
-
-
.. _cascade_scalar_deletes:
Cascading Scalar Deletes
------------------------
-.. versionadded:: 1.3
-
Given a mapping as::
from __future__ import annotations
# the "query" argument, pass that.
my_q += lambda q: q.filter(my_subq.to_query(q).exists())
-.. versionadded:: 1.3
-
.. _baked_with_before_compile:
Using the before_compile event
given :class:`_query.Query` in exactly the same way every time, not dependent
on specific parameters or external state that changes.
-.. versionadded:: 1.3.11 - added the "bake_ok" flag to the
- :meth:`.QueryEvents.before_compile` event and disallowed caching via
- the "baked" extension from occurring for event handlers that
- return a new :class:`_query.Query` object if this flag is not set.
-
-
Disabling Baked Queries Session-wide
------------------------------------
baked queries or other baked query issues can turn the behavior off, in
order to identify or eliminate baked queries as the cause of an issue.
-.. versionadded:: 1.2
-
Lazy Loading Integration
------------------------
``Point.geom`` expressions. The :func:`.foreign` annotation additionally notes
which column takes on the "foreign key" role in this particular relationship.
-.. versionadded:: 1.3 Added :meth:`.FunctionElement.as_comparison`.
-
.. _relationship_overlapping_foreignkeys:
Overlapping Foreign Keys
stmt = select(AddressUser).group_by(*AddressUser.id.expressions)
-.. versionadded:: 1.3.17 Added the
- :attr:`.ColumnProperty.Comparator.expressions` accessor.
-
-
.. note::
A mapping against multiple tables as illustrated above supports
((SELECT coalesce(max(foo.foopk) + %(max_1)s, %(coalesce_2)s) AS coalesce_1
FROM foo), %(bar)s) RETURNING foo.foopk
-.. versionadded:: 1.3
- SQL expressions can now be passed to a primary key column during an ORM
- flush; if the database supports RETURNING, or if pysqlite is in use, the
- ORM will be able to retrieve the server-generated value as the value
- of the primary key attribute.
-
.. _session_sql_expressions:
Using SQL Expressions with Sessions
addition to ``start`` and ``increment``. These are not supported by
SQL Server and will be ignored when generating the CREATE TABLE ddl.
-.. versionchanged:: 1.3.19 The :class:`_schema.Identity` object is
- now used to affect the
- ``IDENTITY`` generator for a :class:`_schema.Column` under SQL Server.
- Previously, the :class:`.Sequence` object was used. As SQL Server now
- supports real sequences as a separate construct, :class:`.Sequence` will be
- functional in the normal way starting from SQLAlchemy version 1.4.
-
Using IDENTITY with Non-Integer numeric types
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
schema="[MyDataBase.Period].[MyOwner.Dot]",
)
-.. versionchanged:: 1.2 the SQL Server dialect now treats brackets as
- identifier delimiters splitting the schema into separate database
- and owner tokens, to allow dots within either name itself.
-
.. _legacy_schema_rendering:
Legacy Schema Mode
would render the index as ``CREATE INDEX my_index ON table (x) WHERE x > 10``.
-.. versionadded:: 1.3.4
-
Index ordering
^^^^^^^^^^^^^^
TIMESTAMP type, which is not supported by SQL Server. It
is a read-only datatype that does not support INSERT of values.
- .. versionadded:: 1.2
-
.. seealso::
:class:`_mssql.ROWVERSION`
:param convert_int: if True, binary integer values will
be converted to integers on read.
- .. versionadded:: 1.2
-
"""
self.convert_int = convert_int
This is a read-only datatype that does not support INSERT of values.
- .. versionadded:: 1.2
-
.. seealso::
:class:`_mssql.TIMESTAMP`
as Python uuid objects, converting to/from string via the
DBAPI.
- .. versionchanged: 2.0 Added direct "uuid" support to the
+ .. versionchanged:: 2.0 Added direct "uuid" support to the
:class:`_mssql.UNIQUEIDENTIFIER` datatype; uuid interpretation
defaults to ``True``.
feature would cause ``fast_executemany`` to not be used in most cases
even if specified.
-.. versionadded:: 1.3
-
.. seealso::
`fast executemany <https://github.com/mkleehammer/pyodbc/wiki/Features-beyond-the-DB-API#fast_executemany>`_
{printsql}INSERT INTO my_table (id, data) VALUES (%s, %s)
ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP
-.. versionchanged:: 1.3 support for parameter-ordered UPDATE clause within
- MySQL ON DUPLICATE KEY UPDATE
-
.. warning::
The :meth:`_mysql.Insert.on_duplicate_key_update`
When rendered, the "inserted" namespace will produce the expression
``VALUES(<columnname>)``.
-.. versionadded:: 1.2 Added support for MySQL ON DUPLICATE KEY UPDATE clause
-
-
-
rowcount Support
----------------
mariadb_with_parser="ngram",
)
-.. versionadded:: 1.3
-
-
.. _mysql_foreign_keys:
MySQL / MariaDB Foreign Keys
The :class:`~.mysql.Insert` object is created using the
:func:`sqlalchemy.dialects.mysql.insert` function.
- .. versionadded:: 1.2
-
"""
stringify_dialect = "mysql"
]
)
- .. versionchanged:: 1.3 parameters can be specified as a dictionary
- or list of 2-tuples; the latter form provides for parameter
- ordering.
-
-
- .. versionadded:: 1.2
-
.. seealso::
:ref:`mysql_insert_on_duplicate_key_update`
quotes when generating the schema. This object may also be a
PEP-435-compliant enumerated type.
- .. versionadded: 1.1 added support for PEP-435-compliant enumerated
- types.
-
:param strict: This flag has no effect.
.. versionchanged:: The MySQL ENUM type as well as the base Enum
warning is emitted for this initial first-connect condition as it is
expected to be a common restriction on Oracle databases.
-.. versionadded:: 1.3.16 added support for AUTOCOMMIT to the cx_Oracle dialect
- as well as the notion of a default isolation level
-
-.. versionadded:: 1.3.21 Added support for SERIALIZABLE as well as live
- reading of the isolation level.
-
-.. versionchanged:: 1.3.22 In the event that the default isolation
- level cannot be read due to permissions on the v$transaction view as
- is common in Oracle installations, the default isolation level is hardcoded
- to "READ COMMITTED" which was the behavior prior to 1.3.21.
-
.. seealso::
:ref:`dbapi_autocommit`
:meth:`_reflection.Inspector.get_check_constraints`, and
:meth:`_reflection.Inspector.get_indexes`.
-.. versionchanged:: 1.2 The Oracle Database dialect can now reflect UNIQUE and
- CHECK constraints.
-
When using reflection at the :class:`_schema.Table` level, the
:class:`_schema.Table`
will also include these constraints.
"oracle+cx_oracle://user:pass@dsn?encoding=UTF-8&nencoding=UTF-8&mode=SYSDBA&events=true"
)
-.. versionchanged:: 1.3 the cx_Oracle dialect now accepts all argument names
- within the URL string itself, to be passed to the cx_Oracle DBAPI. As
- was the case earlier but not correctly documented, the
- :paramref:`_sa.create_engine.connect_args` parameter also accepts all
- cx_Oracle DBAPI connect arguments.
-
To pass arguments directly to ``.connect()`` without using the query
string, use the :paramref:`_sa.create_engine.connect_args` dictionary.
Any cx_Oracle parameter value and/or constant may be passed, such as::
the SQLAlchemy dialect to use NCHAR/NCLOB for the :class:`.Unicode` /
:class:`.UnicodeText` datatypes instead of VARCHAR/CLOB.
-.. versionchanged:: 1.3 The :class:`.Unicode` and :class:`.UnicodeText`
- datatypes now correspond to the ``VARCHAR2`` and ``CLOB`` Oracle Database
- datatypes unless the ``use_nchar_for_unicode=True`` is passed to the dialect
- when :func:`_sa.create_engine` is called.
-
-
.. _cx_oracle_unicode_encoding_errors:
Encoding Errors
``Cursor.var()``, as well as SQLAlchemy's own decoding function, as the
cx_Oracle dialect makes use of both under different circumstances.
-.. versionadded:: 1.3.11
-
-
.. _cx_oracle_setinputsizes:
Fine grained control over cx_Oracle data binding performance with setinputsizes
well as to fully control how ``setinputsizes()`` is used on a per-statement
basis.
-.. versionadded:: 1.2.9 Added :meth:`.DialectEvents.setinputsizes`
-
-
Example 1 - logging all setinputsizes calls
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SQL statements that are not otherwise associated with a :class:`.Numeric`
SQLAlchemy type (or a subclass of such).
-.. versionchanged:: 1.2 The numeric handling system for cx_Oracle has been
- reworked to take advantage of newer cx_Oracle features as well
- as better integration of outputtypehandlers.
-
""" # noqa
from __future__ import annotations
the SQLAlchemy dialect to use NCHAR/NCLOB for the :class:`.Unicode` /
:class:`.UnicodeText` datatypes instead of VARCHAR/CLOB.
-.. versionchanged:: 1.3 The :class:`.Unicode` and :class:`.UnicodeText`
- datatypes now correspond to the ``VARCHAR2`` and ``CLOB`` Oracle Database
- datatypes unless the ``use_nchar_for_unicode=True`` is passed to the dialect
- when :func:`_sa.create_engine` is called.
-
-
.. _oracledb_unicode_encoding_errors:
Encoding Errors
``Cursor.var()``, as well as SQLAlchemy's own decoding function, as the
python-oracledb dialect makes use of both under different circumstances.
-.. versionadded:: 1.3.11
-
-
.. _oracledb_setinputsizes:
Fine grained control over python-oracledb data binding with setinputsizes
well as to fully control how ``setinputsizes()`` is used on a per-statement
basis.
-.. versionadded:: 1.2.9 Added :meth:`.DialectEvents.setinputsizes`
-
-
Example 1 - logging all setinputsizes calls
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SQL statements that are not otherwise associated with a :class:`.Numeric`
SQLAlchemy type (or a subclass of such).
-.. versionchanged:: 1.2 The numeric handling system for the oracle dialects has
- been reworked to take advantage of newer driver features as well as better
- integration of outputtypehandlers.
-
.. versionadded:: 2.0.0 added support for the python-oracledb driver.
""" # noqa
ARRAY[q, x]
] AS anon_1
- .. versionadded:: 1.3.6 added support for multidimensional array literals
-
.. seealso::
:class:`_postgresql.ARRAY`
:paramref:`_postgresql.ExcludeConstraint.ops` parameter. See that parameter for
details.
-.. versionadded:: 1.3.21 added support for operator classes with
- :class:`_postgresql.ExcludeConstraint`.
-
-
Index Types
^^^^^^^^^^^
postgresql_partition_by="LIST (part_column)",
)
- .. versionadded:: 1.2.6
-
*
``TABLESPACE``::
SELECT string_agg(a, ',' ORDER BY a) FROM table;
- .. versionchanged:: 1.2.13 - the ORDER BY argument may be multiple terms
-
.. seealso::
:class:`_functions.array_agg`
:ref:`postgresql_ops <postgresql_operator_classes>`
parameter specified to the :class:`_schema.Index` construct.
- .. versionadded:: 1.3.21
-
.. seealso::
:ref:`postgresql_operator_classes` - general description of how
is repaired, previously ports were not correctly interpreted in this context.
libpq comma-separated format is also now supported.
-.. versionadded:: 1.3.20 Support for multiple hosts in PostgreSQL connection
- string.
-
.. seealso::
`libpq connection strings <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING>`_ - please refer
In the above form, a blank "dsn" string is passed to the ``psycopg2.connect()``
function which in turn represents an empty DSN passed to libpq.
-.. versionadded:: 1.3.2 support for parameter-less connections with psycopg2.
-
.. seealso::
`Environment Variables\
def column_expression(self, column: Any):
return cast(column, Numeric())
- .. versionadded:: 1.2
-
""" # noqa: E501
__visit_name__ = "MONEY"
class REGCLASS(sqltypes.TypeEngine[str]):
- """Provide the PostgreSQL REGCLASS type.
-
- .. versionadded:: 1.2.7
-
- """
+ """Provide the PostgreSQL REGCLASS type."""
__visit_name__ = "REGCLASS"
to be limited, such as ``"YEAR"``, ``"MONTH"``, ``"DAY TO HOUR"``,
etc.
- .. versionadded:: 1.2
-
"""
self.precision = precision
self.fields = fields
attribute on the DBAPI connection and set it to None for the duration
of the setting.
-.. versionadded:: 1.3.16 added support for SQLite AUTOCOMMIT isolation level
- when using the pysqlite / sqlite3 SQLite driver.
-
-
The other axis along which SQLite's transactional locking is impacted is
via the nature of the ``BEGIN`` statement used. The three varieties
are "deferred", "immediate", and "exclusive", as described at
`ON CONFLICT <https://www.sqlite.org/lang_conflict.html>`_ - in the SQLite
documentation
-.. versionadded:: 1.3
-
-
The ``sqlite_on_conflict`` parameters accept a string argument which is just
the resolution name to be chosen, which on SQLite can be one of ROLLBACK,
ABORT, FAIL, IGNORE, and REPLACE. For example, to add a UNIQUE constraint
always JSON string values.
- .. versionadded:: 1.3
-
-
.. _JSON1: https://www.sqlite.org/json1.html
"""
parameter which allows for a custom callable
that creates a Python sqlite3 driver level connection directly.
-.. versionadded:: 1.3.9
-
.. seealso::
`Uniform Resource Identifiers <https://www.sqlite.org/uri.html>`_ - in
def get_execution_options(self) -> _ExecuteOptions:
"""Get the non-SQL options which will take effect during execution.
- .. versionadded:: 1.3
-
.. seealso::
:meth:`_engine.Connection.execution_options`
def get_execution_options(self) -> _ExecuteOptions:
"""Get the non-SQL options which will take effect during execution.
- .. versionadded: 1.3
-
.. seealso::
:meth:`_engine.Engine.execution_options`
will not be displayed in INFO logging nor will they be formatted into
the string representation of :class:`.StatementError` objects.
- .. versionadded:: 1.3.8
-
.. seealso::
:ref:`dbengine_logging` - further detail on how to configure
to a Python object. By default, the Python ``json.loads`` function is
used.
- .. versionchanged:: 1.3.7 The SQLite dialect renamed this from
- ``_json_deserializer``.
-
:param json_serializer: for dialects that support the :class:`_types.JSON`
datatype, this is a Python callable that will render a given object
as JSON. By default, the Python ``json.dumps`` function is used.
- .. versionchanged:: 1.3.7 The SQLite dialect renamed this from
- ``_json_serializer``.
-
-
:param label_length=None: optional integer value which limits
the size of dynamically generated column labels to that many
characters. If less than 6, labels are generated as
SQLAlchemy's dialect has not been adjusted, the value may be passed
here.
- .. versionadded:: 1.3.9
-
.. seealso::
:paramref:`_sa.create_engine.label_length`
"pre-ping" feature that tests connections for liveness upon
each checkout.
- .. versionadded:: 1.2
-
.. seealso::
:ref:`pool_disconnects_pessimistic`
use. When planning for server-side timeouts, ensure that a recycle or
pre-ping strategy is in use to gracefully handle stale connections.
- .. versionadded:: 1.3
-
.. seealso::
:ref:`pool_use_lifo`
:param plugins: string list of plugin names to load. See
:class:`.CreateEnginePlugin` for background.
- .. versionadded:: 1.2.3
-
:param query_cache_size: size of the cache used to cache the SQL string
form of queries. Set to zero to disable caching.
If the dialect's class level max_identifier_length should be used,
can return None.
- .. versionadded:: 1.3.9
-
"""
return None
By default, calls the :meth:`_engine.Interfaces.get_isolation_level`
method, propagating any exceptions raised.
- .. versionadded:: 1.3.22
-
"""
return self.get_isolation_level(dbapi_conn)
raw parameters of the statement are returned including the
naming convention used in the case of multi-valued INSERT.
- .. versionadded:: 1.2 added
- :meth:`.DefaultExecutionContext.get_current_parameters`
- which provides more functionality over the existing
- :attr:`.DefaultExecutionContext.current_parameters`
- attribute.
-
.. seealso::
:attr:`.DefaultExecutionContext.current_parameters`
the connection, and those passed in to the method itself for
the 2.0 style of execution.
- .. versionadded: 1.4
+ .. versionadded:: 1.4
.. seealso::
the connection, and those passed in to the method itself for
the 2.0 style of execution.
- .. versionadded: 1.4
+ .. versionadded:: 1.4
:param result: :class:`_engine.CursorResult` generated by the
execution.
:ref:`mssql_pyodbc_setinputsizes`
- .. versionadded:: 1.2.9
-
.. seealso::
:ref:`cx_oracle_setinputsizes`
computed: NotRequired[ReflectedComputed]
"""indicates that this column is computed by the database.
Only some dialects return this key.
-
- .. versionadded:: 1.3.16 - added support for computed reflection.
"""
identity: NotRequired[ReflectedIdentity]
dialect_options: NotRequired[Dict[str, Any]]
"""Additional dialect-specific options detected for this check constraint
-
- .. versionadded:: 1.3.8
"""
"""optional dict mapping column names or expressions to tuple of sort
keywords, which may include ``asc``, ``desc``, ``nulls_first``,
``nulls_last``.
-
- .. versionadded:: 1.3.5
"""
dialect_options: NotRequired[Dict[str, Any]]
:raise: ``NotImplementedError`` for dialects that don't support
comments.
- .. versionadded:: 1.2
-
"""
raise NotImplementedError()
The method defaults to using the :meth:`.Dialect.get_isolation_level`
method unless overridden by a dialect.
- .. versionadded:: 1.3.22
-
"""
raise NotImplementedError()
except ImportError:
pass
- .. versionadded:: 1.3.14
-
"""
@classmethod
"mysql+pymysql://scott:tiger@localhost/test", plugins=["myplugin"]
)
- .. versionadded:: 1.2.3 plugin names can also be specified
- to :func:`_sa.create_engine` as a list
-
A plugin may consume plugin-specific arguments from the
:class:`_engine.URL` object as well as the ``kwargs`` dictionary, which is
the dictionary of arguments passed to the :func:`_sa.create_engine`
:return: a dictionary, with the table comment.
- .. versionadded:: 1.2
-
.. seealso:: :meth:`Inspector.get_multi_table_comment`
"""
If exec_once was already called, then this method will never run
the callable regardless of whether it raised or not.
- .. versionadded:: 1.3.8
-
"""
if not self._exec_once:
self._exec_once_impl(True, *args, **kw)
:class:`_exc.DisconnectionError`, allowing three attempts to reconnect
before giving up.
- .. versionadded:: 1.2
-
"""
invalidate_pool: bool = True
class UnreflectableTableError(InvalidRequestError):
- """Table exists but can't be reflected for some reason.
-
- .. versionadded:: 1.2
-
- """
+ """Table exists but can't be reflected for some reason."""
class UnboundExecutionError(InvalidRequestError):
source, as this object may have other state that is still to be
kept.
- .. versionadded:: 1.3
-
.. seealso::
:ref:`cascade_scalar_deletes` - complete usage example
to look at the type of the actual destination object to get the
complete path.
- .. versionadded:: 1.3 - :class:`.AssociationProxy` no longer stores
- any state specific to a particular parent class; the state is now
- stored in per-class :class:`.AssociationProxyInstance` objects.
-
-
"""
return self._as_instance(class_, obj)
>>> proxy_state.scalar
False
- .. versionadded:: 1.3
-
""" # noqa
collection_class: Optional[Type[Any]]
Proxied for the :class:`_engine.Engine` class on
behalf of the :class:`_asyncio.AsyncEngine` class.
- .. versionadded: 1.3
-
.. seealso::
:meth:`_engine.Engine.execution_options`
:attr:`.AutomapBase.by_module` when explicit ``__module__`` conventions are
present.
-.. versionadded: 2.0
+.. versionadded:: 2.0
Added the :attr:`.AutomapBase.by_module` collection, which stores
classes within a named hierarchy based on dot-separated module names,
:meth:`.BakedQuery.bakery`. It exists as an object
so that the "cache" can be easily inspected.
- .. versionadded:: 1.2
-
-
"""
__slots__ = "cls", "cache"
:class:`.Session` object, that is assumed to be within the context
of an enclosing :class:`.BakedQuery` callable.
-
- .. versionadded:: 1.3
-
-
""" # noqa: E501
if isinstance(query_or_session, Session):
:meth:`_query.Query.execution_options`
methods should be used.
-
- .. versionadded:: 1.2
-
-
"""
return self._using_post_criteria([fn])
class Employee(ConcreteBase, Base):
_concrete_discriminator_name = "_concrete_discriminator"
- .. versionadded:: 1.3.19 Added the ``_concrete_discriminator_name``
- attribute to :class:`_declarative.ConcreteBase` so that the
- virtual discriminator column name can be customized.
-
.. versionchanged:: 1.4.2 The ``_concrete_discriminator_name`` attribute
need only be placed on the basemost class to take correct effect for
all subclasses. An explicit error message is now raised if the
def foobar(cls):
return func.subfoobar(self._foobar)
- .. versionadded:: 1.2
-
.. seealso::
:ref:`hybrid_reuse_subclass`
return hybrid_property._InPlace(self)
def getter(self, fget: _HybridGetterType[_T]) -> hybrid_property[_T]:
- """Provide a modifying decorator that defines a getter method.
-
- .. versionadded:: 1.2
-
- """
+ """Provide a modifying decorator that defines a getter method."""
return self._copy(fget=fget)
fname, lname = value.split(" ", 1)
return [(cls.first_name, fname), (cls.last_name, lname)]
- .. versionadded:: 1.2
-
"""
return self._copy(update_expr=meth)
default, changes in state will be back-populated only if neither
sides of a relationship is viewonly.
- .. versionadded:: 1.3.17
-
.. versionchanged:: 1.4 - A relationship that specifies
:paramref:`_orm.relationship.viewonly` automatically implies
that :paramref:`_orm.relationship.sync_backref` is ``False``.
automatically detected; if it is not detected, then the
optimization is not supported.
- .. versionchanged:: 1.3.11 setting ``omit_join`` to True will now
- emit a warning as this was not the intended use of this flag.
-
- .. versionadded:: 1.3
-
:param init: Specific to :ref:`orm_declarative_native_dataclasses`,
specifies if the mapped attribute should be part of the ``__init__()``
method as generated by the dataclass process.
:param default_expr: Optional SQL expression object that will be used in
all cases if not assigned later with :func:`_orm.with_expression`.
- .. versionadded:: 1.2
-
.. seealso::
:ref:`orm_queryguide_with_expression` - background and usage examples
is being supplied; the object may be used to track the origin of the
chain of events.
- .. versionadded:: 1.2.3
-
"""
state, dict_ = instance_state(instance), instance_dict(instance)
state.manager[key].impl.set(state, dict_, value, initiator)
may establish changes on it, which will then be included in the SQL
emitted.
- .. versionadded:: 1.2
-
.. seealso::
:func:`.attributes.flag_modified`
"""
_is_internal_proxy = False
- """True if this object is an internal proxy object.
-
- .. versionadded:: 1.2.12
-
- """
+ """True if this object is an internal proxy object."""
is_clause_element = False
"""True if this object is an instance of
object is moved to a new loader context from within one of these
events if this flag is not set.
- .. versionadded:: 1.3.14
-
-
"""
_target_class_doc = "SomeClass"
def on_load(instance, context):
instance.some_unloaded_attribute
- .. versionchanged:: 1.3.14 Added
- :paramref:`.InstanceEvents.restore_load_context`
- and :paramref:`.SessionEvents.restore_load_context` flags which
- apply to "on load" events, which will ensure that the loading
- context for an object is restored when the event hook is
- complete; a warning is emitted if the load context of the object
- changes without this flag being set.
-
-
The :meth:`.InstanceEvents.load` event is also available in a
class-method decorator format called :func:`_orm.reconstructor`.
meaningful return value when it is registered with the ``retval=True``
parameter.
- .. versionadded:: 1.3
-
e.g.::
from sqlalchemy.orm import EXT_SKIP
objects will be the instance's :class:`.InstanceState` management
object, rather than the mapped instance itself.
- .. versionadded:: 1.3.14
-
:param restore_load_context=False: Applies to the
:meth:`.SessionEvents.loaded_as_persistent` event. Restores the loader
context of the object when the event hook is complete, so that ongoing
warning is emitted if the object is moved to a new loader context from
within this event if this flag is not set.
- .. versionadded:: 1.3.14
-
"""
_target_class_doc = "SomeSessionClassOrObject"
else:
return value
- .. versionadded:: 1.2
-
:param target: the object instance receiving the event.
If the listener is registered with ``raw=True``, this will
be the :class:`.InstanceState` object.
The old collection received will contain its previous contents.
- .. versionchanged:: 1.2 The collection passed to
- :meth:`.AttributeEvents.dispose_collection` will now have its
- contents before the dispose intact; previously, the collection
- would be empty.
-
.. seealso::
:class:`.AttributeEvents` - background on listener options such
function is used to trigger a modify event on an attribute without
any specific value being set.
- .. versionadded:: 1.2
-
:param target: the object instance receiving the event.
If the listener is registered with ``raw=True``, this will
be the :class:`.InstanceState` object.
once, and not called for subsequent invocations of a particular query
that is being cached.
- .. versionadded:: 1.3.11 - added the "bake_ok" flag to the
- :meth:`.QueryEvents.before_compile` event and disallowed caching via
- the "baked" extension from occurring for event handlers that
- return a new :class:`_query.Query` object if this flag is not set.
-
.. seealso::
:meth:`.QueryEvents.before_compile_update`
dictionary can be modified to alter the VALUES clause of the
resulting UPDATE statement.
- .. versionadded:: 1.2.17
-
.. seealso::
:meth:`.QueryEvents.before_compile`
the same kind of object as described in
:paramref:`.QueryEvents.after_bulk_delete.delete_context`.
- .. versionadded:: 1.2.17
-
.. seealso::
:meth:`.QueryEvents.before_compile`
module, which provides the means to build and specify
alternate instrumentation forms.
-.. versionchanged: 0.8
- The instrumentation extension system was moved out of the
- ORM and into the external :mod:`sqlalchemy.ext.instrumentation`
- package. When that package is imported, it installs
- itself within sqlalchemy.orm so that its more comprehensive
- resolution mechanics take effect.
-
"""
the columns specific to this subclass. The SELECT uses
IN to fetch multiple subclasses at once.
- .. versionadded:: 1.2
-
.. seealso::
:ref:`with_polymorphic_mapper_config`
The above process produces an ordering that is deterministic in terms
of the order in which attributes were assigned to the class.
- .. versionchanged:: 1.3.19 ensured deterministic ordering for
- :meth:`_orm.Mapper.all_orm_descriptors`.
-
When dealing with a :class:`.QueryableAttribute`, the
:attr:`.QueryableAttribute.property` attribute refers to the
:class:`.MapperProperty` property, which is what you get when
"""The full sequence of columns referenced by this
attribute, adjusted for any aliasing in progress.
- .. versionadded:: 1.3.17
-
.. seealso::
:ref:`maptojoin` - usage example
"""The full sequence of columns referenced by this
attribute, adjusted for any aliasing in progress.
- .. versionadded:: 1.3.17
-
"""
if self.adapter:
return [
in its result list, and False if this query returns a tuple of entities
for each result.
- .. versionadded:: 1.3.11
-
.. seealso::
:meth:`_query.Query.only_return_tuples`
my_object = query.get({"id": 5, "version_id": 10})
- .. versionadded:: 1.3 the :meth:`_query.Query.get`
- method now optionally
- accepts a dictionary of attribute names to values in order to
- indicate a primary key identifier.
-
-
:return: The object instance, or ``None``.
""" # noqa: E501
def get_execution_options(self) -> _ImmutableExecuteOptions:
"""Get the non-SQL options which will take effect during execution.
- .. versionadded:: 1.3
-
.. seealso::
:meth:`_query.Query.execution_options`
:meth:`.Session.delete` - main documentation on delete
- .. versionadded: 2.1
+ .. versionadded:: 2.1
""" # noqa: E501
Contents of this dictionary are passed to the
:meth:`.Session.get_bind` method.
- .. versionadded: 2.0.0rc1
+ .. versionadded:: 2.0.0rc1
:return: The object instance, or ``None``.
:meth:`.Session.merge` - main documentation on merge
- .. versionadded: 2.1
+ .. versionadded:: 2.1
""" # noqa: E501
:meth:`.Session.delete` - main documentation on delete
- .. versionadded: 2.1
+ .. versionadded:: 2.1
"""
Contents of this dictionary are passed to the
:meth:`.Session.get_bind` method.
- .. versionadded: 2.0.0rc1
+ .. versionadded:: 2.0.0rc1
:return: The object instance, or ``None``.
:meth:`.Session.merge` - main documentation on merge
- .. versionadded: 2.1
+ .. versionadded:: 2.1
"""
This function is not for general use but may be useful for test suites
within the teardown scheme.
- .. versionadded:: 1.3
-
"""
for sess in _sessions.values():
:class:`.Session`, use the :attr:`.InstanceState.was_deleted`
accessor.
- .. versionadded: 1.1
-
.. seealso::
:ref:`session_object_states`
"""Track the last known value of a particular key after expiration
operations.
- .. versionadded:: 1.3
-
"""
lkv = self._last_known_values
with_expression(SomeClass.x_y_expr, SomeClass.x + SomeClass.y)
)
- .. versionadded:: 1.2
-
:param key: Attribute to be populated
:param expr: SQL expression to be applied to the attribute.
key values, and is the per-query analogue to the ``"selectin"``
setting on the :paramref:`.mapper.polymorphic_load` parameter.
- .. versionadded:: 1.2
-
.. seealso::
:ref:`polymorphic_selectin`
:class:`_orm.Load` objects) which should be applied to the path
specified by this :class:`_orm.Load` object.
- .. versionadded:: 1.3.6
-
.. seealso::
:func:`.defaultload`
:param ident: primary key, may be a scalar or tuple argument.
:param identity_token: optional identity token
- .. versionadded:: 1.2 added identity_token
-
-
* ``identity_key(instance=instance)``
This form will produce the identity key for a given instance. The
(must be given as a keyword arg)
:param identity_token: optional identity token
- .. versionadded:: 1.2 added identity_token
-
""" # noqa: E501
if class_ is not None:
mapper = class_mapper(class_)
Entity in which to consider as the left side. This defaults to the
"zero" entity of the :class:`_query.Query` itself.
- .. versionadded:: 1.2
-
""" # noqa: E501
prop_t: RelationshipProperty[Any]
invalidated. Requires that a dialect is passed as well to
interpret the disconnection error.
- .. versionadded:: 1.2
-
"""
if logging_name:
self.logging_name = self._orig_logging_name = logging_name
timeouts, ensure that a recycle or pre-ping strategy is in use to
gracefully handle stale connections.
- .. versionadded:: 1.3
-
.. seealso::
:ref:`pool_use_lifo`
The collation expression is also quoted if it is a case sensitive
identifier, e.g. contains uppercase characters.
- .. versionchanged:: 1.2 quoting is automatically applied to COLLATE
- expressions if they are case sensitive.
-
"""
return CollationClause._create_collation_expression(expression, collation)
.. note:: The "expanding" feature does not support "executemany"-
style parameter sets.
- .. versionadded:: 1.2
-
- .. versionchanged:: 1.3 the "expanding" bound parameter feature now
- supports empty lists.
-
:param literal_execute:
if True, the bound parameter will be rendered in the compile phase
with a special "POSTCOMPILE" token, and the SQLAlchemy compiler will
tuple_(table.c.col1, table.c.col2).in_([(1, 2), (5, 12), (10, 19)])
- .. versionchanged:: 1.3.6 Added support for SQLite IN tuples.
-
.. warning::
The composite IN construct is not supported by all backends, and is
:param schema: The schema name for this table.
- .. versionadded:: 1.3.18 :func:`_expression.table` can now
- accept a ``schema`` argument.
"""
return TableClause(name, *columns, **kw)
def get_execution_options(self) -> _ExecuteOptions:
"""Get the non-SQL options which will take effect during execution.
- .. versionadded:: 1.3
-
.. seealso::
:meth:`.Executable.execution_options`
a VALUES expression, the string is assigned here, where it can be
used for insert batching schemes to rewrite the VALUES expression.
- .. versionadded:: 1.3.8
-
.. versionchanged:: 2.0 This collection is no longer used by
SQLAlchemy's built-in dialects, in favor of the currently
internal ``_insertmanyvalues`` collection that is used only by
by a ``visit_`` method, as it is not guaranteed to be assigned
nor guaranteed to correspond to the current statement being compiled.
- .. versionadded:: 1.3.21
-
- For compatibility with previous versions, use the following
- recipe::
-
- statement = getattr(self, "current_executable", False)
- if statement is False:
- statement = self.stack[-1]["selectable"]
-
- For versions 1.4 and above, ensure only .current_executable
- is used; the format of "self.stack" may change.
-
-
"""
try:
return self.stack[-1]["selectable"]
such as "INITIALLY", "INITIALLY DEFERRED", etc. no special characters
should be present.
- .. versionadded:: 1.3
-
"""
if element is not None and not reg.match(element):
collection when cycles are detected so that they may be applied
to a schema separately.
- .. versionchanged:: 1.3.17 - a warning is emitted when
- :func:`_schema.sort_tables` cannot perform a proper sort due to
- cyclical dependencies. This will be an exception in a future
- release. Additionally, the sort will continue to return
- other tables not involved in the cycle in dependency order
- which was not the case previously.
-
:param tables: a sequence of :class:`_schema.Table` objects.
:param skip_fn: optional callable which will be passed a
upd = table.update().dialect_options(mysql_limit=10)
- .. versionadded: 1.4 - this method supersedes the dialect options
+ .. versionadded:: 1.4 - this method supersedes the dialect options
associated with the constructor.
select id from table where name=:name_1
UNION ALL select id from table where name=:name_2
- .. versionadded:: 1.3.11 Added support for the
- :paramref:`.BindParameter.unique` flag to work with
- :func:`_expression.text`
- constructs.
-
""" # noqa: E501
self._bindparams = new_params = self._bindparams.copy()
backend, passing the name exactly as ``"some_table"`` without converting to
upper case.
- .. versionchanged:: 1.2 The :class:`.quoted_name` construct is now
- importable from ``sqlalchemy.sql``, in addition to the previous
- location of ``sqlalchemy.sql.elements``.
-
"""
__slots__ = "quote", "lower", "upper"
:param right_index: the integer 1-based index of the function argument
that serves as the "right" side of the expression.
- .. versionadded:: 1.3
-
.. seealso::
:ref:`relationship_custom_operator_sql_function` -
connection.scalar(select(func.as_utc()))
- .. versionadded:: 1.3.13 The :class:`.quoted_name` construct is now
- recognized for quoting when used with the "name" attribute of the
- object, so that quoting can be forced on or off for the function
- name.
-
-
"""
coerce_arguments = True
func.sum(table.c.value), table.c.col_1, table.c.col_2
).group_by(func.cube(table.c.col_1, table.c.col_2))
- .. versionadded:: 1.2
-
"""
_has_args = True
func.sum(table.c.value), table.c.col_1, table.c.col_2
).group_by(func.rollup(table.c.col_1, table.c.col_2))
- .. versionadded:: 1.2
-
"""
_has_args = True
)
)
- .. versionadded:: 1.2
-
""" # noqa: E501
_has_args = True
The return type of this function is :class:`.String`.
- .. versionadded: 2.0.21
+ .. versionadded:: 2.0.21
"""
WHERE COL IN (?, ?, ?)
- .. versionadded:: 1.2 added "expanding" bound parameters
-
If an empty list is passed, a special "empty list" expression,
which is specific to the database in use, is rendered. On
SQLite this would be:
WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
- .. versionadded:: 1.3 "expanding" bound parameters now support
- empty lists
-
* a :func:`_expression.select` construct, which is usually a
correlated scalar select::
``notin_()`` in previous releases. The previous name remains
available for backwards compatibility.
- .. versionchanged:: 1.2 The :meth:`.ColumnOperators.in_` and
- :meth:`.ColumnOperators.not_in` operators
- now produce a "static" expression for an empty IN sequence
- by default.
-
.. seealso::
:meth:`.ColumnOperators.in_`
:class:`_schema.Table` will
resolve to that table normally.
- .. versionadded:: 1.3
-
.. seealso::
:paramref:`.MetaData.reflect.resolve_fks`
:param comment: Optional string that will render an SQL comment on table
creation.
- .. versionadded:: 1.2 Added the :paramref:`_schema.Table.comment`
- parameter
- to :class:`_schema.Table`.
-
:param \**kw: Additional keyword arguments not mentioned above are
dialect specific, and passed in the form ``<dialectname>_<argname>``.
See the documentation regarding an individual dialect at
:param insert_default: An alias of :paramref:`.Column.default`
for compatibility with :func:`_orm.mapped_column`.
- .. versionadded: 2.0.31
+ .. versionadded:: 2.0.31
:param doc: optional String that can be used by the ORM or similar
to document attributes on the Python side. This attribute does
:param comment: Optional string that will render an SQL comment on
table creation.
- .. versionadded:: 1.2 Added the
- :paramref:`_schema.Column.comment`
- parameter to :class:`_schema.Column`.
-
:param insert_sentinel: Marks this :class:`_schema.Column` as an
:term:`insert sentinel` used for optimizing the performance of the
:term:`insertmanyvalues` feature for tables that don't
class ScalarElementColumnDefault(ColumnDefault):
"""default generator for a fixed scalar Python value
- .. versionadded: 2.0
+ .. versionadded:: 2.0
"""
class IdentityOptions(DialectKWArgs):
"""Defines options for a named database sequence or an identity column.
- .. versionadded:: 1.3.18
-
.. seealso::
:class:`.Sequence`
it along with a ``fn(constraint, table)`` callable to the
naming_convention dictionary.
- .. versionadded:: 1.3.0 - added new ``%(column_0N_name)s``,
- ``%(column_0_N_name)s``, and related tokens that produce
- concatenations of names, keys, or labels for all columns referred
- to by a given constraint.
-
.. seealso::
:ref:`constraint_naming_conventions` - for detailed usage
collection when cycles are detected so that they may be applied
to a schema separately.
- .. versionchanged:: 1.3.17 - a warning is emitted when
- :attr:`.MetaData.sorted_tables` cannot perform a proper sort
- due to cyclical dependencies. This will be an exception in a
- future release. Additionally, the sort will continue to return
- other tables not involved in the cycle in dependency order which
- was not the case previously.
-
.. seealso::
:func:`_schema.sort_tables`
operation is
complete. Defaults to True.
- .. versionadded:: 1.3.0
-
.. seealso::
:paramref:`_schema.Table.resolve_fks`
See the linked documentation below for complete details.
- .. versionadded:: 1.3.11
-
.. seealso::
:ref:`computed_ddl`
method may be
used to establish these.
- .. versionchanged:: 1.3.13 Added support for prefixes.
- In particular - MATERIALIZED and NOT MATERIALIZED.
-
:param name: name given to the common table expression. Like
:meth:`_expression.FromClause.alias`, the name can be left as
``None`` in which case an anonymous symbol will be used at query
:meth:`_expression.SelectBase.subquery`
method.
- .. versionchanged: 1.4 - the ``.as_scalar()`` method was renamed to
+ .. versionchanged:: 1.4 - the ``.as_scalar()`` method was renamed to
:meth:`_expression.SelectBase.scalar_subquery`.
.. seealso::
``__member__`` attribute. For example
``lambda x: [i.value for i in x]``.
- .. versionadded:: 1.2.3
-
:param sort_key_function: a Python callable which may be used as the
"key" argument in the Python ``sorted()`` built-in. The SQLAlchemy
ORM requires that primary key columns which are mapped must
default, the database value of the enumeration is used as the
sorting function.
- .. versionadded:: 1.3.8
-
:param omit_aliases: A boolean that when true will remove aliases from
pep 435 enums. defaults to ``True``.
don't support a "native boolean" datatype, an option exists to
also create a CHECK constraint on the target column
- .. versionchanged:: 1.2 the :class:`.Boolean` datatype now asserts that
- incoming Python values are already in pure boolean form.
-
-
"""
__visit_name__ = "boolean"
data_table.c.data["some key"].as_integer()
- .. versionadded:: 1.3.11
-
Additional operations may be available from the dialect-specific versions
of :class:`_types.JSON`, such as
:class:`sqlalchemy.dialects.postgresql.JSON` and
# boolean comparison
data_table.c.data["some_boolean"].as_boolean() == True
- .. versionadded:: 1.3.11 Added type-specific casters for the basic JSON
- data element types.
-
.. note::
The data caster functions are new in version 1.3.11, and supersede
json_serializer=lambda obj: json.dumps(obj, ensure_ascii=False),
)
- .. versionchanged:: 1.3.7
-
- SQLite dialect's ``json_serializer`` and ``json_deserializer``
- parameters renamed from ``_json_serializer`` and
- ``_json_deserializer``.
-
.. seealso::
:class:`sqlalchemy.dialects.postgresql.JSON`
mytable.c.json_column["some_data"].as_boolean() == True
)
- .. versionadded:: 1.3.11
-
""" # noqa: E501
return self._binary_w_type(Boolean(), "as_boolean")
mytable.c.json_column["some_data"].as_string() == "some string"
)
- .. versionadded:: 1.3.11
-
""" # noqa: E501
return self._binary_w_type(Unicode(), "as_string")
mytable.c.json_column["some_data"].as_integer() == 5
)
- .. versionadded:: 1.3.11
-
""" # noqa: E501
return self._binary_w_type(Integer(), "as_integer")
mytable.c.json_column["some_data"].as_float() == 29.75
)
- .. versionadded:: 1.3.11
-
""" # noqa: E501
return self._binary_w_type(Float(), "as_float")
Note that comparison of full JSON structures may not be
supported by all backends.
- .. versionadded:: 1.3.11
-
"""
return self.expr
as Python uuid objects, converting to/from string via the
DBAPI.
- .. versionchanged: 2.0 ``as_uuid`` now defaults to ``True``.
+ .. versionchanged:: 2.0 ``as_uuid`` now defaults to ``True``.
:param native_uuid=True: if True, backends that support either the
``UUID`` datatype directly, or a UUID-storing value
as Python uuid objects, converting to/from string via the
DBAPI.
- .. versionchanged: 2.0 ``as_uuid`` now defaults to ``True``.
+ .. versionchanged:: 2.0 ``as_uuid`` now defaults to ``True``.
"""
self.as_uuid = as_uuid
The default value of ``None`` indicates that the values stored by
this type are self-sorting.
- .. versionadded:: 1.3.8
-
"""
should_evaluate_none: bool = False
Current examples of :class:`.Emulated` are: :class:`.Interval`,
:class:`.Enum`, :class:`.Boolean`.
- .. versionadded:: 1.2.0b3
-
"""
native: bool
class NativeForEmulated(TypeEngineMixin):
- """Indicates DB-native types supported by an :class:`.Emulated` type.
-
- .. versionadded:: 1.2.0b3
-
- """
+ """Indicates DB-native types supported by an :class:`.Emulated` type."""
@classmethod
def adapt_native_to_emulated(