1. Section decorators to [one style](http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#sections):
without inset at both side and with same length as text.
2. Fix broken [reference](http://docs.sqlalchemy.org/en/latest/core/type_basics.html#generic-types).
3. Convert tabs to space in some small files.
4. Some python code snippets have python+sql syntax hint.
Change-Id: I39a7a41ef0b0591c6bf1e610748e2b5c19fc5379
Pull-request: https://github.com/zzzeek/sqlalchemy/pull/361
-==============
+=============
0.1 Changelog
-==============
+=============
.. changelog::
-==============
+=============
0.2 Changelog
-==============
+=============
.. changelog::
-==============
+=============
0.3 Changelog
-==============
+=============
.. changelog::
-==============
+=============
0.4 Changelog
-==============
+=============
.. changelog::
-==============
+=============
0.5 Changelog
-==============
+=============
.. changelog::
-==============
+=============
0.6 Changelog
-==============
+=============
.. changelog::
-==============
+=============
0.7 Changelog
-==============
+=============
.. changelog::
:version: 0.7.11
-==============
+=============
0.8 Changelog
-==============
+=============
.. changelog_imports::
-==============
+=============
0.9 Changelog
-==============
+=============
.. changelog_imports::
-==============
+=============
1.0 Changelog
-==============
+=============
.. changelog_imports::
-==============
+=============
1.1 Changelog
-==============
+=============
.. changelog_imports::
-==============
+=============
1.2 Changelog
-==============
+=============
.. changelog_imports::
within the main documentation.
Current Migration Guide
-------------------------
+-----------------------
.. toctree::
:titlesonly:
-==============================
+=============================
What's New in SQLAlchemy 0.6?
-==============================
+=============================
.. admonition:: About this Document
-==============================
+=============================
What's New in SQLAlchemy 0.7?
-==============================
+=============================
.. admonition:: About this Document
-==============================
+=============================
What's New in SQLAlchemy 0.8?
-==============================
+=============================
.. admonition:: About this Document
:ticket:`2245`
Query.update() supports UPDATE..FROM
--------------------------------------
+------------------------------------
The new UPDATE..FROM mechanics work in query.update().
Below, we emit an UPDATE against ``SomeEntity``, adding
:ticket:`2452`
Caching Example now uses dogpile.cache
----------------------------------------
+--------------------------------------
The caching example now uses `dogpile.cache <https://dogpilecache.readthedocs.io/>`_.
Dogpile.cache is a rewrite of the caching portion
:ticket:`2589`
New Core Features
-==================
+=================
Fully extensible, type-level operator support in Core
-----------------------------------------------------
.. _feature_2623:
Multiple-VALUES support for Insert
------------------------------------
+----------------------------------
The :meth:`.Insert.values` method now supports a list of dictionaries,
which will render a multi-VALUES statement such as
:ticket:`2623`
Type Expressions
------------------
+----------------
SQL expressions can now be associated with types. Historically,
:class:`.TypeEngine` has always allowed Python-side functions which
:ticket:`1534`
Core Inspection System
------------------------
+----------------------
The :func:`.inspect` function introduced in :ref:`feature_orminspection_08`
also applies to the core. Applied to an :class:`.Engine` it produces
:ticket:`2664`
Repaired the Event Targeting of :class:`.InstrumentationEvents`
-----------------------------------------------------------------
+---------------------------------------------------------------
The :class:`.InstrumentationEvents` series of event targets have
documented that the events will only be fired off according to
-==============================
+=============================
What's New in SQLAlchemy 1.0?
-==============================
+=============================
.. admonition:: About this Document
:ticket:`3100`
New Performance Example Suite
-------------------------------
+-----------------------------
Inspired by the benchmarking done for the :ref:`bulk_operations` feature
as well as for the :ref:`faq_how_to_profile` section of the FAQ, a new
.. _feature_3150:
Improvements to declarative mixins, ``@declared_attr`` and related features
-----------------------------------------------------------------------------
+---------------------------------------------------------------------------
The declarative system in conjunction with :class:`.declared_attr` has been
overhauled to support new capabilities.
.. _feature_slots:
Significant Improvements in Structural Memory Use
---------------------------------------------------
+-------------------------------------------------
Structural memory use has been improved via much more significant use
of ``__slots__`` for many internal objects. This optimization is
.. _feature_updatemany:
UPDATE statements are now batched with executemany() in a flush
-----------------------------------------------------------------
+---------------------------------------------------------------
UPDATE statements can now be batched within an ORM flush
into more performant executemany() call, similarly to how INSERT
.. _bug_3227:
Session.get_bind() will receive the Mapper in all relevant Query cases
------------------------------------------------------------------------
+----------------------------------------------------------------------
A series of issues were repaired where the :meth:`.Session.get_bind`
would not receive the primary :class:`.Mapper` of the :class:`.Query`,
.. _bug_3188:
ColumnProperty constructs work a lot better with aliases, order_by
--------------------------------------------------------------------
+------------------------------------------------------------------
A variety of issues regarding :func:`.column_property` have been fixed,
most specifically with regards to the :func:`.aliased` construct as well
.. _feature_3034:
Select/Query LIMIT / OFFSET may be specified as an arbitrary SQL expression
-----------------------------------------------------------------------------
+---------------------------------------------------------------------------
The :meth:`.Select.limit` and :meth:`.Select.offset` methods now accept
any SQL expression, in addition to integer values, as arguments. The ORM
.. _feature_insert_from_select_defaults:
INSERT FROM SELECT now includes Python and SQL-expression defaults
--------------------------------------------------------------------
+------------------------------------------------------------------
:meth:`.Insert.from_select` now includes Python and SQL-expression defaults if
otherwise unspecified; the limitation where non-server column defaults
.. _bug_3233:
Changes and fixes in handling of duplicate join targets
---------------------------------------------------------
+-------------------------------------------------------
Changes here encompass bugs where an unexpected and inconsistent
behavior would occur in some scenarios when joining to an entity
.. _feature_3084:
MetaData.sorted_tables accessor is "deterministic"
------------------------------------------------------
+--------------------------------------------------
The sorting of tables resulting from the :attr:`.MetaData.sorted_tables`
accessor is "deterministic"; the ordering should be the same in all cases
:ticket:`3319`
New PostgreSQL Table options
------------------------------
+----------------------------
Added support for PG table options TABLESPACE, ON COMMIT,
WITH(OUT) OIDS, and INHERITS, when rendering DDL via
:class:`.FunctionFilter`
PG8000 dialect supports client side encoding
----------------------------------------------
+--------------------------------------------
The :paramref:`.create_engine.encoding` parameter is now honored
by the pg8000 dialect, using on connect handler which
emits ``SET CLIENT_ENCODING`` matching the selected encoding.
PG8000 native JSONB support
---------------------------------------
+---------------------------
Support for PG8000 versions greater than 1.10.1 has been added, where
JSONB is supported natively.
:mod:`sqlalchemy.dialects.postgresql.psycopg2cffi`
Dialect Improvements and Changes - MySQL
-=============================================
+========================================
.. _change_3155:
MySQL TIMESTAMP Type now renders NULL / NOT NULL in all cases
---------------------------------------------------------------
+-------------------------------------------------------------
The MySQL dialect has always worked around MySQL's implicit NOT NULL
default associated with TIMESTAMP columns by emitting NULL for
.. _change_3283:
MySQL SET Type Overhauled to support empty sets, unicode, blank value handling
--------------------------------------------------------------------------------
+------------------------------------------------------------------------------
The :class:`.mysql.SET` type historically not included a system of handling
blank sets and empty values separately; as different drivers had different
on polishing it.
Dialect Improvements and Changes - SQLite
-=============================================
+=========================================
SQLite named and unnamed UNIQUE and FOREIGN KEY constraints will inspect and reflect
-------------------------------------------------------------------------------------
Microsoft. See :ref:`mssql_large_type_deprecation` for details.
Dialect Improvements and Changes - Oracle
-=============================================
+=========================================
.. _change_3220:
:ticket:`3220`
New Oracle Keywords for DDL
------------------------------
+---------------------------
Keywords such as COMPRESS, ON COMMIT, BITMAP:
-==============================
+=============================
What's New in SQLAlchemy 1.1?
-==============================
+=============================
.. admonition:: About this Document
.. seealso::
- :ref:`installation`
+ :ref:`installation`
:ticket:`3489`
.. seealso::
- :ref:`c_extensions`
+ :ref:`c_extensions`
:ticket:`3500`
.. _change_3749:
Same-named relationships on inheriting mappers no longer warn
---------------------------------------------------------------
+-------------------------------------------------------------
When creating two mappers in an inheritance scenario, placing a relationship
on both with the same name would emit the warning
.. _change_2857:
Support for the SQL LATERAL keyword
-------------------------------------
+-----------------------------------
The LATERAL keyword is currently known to only be supported by PostgreSQL 9.3
and greater, however as it is part of the SQL standard support for this keyword
.. _change_is_distinct_from:
Support for IS DISTINCT FROM and IS NOT DISTINCT FROM
-------------------------------------------------------
+-----------------------------------------------------
New operators :meth:`.ColumnOperators.is_distinct_from` and
:meth:`.ColumnOperators.isnot_distinct_from` allow the IS DISTINCT
.. _change_3292:
Support for Python's native ``enum`` type and compatible forms
----------------------------------------------------------------
+--------------------------------------------------------------
The :class:`.Enum` type can now be constructed using any
PEP-435 compliant enumerated type. When using this mode, input values
assert e.scalar(t.select()) is MyEnum.two
The ``Enum.enums`` collection is now a list instead of a tuple
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
As part of the changes to :class:`.Enum`, the :attr:`.Enum.enums` collection
of elements is now a list instead of a tuple. This because lists
.. _change_3503:
Correct SQL Types are Established from Indexed Access of ARRAY, JSON, HSTORE
------------------------------------------------------------------------------
+----------------------------------------------------------------------------
For all three of :class:`~.postgresql.ARRAY`, :class:`~.postgresql.JSON` and :class:`.HSTORE`,
the SQL type assigned to the expression returned by indexed access, e.g.
.. _change_3503_cast:
The JSON cast() operation now requires ``.astext`` is called explicitly
-------------------------------------------------------------------------
+-----------------------------------------------------------------------
As part of the changes in :ref:`change_3503`, the workings of the
:meth:`.ColumnElement.cast` operator on :class:`.postgresql.JSON` and
:ref:`dialect-postgresql-pygresql`
The "postgres" module is removed
----------------------------------
+--------------------------------
The ``sqlalchemy.dialects.postgres`` module, long deprecated, is
removed; this has emitted a warning for many years and projects
stmt = select([table]).with_for_update(read=True, key_share=True)
Dialect Improvements and Changes - MySQL
-=============================================
+========================================
.. _change_3547:
Dialect Improvements and Changes - SQLite
-=============================================
+=========================================
.. _change_3634:
.. _change_3629:
Reflection of the name of PRIMARY KEY constraints
---------------------------------------------------
+-------------------------------------------------
The SQLite backend now takes advantage of the "sqlite_master" view
of SQLite in order to extract the name of the primary key constraint
:ticket:`3434`
Dialect Improvements and Changes - Oracle
-=============================================
+=========================================
Support for SKIP LOCKED
-----------------------
-==============================
+=============================
What's New in SQLAlchemy 1.2?
-==============================
+=============================
.. admonition:: About this Document
.. _change_3740:
Percent signs in literal_column() now conditionally escaped
-------------------------------------------------------------
+-----------------------------------------------------------
The :obj:`.literal_column` construct now escapes percent sign characters
conditionally, based on whether or not the DBAPI in use makes use of a
:ticket:`3959`
Dialect Improvements and Changes - MySQL
-=============================================
+========================================
Dialect Improvements and Changes - SQLite
-=============================================
+=========================================
Dialect Improvements and Changes - Oracle
-=============================================
+=========================================
.. _change_3276:
.. _change_2626:
SQL Server schema names with embedded dots supported
------------------------------------------------------
+----------------------------------------------------
The SQL Server dialect has a behavior such that a schema name with a dot inside
of it is assumed to be a "database"."owner" identifier pair, which is
-=================
+===============
Core API Basics
-=================
+===============
.. toctree::
:maxdepth: 2
.. _connections_toplevel:
-=====================================
+====================================
Working with Engines and Connections
-=====================================
+====================================
.. module:: sqlalchemy.engine
.. _connections_nested_transactions:
Nesting of Transaction Blocks
-------------------------------
+-----------------------------
The :class:`.Transaction` object also handles "nested"
behavior by keeping track of the outermost begin/commit pair. In this example,
.. _dbengine_implicit:
Connectionless Execution, Implicit Execution
-=============================================
+============================================
Recall from the first section we mentioned executing with and without explicit
usage of :class:`.Connection`. "Connectionless" execution
.. module:: sqlalchemy.schema
-=================================
+================================
Defining Constraints and Indexes
-=================================
+================================
This section will discuss SQL :term:`constraints` and indexes. In SQLAlchemy
the key classes include :class:`.ForeignKeyConstraint` and :class:`.Index`.
:class:`.PrimaryKeyConstraint` - detailed API documentation.
Setting up Constraints when using the Declarative ORM Extension
-----------------------------------------------------------------
+---------------------------------------------------------------
The :class:`.Table` is the SQLAlchemy Core construct that allows one to define
table metadata, which among other things can be used by the SQLAlchemy ORM
.. _naming_check_constraints:
Naming CHECK Constraints
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~
The :class:`.CheckConstraint` object is configured against an arbitrary
SQL expression, which can have any number of columns present, and additionally
.. _naming_schematypes:
Configuring Naming for Boolean, Enum, and other schema types
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :class:`.SchemaType` class refers to type objects such as :class:`.Boolean`
and :class:`.Enum` which generate a CHECK constraint accompanying the type.
.. _schema_indexes_functional:
Functional Indexes
-~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~
:class:`.Index` supports SQL and function expressions, as supported by the
target backend. To create an index against a column using a descending
return uuid.UUID(value)
Marshal JSON Strings
-^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^
This type uses ``simplejson`` to marshal Python data structures
to/from JSON. Can be modified to use Python's builtin json encoder::
DROP TABLE users{stop}
Using the built-in DDLElement Classes
---------------------------------------
+-------------------------------------
The ``sqlalchemy.schema`` package contains SQL expression constructs that
provide DDL expressions. For example, to produce a ``CREATE TABLE`` statement:
.. _metadata_defaults:
Column Insert/Update Defaults
-==============================
+=============================
SQLAlchemy provides a very rich featureset regarding column level events which
take place during INSERT and UPDATE statements. Options include:
.. _triggered_columns:
Triggered Columns
-------------------
+-----------------
Columns with values set by a database trigger or other external process may be
called out using :class:`.FetchedValue` as a marker::
Defining Sequences
--------------------
+------------------
SQLAlchemy represents database sequences using the
:class:`~sqlalchemy.schema.Sequence` object, which is considered to be a
.. _supported_dbapis:
Supported Databases
-====================
+===================
SQLAlchemy includes many :class:`.Dialect` implementations for various
backends. Dialects for the most common databases are included with SQLAlchemy; a handful
.. _custom_dbapi_args:
Custom DBAPI connect() arguments
-=================================
+================================
Custom arguments used when issuing the ``connect()`` call to the underlying
DBAPI may be issued in three distinct ways. String-based arguments can be
.. _dbengine_logging:
Configuring Logging
-====================
+===================
Python's standard `logging
<http://docs.python.org/library/logging.html>`_ module is used to
listen(my_engine, 'connect', my_on_connect)
Modifiers
-----------
+---------
Some listeners allow modifiers to be passed to :func:`.listen`. These
modifiers sometimes provide alternate calling signatures for
listen(UserContact.phone, 'set', validate_phone, retval=True)
Event Reference
-----------------
+---------------
Both SQLAlchemy Core and SQLAlchemy ORM feature a wide variety of event hooks:
.. _core_event_toplevel:
Core Events
-============
+===========
This section describes the event interfaces provided in
SQLAlchemy Core.
:members:
Connection Pool Events
------------------------
+----------------------
.. autoclass:: sqlalchemy.events.PoolEvents
:members:
SQL Execution and Connection Events
-------------------------------------
+-----------------------------------
.. autoclass:: sqlalchemy.events.ConnectionEvents
:members:
:members:
Schema Events
------------------------
+-------------
.. autoclass:: sqlalchemy.events.DDLEvents
:members:
.. _dep_interfaces_core_toplevel:
Deprecated Event Interfaces
-============================
+===========================
.. module:: sqlalchemy.interfaces
Specifying the Schema Name
----------------------------
+--------------------------
Some databases support the concept of multiple schemas. A
:class:`~sqlalchemy.schema.Table` can reference this by specifying the
that is not at all supported by SQLAlchemy.
Constructing a Pool
-------------------------
+-------------------
To use a :class:`.Pool` by itself, the ``creator`` function is
the only argument that's required and is passed first, followed
Disconnect Handling - Optimistic
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When pessimistic handling is not employed, as well as when the database is
shutdown and/or restarted in the middle of a connection's period of use within
.. _pool_setting_recycle:
Setting Pool Recycle
-~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~
An additional setting that can augment the "optimistic" approach is to set the
pool recycle parameter. This parameter prevents the pool from using a particular
API Documentation - Available Pool Implementations
----------------------------------------------------
+--------------------------------------------------
.. autoclass:: sqlalchemy.pool.Pool
reflection queries.
Overriding Reflected Columns
------------------------------
+----------------------------
Individual columns can be overridden with explicit values when reflecting
tables; this is handy for specifying custom datatypes, constraints such as
... autoload=True)
Reflecting Views
------------------
+----------------
The reflection system can also reflect views. Basic usage is the same as that
of a table::
connecting to several kinds of databases with links to more information.
Define and Create Tables
-=========================
+========================
The SQL Expression Language constructs its expressions in most cases against
table columns. In SQLAlchemy, a column is most often represented by an object
{'fullname': 'Jack Jones', 'name': 'jack'}
Executing
-==========
+=========
The interesting part of an :class:`~sqlalchemy.sql.expression.Insert` is
executing it. In this tutorial, we will generally focus on the most explicit
.. _execute_multiple:
Executing Multiple Statements
-==============================
+=============================
Our insert example above was intentionally a little drawn out to show some
various behaviors of expression language constructs. In the usual case, an
.. _coretutorial_selecting:
Selecting
-==========
+=========
We began with inserts just so that our test database had some data in it. The
more interesting part of the data is selecting it! We'll cover UPDATE and
base class of all of these expressions as :class:`~.expression.ColumnElement`.
Operators
-==========
+=========
Since we've stumbled upon SQLAlchemy's operator paradigm, let's go through
some of its capabilities. We've seen how to equate two columns to each other:
is a bitwise AND of the value in `somecolumn`.
Operator Customization
------------------------
+----------------------
While :meth:`.ColumnOperators.op` is handy to get at a custom operator in a hurry,
the Core supports fundamental customization and extension of the operator system at
Conjunctions
-=============
+============
We'd like to show off some of our operators inside of :func:`.select`
as additional arguments.
Specifying Bound Parameter Behaviors
-------------------------------------------
+------------------------------------
The :func:`~.expression.text` construct supports pre-established bound values
using the :meth:`.TextClause.bindparams` method::
.. _sqlexpression_text_columns:
Specifying Result-Column Behaviors
-----------------------------------------------
+----------------------------------
We may also specify information about the result columns using the
:meth:`.TextClause.columns` method; this method can be used to specify
Using Aliases
-==============
+=============
The alias in SQL corresponds to a "renamed" version of a table or SELECT
statement, which occurs anytime you say "SELECT .. FROM sometable AS
{stop}[(u'jack',)]
Using Joins
-============
+===========
We're halfway along to being able to construct any SELECT expression. The next
cornerstone of the SELECT is the JOIN expression. We've already been doing
:class:`.Join`
Everything Else
-================
+===============
The concepts of creating SQL expressions have been introduced. What's left are
more variants of the same themes. So now we'll catalog the rest of the
.. _window_functions:
Window Functions
------------------
+----------------
Any :class:`.FunctionElement`, including functions generated by
:data:`~.expression.func`, can be turned into a "window function", that is an
.. _updates_order_parameters:
Parameter-Ordered Updates
---------------------------
+-------------------------
The default behavior of the :func:`.update` construct when rendering the SET
clauses is to render them using the column ordering given in the
1
Further Reference
-==================
+=================
Expression Language Reference: :ref:`expression_api_toplevel`
.. _types_api:
Base Type API
---------------
+-------------
.. autoclass:: TypeEngine
:members:
on top of `pythone-tds <https://github.com/denisenkom/pytds>`_.
Experimental / Incomplete
-^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^
Dialects that are in an incomplete state or are considered somewhat experimental.
.. automodule:: sqlalchemy.dialects.mssql.base
SQL Server Data Types
------------------------
+---------------------
As with all SQLAlchemy dialects, all UPPERCASE types that are known to be
valid with SQL server are importable from the top level dialect, whether
.. automodule:: sqlalchemy.dialects.mssql.pymssql
zxjdbc
---------------
+------
.. automodule:: sqlalchemy.dialects.mssql.zxjdbc
.. automodule:: sqlalchemy.dialects.mysql.base
MySQL Data Types
-------------------
+----------------
As with all SQLAlchemy dialects, all UPPERCASE types that are known to be
valid with MySQL are importable from the top level dialect::
MySQL-Python
---------------------
+------------
.. automodule:: sqlalchemy.dialects.mysql.mysqldb
pymysql
--------------
+-------
.. automodule:: sqlalchemy.dialects.mysql.pymysql
MySQL-Connector
-----------------------
+---------------
.. automodule:: sqlalchemy.dialects.mysql.mysqlconnector
cymysql
-------------
+-------
.. automodule:: sqlalchemy.dialects.mysql.cymysql
OurSQL
---------------
+------
.. automodule:: sqlalchemy.dialects.mysql.oursql
Google App Engine
------------------------
+-----------------
.. automodule:: sqlalchemy.dialects.mysql.gaerdbms
.. automodule:: sqlalchemy.dialects.mysql.pyodbc
zxjdbc
---------------
+------
.. automodule:: sqlalchemy.dialects.mysql.zxjdbc
.. automodule:: sqlalchemy.dialects.oracle.base
Oracle Data Types
--------------------
+-----------------
As with all SQLAlchemy dialects, all UPPERCASE types that are known to be
valid with Oracle are importable from the top level dialect, whether
cx_Oracle
-----------
+---------
.. automodule:: sqlalchemy.dialects.oracle.cx_oracle
zxjdbc
--------
+------
.. automodule:: sqlalchemy.dialects.oracle.zxjdbc
.. automodule:: sqlalchemy.dialects.postgresql.base
PostgreSQL Data Types
-------------------------
+---------------------
As with all SQLAlchemy dialects, all UPPERCASE types that are known to be
valid with PostgreSQL are importable from the top level dialect, whether
)
PostgreSQL DML Constructs
----------------------------
+-------------------------
.. autofunction:: sqlalchemy.dialects.postgresql.dml.insert
.. automodule:: sqlalchemy.dialects.sqlite.base
SQLite Data Types
-------------------------
+-----------------
As with all SQLAlchemy dialects, all UPPERCASE types that are known to be
valid with SQLite are importable from the top level dialect, whether
.. automodule:: sqlalchemy.dialects.sybase.base
python-sybase
--------------------
+-------------
.. automodule:: sqlalchemy.dialects.sybase.pysybase
pyodbc
-------------
+------
.. automodule:: sqlalchemy.dialects.sybase.pyodbc
mxodbc
-------------
+------
.. automodule:: sqlalchemy.dialects.sybase.mxodbc
For more detail, see :ref:`engines_toplevel` and :ref:`pooling_toplevel`.
How do I pass custom connect arguments to my database API?
------------------------------------------------------------
+----------------------------------------------------------
The :func:`.create_engine` call accepts additional arguments either
directly via the ``connect_args`` keyword argument::
see :ref:`session_faq_threadsafe`.
Why does SQLAlchemy issue so many ROLLBACKs?
----------------------------------------------
+--------------------------------------------
SQLAlchemy currently assumes DBAPI connections are in "non-autocommit" mode -
this is the default behavior of the Python database API, meaning it
http://dev.mysql.com/doc/refman/5.1/en/innodb-transaction-model.html
I'm on MyISAM - how do I turn it off?
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The behavior of the connection pool's connection return behavior can be
configured using ``reset_on_return``::
engine = create_engine('mysql://scott:tiger@localhost/myisam_database', pool=QueuePool(reset_on_return=False))
I'm on SQL Server - how do I turn those ROLLBACKs into COMMITs?
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``reset_on_return`` accepts the values ``commit``, ``rollback`` in addition
to ``True``, ``False``, and ``None``. Setting to ``commit`` will cause
.. _faq_toplevel:
-============================
+==========================
Frequently Asked Questions
-============================
+==========================
The Frequently Asked Questions section is a growing collection of commonly
observed questions to well-known issues.
-==================
+=================
MetaData / Schema
-==================
+=================
.. contents::
:local:
or SQLAlchemy-Migrate; see :ref:`schema_migrations` for discussion on this.
How can I sort Table objects in order of their dependency?
-===========================================================================
+==========================================================
This is available via the :attr:`.MetaData.sorted_tables` function::
print(t)
How can I get the CREATE TABLE/ DROP TABLE output as a string?
-===========================================================================
+==============================================================
Modern SQLAlchemy has clause constructs which represent DDL operations. These
can be rendered to strings like any other SQL expression::
an "offline" SQL generation mode that renders database migrations as SQL scripts.
How can I subclass Table/Column to provide certain behaviors/configurations?
-=============================================================================
+============================================================================
:class:`.Table` and :class:`.Column` are not good targets for direct subclassing.
However, there are simple ways to get on-construction behaviors using creation
ORM Configuration
-==================
+=================
.. contents::
:local:
How do I configure a Column that is a Python reserved word or similar?
-----------------------------------------------------------------------------
+----------------------------------------------------------------------
Column-based attributes can be given any name desired in the mapping. See
:ref:`mapper_column_distinct_names`.
is query profiling, and the other is code profiling.
Query Profiling
-^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^
Sometimes just plain SQL logging (enabled via python's logging module
or via the ``echo=True`` argument on :func:`.create_engine`) can give an
SHOW PLAN, etc. as is provided by the database backend.
Result Fetching Slowness - Core
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If on the other hand you see many thousands of calls related to fetching rows,
or very long calls to ``fetchall()``, it may
and too much time is spent with data moving over the network.
Result Fetching Slowness - ORM
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To detect slowness in ORM fetching of rows (which is the most common area
of performance concern), calls like ``populate_state()`` and ``_instance()`` will
with bundled profiling capabilities.
I'm inserting 400,000 rows with the ORM and it's really slow!
---------------------------------------------------------------
+-------------------------------------------------------------
The SQLAlchemy ORM uses the :term:`unit of work` pattern when synchronizing
changes to the database. This pattern goes far beyond simple "inserts"
.. _faq_compiled_cache_threshold:
How do I deal with "compiled statement cache reaching its size threshhold"?
------------------------------------------------------------------------------
+---------------------------------------------------------------------------
Some parts of the ORM make use of a least-recently-used (LRU) cache in order
to cache generated SQL statements for fast reuse. More generally, these
should never be reached. If this warning is occurring and the application
is not generating hundreds of engines, please report the issue to the
SQLAlchemy developers on the mailing list; see the guidelines
-at http://www.sqlalchemy.org/support.html#mailinglist.
\ No newline at end of file
+at http://www.sqlalchemy.org/support.html#mailinglist.
Sessions / Queries
-===================
+==================
.. contents::
:local:
please see :ref:`session_faq_whentocreate`.
But why does flush() insist on issuing a ROLLBACK?
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
It would be great if :meth:`.Session.flush` could partially complete and then not roll
back, however this is beyond its current capabilities since its internal
LEN!
How Do I use Textual SQL with ORM Queries?
--------------------------------------------
+------------------------------------------
See:
See :ref:`mapping_constructors` for a description of this behavior.
how do I use ON DELETE CASCADE with SA's ORM?
-----------------------------------------------
+---------------------------------------------
SQLAlchemy will always issue UPDATE or DELETE statements for dependent
rows which are currently loaded in the :class:`.Session`. For rows which
SQL Expressions
-=================
+===============
.. contents::
:local:
using :paramref:`~.relationship.back_populates` on each.
Backref Arguments
-~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~
We've established that the :paramref:`~.relationship.backref` keyword is merely a shortcut for building
two individual :func:`.relationship` constructs that refer to each other. Part of
arguments to be applied to the new relationship it creates.
One Way Backrefs
-~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~
An unusual case is that of the "one way backref". This is where the
"back-populating" behavior of the backref is only desirable in one
.. _relationship_patterns:
Basic Relationship Patterns
-----------------------------
+---------------------------
A quick walkthrough of the basic relational patterns.
One To Many
-~~~~~~~~~~~~
+~~~~~~~~~~~
A one to many relationship places a foreign key on the child table referencing
the parent. :func:`.relationship` is then specified on the parent, as referencing
Many To One
-~~~~~~~~~~~~
+~~~~~~~~~~~
Many to one places a foreign key in the parent table referencing the child.
:func:`.relationship` is declared on the parent, where a new scalar-holding
.. _relationships_one_to_one:
One To One
-~~~~~~~~~~~
+~~~~~~~~~~
One To One is essentially a bidirectional relationship with a scalar
attribute on both sides. To achieve this, the :paramref:`~.relationship.uselist` flag indicates
.. _relationships_many_to_many:
Many To Many
-~~~~~~~~~~~~~
+~~~~~~~~~~~~
Many to Many adds an association table between two classes. The association
table is indicated by the :paramref:`~.relationship.secondary` argument to
.. currentmodule:: sqlalchemy.orm
Working with Large Collections
-===============================
+==============================
The default behavior of :func:`.relationship` is to fully load
the collection of items in, as according to the loading strategy of the
.. _dynamic_relationship:
Dynamic Relationship Loaders
------------------------------
+----------------------------
A key feature to enable management of a large collection is the so-called "dynamic"
relationship. This is an optional form of :func:`~sqlalchemy.orm.relationship` which
.. _passive_deletes:
Using Passive Deletes
-----------------------
+---------------------
Use :paramref:`~.relationship.passive_deletes` to disable child object loading on a DELETE
operation, in conjunction with "ON DELETE (CASCADE|SET NULL)" on your database
assert child in parent.children
Dictionary Collections
------------------------
+----------------------
A little extra detail is needed when using a dictionary as a collection.
This because objects are always loaded from the database as lists, and a key-generation
.. autofunction:: mapped_collection
Custom Collection Implementations
-==================================
+=================================
You can use your own types for collections as well. In simple cases,
inherting from ``list`` or ``set``, adding custom behavior, is all that's needed.
for its container type, or when you otherwise would like to use a different method to
get the job done.
-.. sourcecode:: python+sql
+.. sourcecode:: python
from sqlalchemy.orm.collections import collection
subclass when a ``list``, ``set`` or ``dict`` is used directly.
Collection Internals
-=====================
+====================
Various internal methods.
.. _mapper_composite:
Composite Column Types
-=======================
+======================
Sets of columns can be associated with a single user-defined datatype. The ORM
provides a single attribute which represents the group of columns using the
.. _mapping_constructors:
Constructors and Object Initialization
-=======================================
+======================================
Mapping imposes no restrictions or requirements on the constructor
(``__init__``) method for the class. You are free to require any arguments for
.. _unitofwork_contextual:
Contextual/Thread-local Sessions
-=================================
+================================
Recall from the section :ref:`session_faq_whentocreate`, the concept of
"session scopes" was introduced, with an emphasis on web applications
.. _dep_interfaces_orm_toplevel:
Deprecated ORM Event Interfaces
-================================
+===============================
.. module:: sqlalchemy.orm.interfaces
a consistent interface to all events without the need for subclassing.
Mapper Events
------------------
+-------------
.. autoclass:: MapperExtension
:members:
Session Events
------------------
+--------------
.. autoclass:: SessionExtension
:members:
Attribute Events
---------------------
+----------------
.. autoclass:: AttributeExtension
:members:
:members:
Mapper Events
----------------
+-------------
.. autoclass:: sqlalchemy.orm.events.MapperEvents
:members:
:members:
Query Events
--------------
+------------
.. autoclass:: sqlalchemy.orm.events.QueryEvents
:members:
Instrumentation Events
------------------------
+----------------------
.. automodule:: sqlalchemy.orm.instrumentation
.. automodule:: examples.graphs
Dynamic Relations as Dictionaries
-------------------------------------
+---------------------------------
.. automodule:: examples.dynamic_dict
.. _examples_generic_associations:
Generic Associations
-------------------------
+--------------------
.. automodule:: examples.generic_associations
Large Collections
-------------------------
+-----------------
.. automodule:: examples.large_collection
.. automodule:: examples.materialized_paths
Nested Sets
-------------
+-----------
.. automodule:: examples.nested_sets
.. _examples_xmlpersistence:
XML Persistence
-------------------------
+---------------
.. automodule:: examples.elementtree
Versioning Objects
-------------------------
+------------------
.. _examples_versioned_history:
.. automodule:: examples.versioned_rows
Vertical Attribute Mapping
-------------------------------------
+--------------------------
.. automodule:: examples.vertical
.. _examples_inheritance:
Inheritance Mapping Recipes
-============================
+===========================
Basic Inheritance Mappings
-----------------------------------
+--------------------------
.. automodule:: examples.inheritance
.. _examples_instrumentation:
Attribute Instrumentation
-------------------------------------
+-------------------------
.. automodule:: examples.custom_attributes
.. _examples_sharding:
Horizontal Sharding
-------------------------
+-------------------
.. automodule:: examples.sharding
.. _examples_caching:
Dogpile Caching
-------------------------
+---------------
.. automodule:: examples.dogpile_caching
.. _examples_postgis:
PostGIS Integration
-------------------------
+-------------------
.. automodule:: examples.postgis
====================
.. toctree::
- :maxdepth: 2
+ :maxdepth: 2
- events
- internals
- exceptions
- deprecated
+ events
+ internals
+ exceptions
+ deprecated
the underlying collection or attribute does.
Creation of New Values
------------------------
+----------------------
When a list append() event (or set add(), dictionary __setitem__(), or scalar
assignment event) is intercepted by the association proxy, it instantiates a
.. _proxying_dictionaries:
Proxying to Dictionary Based Collections
------------------------------------------
+----------------------------------------
The association proxy can proxy to dictionary based collections as well. SQLAlchemy
mappings usually use the :func:`.attribute_mapped_collection` collection type to
.. _declarative_abstract:
``__abstract__``
-~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~
``__abstract__`` causes declarative to skip the production
of a table or mapper for the class entirely. A class can be added within a
references can be resolved without issue.
Accessing the MetaData
-=======================
+======================
The :func:`declarative_base` base class contains a
:class:`.MetaData` object where newly defined
.. _declarative_mixins:
Mixin and Custom Base Classes
-==============================
+=============================
A common need when using :mod:`~sqlalchemy.ext.declarative` is to
share some functionality, such as a set of common columns, some common
that will be mapped.
Mixing in Association Proxy and Other Attributes
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mixins can specify user-defined attributes as well as other extension
units such as :func:`.association_proxy`. The usage of
.. _decl_mixin_inheritance:
Controlling table inheritance with mixins
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ``__tablename__`` attribute may be used to provide a function that
will determine the name of the table used for each class in an inheritance
.. _mixin_inheritance_columns:
Mixing in Columns in Inheritance Scenarios
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In constrast to how ``__tablename__`` and other special names are handled when
used with :class:`.declared_attr`, when we mix in columns and properties (e.g.
)
Using a Hybrid Approach with __table__
-=======================================
+======================================
As an alternative to ``__tablename__``, a direct
:class:`~sqlalchemy.schema.Table` construct may be used. The
-------------
.. autoclass:: sqlalchemy.ext.indexable.index_property
- :members:
+ :members:
.. _instrumentation_toplevel:
Alternate Class Instrumentation
-================================
+===============================
.. automodule:: sqlalchemy.ext.instrumentation
.. _mutable_toplevel:
Mutation Tracking
-==================
+=================
.. automodule:: sqlalchemy.ext.mutable
:members:
.. autoclass:: MutableDict
- :members:
- :undoc-members:
+ :members:
+ :undoc-members:
.. autoclass:: MutableList
- :members:
- :undoc-members:
+ :members:
+ :undoc-members:
.. autoclass:: MutableSet
- :members:
- :undoc-members:
+ :members:
+ :undoc-members:
.. _orm_toplevel:
SQLAlchemy ORM
-===============
+==============
Here, the Object Relational Mapper is introduced and fully described. If you
want to work with higher-level SQL which is constructed automatically for you,
.. _inheritance_toplevel:
Mapping Class Inheritance Hierarchies
-======================================
+=====================================
SQLAlchemy supports three forms of inheritance: **single table inheritance**,
where several types of classes are represented by a single table, **concrete
.. _joined_inheritance:
Joined Table Inheritance
--------------------------
+------------------------
In joined table inheritance, each class along a hierarchy of classes
is represented by a distinct table. Querying for a particular subclass
.. _with_polymorphic:
Using with_polymorphic
------------------------
+----------------------
For the following sections, assume the ``Employee`` / ``Engineer`` / ``Manager``
examples introduced in :ref:`inheritance_toplevel`.
with a ``Company`` object. We'll add a ``company_id`` column to the
``employees`` table and a new table ``companies``:
-.. sourcecode:: python+sql
+.. sourcecode:: python
class Company(Base):
__tablename__ = 'company'
.. _loading_joined_inheritance:
Loading objects with joined table inheritance
------------------------------------------------
+---------------------------------------------
When using joined table inheritance, if we query for a specific subclass
that represents a JOIN of two tables such as our ``Engineer`` example
.. _loading_single_inheritance:
Loading objects with single table inheritance
------------------------------------------------
+---------------------------------------------
In modern Declarative, single inheritance mappings produce :class:`.Column`
objects that are mapped only to a subclass, and not available from the
Inheritance Loading API
-------------------------
+-----------------------
.. autofunction:: sqlalchemy.orm.with_polymorphic
.. _relationship_configure_joins:
Configuring how Relationship Joins
-------------------------------------
+----------------------------------
:func:`.relationship` will normally create a join between two tables
by examining the foreign key relationship between the two tables
.. _relationship_primaryjoin:
Specifying Alternate Join Conditions
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The default behavior of :func:`.relationship` when constructing a join
is that it equates the value of primary key columns
.. _relationship_custom_operator:
Using custom operators in join conditions
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Another use case for relationships is the use of custom operators, such
as PostgreSQL's "is contained within" ``<<`` operator when joining with
.. _self_referential_many_to_many:
Self-Referential Many-to-Many Relationship
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Many to many relationships can be customized by one or both of :paramref:`~.relationship.primaryjoin`
and :paramref:`~.relationship.secondaryjoin` - the latter is significant for a relationship that
Building Query-Enabled Properties
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Very ambitious custom join conditions may fail to be directly persistable, and
in some cases may not even load correctly. To remove the persistence part of
However, in extreme cases, consider using a regular Python property in
conjunction with :class:`.Query` as follows:
-.. sourcecode:: python+sql
+.. sourcecode:: python
class User(Base):
__tablename__ = 'user'
.. _deferred:
Deferred Column Loading
-========================
+=======================
This feature allows particular columns of a table be loaded only
upon direct access, instead of when the entity is queried using
query.options(undefer_group('photos')).all()
Load Only Cols
----------------
+--------------
An arbitrary set of columns can be selected as "load only" columns, which will
be loaded while deferring all other columns on a given entity, using :func:`.orm.load_only`::
.. _bundles:
Column Bundles
-===============
+==============
The :class:`.Bundle` may be used to query for groups of columns under one
namespace.
-=======================
+===============
Loading Objects
-=======================
+===============
Notes and features regarding the general loading of mapped objects.
.. _subqueryload_ordering:
The Importance of Ordering
-^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^
A query which makes use of :func:`.subqueryload` in conjunction with a
limiting modifier such as :meth:`.Query.first`, :meth:`.Query.limit`,
.. _contains_eager:
Routing Explicit Joins/Statements into Eagerly Loaded Collections
-------------------------------------------------------------------
+-----------------------------------------------------------------
The behavior of :func:`~sqlalchemy.orm.joinedload()` is such that joins are
created automatically, using anonymous aliases as targets, the results of which
contains_eager(Order.items))
Using contains_eager() to load a custom-filtered collection result
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When we use :func:`.contains_eager`, *we* are constructing ourselves the
SQL that will be used to populate collections. From this, it naturally follows
Advanced Usage with Arbitrary Statements
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The ``alias`` argument can be more creatively used, in that it can be made
to represent any set of arbitrary names to match up into a statement.
options(contains_eager(User.addresses, alias=eager_columns))
Creating Custom Load Rules
----------------------------
+--------------------------
.. warning:: This is an advanced technique! Great care and testing
should be applied.
Relationship Loader API
-------------------------
+-----------------------
.. autofunction:: contains_alias
.. module:: sqlalchemy.orm
Changing Attribute Behavior
-============================
+===========================
.. _simple_validators:
.. _mapper_sql_expressions:
SQL Expressions as Mapped Attributes
-=====================================
+====================================
Attributes on a mapped class can be linked to SQL expressions, which can
be used in queries.
})
Using a plain descriptor
--------------------------
+------------------------
In cases where a SQL query more elaborate than what :func:`.orm.column_property`
or :class:`.hybrid_property` can provide must be emitted, a regular Python
Using column_property for column level options
------------------------------------------------
+----------------------------------------------
Options can be specified when mapping a :class:`.Column` using the
:func:`.column_property` function. This function
.. _maptojoin:
Mapping a Class against Multiple Tables
-========================================
+=======================================
Mappers can be constructed against arbitrary relational units (called
*selectables*) in addition to plain tables. For example, the :func:`~.expression.join`
.. _flush_embedded_sql_expressions:
Embedding SQL Insert/Update Expressions into a Flush
-=====================================================
+====================================================
This feature allows the value of a database column to be set to a SQL
expression instead of a literal value. It's especially useful for atomic
.. _session_sql_expressions:
Using SQL Expressions with Sessions
-====================================
+===================================
SQL expressions and strings can be executed via the
:class:`~sqlalchemy.orm.session.Session` within its transactional context.
.. autoclass:: sqlalchemy.orm.util.AliasedInsp
.. autoclass:: sqlalchemy.orm.query.Bundle
- :members:
+ :members:
.. autoclass:: sqlalchemy.util.KeyedTuple
- :members: keys, _fields, _asdict
+ :members: keys, _fields, _asdict
.. autoclass:: sqlalchemy.orm.strategy_options.Load
- :members:
+ :members:
.. autofunction:: join
.. _passive_updates:
Mutable Primary Keys / Update Cascades
----------------------------------------
+--------------------------------------
When the primary key of an entity changes, related items
which reference the primary key must also be updated as
.. _self_referential:
Adjacency List Relationships
------------------------------
+----------------------------
The **adjacency list** pattern is a common relational pattern whereby a table
contains a foreign key reference to itself. This is the most common
where a column points to itself.
Self-Referential Query Strategies
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Querying of self-referential structures works like any other query::
.. _self_referential_eager_loading:
Configuring Self-Referential Eager Loading
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Eager loading of relationships occurs using joins or outerjoins from parent to
child table during a normal query operation, such that the parent and its
.. module:: sqlalchemy.orm.session
Session API
-============
+===========
Session and sessionmaker()
----------------------------
+--------------------------
.. autoclass:: sessionmaker
:members:
.. autofunction:: sqlalchemy.orm.util.was_deleted
Attribute and State Management Utilities
------------------------------------------
+----------------------------------------
These functions are provided by the SQLAlchemy attribute
instrumentation API to provide a detailed interface for dealing
-==========================
+==============
Session Basics
-==========================
+==============
What does the Session do ?
==========================
section :ref:`session_faq_whentocreate`.
Adding Additional Configuration to an Existing sessionmaker()
---------------------------------------------------------------
+-------------------------------------------------------------
A common scenario is where the :class:`.sessionmaker` is invoked
at module import time, however the generation of one or more :class:`.Engine`
session = Session()
Creating Ad-Hoc Session Objects with Alternate Arguments
----------------------------------------------------------
+--------------------------------------------------------
For the use case where an application needs to create a new :class:`.Session` with
special arguments that deviate from what is normally used throughout the application,
.. _session_faq:
Session Frequently Asked Questions
-===================================
+==================================
By this point, many users already have questions about sessions.
This section presents a mini-FAQ (note that we have also a :doc:`real FAQ </faq/index>`)
of the most basic issues one is presented with when using a :class:`.Session`.
When do I make a :class:`.sessionmaker`?
-------------------------------------------
+----------------------------------------
Just one time, somewhere in your application's global scope. It should be
looked upon as part of your application's configuration. If your
Is the Session a cache?
-----------------------------------
+-----------------------
Yeee...no. It's somewhat used as a cache, in that it implements the
:term:`identity map` pattern, and stores objects keyed to their primary key.
.. _session_faq_threadsafe:
Is the session thread-safe?
-------------------------------
+---------------------------
The :class:`.Session` is very much intended to be used in a
**non-concurrent** fashion, which usually means in only one thread at a
a new object local to a different :class:`.Session`.
Basics of Using a Session
-===========================
+=========================
The most basic :class:`.Session` use patterns are presented here.
.. _session_deleting_from_collections:
Deleting from Collections
-~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~
A common confusion that arises regarding :meth:`~.Session.delete` is when
objects which are members of a collection are being deleted. While the
print("pending to persistent: %s" % object_)
Pending to Transient
-^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^
The :term:`pending` object can revert back to :term:`transient` if the
:meth:`.Session.rollback` method is called before the pending object
print("transient to pending: %s" % object_)
Loaded as Persistent
-^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^
Objects can appear in the :class:`.Session` directly in the :term:`persistent`
state when they are loaded from the database. Tracking this state transition
Deleted to Detached
-^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^
The deleted object becomes :term:`detached` when the session's transaction
is committed. After the :meth:`.Session.commit` method is called, the
Persistent to Detached
-^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^
The persistent object becomes :term:`detached` when the object is de-associated
with the :class:`.Session`, via the :meth:`.Session.expunge`,
print("object became detached: %s" % object_)
Detached to Persistent
-^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^^
The detached object becomes persistent when it is re-associated with a
session using the :meth:`.Session.add` or equivalent method. Track
Deleted to Persistent
-^^^^^^^^^^^^^^^^^^^^^^^
+^^^^^^^^^^^^^^^^^^^^^
The :term:`deleted` object can be reverted to the :term:`persistent`
state when the transaction in which it was DELETEd was rolled back
When to Expire or Refresh
-~~~~~~~~~~~~~~~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~~~~~~
The :class:`.Session` uses the expiration feature automatically whenever
the transaction referred to by the session ends. Meaning, whenever :meth:`.Session.commit`
-=======================================
+======================================
Transactions and Connection Management
-=======================================
+======================================
.. _unitofwork_transaction:
table which stores email addresses, which we will call ``addresses``. Using
declarative, we define this table along with its mapped class, ``Address``:
-.. sourcecode:: python+sql
+.. sourcecode:: python
>>> from sqlalchemy import ForeignKey
>>> from sqlalchemy.orm import relationship
COMMIT
Working with Related Objects
-=============================
+============================
Now when we create a ``User``, a blank ``addresses`` collection will be
present. Various collection types, such as sets and dictionaries, are possible
.. _ormtutorial_joins:
Querying with Joins
-====================
+===================
Now that we have two tables, we can show some more features of :class:`.Query`,
specifically how to create queries that deal with both tables at the same time.
ensure correct results. See :ref:`subqueryload_ordering`.
Joined Load
--------------
+-----------
The other automatic eager loading function is more well known and is called
:func:`.orm.joinedload`. This style of loading emits a JOIN, by default
a detailed description of how this is used.
Explicit Join + Eagerload
---------------------------
+-------------------------
A third style of eager loading is when we are constructing a JOIN explicitly in
order to locate the primary rows, and would like to additionally apply the extra
Support for server side version identifier tracking.
Programmatic or Conditional Version Counters
----------------------------------------------
+--------------------------------------------
When ``version_id_generator`` is set to False, we can also programmatically
(and conditionally) set the version identifier on our object in the same way