Using Transactions
==================
-.. note:: This section describes how to use transactions when working directly
+.. note::
+
+ This section describes how to use transactions when working directly
with :class:`.Engine` and :class:`.Connection` objects. When using the
SQLAlchemy ORM, the public API for transaction control is via the
:class:`.Session` object, which makes usage of the :class:`.Transaction`
:class:`.Engine` per database established within an
application, rather than creating a new one for each connection.
-.. note:: :class:`.QueuePool` is not used by default for SQLite engines. See
- :ref:`sqlite_toplevel` for details on SQLite connection pool usage.
+.. note::
+
+ :class:`.QueuePool` is not used by default for SQLite engines. See
+ :ref:`sqlite_toplevel` for details on SQLite connection pool usage.
.. autoclass:: sqlalchemy.engine.url.URL
:members:
"pool_logging_name" keyword arguments with :func:`sqlalchemy.create_engine`.
.. note::
- The SQLAlchemy :class:`.Engine` conserves Python function call overhead
- by only emitting log statements when the current logging level is detected
- as ``logging.INFO`` or ``logging.DEBUG``. It only checks this level when
- a new connection is procured from the connection pool. Therefore when
- changing the logging configuration for an already-running application, any
- :class:`.Connection` that's currently active, or more commonly a
- :class:`~.orm.session.Session` object that's active in a transaction, won't log any
- SQL according to the new configuration until a new :class:`.Connection`
- is procured (in the case of :class:`~.orm.session.Session`, this is
- after the current transaction ends and a new one begins).
+
+ The SQLAlchemy :class:`.Engine` conserves Python function call overhead
+ by only emitting log statements when the current logging level is detected
+ as ``logging.INFO`` or ``logging.DEBUG``. It only checks this level when
+ a new connection is procured from the connection pool. Therefore when
+ changing the logging configuration for an already-running application, any
+ :class:`.Connection` that's currently active, or more commonly a
+ :class:`~.orm.session.Session` object that's active in a transaction, won't log any
+ SQL according to the new configuration until a new :class:`.Connection`
+ is procured (in the case of :class:`~.orm.session.Session`, this is
+ after the current transaction ends and a new one begins).
()
COMMIT
-.. note:: Users familiar with the syntax of CREATE TABLE may notice that the
+.. note::
+
+ Users familiar with the syntax of CREATE TABLE may notice that the
VARCHAR columns were generated without a length; on SQLite and Postgresql,
this is a valid datatype, but on others, it's not allowed. So if running
this tutorial on one of those databases, and you wish to use SQLAlchemy to
Multiple Table Updates
----------------------
-.. note:: This feature is new as of version 0.7.4.
+.. note::
+
+ This feature is new as of version 0.7.4.
The Postgresql, Microsoft SQL Server, and MySQL backends all support UPDATE statements
that refer to multiple tables. For PG and MSSQL, this is the "UPDATE FROM" syntax,
rides on top of ``setuptools`` or ``distribute``, replacing the usage
of ``easy_install``. It is often preferred for its simpler mode of usage.
-.. note:: It is strongly recommended that either ``setuptools`` or ``distribute`` be installed.
+.. note::
+
+ It is strongly recommended that either ``setuptools`` or ``distribute`` be installed.
Python's built-in ``distutils`` lacks many widely used installation features.
Install via easy_install or pip
python setup.py --without-cextensions install
-.. note:: The ``--without-cextensions`` flag is available **only** if ``setuptools``
+.. note::
+
+ The ``--without-cextensions`` flag is available **only** if ``setuptools``
or ``distribute`` is installed. It is not available on a plain Python ``distutils``
installation. The library will still install without the C extensions if they
cannot be built, however.
Note that eager/lazy loading options cannot be used in conjunction dynamic relationships at this time.
-.. note:: The :func:`~.orm.dynamic_loader` function is essentially the same
+.. note::
+
+ The :func:`~.orm.dynamic_loader` function is essentially the same
as :func:`~.orm.relationship` with the ``lazy='dynamic'`` argument specified.
ability to load elements "polymorphically", meaning that a single query can
return objects of multiple types.
-.. note:: This section currently uses classical mappings to illustrate inheritance
+.. note::
+
+ This section currently uses classical mappings to illustrate inheritance
configurations, and will soon be updated to standardize on Declarative.
Until then, please refer to :ref:`declarative_inheritance` for information on
how common inheritance mappings are constructed declaratively.
'primary_key' : [user_table.c.id]
}
-.. note:: insert and update defaults configured on individual
- :class:`.Column` objects, i.e. those described at :ref:`metadata_defaults`
- including those configured by the ``default``, ``update``,
- ``server_default`` and ``server_onupdate`` arguments, will continue to
- function normally even if those :class:`.Column` objects are not mapped.
- This is because in the case of ``default`` and ``update``, the
- :class:`.Column` object is still present on the underlying
- :class:`.Table`, thus allowing the default functions to take place when
- the ORM emits an INSERT or UPDATE, and in the case of ``server_default``
- and ``server_onupdate``, the relational database itself maintains these
- functions.
+.. note::
+
+ insert and update defaults configured on individual
+ :class:`.Column` objects, i.e. those described at :ref:`metadata_defaults`
+ including those configured by the ``default``, ``update``,
+ ``server_default`` and ``server_onupdate`` arguments, will continue to
+ function normally even if those :class:`.Column` objects are not mapped.
+ This is because in the case of ``default`` and ``update``, the
+ :class:`.Column` object is still present on the underlying
+ :class:`.Table`, thus allowing the default functions to take place when
+ the ORM emits an INSERT or UPDATE, and in the case of ``server_default``
+ and ``server_onupdate``, the relational database itself maintains these
+ functions.
.. _deferred:
access two "hops" with a single access, one "hop" to the
associated object, and a second to a target attribute.
-.. note:: When using the association object pattern, it is
+.. note::
+
+ When using the association object pattern, it is
advisable that the association-mapped table not be used
as the ``secondary`` argument on a :func:`.relationship`
elsewhere, unless that :func:`.relationship` contains
setting ``autocommit=True``. In autocommit mode, a transaction can be
initiated by calling the :func:`~sqlalchemy.orm.session.Session.begin` method.
-.. note:: The term "transaction" here refers to a transactional
+.. note::
+
+ The term "transaction" here refers to a transactional
construct within the :class:`.Session` itself which may be
maintaining zero or more actual database (DBAPI) transactions. An individual
DBAPI connection begins participation in the "transaction" as it is first
def get_select_precolumns(self, select):
"""Add special MySQL keywords in place of DISTINCT.
- .. note:: this usage is deprecated. :meth:`.Select.prefix_with`
+ .. note::
+
+ this usage is deprecated. :meth:`.Select.prefix_with`
should be used for special keywords at the start
of a SELECT.
performance implications (default changed from ``True`` in
0.7.0).
- .. note:: This functionality is now superseded by the
+ .. note::
+
+ This functionality is now superseded by the
``sqlalchemy.ext.mutable`` extension described in
:ref:`mutable_toplevel`.
prevents a connection from being used again in a different thread and works
best with SQLite's coarse-grained file locking.
- .. note:: The default selection of :class:`.NullPool` for SQLite file-based databases
- is new in SQLAlchemy 0.7. Previous versions
- select :class:`.SingletonThreadPool` by
- default for all SQLite databases.
+ .. note::
+
+ The default selection of :class:`.NullPool` for SQLite file-based databases
+ is new in SQLAlchemy 0.7. Previous versions
+ select :class:`.SingletonThreadPool` by
+ default for all SQLite databases.
Modern versions of SQLite no longer have the threading restrictions, and assuming
the sqlite3/pysqlite library was built with SQLite's default threading mode
"""Mark a class-level method as representing the definition of
a mapped property or special declarative member name.
- .. note:: @declared_attr is available as
- ``sqlalchemy.util.classproperty`` for SQLAlchemy versions
- 0.6.2, 0.6.3, 0.6.4.
+ .. note::
+
+ @declared_attr is available as
+ ``sqlalchemy.util.classproperty`` for SQLAlchemy versions
+ 0.6.2, 0.6.3, 0.6.4.
@declared_attr turns the attribute into a scalar-like
property that can be invoked from the uninstantiated class.
This is a convenience method that calls ``associate_with_attribute`` automatically.
- .. warning:: The listeners established by this method are *global*
+ .. warning::
+
+ The listeners established by this method are *global*
to all mappers, and are *not* garbage collected. Only use
:meth:`.associate_with` for types that are permanent to an application,
not with ad-hoc types else this will cause unbounded growth
of the particular :meth:`.Mutable` subclass to establish a global
association.
- .. warning:: The listeners established by this method are *global*
+ .. warning::
+
+ The listeners established by this method are *global*
to all mappers, and are *not* garbage collected. Only use
:meth:`.as_mutable` for types that are permanent to an application,
not with ad-hoc types else this will cause unbounded growth
See the example in :ref:`mutable_composites` for usage information.
- .. warning:: The listeners established by the :class:`.MutableComposite`
+ .. warning::
+
+ The listeners established by the :class:`.MutableComposite`
class are *global* to all mappers, and are *not* garbage collected. Only use
:class:`.MutableComposite` for types that are permanent to an application,
not with ad-hoc types else this will cause unbounded growth
(as in the mapper example above). This implementation depends on the list
starting in the proper order, so be SURE to put an order_by on your relationship.
-.. warning:: ``ordering_list`` only provides limited functionality when a primary
+.. warning::
+
+ ``ordering_list`` only provides limited functionality when a primary
key column or unique column is the target of the sort. Since changing the order of
entries often means that two rows must trade values, this is not possible when
the value is constrained by a primary key or unique constraint, since one of the rows
"""
-.. note:: SQLSoup will no longer be included with SQLAlchemy as of 0.8.
+.. note::
+
+ SQLSoup will no longer be included with SQLAlchemy as of 0.8.
Look for a third party project replicating its functionality soon.
Sessions, Transations and Application Integration
-------------------------------------------------
-**Note:** please read and understand this section thoroughly
-before using SqlSoup in any web application.
+.. note::
+
+ Please read and understand this section thoroughly
+ before using SqlSoup in any web application.
SqlSoup uses a ScopedSession to provide thread-local sessions.
You can get a reference to the current one like this::
class PoolListener(object):
"""Hooks into the lifecycle of connections in a :class:`.Pool`.
- .. note:: :class:`.PoolListener` is deprecated. Please
+ .. note::
+
+ :class:`.PoolListener` is deprecated. Please
refer to :class:`.PoolEvents`.
Usage::
class ConnectionProxy(object):
"""Allows interception of statement execution by Connections.
- .. note:: :class:`.ConnectionProxy` is deprecated. Please
+ .. note::
+
+ :class:`.ConnectionProxy` is deprecated. Please
refer to :class:`.ConnectionEvents`.
Either or both of the ``execute()`` and ``cursor_execute()``
def relationship(argument, secondary=None, **kwargs):
"""Provide a relationship of a primary Mapper to a secondary Mapper.
- .. note:: :func:`relationship` is historically known as
+ .. note::
+
+ :func:`relationship` is historically known as
:func:`relation` prior to version 0.6.
This corresponds to a parent-child or associative table relationship. The
comparator_factory=None, doc=None):
"""Denote an attribute name as a synonym to a mapped property.
- .. note:: :func:`.synonym` is superseded as of 0.7 by
+ .. note::
+
+ :func:`.synonym` is superseded as of 0.7 by
the :mod:`~sqlalchemy.ext.hybrid` extension. See
the documentation for hybrids at :ref:`hybrids_toplevel`.
"""Provides a method of applying a :class:`.PropComparator`
to any Python descriptor attribute.
- .. note:: :func:`.comparable_property` is superseded as of 0.7 by
+ .. note::
+
+ :func:`.comparable_property` is superseded as of 0.7 by
the :mod:`~sqlalchemy.ext.hybrid` extension. See the example
at :ref:`hybrid_custom_comparators`.
"""Return a ``MapperOption`` that will convert the property of the given
name or series of mapped attributes into an joined eager load.
- .. note:: This function is known as :func:`eagerload` in all versions
- of SQLAlchemy prior to version 0.6beta3, including the 0.5 and 0.4
- series. :func:`eagerload` will remain available for the foreseeable
- future in order to enable cross-compatibility.
+ .. note::
+
+ This function is known as :func:`eagerload` in all versions
+ of SQLAlchemy prior to version 0.6beta3, including the 0.5 and 0.4
+ series. :func:`eagerload` will remain available for the foreseeable
+ future in order to enable cross-compatibility.
Used with :meth:`~sqlalchemy.orm.query.Query.options`.
query(Order).options(joinedload(Order.user, innerjoin=True))
- .. note:: The join created by :func:`joinedload` is anonymously aliased such that
+ .. note::
+
+ The join created by :func:`joinedload` is anonymously aliased such that
it **does not affect the query results**. An :meth:`.Query.order_by`
or :meth:`.Query.filter` call **cannot** reference these aliased
tables - so-called "user space" joins are constructed using
given dot-separated path or series of mapped attributes
into an joined eager load.
- .. note:: This function is known as :func:`eagerload_all` in all versions
- of SQLAlchemy prior to version 0.6beta3, including the 0.5 and 0.4
- series. :func:`eagerload_all` will remain available for the
- foreseeable future in order to enable cross-compatibility.
+ .. note::
+
+ This function is known as :func:`eagerload_all` in all versions
+ of SQLAlchemy prior to version 0.6beta3, including the 0.5 and 0.4
+ series. :func:`eagerload_all` will remain available for the
+ foreseeable future in order to enable cross-compatibility.
Used with :meth:`~sqlalchemy.orm.query.Query.options`.
class MapperExtension(object):
"""Base implementation for :class:`.Mapper` event hooks.
- .. note:: :class:`.MapperExtension` is deprecated. Please
+ .. note::
+
+ :class:`.MapperExtension` is deprecated. Please
refer to :func:`.event.listen` as well as
:class:`.MapperEvents`.
"""Base implementation for :class:`.Session` event hooks.
- .. note:: :class:`.SessionExtension` is deprecated. Please
+ .. note::
+
+ :class:`.SessionExtension` is deprecated. Please
refer to :func:`.event.listen` as well as
:class:`.SessionEvents`.
"""Base implementation for :class:`.AttributeImpl` event hooks, events
that fire upon attribute mutations in user code.
- .. note:: :class:`.AttributeExtension` is deprecated. Please
+ .. note::
+
+ :class:`.AttributeExtension` is deprecated. Please
refer to :func:`.event.listen` as well as
:class:`.AttributeEvents`.
q = session.query(User).join(Address, User.id==Address.user_id)
- .. note:: In SQLAlchemy 0.6 and earlier, the two argument form of
+ .. note::
+
+ In SQLAlchemy 0.6 and earlier, the two argument form of
:meth:`~.Query.join` requires the usage of a tuple::
query(User).join((Address, User.id==Address.user_id))
return session.is_modified(someobject, passive=True)
- .. note:: In SQLAlchemy 0.7 and earlier, the ``passive``
+ .. note::
+
+ In SQLAlchemy 0.7 and earlier, the ``passive``
flag should **always** be explicitly set to ``True``.
The current default value of :data:`.attributes.PASSIVE_OFF`
for this flag is incorrect, in that it loads unloaded
``distinct`` is also available via the :meth:`~.Select.distinct`
generative method.
- .. note:: The ``distinct`` keyword's acceptance of a string
- argument for usage with MySQL is deprecated. Use
- the ``prefixes`` argument or :meth:`~.Select.prefix_with`.
+ .. note::
+
+ The ``distinct`` keyword's acceptance of a string
+ argument for usage with MySQL is deprecated. Use
+ the ``prefixes`` argument or :meth:`~.Select.prefix_with`.
:param for_update=False:
when ``True``, applies ``FOR UPDATE`` to the end of the
"""Return a new :func:`.select` construct with its columns
clause replaced with the given columns.
- .. note:: Due to a bug fix, this method has a slight
+ .. note::
+
+ Due to a bug fix, this method has a slight
behavioral change as of version 0.7.3.
Prior to version 0.7.3, the FROM clause of
a :func:`.select` was calculated upfront and as new columns
are serialized into strings are examples of "mutable"
column structures.
- .. note:: This functionality is now superseded by the
- ``sqlalchemy.ext.mutable`` extension described in
- :ref:`mutable_toplevel`.
+ .. note::
+
+ This functionality is now superseded by the
+ ``sqlalchemy.ext.mutable`` extension described in
+ :ref:`mutable_toplevel`.
When this method is overridden, :meth:`copy_value` should
also be supplied. The :class:`.MutableType` mixin
are serialized into strings are examples of "mutable"
column structures.
- .. note:: This functionality is now superseded by the
- ``sqlalchemy.ext.mutable`` extension described in
- :ref:`mutable_toplevel`.
+ .. note::
+
+ This functionality is now superseded by the
+ ``sqlalchemy.ext.mutable`` extension described in
+ :ref:`mutable_toplevel`.
"""
return self.impl.is_mutable()
a mutable Python object type. This functionality is used
only by the ORM.
- .. note:: :class:`.MutableType` is superseded as of SQLAlchemy 0.7
+ .. note::
+
+ :class:`.MutableType` is superseded as of SQLAlchemy 0.7
by the ``sqlalchemy.ext.mutable`` extension described in
:ref:`mutable_toplevel`. This extension provides an event
driven approach to in-place mutation detection that does not
type - implementing subclasses should override these
appropriately.
- .. warning:: The usage of mutable types has significant performance
+ .. warning::
+
+ The usage of mutable types has significant performance
implications when using the ORM. In order to detect changes, the
ORM must create a copy of the value when it is first
accessed, so that changes to the current value can be compared
``decimal.Decimal`` objects by default, applying
conversion as needed.
- .. note:: The `cdecimal <http://pypi.python.org/pypi/cdecimal/>`_ library
+ .. note::
+
+ The `cdecimal <http://pypi.python.org/pypi/cdecimal/>`_ library
is a high performing alternative to Python's built-in
``decimal.Decimal`` type, which performs very poorly in high volume
situations. SQLAlchemy 0.7 is tested against ``cdecimal`` and supports
behavior. (default changed from ``True`` in
0.7.0).
- .. note:: This functionality is now superseded by the
+ .. note::
+
+ This functionality is now superseded by the
``sqlalchemy.ext.mutable`` extension described in
:ref:`mutable_toplevel`.
If msg is a string, :class:`.exc.SAWarning` is used as
the category.
- .. note:: This function is swapped out when the test suite
+ .. note::
+
+ This function is swapped out when the test suite
runs, with a compatible version that uses
warnings.warn_explicit, so that the warnings registry can
be controlled.