]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
remove old files
authorMike Bayer <mike_mp@zzzcomputing.com>
Sat, 6 Dec 2008 17:00:17 +0000 (17:00 +0000)
committerMike Bayer <mike_mp@zzzcomputing.com>
Sat, 6 Dec 2008 17:00:17 +0000 (17:00 +0000)
15 files changed:
doc/build/oldcontent/copyright.txt [deleted file]
doc/build/oldcontent/dbengine.txt [deleted file]
doc/build/oldcontent/docstrings.html [deleted file]
doc/build/oldcontent/documentation.html [deleted file]
doc/build/oldcontent/index.html [deleted file]
doc/build/oldcontent/intro.txt [deleted file]
doc/build/oldcontent/mappers.txt [deleted file]
doc/build/oldcontent/metadata.txt [deleted file]
doc/build/oldcontent/ormtutorial.txt [deleted file]
doc/build/oldcontent/plugins.txt [deleted file]
doc/build/oldcontent/pooling.txt [deleted file]
doc/build/oldcontent/session.txt [deleted file]
doc/build/oldcontent/sqlexpression.txt [deleted file]
doc/build/oldcontent/tutorial.txt [deleted file]
doc/build/oldcontent/types.txt [deleted file]

diff --git a/doc/build/oldcontent/copyright.txt b/doc/build/oldcontent/copyright.txt
deleted file mode 100644 (file)
index a9e2cb2..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-Appendix:  Copyright {@name=copyright}
-================
-
-This is the MIT license: http://www.opensource.org/licenses/mit-license.php
-
-Copyright (c) 2005, 2006, 2007, 2008 Michael Bayer and contributors. SQLAlchemy is a trademark of Michael
-Bayer.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this
-software and associated documentation files (the "Software"), to deal in the Software
-without restriction, including without limitation the rights to use, copy, modify, merge,
-publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
-to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or
-substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-DEALINGS IN THE SOFTWARE.
-
diff --git a/doc/build/oldcontent/dbengine.txt b/doc/build/oldcontent/dbengine.txt
deleted file mode 100644 (file)
index dd18aee..0000000
+++ /dev/null
@@ -1,399 +0,0 @@
-Database Engines {@name=dbengine}
-============================
-
-The **Engine** is the starting point for any SQLAlchemy application.  It's "home base" for the actual database and its DBAPI, delivered to the SQLAlchemy application through a connection pool and a **Dialect**, which describes how to talk to a specific kind of database and DBAPI combination.
-
-The general structure is this:
-
-    {diagram}
-                                         +-----------+                        __________
-                                     /---|   Pool    |---\                   (__________)
-                 +-------------+    /    +-----------+    \     +--------+   |          |
-    connect() <--|   Engine    |---x                       x----| DBAPI  |---| database |
-                 +-------------+    \    +-----------+    /     +--------+   |          |
-                                     \---|  Dialect  |---/                   |__________|
-                                         +-----------+                       (__________)
-
-Where above, a [sqlalchemy.engine.Engine](rel:docstrings_sqlalchemy.engine_Engine) references both a  [sqlalchemy.engine.Dialect](rel:docstrings_sqlalchemy.engine_Dialect) and [sqlalchemy.pool.Pool](rel:docstrings_sqlalchemy.pool_Pool), which together interpret the DBAPI's module functions as well as the behavior of the database.
-
-Creating an engine is just a matter of issuing a single call, `create_engine()`:
-
-    {python}
-    engine = create_engine('postgres://scott:tiger@localhost:5432/mydatabase')
-    
-The above engine invokes the `postgres` dialect and a connection pool which references `localhost:5432`.
-
-The engine can be used directly to issue SQL to the database.  The most generic way is to use connections, which you get via the `connect()` method:
-
-    {python}
-    connection = engine.connect()
-    result = connection.execute("select username from users")
-    for row in result:
-        print "username:", row['username']
-    connection.close()
-    
-The connection is an instance of [sqlalchemy.engine.Connection](rel:docstrings_sqlalchemy.engine_Connection), which is a **proxy** object for an actual DBAPI connection.  The returned result is an instance of [sqlalchemy.engine.ResultProxy](rel:docstrings_sqlalchemy.engine_ResultProxy), which acts very much like a DBAPI cursor.
-
-When you say `engine.connect()`, a new `Connection` object is created, and a DBAPI connection is retrieved from the connection pool.  Later, when you call `connection.close()`, the DBAPI connection is returned to the pool; nothing is actually "closed" from the perspective of the database.
-
-To execute some SQL more quickly, you can skip the `Connection` part and just say:
-
-    {python}
-    result = engine.execute("select username from users")
-    for row in result:
-        print "username:", row['username']
-    result.close()
-
-Where above, the `execute()` method on the `Engine` does the `connect()` part for you, and returns the `ResultProxy` directly.  The actual `Connection` is *inside* the `ResultProxy`, waiting for you to finish reading the result.  In this case, when you `close()` the `ResultProxy`, the underlying `Connection` is closed, which returns the DBAPI connection to the pool. 
-
-To summarize the above two examples, when you use a `Connection` object, it's known as **explicit execution**.  When you don't see the `Connection` object, but you still use the `execute()` method on the `Engine`, it's called **explicit, connectionless execution**.   A third variant of execution also exists called **implicit execution**; this will be described later.
-
-The `Engine` and `Connection` can do a lot more than what we illustrated above; SQL strings are only its most rudimentary function.  Later chapters will describe how "constructed SQL" expressions can be used with engines; in many cases, you don't have to deal with the `Engine` at all after it's created.  The Object Relational Mapper (ORM), an optional feature of SQLAlchemy, also uses the `Engine` in order to get at connections; that's also a case where you can often create the engine once, and then forget about it.
-
-### Supported Databases {@name=supported}
-
-Recall that the `Dialect` is used to describe how to talk to a specific kind of database.  Dialects are included with SQLAlchemy for SQLite, Postgres, MySQL, MS-SQL, Firebird, Informix, and Oracle; these can each be seen as a Python module present in the `sqlalchemy.databases` package.  Each dialect requires the appropriate DBAPI drivers to be installed separately.
-
-Downloads for each DBAPI at the time of this writing are as follows:
-
-* Postgres:  [psycopg2](http://www.initd.org/tracker/psycopg/wiki/PsycopgTwo)
-* SQLite:  [sqlite3](http://www.python.org/doc/2.5.2/lib/module-sqlite3.html) [pysqlite](http://initd.org/tracker/pysqlite)
-* MySQL:   [MySQLDB](http://sourceforge.net/projects/mysql-python)
-* Oracle:  [cx_Oracle](http://www.cxtools.net/default.aspx?nav=home)
-* MS-SQL:  [pyodbc](http://pyodbc.sourceforge.net/) (recommended) [adodbapi](http://adodbapi.sourceforge.net/)  [pymssql](http://pymssql.sourceforge.net/)
-* Firebird:  [kinterbasdb](http://kinterbasdb.sourceforge.net/)
-* Informix:  [informixdb](http://informixdb.sourceforge.net/)
-
-The SQLAlchemy Wiki contains a page of database notes, describing whatever quirks and behaviors have been observed.  Its a good place to check for issues with specific databases.  [Database Notes](http://www.sqlalchemy.org/trac/wiki/DatabaseNotes)
-
-### create_engine() URL Arguments {@name=establishing}
-
-SQLAlchemy indicates the source of an Engine strictly via [RFC-1738](http://rfc.net/rfc1738.html) style URLs, combined with optional keyword arguments to specify options for the Engine.  The form of the URL is:
-
-    driver://username:password@host:port/database
-
-Available drivernames are `sqlite`, `mysql`, `postgres`, `oracle`, `mssql`, and `firebird`.  For sqlite, the database name is the filename to connect to, or the special name ":memory:" which indicates an in-memory database.  The URL is typically sent as a string to the `create_engine()` function:
-
-    {python}
-    # postgres
-    pg_db = create_engine('postgres://scott:tiger@localhost:5432/mydatabase')
-    
-    # sqlite (note the four slashes for an absolute path)
-    sqlite_db = create_engine('sqlite:////absolute/path/to/database.txt')
-    sqlite_db = create_engine('sqlite:///relative/path/to/database.txt')
-    sqlite_db = create_engine('sqlite://')  # in-memory database
-    sqlite_db = create_engine('sqlite://:memory:')  # the same
-    
-    # mysql
-    mysql_db = create_engine('mysql://localhost/foo')
-
-    # oracle via TNS name
-    oracle_db = create_engine('oracle://scott:tiger@dsn')
-
-    # oracle will feed host/port/SID into cx_oracle.makedsn
-    oracle_db = create_engine('oracle://scott:tiger@127.0.0.1:1521/sidname')
-
-    # mssql
-    mssql_db = create_engine('mssql://username:password@localhost/database')
-
-    # mssql via a DSN connection
-    mssql_db = create_engine('mssql://username:password@/?dsn=mydsn') 
-
-The `Engine` will ask the connection pool for a connection when the `connect()` or `execute()` methods are called.  The default connection pool, `QueuePool`, as well as the default connection pool used with SQLite, `SingletonThreadPool`, will open connections to the database on an as-needed basis.  As concurrent statements are executed, `QueuePool` will grow its pool of connections to a default size of five, and will allow a default "overflow" of ten.   Since the `Engine` is essentially "home base" for the connection pool, it follows that you should keep a single `Engine` per database established within an application, rather than creating a new one for each connection.
-
-#### 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 passed directly from the URL string as query arguments:
-
-    {python}
-    db = create_engine('postgres://scott:tiger@localhost/test?argument1=foo&argument2=bar')
-
-If SQLAlchemy's database connector is aware of a particular query argument, it may convert its type from string to its proper type.
-    
-`create_engine` also takes an argument `connect_args` which is an additional dictionary that will be passed to `connect()`.  This can be used when arguments of a type other than string are required, and SQLAlchemy's database connector has no type conversion logic present for that parameter:
-
-    {python}
-    db = create_engine('postgres://scott:tiger@localhost/test', connect_args = {'argument1':17, 'argument2':'bar'})
-
-The most customizable connection method of all is to pass a `creator` argument, which specifies a callable that returns a DBAPI connection:
-
-    {python}
-    def connect():
-        return psycopg.connect(user='scott', host='localhost')
-
-    db = create_engine('postgres://', creator=connect)
-        
-### Database Engine Options {@name=options}
-
-Keyword options can also be specified to `create_engine()`, following the string URL as follows:
-
-    {python}
-    db = create_engine('postgres://...', encoding='latin1', echo=True)
-
-A list of all standard options, as well as several that are used by particular database dialects, is as follows:
-
-* **assert_unicode=False** - When set to `True` alongside convert_unicode=`True`, asserts that incoming string bind parameters are instances of `unicode`, otherwise raises an error.  Only takes effect when `convert_unicode==True`.  This flag is also available on the `String` type and its descendants. New in 0.4.2.  
-* **connect_args** - a dictionary of options which will be passed directly to the DBAPI's `connect()` method as additional keyword arguments.
-* **convert_unicode=False** - if set to True, all String/character based types will convert Unicode values to raw byte values going into the database, and all raw byte values to Python Unicode coming out in result sets.  This is an engine-wide method to provide unicode conversion across the board.  For unicode conversion on a column-by-column level, use the `Unicode` column type instead, described in [types](rel:types).
-* **creator** - a callable which returns a DBAPI connection.  This creation function will be passed to the underlying connection pool and will be used to create all new database connections.  Usage of this function causes connection parameters specified in the URL argument to be bypassed.
-* **echo=False** - if True, the Engine will log all statements as well as a repr() of their parameter lists to the engines logger, which defaults to sys.stdout.  The `echo` attribute of `Engine` can be modified at any time to turn logging on and off.  If set to the string `"debug"`, result rows will be printed to the standard output as well.  This flag ultimately controls a Python logger; see [dbengine_logging](rel:dbengine_logging) at the end of this chapter for information on how to configure logging directly.
-* **echo_pool=False** - if True, the connection pool will log all checkouts/checkins to the logging stream, which defaults to sys.stdout.  This flag ultimately controls a Python logger; see [dbengine_logging](rel:dbengine_logging) for information on how to configure logging directly.
-* **encoding='utf-8'** - the encoding to use for all Unicode translations, both by engine-wide unicode conversion as well as the `Unicode` type object.
-* **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 "_(counter)".  If `None`, the value of `dialect.max_identifier_length` is used instead.
-* **module=None** - used by database implementations which support multiple DBAPI modules, this is a reference to a DBAPI2 module to be used instead of the engine's default module.  For Postgres, the default is psycopg2.  For Oracle, it's cx_Oracle.
-* **pool=None** - an already-constructed instance of `sqlalchemy.pool.Pool`, such as a `QueuePool` instance.  If non-None, this pool will be used directly as the underlying connection pool for the engine, bypassing whatever connection parameters are present in the URL argument.  For information on constructing connection pools manually, see [pooling](rel:pooling).
-* **poolclass=None** - a `sqlalchemy.pool.Pool` subclass, which will be used to create a connection pool instance using the connection parameters given in the URL.  Note this differs from `pool` in that you don't actually instantiate the pool in this case, you just indicate what type of pool to be used.
-* **max_overflow=10** - the number of connections to allow in connection pool "overflow", that is connections that can be opened above and beyond the pool_size setting, which defaults to five.  this is only used with `QueuePool`.
-* **pool_size=5** - the number of connections to keep open inside the connection pool.  This used with `QueuePool` as well as `SingletonThreadPool`.
-* **pool_recycle=-1** - this setting causes the pool to recycle connections after the given number of seconds has passed.  It defaults to -1, or no timeout.  For example, setting to 3600 means connections will be recycled after one hour.  Note that MySQL in particular will **disconnect automatically** if no activity is detected on a connection for eight hours (although this is configurable with the MySQLDB connection itself and the  server configuration as well).
-* **pool_timeout=30** - number of seconds to wait before giving up on getting a connection from the pool.  This is only used with `QueuePool`.
-* **strategy='plain'** - used to invoke alternate `Engine` implementations.  Currently available is the `threadlocal` strategy, which is described in  [dbengine_implicit_strategies](rel:dbengine_implicit_strategies).
-
-### More On Connections {@name=connections}
-
-Recall from the beginning of this section that the Engine provides a `connect()` method which returns a `Connection` object.  `Connection` is a *proxy* object which maintains a reference to a DBAPI connection instance.  The `close()` method on `Connection` does not actually close the DBAPI connection, but instead returns it to the connection pool referenced by the `Engine`.  `Connection` will also automatically return its resources to the connection pool when the object is garbage collected, i.e. its `__del__()` method is called.  When using the standard C implementation of Python, this method is usually called immediately as soon as the object is dereferenced.  With other Python implementations such as Jython, this is not so guaranteed.  
-    
-The `execute()` methods on both `Engine` and `Connection` can also receive SQL clause constructs as well:
-
-    {python}
-    connection = engine.connect()
-    result = connection.execute(select([table1], table1.c.col1==5))
-    for row in result:
-        print row['col1'], row['col2']
-    connection.close()
-
-The above SQL construct is known as a `select()`.  The full range of SQL constructs available are described in [sql](rel:sql).
-
-Both `Connection` and `Engine` fulfill an interface known as `Connectable` which specifies common functionality between the two objects, namely being able to call `connect()` to return a `Connection` object (`Connection` just returns itself), and being able to call `execute()` to get a result set.   Following this, most SQLAlchemy functions and objects which accept an `Engine` as a parameter or attribute with which to execute SQL will also accept a `Connection`.  As of SQLAlchemy 0.3.9, this argument is named `bind`.
-
-    {python title="Specify Engine or Connection"}
-    engine = create_engine('sqlite:///:memory:')
-    
-    # specify some Table metadata
-    metadata = MetaData()
-    table = Table('sometable', metadata, Column('col1', Integer))
-    
-    # create the table with the Engine
-    table.create(bind=engine)
-    
-    # drop the table with a Connection off the Engine
-    connection = engine.connect()
-    table.drop(bind=connection)
-
-Connection facts:
-
- * the Connection object is **not threadsafe**.  While a Connection can be shared among threads using properly synchronized access, this is also not recommended as many DBAPIs have issues with, if not outright disallow, sharing of connection state between threads.
- * The Connection object represents a single dbapi connection checked out from the connection pool.  In this state, the connection pool has no affect upon the connection, including its expiration or timeout state.  For the connection pool to properly manage connections, **connections should be returned to the connection pool (i.e. `connection.close()`) whenever the connection is not in use**.  If your application has a need for management of multiple connections or is otherwise long running (this includes all web applications, threaded or not), don't hold a single connection open at the module level.
-### Using Transactions with Connection {@name=transactions}
-
-The `Connection` object provides a `begin()` method which returns a `Transaction` object.  This object is usually used within a try/except clause so that it is guaranteed to `rollback()` or `commit()`:
-
-    {python}
-    trans = connection.begin()
-    try:
-        r1 = connection.execute(table1.select())
-        connection.execute(table1.insert(), col1=7, col2='this is some data')
-        trans.commit()
-    except:
-        trans.rollback()
-        raise
-
-The `Transaction` object also handles "nested" behavior by keeping track of the outermost begin/commit pair.  In this example, two functions both issue a transaction on a Connection, but only the outermost Transaction object actually takes effect when it is committed.
-
-    {python}
-    # method_a starts a transaction and calls method_b
-    def method_a(connection):
-        trans = connection.begin() # open a transaction
-        try:
-            method_b(connection)
-            trans.commit()  # transaction is committed here
-        except:
-            trans.rollback() # this rolls back the transaction unconditionally
-            raise
-
-    # method_b also starts a transaction
-    def method_b(connection):
-        trans = connection.begin() # open a transaction - this runs in the context of method_a's transaction
-        try:
-            connection.execute("insert into mytable values ('bat', 'lala')")
-            connection.execute(mytable.insert(), col1='bat', col2='lala')
-            trans.commit()  # transaction is not committed yet
-        except:
-            trans.rollback() # this rolls back the transaction unconditionally
-            raise
-
-    # open a Connection and call method_a
-    conn = engine.connect()                
-    method_a(conn)
-    conn.close()
-
-Above, `method_a` is called first, which calls `connection.begin()`.  Then it calls `method_b`. When `method_b` calls `connection.begin()`, it just increments a counter that is decremented when it calls `commit()`.  If either `method_a` or `method_b` calls `rollback()`, the whole transaction is rolled back.  The transaction is not committed until `method_a` calls the `commit()` method.  This "nesting" behavior allows the creation of functions which "guarantee" that a transaction will be used if one was not already available, but will automatically participate in an enclosing transaction if one exists.
-
-Note that SQLAlchemy's Object Relational Mapper also provides a way to control transaction scope at a higher level; this is described in [unitofwork_transaction](rel:unitofwork_transaction).
-
-Transaction Facts:
-
- * the Transaction object, just like its parent Connection, is **not threadsafe**.
- * SQLAlchemy 0.4 will feature transactions with two-phase commit capability as well as SAVEPOINT capability.
-
-#### Understanding Autocommit
-
-The above transaction example illustrates how to use `Transaction` so that several executions can take part in the same transaction.  What happens when we issue an INSERT, UPDATE or DELETE call without using `Transaction`?  The answer is **autocommit**.  While many DBAPIs  implement a flag called `autocommit`, the current SQLAlchemy behavior is such that it implements its own autocommit.  This is achieved by detecting statements which represent data-changing operations, i.e. INSERT, UPDATE, DELETE, etc., and then issuing a COMMIT automatically if no transaction is in progress.  The detection is based on compiled statement attributes, or in the case of a text-only statement via regular expressions.
-
-    {python}
-    conn = engine.connect()
-    conn.execute("INSERT INTO users VALUES (1, 'john')")  # autocommits
-
-### Connectionless Execution, Implicit Execution {@name=implicit}
-
-Recall from the first section we mentioned executing with and without a `Connection`.  `Connectionless` execution refers to calling the `execute()` method on an object which is not a `Connection`, which could be on the `Engine` itself, or could be a constructed SQL object.  When we say "implicit", we mean that we are calling the `execute()` method on an object which is neither a `Connection` nor an `Engine` object; this can only be used with constructed SQL objects which have their own `execute()` method, and can be "bound" to an `Engine`.  A description of "constructed SQL objects" may be found in [sql](rel:sql).
-
-A summary of all three methods follows below.  First, assume the usage of the following `MetaData` and `Table` objects; while we haven't yet introduced these concepts, for now you only need to know that we are representing a database table, and are creating an "executable" SQL construct which issues a statement to the database.  These objects are described in [metadata](rel:metadata).
-
-    {python}
-    meta = MetaData()
-    users_table = Table('users', meta, 
-        Column('id', Integer, primary_key=True), 
-        Column('name', String(50))
-    )
-    
-Explicit execution delivers the SQL text or constructed SQL expression to the `execute()` method of `Connection`:
-
-    {python}
-    engine = create_engine('sqlite:///file.db')
-    connection = engine.connect()
-    result = connection.execute(users_table.select())
-    for row in result:
-        # ....
-    connection.close()
-
-Explicit, connectionless execution delivers the expression to the `execute()` method of `Engine`:
-
-    {python}
-    engine = create_engine('sqlite:///file.db')
-    result = engine.execute(users_table.select())
-    for row in result:
-        # ....
-    result.close()
-
-Implicit execution is also connectionless, and calls the `execute()` method on the expression itself, utilizing the fact that either an `Engine` or `Connection` has been *bound* to the expression object (binding is discussed further in the next section, [metadata](rel:metadata)):
-
-    {python}
-    engine = create_engine('sqlite:///file.db')
-    meta.bind = engine
-    result = users_table.select().execute()
-    for row in result:
-        # ....
-    result.close()
-    
-In both "connectionless" examples, the `Connection` is created behind the scenes; the `ResultProxy` returned by the `execute()` call references the `Connection` used to issue the SQL statement.   When we issue `close()` on the `ResultProxy`, or if the result set object falls out of scope and is garbage collected, the underlying `Connection` is closed for us, resulting in the DBAPI connection being returned to the pool.
-
-#### Using the Threadlocal Execution Strategy {@name=strategies}
-
-The "threadlocal" engine strategy is used by non-ORM applications which wish to bind a transaction to the current thread, such that all parts of the application can participate in that transaction implicitly without the need to explicitly reference a `Connection`.   "threadlocal" is designed for a very specific pattern of use, and is not appropriate unless this very specfic pattern, described below, is what's desired.  It has **no impact** on the "thread safety" of SQLAlchemy components or one's application.  It also should not be used when using an ORM `Session` object, as the `Session` itself represents an ongoing transaction and itself handles the job of maintaining connection and transactional resources.
-
-Enabling `threadlocal` is achieved as follows:
-
-    {python}
-    db = create_engine('mysql://localhost/test', strategy='threadlocal')
-    
-When the engine above is used in a "connectionless" style, meaning `engine.execute()` is called, a DBAPI connection is retrieved from the connection pool and then associated with the current thread.   Subsequent operations on the `Engine` while the DBAPI connection remains checked out will make use of the *same* DBAPI connection object.  The connection stays allocated until all returned `ResultProxy` objects are closed, which occurs for a particular `ResultProxy` after all pending results are fetched, or immediately for an operation which returns no rows (such as an INSERT).
-
-    {python}
-    # execute one statement and receive results.  r1 now references a DBAPI connection resource.
-    r1 = db.execute("select * from table1")
-
-    # execute a second statement and receive results.  r2 now references the *same* resource as r1
-    r2 = db.execute("select * from table2")
-
-    # fetch a row on r1 (assume more results are pending)
-    row1 = r1.fetchone()
-
-    # fetch a row on r2 (same)
-    row2 = r2.fetchone()
-
-    # close r1.  the connection is still held by r2.
-    r1.close()
-
-    # close r2.  with no more references to the underlying connection resources, they
-    # are returned to the pool.
-    r2.close()
-
-The above example does not illustrate any pattern that is particularly useful, as it is not a frequent occurence that two execute/result fetching operations "leapfrog" one another.  There is a slight savings of connection pool checkout overhead between the two operations, and an implicit sharing of the same transactional context, but since there is no explicitly declared transaction, this association is short lived.
-
-The real usage of "threadlocal" comes when we want several operations to occur within the scope of a shared transaction.  The `Engine` now has `begin()`, `commit()` and `rollback()` methods which will retrieve a connection resource from the pool and establish a new transaction, maintaining the connection against the current thread until the transaction is committed or rolled back:
-
-    {python}
-    db.begin()
-    try:
-        call_operation1()
-        call_operation2()
-        db.commit()
-    except:
-        db.rollback()
-        
-`call_operation1()` and `call_operation2()` can make use of the `Engine` as a global variable, using the "connectionless" execution style, and their operations will participate in the same transaction:
-
-    {python}
-    def call_operation1():
-        engine.execute("insert into users values (?, ?)", 1, "john")
-        
-    def call_operation2():
-        users.update(users.c.user_id==5).execute(name='ed')
-    
-When using threadlocal, operations that do call upon the `engine.connect()` method will receive a `Connection` that is **outside** the scope of the transaction.  This can be used for operations such as logging the status of an operation regardless of transaction success:
-
-    {python}
-    db.begin()
-    conn = db.connect()
-    try:
-        conn.execute(log_table.insert(), message="Operation started")
-        call_operation1()
-        call_operation2()
-        db.commit()
-        conn.execute(log_table.insert(), message="Operation succeeded")
-    except:
-        db.rollback()
-        conn.execute(log_table.insert(), message="Operation failed")
-    finally:
-        conn.close()
-
-Functions which are written to use an explicit `Connection` object, but wish to participate in the threadlocal transaction, can receive their `Connection` object from the `contextual_connect()` method, which returns a `Connection` that is **inside** the scope of the transaction:
-
-    {python}
-    conn = db.contextual_connect()
-    call_operation3(conn)
-    conn.close()
-    
-Calling `close()` on the "contextual" connection does not release the connection resources to the pool if other resources are making use of it.  A resource-counting mechanism is employed so that the connection is released back to the pool only when all users of that connection, including the transaction established by `engine.begin()`, have been completed.
-
-So remember - if you're not sure if you need to use `strategy="threadlocal"` or not, the answer is **no** !  It's driven by a specific programming pattern that is generally not the norm.
-
-### Configuring Logging {@name=logging}
-
-Python's standard [logging](http://www.python.org/doc/lib/module-logging.html) module is used to implement informational and debug log output with SQLAlchemy.  This allows SQLAlchemy's logging to integrate in a standard way with other applications and libraries.  The `echo` and `echo_pool` flags that are present on `create_engine()`, as well as the `echo_uow` flag used on `Session`, all interact with regular loggers.
-
-This section assumes familiarity with the above linked logging module.  All logging performed by SQLAlchemy exists underneath the `sqlalchemy` namespace, as used by `logging.getLogger('sqlalchemy')`.  When logging has been configured (i.e. such as via `logging.basicConfig()`), the general namespace of SA loggers that can be turned on is as follows:
-
-* `sqlalchemy.engine` - controls SQL echoing.  set to `logging.INFO` for SQL query output, `logging.DEBUG` for query + result set output.
-* `sqlalchemy.pool` - controls connection pool logging.  set to `logging.INFO` or lower to log connection pool checkouts/checkins.
-* `sqlalchemy.orm` - controls logging of various ORM functions.  set to `logging.INFO` for configurational logging as well as unit of work dumps, `logging.DEBUG` for extensive logging during query and flush() operations.  Subcategories of `sqlalchemy.orm` include:
-    * `sqlalchemy.orm.attributes` - logs certain instrumented attribute operations, such as triggered callables
-    * `sqlalchemy.orm.mapper` - logs Mapper configuration and operations
-    * `sqlalchemy.orm.unitofwork` - logs flush() operations, including dependency sort graphs and other operations
-    * `sqlalchemy.orm.strategies` - logs relation loader operations (i.e. lazy and eager loads)
-    * `sqlalchemy.orm.sync` - logs synchronization of attributes from parent to child instances during a flush()
-
-For example, to log SQL queries as well as unit of work debugging:
-
-    {python}
-    import logging
-    
-    logging.basicConfig()
-    logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
-    logging.getLogger('sqlalchemy.orm.unitofwork').setLevel(logging.DEBUG)
-    
-By default, the log level is set to `logging.ERROR` within the entire `sqlalchemy` namespace so that no log operations occur, even within an application that has logging enabled otherwise.
-
-The `echo` flags present as keyword arguments to `create_engine()` and others as well as the `echo` property on `Engine`, when set to `True`, will first attempt to ensure that logging is enabled.  Unfortunately, the `logging` module provides no way of determining if output has already been configured (note we are referring to if a logging configuration has been set up, not just that the logging level is set).  For this reason, any `echo=True` flags will result in a call to `logging.basicConfig()` using sys.stdout as the destination.  It also sets up a default format using the level name, timestamp, and logger name.  Note that this configuration has the affect of being configured **in addition** to any existing logger configurations.  Therefore, **when using Python logging, ensure all echo flags are set to False at all times**, to avoid getting duplicate log lines.  
diff --git a/doc/build/oldcontent/docstrings.html b/doc/build/oldcontent/docstrings.html
deleted file mode 100644 (file)
index e2f0073..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-# -*- coding: utf-8 -*-
-<%inherit file="content_layout.html"/>
-<%page args="toc, extension, paged"/>
-<%namespace  name="formatting" file="formatting.html"/>
-<%namespace  name="nav" file="nav.html"/>
-<%namespace name="pydoc" file="pydoc.html"/>
-<%def name="title()">SQLAlchemy 0.5 Documentation - Modules and Classes</%def>
-
-<%!
-    filename = 'docstrings'
-%>
-
diff --git a/doc/build/oldcontent/documentation.html b/doc/build/oldcontent/documentation.html
deleted file mode 100644 (file)
index c850749..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-<%inherit file="base.html"/>
-<%namespace name="tocns" file="toc.html"/>
-<%namespace name="nav" file="nav.html"/>
-<%page args="toc, extension"/>
-
-${tocns.toc(toc, extension=extension, paged=False)}
-
-<%def name="title()">
-    SQLAlchemy Documentation
-</%def>
-
-% for file in toc.filenames:
-    <%
-        item = toc.get_by_file(file)
-    %>
-    
-    <A name="${item.path}"></a>
-
-    % if not item.requires_paged:
-        ${nav.pagenav(item=item, paged=False, extension=extension)}
-
-        ${self.get_namespace(file + '.html').body(toc=toc, extension=extension, paged=False)}
-    % endif
-% endfor
-
diff --git a/doc/build/oldcontent/index.html b/doc/build/oldcontent/index.html
deleted file mode 100644 (file)
index e4f3518..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-<%inherit file="base.html"/>
-<%page args="toc, extension"/>
-
-<%namespace name="tocns" file="toc.html"/>
-
-${tocns.toc(toc, paged=True, extension=extension)}
diff --git a/doc/build/oldcontent/intro.txt b/doc/build/oldcontent/intro.txt
deleted file mode 100644 (file)
index c45577d..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-Overview / Installation
-============
-
-## Overview
-
-The SQLAlchemy SQL Toolkit and Object Relational Mapper is a comprehensive set of tools for working with databases and Python.  It has several distinct areas of functionality which can be used individually or combined together.  Its major API components, all public-facing, are illustrated below:
-
-    {diagram}
-               +-----------------------------------------------------------+
-               |             Object Relational Mapper (ORM)                |
-               |                [[tutorial]](rel:datamapping)    [[docs]](rel:advdatamapping)                       |
-               +-----------------------------------------------------------+
-               +---------+ +------------------------------------+ +--------+
-               |         | |       SQL Expression Language      | |        |
-               |         | |        [[tutorial]](rel:sql)  [[docs]](rel:docstrings_sqlalchemy.sql.expression)          | |        |
-               |         | +------------------------------------+ |        |
-               |         +-----------------------+ +--------------+        |
-               |        Dialect/Execution        | |    Schema Management  |
-               |              [[docs]](rel:dbengine)             | |        [[docs]](rel:metadata)         |
-               +---------------------------------+ +-----------------------+
-               +----------------------+ +----------------------------------+
-               |  Connection Pooling  | |              Types               |
-               |        [[docs]](rel:pooling)        | |              [[docs]](rel:types)              |
-               +----------------------+ +----------------------------------+
-
-Above, the two most significant front-facing portions of SQLAlchemy are the **Object Relational Mapper** and the **SQL Expression Language**.  These are two separate toolkits, one building off the other.  SQL Expressions can be used independently of the ORM.  When using the ORM, the SQL Expression language is used to establish object-relational configurations as well as in querying.
-
-## Tutorials
-
- * [Object Relational Tutorial](rel:datamapping) - This describes the richest feature of SQLAlchemy, its object relational mapper.  If you want to work with higher-level SQL which is constructed automatically for you, as well as management of Python objects, proceed to this tutorial.
- * [SQL Expression Tutorial](rel:sql) - The core of SQLAlchemy is its SQL expression language.  The SQL Expression Language is a toolkit all its own, independent of the ORM package, which can be used to construct manipulable SQL expressions which can be programmatically constructed, modified, and executed, returning cursor-like result sets.  It's a lot more lightweight than the ORM and is appropriate for higher scaling SQL operations.  It's also heavily present within the ORM's public facing API, so advanced ORM users will want to master this language as well.
-
-## Reference Documentation
-
- * [Datamapping](rel:advdatamapping) - A comprehensive walkthrough of major ORM patterns and techniques.
- * [Session](rel:unitofwork) - A detailed description of SQLAlchemy's Session object
- * [Engines](rel:dbengine) - Describes SQLAlchemy's database-connection facilities, including connection documentation and working with connections and transactions. 
- * [Connection Pools](rel:pooling) - Further detail about SQLAlchemy's connection pool library.
- * [Metadata](rel:metadata) - All about schema management using `MetaData` and `Table` objects; reading database schemas into your application, creating and dropping tables, constraints, defaults, sequences, indexes.
- * [Types](rel:types) - Datatypes included with SQLAlchemy, their functions, as well as how to create your own types.
- * [Plugins](rel:plugins) - Included addons for SQLAlchemy
-
-## Installing SQLAlchemy {@name=sqlalchemy}
-
-Installing SQLAlchemy from scratch is most easily achieved with [setuptools][].  ([setuptools installation][install setuptools]). Just run this from the command-line:
-    
-    # easy_install SQLAlchemy
-
-This command will download the latest version of SQLAlchemy from the [Python Cheese Shop][pypi] and install it to your system.
-
-[setuptools]: http://peak.telecommunity.com/DevCenter/setuptools
-[install setuptools]: http://peak.telecommunity.com/DevCenter/EasyInstall#installation-instructions
-[pypi]: http://pypi.python.org/pypi/SQLAlchemy
-
-Otherwise, you can install from the distribution using the `setup.py` script:
-
-    # python setup.py install
-
-### Installing a Database API {@name=dbms}
-
-SQLAlchemy is designed to operate with a [DB-API](http://www.python.org/doc/peps/pep-0249/) implementation built for a particular database, and includes support for the most popular databases:
-
-* Postgres:  [psycopg2](http://www.initd.org/tracker/psycopg/wiki/PsycopgTwo)
-* SQLite:  [pysqlite](http://initd.org/tracker/pysqlite), [sqlite3](http://docs.python.org/lib/module-sqlite3.html) (included with Python 2.5 or greater)
-* MySQL:   [MySQLdb](http://sourceforge.net/projects/mysql-python)
-* Oracle:  [cx_Oracle](http://www.cxtools.net/default.aspx?nav=home)
-* MS-SQL, MSAccess:  [pyodbc](http://pyodbc.sourceforge.net/) (recommended), [adodbapi](http://adodbapi.sourceforge.net/)  or [pymssql](http://pymssql.sourceforge.net/)
-* Firebird:  [kinterbasdb](http://kinterbasdb.sourceforge.net/)
-* Informix:  [informixdb](http://informixdb.sourceforge.net/)
-* DB2/Informix IDS: [ibm-db](http://code.google.com/p/ibm-db/)
-* Sybase:   TODO
-* MAXDB:    TODO
-
-### Checking the Installed SQLAlchemy Version
-This documentation covers SQLAlchemy version 0.5.  If you're working on a system that already has SQLAlchemy installed, check the version from your Python prompt like this:
-
-     {python}
-     >>> import sqlalchemy
-     >>> sqlalchemy.__version__ # doctest: +SKIP
-     0.5.0
-
-## 0.4 to 0.5 Migration {@name=migration}
-
-Notes on what's changed from 0.4 to 0.5 is available on the SQLAlchemy wiki at [05Migration](http://www.sqlalchemy.org/trac/wiki/05Migration).
diff --git a/doc/build/oldcontent/mappers.txt b/doc/build/oldcontent/mappers.txt
deleted file mode 100644 (file)
index acf48bb..0000000
+++ /dev/null
@@ -1,1615 +0,0 @@
-[alpha_api]: javascript:alphaApi()
-[alpha_implementation]: javascript:alphaImplementation()
-
-Mapper Configuration {@name=advdatamapping}
-======================
-
-This section references most major configurational patterns involving the [mapper()](rel:docstrings_sqlalchemy.orm_modfunc_mapper) and [relation()](rel:docstrings_sqlalchemy.orm_modfunc_relation) functions.  It assumes you've worked through the [datamapping](rel:datamapping) and know how to construct and use rudimentary mappers and relations.
-
-### Mapper Configuration
-
-Full API documentation for the ORM:
-
-[docstrings_sqlalchemy.orm](rel:docstrings_sqlalchemy.orm).
-
-Options for the `mapper()` function:
-
-[docstrings_sqlalchemy.orm_modfunc_mapper](rel:docstrings_sqlalchemy.orm_modfunc_mapper).
-
-#### Customizing Column Properties {@name=columns}
-
-The default behavior of a `mapper` is to assemble all the columns in the mapped `Table` into mapped object attributes.  This behavior can be modified in several ways, as well as enhanced by SQL expressions.
-
-To load only a part of the columns referenced by a table as attributes, use the `include_properties` and `exclude_properties` arguments:
-
-    {python}
-    mapper(User, users_table, include_properties=['user_id', 'user_name'])
-
-    mapper(Address, addresses_table, exclude_properties=['street', 'city', 'state', 'zip'])
-
-To change the name of the attribute mapped to a particular column, place the `Column` object in the `properties` dictionary with the desired key:
-
-    {python}
-    mapper(User, users_table, properties={
-       'id': users_table.c.user_id,
-       'name': users_table.c.user_name,
-    })
-
-To change the names of all attributes using a prefix, use the `column_prefix` option.  This is useful for classes which wish to add their own `property` accessors:
-
-    {python}
-    mapper(User, users_table, column_prefix='_')
-
-The above will place attribute names such as `_user_id`, `_user_name`, `_password` etc. on the mapped `User` class.
-
-To place multiple columns which are known to be "synonymous" based on foreign key relationship or join condition into the same mapped attribute, put  them together using a list, as below where we map to a `Join`:
-
-    {python}
-    # join users and addresses
-    usersaddresses = sql.join(users_table, addresses_table, \
-        users_table.c.user_id == addresses_table.c.user_id)
-
-    mapper(User, usersaddresses, properties={
-        'id':[users_table.c.user_id, addresses_table.c.user_id],
-    })
-
-#### Deferred Column Loading {@name=deferred}
-
-This feature allows particular columns of a table to not be loaded by default, instead being loaded later on when first referenced.  It is essentially "column-level lazy loading".   This feature is useful when one wants to avoid loading a large text or binary field into memory when it's not needed.  Individual columns can be lazy loaded by themselves or placed into groups that lazy-load together.
-
-    {python}
-    book_excerpts = Table('books', db,
-        Column('book_id', Integer, primary_key=True),
-        Column('title', String(200), nullable=False),
-        Column('summary', String(2000)),
-        Column('excerpt', String),
-        Column('photo', Binary)
-    )
-
-    class Book(object):
-        pass
-
-    # define a mapper that will load each of 'excerpt' and 'photo' in
-    # separate, individual-row SELECT statements when each attribute
-    # is first referenced on the individual object instance
-    mapper(Book, book_excerpts, properties={
-       'excerpt': deferred(book_excerpts.c.excerpt),
-       'photo': deferred(book_excerpts.c.photo)
-    })
-
-Deferred columns can be placed into groups so that they load together:
-
-    {python}
-    book_excerpts = Table('books', db,
-      Column('book_id', Integer, primary_key=True),
-      Column('title', String(200), nullable=False),
-      Column('summary', String(2000)),
-      Column('excerpt', String),
-      Column('photo1', Binary),
-      Column('photo2', Binary),
-      Column('photo3', Binary)
-    )
-
-    class Book(object):
-      pass
-
-    # define a mapper with a 'photos' deferred group.  when one photo is referenced,
-    # all three photos will be loaded in one SELECT statement.  The 'excerpt' will
-    # be loaded separately when it is first referenced.
-    mapper(Book, book_excerpts, properties = {
-      'excerpt': deferred(book_excerpts.c.excerpt),
-      'photo1': deferred(book_excerpts.c.photo1, group='photos'),
-      'photo2': deferred(book_excerpts.c.photo2, group='photos'),
-      'photo3': deferred(book_excerpts.c.photo3, group='photos')
-    })
-
-You can defer or undefer columns at the `Query` level using the `defer` and `undefer` options:
-
-    {python}
-    query = session.query(Book)
-    query.options(defer('summary')).all()
-    query.options(undefer('excerpt')).all()
-
-And an entire "deferred group", i.e. which uses the `group` keyword argument to `deferred()`, can be undeferred using `undefer_group()`, sending in the group name:
-
-    {python}
-    query = session.query(Book)
-    query.options(undefer_group('photos')).all()
-
-#### SQL Expressions as Mapped Attributes {@name=expressions}
-
-To add a SQL clause composed of local or external columns as a read-only, mapped column attribute, use the `column_property()` function.  Any scalar-returning `ClauseElement` may be used, as long as it has a `name` attribute; usually, you'll want to call `label()` to give it a specific name:
-
-    {python}
-    mapper(User, users_table, properties={
-        'fullname': column_property(
-            (users_table.c.firstname + " " + users_table.c.lastname).label('fullname')
-        )
-    })
-
-Correlated subqueries may be used as well:
-
-    {python}
-    mapper(User, users_table, properties={
-        'address_count': column_property(
-                select(
-                    [func.count(addresses_table.c.address_id)],
-                    addresses_table.c.user_id==users_table.c.user_id
-                ).label('address_count')
-            )
-    })
-
-#### Changing Attribute Behavior {@name=attributes}
-
-##### Simple Validators {@name=validators}
-
-A quick way to add a "validation" routine to an attribute is to use the `@validates` decorator.  This is a shortcut for using the [docstrings_sqlalchemy.orm_Validator](rel:docstrings_sqlalchemy.orm_Validator) attribute extension with individual column or relation based attributes.   An attribute validator can raise an exception, halting the process of mutating the attribute's value, or can change the given value into something different.   Validators, like all attribute extensions, are only called by normal userland code; they are not issued when the ORM is populating the object.
-
-    {python}
-    addresses_table = Table('addresses', metadata, 
-        Column('id', Integer, primary_key=True),
-        Column('email', String)
-    )
-    
-    class EmailAddress(object):
-        @validates('email')
-        def validate_email(self, key, address):
-            assert '@' in address
-            return address
-            
-    mapper(EmailAddress, addresses_table)
-        
-Validators also receive collection events, when items are added to a collection:
-
-    {python}
-    class User(object):
-        @validates('addresses')
-        def validate_address(self, key, address):
-            assert '@' in address.email
-            return address
-    
-##### Using Descriptors {@name=overriding}
-
-A more comprehensive way to produce modified behavior for an attribute is to use descriptors.   These are commonly used in Python using the `property()` function.   The standard SQLAlchemy technique for descriptors is to create a plain descriptor, and to have it read/write from a mapped attribute with a different name.  To have the descriptor named the same as a column, map the column under a different name, i.e.:
-
-    {python}
-    class EmailAddress(object):
-       def _set_email(self, email):
-          self._email = email
-       def _get_email(self):
-          return self._email
-       email = property(_get_email, _set_email)
-
-    mapper(MyAddress, addresses_table, properties={
-        '_email': addresses_table.c.email
-    })
-    
-However, the approach above is not complete.  While our `EmailAddress` object will shuttle the value through the `email` descriptor and into the `_email` mapped attribute, the class level `EmailAddress.email` attribute does not have the usual expression semantics usable with `Query`.  To provide these, we instead use the `synonym()` function as follows:
-
-    {python}
-    mapper(EmailAddress, addresses_table, properties={
-        'email': synonym('_email', map_column=True)
-    })
-
-The `email` attribute is now usable in the same way as any other mapped attribute, including filter expressions, get/set operations, etc.:
-
-    {python}
-    address = session.query(EmailAddress).filter(EmailAddress.email == 'some address').one()
-
-    address.email = 'some other address'
-    session.flush()
-
-    q = session.query(EmailAddress).filter_by(email='some other address')
-
-If the mapped class does not provide a property, the `synonym()` construct will create a default getter/setter object automatically.
-
-##### Custom Comparators {@name=comparators}
-
-The expressions returned by comparison operations, such as `User.name=='ed'`, can be customized.  SQLAlchemy attributes generate these expressions using [docstrings_sqlalchemy.orm.interfaces_PropComparator](rel:docstrings_sqlalchemy.orm.interfaces_PropComparator) objects, which provide common Python expression overrides including `__eq__()`, `__ne__()`, `__lt__()`, and so on.  Any mapped attribute can be passed a user-defined class via the `comparator_factory` keyword argument, which subclasses the appropriate `PropComparator` in use, which can provide any or all of these methods:
-
-    {python}
-    from sqlalchemy.orm.properties import ColumnProperty
-    class MyComparator(ColumnProperty.Comparator):
-        def __eq__(self, other):
-            return func.lower(self.__clause_element__()) == func.lower(other)
-
-    mapper(EmailAddress, addresses_table, properties={
-        'email':column_property(addresses_table.c.email, comparator_factory=MyComparator)
-    })
-
-Above, comparisons on the `email` column are wrapped in the SQL lower() function to produce case-insensitive matching:
-
-    {python}
-    >>> str(EmailAddress.email == 'SomeAddress@foo.com')
-    lower(addresses.email) = lower(:lower_1)
-
-The `__clause_element__()` method is provided by the base `Comparator` class in use, and represents the SQL element which best matches what this attribute represents.  For a column-based attribute, it's the mapped column.  For a composite attribute, it's a `sqlalchemy.sql.expression.ClauseList` consisting of each column represented.  For a relation, it's the table mapped by the local mapper (not the remote mapper).  `__clause_element__()` should be honored by the custom comparator class in most cases since the resulting element will be applied any translations which are in effect, such as the correctly aliased member when using an `aliased()` construct or certain `with_polymorphic()` scenarios.
-
-There are four kinds of `Comparator` classes which may be subclassed, as according to the type of mapper property configured:
-
-  * `column_property()` attribute - `sqlalchemy.orm.properties.ColumnProperty.Comparator`
-  * `composite()` attribute - `sqlalchemy.orm.properties.CompositeProperty.Comparator`
-  * `relation()` attribute - `sqlalchemy.orm.properties.RelationProperty.Comparator`
-  * `comparable_property()` attribute - `sqlalchemy.orm.interfaces.PropComparator`
-
-When using `comparable_property()`, which is a mapper property that isn't tied to any column or mapped table, the `__clause_element__()` method of `PropComparator` should also be implemented.
-  
-The `comparator_factory` argument is accepted by all `MapperProperty`-producing functions:  `column_property()`, `composite()`, `comparable_property()`, `synonym()`, `relation()`, `backref()`, `deferred()`, and `dynamic_loader()`.
-
-#### Composite Column Types {@name=composite}
-
-Sets of columns can be associated with a single datatype.  The ORM treats the group of columns like a single column which accepts and returns objects using the custom datatype you provide.  In this example, we'll create a table `vertices` which stores a pair of x/y coordinates, and a custom datatype `Point` which is a composite type of an x and y column:
-
-    {python}
-    vertices = Table('vertices', metadata,
-        Column('id', Integer, primary_key=True),
-        Column('x1', Integer),
-        Column('y1', Integer),
-        Column('x2', Integer),
-        Column('y2', Integer),
-        )
-
-The requirements for the custom datatype class are that it have a constructor which accepts positional arguments corresponding to its column format, and also provides a method `__composite_values__()` which returns the state of the object as a list or tuple, in order of its column-based attributes.  It also should supply adequate `__eq__()` and `__ne__()` methods which test the equality of two instances, and may optionally provide a `__set_composite_values__` method which is used to set internal state in some cases (typically when default values have been generated during a flush):
-
-    {python}
-    class Point(object):
-        def __init__(self, x, y):
-            self.x = x
-            self.y = y
-        def __composite_values__(self):
-            return [self.x, self.y]
-        def __set_composite_values__(self, x, y):
-            self.x = x
-            self.y = y
-        def __eq__(self, other):
-            return other.x == self.x and other.y == self.y
-        def __ne__(self, other):
-            return not self.__eq__(other)
-
-If `__set_composite_values__()` is not provided, the names of the mapped columns are taken as the names of attributes on the object, and `setattr()` is used to set data.
-
-Setting up the mapping uses the `composite()` function:
-
-
-    {python}
-    class Vertex(object):
-        pass
-
-    mapper(Vertex, vertices, properties={
-        'start': composite(Point, vertices.c.x1, vertices.c.y1),
-        'end': composite(Point, vertices.c.x2, vertices.c.y2)
-    })
-
-We can now use the `Vertex` instances as well as querying as though the `start` and `end` attributes are regular scalar attributes:
-
-    {python}
-    session = Session()
-    v = Vertex(Point(3, 4), Point(5, 6))
-    session.save(v)
-
-    v2 = session.query(Vertex).filter(Vertex.start == Point(3, 4))
-
-The "equals" comparison operation by default produces an AND of all corresponding columns equated to one another.  This can be changed using the `comparator_factory`, described in [advdatamapping_mapper_attributes_comparators](rel:advdatamapping_mapper_attributes_comparators)
-
-    {python}
-    from sqlalchemy.orm.properties import CompositeProperty
-    from sqlalchemy import sql
-
-    class PointComparator(CompositeProperty.Comparator):
-        def __gt__(self, other):
-            """define the 'greater than' operation"""
-
-            return sql.and_(*[a>b for a, b in
-                              zip(self.__clause_element__().clauses,
-                                  other.__composite_values__())])
-
-    maper(Vertex, vertices, properties={
-        'start': composite(Point, vertices.c.x1, vertices.c.y1, comparator_factory=PointComparator),
-        'end': composite(Point, vertices.c.x2, vertices.c.y2, comparator_factory=PointComparator)
-    })
-
-#### Controlling Ordering {@name=orderby}
-
-As of version 0.5, the ORM does not generate ordering for any query unless explicitly configured.
-
-The "default" ordering for a collection, which applies to list-based collections, can be configured using the `order_by` keyword argument on `relation()`:
-
-    {python}
-    mapper(Address, addresses_table)
-
-    # order address objects by address id
-    mapper(User, users_table, properties={
-        'addresses': relation(Address, order_by=addresses_table.c.address_id)
-    })
-
-Note that when using eager loaders with relations, the tables used by the eager load's join are anonymously aliased.  You can only order by these columns if you specify it at the `relation()` level.  To control ordering at the query level based on a related table, you `join()` to that relation, then order by it:
-
-    {python}
-    session.query(User).join('addresses').order_by(Address.street)
-
-Ordering for rows loaded through `Query` is usually specified using the `order_by()` generative method.  There is also an option to set a default ordering for Queries which are against a single mapped entity and where there was no explicit `order_by()` stated, which is the `order_by` keyword argument to `mapper()`:
-
-    {python}
-    # order by a column
-    mapper(User, users_table, order_by=users_table.c.user_id)
-
-    # order by multiple items
-    mapper(User, users_table, order_by=[users_table.c.user_id, users_table.c.user_name.desc()])
-
-Above, a `Query` issued for the `User` class will use the value of the mapper's `order_by` setting if the `Query` itself has no ordering specified.
-
-#### Mapping Class Inheritance Hierarchies {@name=inheritance}
-
-SQLAlchemy supports three forms of inheritance:  *single table inheritance*, where several types of classes are stored in one table, *concrete table inheritance*, where each type of class is stored in its own table, and *joined table inheritance*, where the parent/child classes are stored in their own tables that are joined together in a select.  Whereas support for single and joined table inheritance is strong, concrete table inheritance is a less common scenario with some particular problems so is not quite as flexible.
-
-When mappers are configured in an inheritance relationship, SQLAlchemy has the ability to load elements "polymorphically", meaning that a single query can return objects of multiple types.
-
-For the following sections, assume this class relationship:
-
-    {python}
-    class Employee(object):
-        def __init__(self, name):
-            self.name = name
-        def __repr__(self):
-            return self.__class__.__name__ + " " + self.name
-
-    class Manager(Employee):
-        def __init__(self, name, manager_data):
-            self.name = name
-            self.manager_data = manager_data
-        def __repr__(self):
-            return self.__class__.__name__ + " " + self.name + " " +  self.manager_data
-
-    class Engineer(Employee):
-        def __init__(self, name, engineer_info):
-            self.name = name
-            self.engineer_info = engineer_info
-        def __repr__(self):
-            return self.__class__.__name__ + " " + self.name + " " +  self.engineer_info
-
-##### Joined Table Inheritance {@name=joined}
-
-In joined table inheritance, each class along a particular classes' list of parents is represented by a unique table.  The total set of attributes for a particular instance is represented as a join along all tables in its inheritance path.  Here, we first define a table to represent the `Employee` class.  This table will contain a primary key column (or columns), and a column for each attribute that's represented by `Employee`.  In this case it's just `name`:
-
-    {python}
-    employees = Table('employees', metadata,
-       Column('employee_id', Integer, primary_key=True),
-       Column('name', String(50)),
-       Column('type', String(30), nullable=False)
-    )
-
-The table also has a column called `type`.  It is strongly advised in both single- and joined- table inheritance scenarios that the root table contains a column whose sole purpose is that of the **discriminator**; it stores a value which indicates the type of object represented within the row.  The column may be of any desired datatype.  While there are some "tricks" to work around the requirement that there be a discriminator column, they are more complicated to configure when one wishes to load polymorphically.
-
-Next we define individual tables for each of `Engineer` and `Manager`, which contain columns that represent the attributes unique to the subclass they represent.  Each table also must contain a primary key column (or columns), and in most cases a foreign key reference to the parent table.  It is  standard practice that the same column is used for both of these roles, and that the column is also named the same as that of the parent table.  However this is optional in SQLAlchemy; separate columns may be used for primary key and parent-relation, the column may be named differently than that of the parent, and even a custom join condition can be specified between parent and child tables instead of using a foreign key. 
-
-    {python}
-    engineers = Table('engineers', metadata,
-       Column('employee_id', Integer, ForeignKey('employees.employee_id'), primary_key=True),
-       Column('engineer_info', String(50)),
-    )
-
-    managers = Table('managers', metadata,
-       Column('employee_id', Integer, ForeignKey('employees.employee_id'), primary_key=True),
-       Column('manager_data', String(50)),
-    )
-
-One natural effect of the joined table inheritance configuration is that the identity of any mapped object can be determined entirely from the base table.  This has obvious advantages, so SQLAlchemy always considers the primary key columns of a joined inheritance class to be those of the base table only, unless otherwise manually configured.  In other words, the `employee_id` column of both the `engineers` and `managers` table is not used to locate the `Engineer` or `Manager` object itself - only the value in `employees.employee_id` is considered, and the primary key in this case is non-composite.  `engineers.employee_id` and `managers.employee_id` are still of course critical to the proper operation of the pattern overall as they are used to locate the joined row, once the parent row has been determined, either through a distinct SELECT statement or all at once within a JOIN.
-
-We then configure mappers as usual, except we use some additional arguments to indicate the inheritance relationship, the polymorphic discriminator column, and the **polymorphic identity** of each class; this is the value that will be stored in the polymorphic discriminator column.
-
-    {python}
-    mapper(Employee, employees, polymorphic_on=employees.c.type, polymorphic_identity='employee')
-    mapper(Engineer, engineers, inherits=Employee, polymorphic_identity='engineer')
-    mapper(Manager, managers, inherits=Employee, polymorphic_identity='manager')
-
-And that's it.  Querying against `Employee` will return a combination of `Employee`, `Engineer` and `Manager` objects.   Newly saved `Engineer`, `Manager`, and `Employee` objects will automatically populate the `employees.type` column with `engineer`, `manager`, or `employee`, as appropriate.
-
-###### Controlling Which Tables are Queried {@name=with_polymorphic}
-
-The `with_polymorphic()` method of `Query` affects the specific subclass tables which the Query selects from.  Normally, a query such as this:
-
-    {python}
-    session.query(Employee).all()
-
-...selects only from the `employees` table.   When loading fresh from the database, our joined-table setup will query from the parent table only, using SQL such as this:
-
-    {python}
-    {opensql}
-    SELECT employees.employee_id AS employees_employee_id, employees.name AS employees_name, employees.type AS employees_type
-    FROM employees
-    []
-
-As attributes are requested from those `Employee` objects which are represented in either the `engineers` or `managers` child tables, a second load is issued for the columns in that related row, if the data was not already loaded.  So above, after accessing the objects you'd see further SQL issued along the lines of:
-
-    {python}
-    {opensql}
-    SELECT managers.employee_id AS managers_employee_id, managers.manager_data AS managers_manager_data
-    FROM managers
-    WHERE ? = managers.employee_id
-    [5]
-    SELECT engineers.employee_id AS engineers_employee_id, engineers.engineer_info AS engineers_engineer_info
-    FROM engineers
-    WHERE ? = engineers.employee_id
-    [2]
-
-This behavior works well when issuing searches for small numbers of items, such as when using `get()`, since the full range of joined tables are not pulled in to the SQL statement unnecessarily.  But when querying a larger span of rows which are known to be of many types, you may want to actively join to some or all of the joined tables.  The `with_polymorphic` feature of `Query` and `mapper` provides this.
-
-Telling our query to polymorphically load `Engineer` and `Manager` objects:
-
-    {python}
-    query = session.query(Employee).with_polymorphic([Engineer, Manager])
-
-produces a query which joins the `employees` table to both the `engineers` and `managers` tables like the following:
-
-    {python}
-    query.all()
-    {opensql}
-    SELECT employees.employee_id AS employees_employee_id, engineers.employee_id AS engineers_employee_id, managers.employee_id AS managers_employee_id, employees.name AS employees_name, employees.type AS employees_type, engineers.engineer_info AS engineers_engineer_info, managers.manager_data AS managers_manager_data
-    FROM employees LEFT OUTER JOIN engineers ON employees.employee_id = engineers.employee_id LEFT OUTER JOIN managers ON employees.employee_id = managers.employee_id
-    []
-
-`with_polymorphic()` accepts a single class or mapper, a list of classes/mappers, or the string `'*'` to indicate all subclasses:
-
-    {python}
-    # join to the engineers table
-    query.with_polymorphic(Engineer)
-    
-    # join to the engineers and managers tables
-    query.with_polymorphic([Engineer, Manager])
-    
-    # join to all subclass tables
-    query.with_polymorphic('*')
-    
-It also accepts a second argument `selectable` which replaces the automatic join creation and instead selects directly from the selectable given.  This feature is normally used with "concrete" inheritance, described later, but can be used with any kind of inheritance setup in the case that specialized SQL should be used to load polymorphically:
-
-    {python}
-    # custom selectable
-    query.with_polymorphic([Engineer, Manager], employees.outerjoin(managers).outerjoin(engineers))
-
-`with_polymorphic()` is also needed when you wish to add filter criterion that is specific to one or more subclasses, so that those columns are available to the WHERE clause:
-
-    {python}
-    session.query(Employee).with_polymorphic([Engineer, Manager]).\
-        filter(or_(Engineer.engineer_info=='w', Manager.manager_data=='q'))
-        
-Note that if you only need to load a single subtype, such as just the `Engineer` objects, `with_polymorphic()` is not needed since you would query against the `Engineer` class directly.
-
-The mapper also accepts `with_polymorphic` as a configurational argument so that the joined-style load will be issued automatically.  This argument may be the string `'*'`, a list of classes, or a tuple consisting of either, followed by a selectable.
-
-    {python}
-    mapper(Employee, employees, polymorphic_on=employees.c.type, \
-        polymorphic_identity='employee', with_polymorphic='*')
-    mapper(Engineer, engineers, inherits=Employee, polymorphic_identity='engineer')
-    mapper(Manager, managers, inherits=Employee, polymorphic_identity='manager')
-
-The above mapping will produce a query similar to that of `with_polymorphic('*')` for every query of `Employee` objects.
-
-Using `with_polymorphic()` with `Query` will override the mapper-level `with_polymorphic` setting.
-
-###### Creating Joins to Specific Subtypes {@name=joins}
-
-The `of_type()` method is a helper which allows the construction of joins along `relation` paths while narrowing the criterion to specific subclasses.  Suppose the `employees` table represents a collection of employees which are associated with a `Company` object.  We'll add a `company_id` column to the `employees` table and a new table `companies`:
-
-    {python}
-    companies = Table('companies', metadata,
-       Column('company_id', Integer, primary_key=True),
-       Column('name', String(50))
-       )
-
-    employees = Table('employees', metadata,
-      Column('employee_id', Integer, primary_key=True),
-      Column('name', String(50)),
-      Column('type', String(30), nullable=False),
-      Column('company_id', Integer, ForeignKey('companies.company_id'))
-    )
-
-    class Company(object):
-        pass
-
-    mapper(Company, companies, properties={
-        'employees': relation(Employee)
-    })
-
-When querying from `Company` onto the `Employee` relation, the `join()` method as well as the `any()` and `has()` operators will create a join from `companies` to `employees`, without including `engineers` or `managers` in the mix.  If we wish to have criterion which is specifically against the `Engineer` class, we can tell those methods to join or subquery against the joined table representing the subclass using the `of_type()` operator:
-
-    {python}
-    session.query(Company).join(Company.employees.of_type(Engineer)).filter(Engineer.engineer_info=='someinfo')
-
-A longhand version of this would involve spelling out the full target selectable within a 2-tuple:
-
-    {python}
-    session.query(Company).join((employees.join(engineers), Company.employees)).filter(Engineer.engineer_info=='someinfo')
-
-Currently, `of_type()` accepts a single class argument.  It may be expanded later on to accept multiple classes.  For now, to join to any group of subclasses, the longhand notation allows this flexibility:
-
-    {python}
-    session.query(Company).join((employees.outerjoin(engineers).outerjoin(managers), Company.employees)).\
-        filter(or_(Engineer.engineer_info=='someinfo', Manager.manager_data=='somedata'))
-
-The `any()` and `has()` operators also can be used with `of_type()` when the embedded criterion is in terms of a subclass:
-
-    {python}
-    session.query(Company).filter(Company.employees.of_type(Engineer).any(Engineer.engineer_info=='someinfo')).all()
-
-Note that the `any()` and `has()` are both shorthand for a correlated EXISTS query.  To build one by hand looks like:
-
-    {python}
-    session.query(Company).filter(
-        exists([1],
-            and_(Engineer.engineer_info=='someinfo', employees.c.company_id==companies.c.company_id),
-            from_obj=employees.join(engineers)
-        )
-    ).all()
-
-The EXISTS subquery above selects from the join of `employees` to `engineers`, and also specifies criterion which correlates the EXISTS subselect back to the parent `companies` table.
-
-##### Single Table Inheritance
-
-Single table inheritance is where the attributes of the base class as well as all subclasses are represented within a single table.  A column is present in the table for every attribute mapped to the base class and all subclasses; the columns which correspond to a single subclass are nullable.  This configuration looks much like joined-table inheritance except there's only one table.  In this case, a `type` column is required, as there would be no other way to discriminate between classes.  The table is specified in the base mapper only; for the inheriting classes, leave their `table` parameter blank:
-
-    {python}
-    employees_table = Table('employees', metadata,
-        Column('employee_id', Integer, primary_key=True),
-        Column('name', String(50)),
-        Column('manager_data', String(50)),
-        Column('engineer_info', String(50)),
-        Column('type', String(20), nullable=False)
-    )
-
-    employee_mapper = mapper(Employee, employees_table, \
-        polymorphic_on=employees_table.c.type, polymorphic_identity='employee')
-    manager_mapper = mapper(Manager, inherits=employee_mapper, polymorphic_identity='manager')
-    engineer_mapper = mapper(Engineer, inherits=employee_mapper, polymorphic_identity='engineer')
-
-Note that the mappers for the derived classes Manager and Engineer omit the specification of their associated table, as it is inherited from the employee_mapper. Omitting the table specification for derived mappers in single-table inheritance is required.
-
-##### Concrete Table Inheritance
-
-This form of inheritance maps each class to a distinct table, as below:
-
-    {python}
-    employees_table = Table('employees', metadata,
-        Column('employee_id', Integer, primary_key=True),
-        Column('name', String(50)),
-    )
-
-    managers_table = Table('managers', metadata,
-        Column('employee_id', Integer, primary_key=True),
-        Column('name', String(50)),
-        Column('manager_data', String(50)),
-    )
-
-    engineers_table = Table('engineers', metadata,
-        Column('employee_id', Integer, primary_key=True),
-        Column('name', String(50)),
-        Column('engineer_info', String(50)),
-    )
-
-Notice in this case there is no `type` column.  If polymorphic loading is not required, there's no advantage to using `inherits` here; you just define a separate mapper for each class.
-
-    {python}
-    mapper(Employee, employees_table)
-    mapper(Manager, managers_table)
-    mapper(Engineer, engineers_table)
-
-To load polymorphically, the `with_polymorphic` argument is required, along with a selectable indicating how rows should be loaded.  In this case we must construct a UNION of all three tables.  SQLAlchemy includes a helper function to create these called `polymorphic_union`, which will map all the different columns into a structure of selects with the same numbers and names of columns, and also generate a virtual `type` column for each subselect:
-
-    {python}
-    pjoin = polymorphic_union({
-        'employee': employees_table,
-        'manager': managers_table,
-        'engineer': engineers_table
-    }, 'type', 'pjoin')
-
-    employee_mapper = mapper(Employee, employees_table, with_polymorphic=('*', pjoin), \
-        polymorphic_on=pjoin.c.type, polymorphic_identity='employee')
-    manager_mapper = mapper(Manager, managers_table, inherits=employee_mapper, \
-        concrete=True, polymorphic_identity='manager')
-    engineer_mapper = mapper(Engineer, engineers_table, inherits=employee_mapper, \
-        concrete=True, polymorphic_identity='engineer')
-
-Upon select, the polymorphic union produces a query like this:
-
-    {python}
-    session.query(Employee).all()
-    {opensql}
-    SELECT pjoin.type AS pjoin_type, pjoin.manager_data AS pjoin_manager_data, pjoin.employee_id AS pjoin_employee_id,
-    pjoin.name AS pjoin_name, pjoin.engineer_info AS pjoin_engineer_info
-    FROM (
-        SELECT employees.employee_id AS employee_id, CAST(NULL AS VARCHAR(50)) AS manager_data, employees.name AS name,
-        CAST(NULL AS VARCHAR(50)) AS engineer_info, 'employee' AS type
-        FROM employees
-    UNION ALL
-        SELECT managers.employee_id AS employee_id, managers.manager_data AS manager_data, managers.name AS name,
-        CAST(NULL AS VARCHAR(50)) AS engineer_info, 'manager' AS type
-        FROM managers
-    UNION ALL
-        SELECT engineers.employee_id AS employee_id, CAST(NULL AS VARCHAR(50)) AS manager_data, engineers.name AS name,
-        engineers.engineer_info AS engineer_info, 'engineer' AS type
-        FROM engineers
-    ) AS pjoin
-    []
-
-##### Using Relations with Inheritance {@name=relations}
-
-Both joined-table and single table inheritance scenarios produce mappings which are usable in relation() functions; that is, it's possible to map a parent object to a child object which is polymorphic.  Similarly, inheriting mappers can have `relation()`s of their own at any level, which are inherited to each child class.  The only requirement for relations is that there is a table relationship between parent and child.  An example is the following modification to the joined table inheritance example, which sets a bi-directional relationship between `Employee` and `Company`:
-
-    {python}
-    employees_table = Table('employees', metadata,
-        Column('employee_id', Integer, primary_key=True),
-        Column('name', String(50)),
-        Column('company_id', Integer, ForeignKey('companies.company_id'))
-    )
-
-    companies = Table('companies', metadata,
-       Column('company_id', Integer, primary_key=True),
-       Column('name', String(50)))
-
-    class Company(object):
-        pass
-
-    mapper(Company, companies, properties={
-       'employees': relation(Employee, backref='company')
-    })
-
-SQLAlchemy has a lot of experience in this area; the optimized "outer join" approach can be used freely for parent and child relationships, eager loads are fully useable, query aliasing and other tricks are fully supported as well.
-
-In a concrete inheritance scenario, mapping `relation()`s is more difficult since the distinct classes do not share a table.  In this case, you *can* establish a relationship from parent to child if a join condition can be constructed from parent to child, if each child table contains a foreign key to the parent:
-
-    {python}
-    companies = Table('companies', metadata,
-       Column('id', Integer, primary_key=True),
-       Column('name', String(50)))
-
-    employees_table = Table('employees', metadata,
-        Column('employee_id', Integer, primary_key=True),
-        Column('name', String(50)),
-        Column('company_id', Integer, ForeignKey('companies.id'))
-    )
-
-    managers_table = Table('managers', metadata,
-        Column('employee_id', Integer, primary_key=True),
-        Column('name', String(50)),
-        Column('manager_data', String(50)),
-        Column('company_id', Integer, ForeignKey('companies.id'))
-    )
-
-    engineers_table = Table('engineers', metadata,
-        Column('employee_id', Integer, primary_key=True),
-        Column('name', String(50)),
-        Column('engineer_info', String(50)),
-        Column('company_id', Integer, ForeignKey('companies.id'))
-    )
-
-    mapper(Employee, employees_table, with_polymorphic=('*', pjoin), polymorphic_on=pjoin.c.type, polymorphic_identity='employee')
-    mapper(Manager, managers_table, inherits=employee_mapper, concrete=True, polymorphic_identity='manager')
-    mapper(Engineer, engineers_table, inherits=employee_mapper, concrete=True, polymorphic_identity='engineer')
-    mapper(Company, companies, properties={
-        'employees': relation(Employee)
-    })
-
-Let's crank it up and try loading with an eager load:
-
-    {python}
-    session.query(Company).options(eagerload('employees')).all()
-    {opensql}
-    SELECT anon_1.type AS anon_1_type, anon_1.manager_data AS anon_1_manager_data, anon_1.engineer_info AS anon_1_engineer_info,
-    anon_1.employee_id AS anon_1_employee_id, anon_1.name AS anon_1_name, anon_1.company_id AS anon_1_company_id,
-    companies.id AS companies_id, companies.name AS companies_name
-    FROM companies LEFT OUTER JOIN (SELECT CAST(NULL AS VARCHAR(50)) AS engineer_info, employees.employee_id AS employee_id,
-    CAST(NULL AS VARCHAR(50)) AS manager_data, employees.name AS name, employees.company_id AS company_id, 'employee' AS type
-    FROM employees UNION ALL SELECT CAST(NULL AS VARCHAR(50)) AS engineer_info, managers.employee_id AS employee_id,
-    managers.manager_data AS manager_data, managers.name AS name, managers.company_id AS company_id, 'manager' AS type
-    FROM managers UNION ALL SELECT engineers.engineer_info AS engineer_info, engineers.employee_id AS employee_id,
-    CAST(NULL AS VARCHAR(50)) AS manager_data, engineers.name AS name, engineers.company_id AS company_id, 'engineer' AS type
-    FROM engineers) AS anon_1 ON companies.id = anon_1.company_id
-    []
-
-The big limitation with concrete table inheritance is that relation()s placed on each concrete mapper do **not** propagate to child mappers.  If you want to have the same relation()s set up on all concrete mappers, they must be configured manually on each.
-
-#### Mapping a Class against Multiple Tables {@name=joins}
-
-Mappers can be constructed against arbitrary relational units (called `Selectables`) as well as plain `Tables`.  For example, The `join` keyword from the SQL package creates a neat selectable unit comprised of multiple tables, complete with its own composite primary key, which can be passed in to a mapper as the table.
-
-    {python}
-    # a class
-    class AddressUser(object):
-        pass
-
-    # define a Join
-    j = join(users_table, addresses_table)
-
-    # map to it - the identity of an AddressUser object will be
-    # based on (user_id, address_id) since those are the primary keys involved
-    mapper(AddressUser, j, properties={
-        'user_id': [users_table.c.user_id, addresses_table.c.user_id]
-    })
-
-A second example:
-
-    {python}
-    # many-to-many join on an association table
-    j = join(users_table, userkeywords,
-            users_table.c.user_id==userkeywords.c.user_id).join(keywords,
-               userkeywords.c.keyword_id==keywords.c.keyword_id)
-
-    # a class
-    class KeywordUser(object):
-        pass
-
-    # map to it - the identity of a KeywordUser object will be
-    # (user_id, keyword_id) since those are the primary keys involved
-    mapper(KeywordUser, j, properties={
-        'user_id': [users_table.c.user_id, userkeywords.c.user_id],
-        'keyword_id': [userkeywords.c.keyword_id, keywords.c.keyword_id]
-    })
-
-In both examples above, "composite" columns were added as properties to the mappers; these are aggregations of multiple columns into one mapper property, which instructs the mapper to keep both of those columns set at the same value.
-
-#### Mapping a Class against Arbitrary Selects {@name=selects}
-
-Similar to mapping against a join, a plain select() object can be used with a mapper as well.  Below, an example select which contains two aggregate functions and a group_by is mapped to a class:
-
-    {python}
-    s = select([customers,
-                func.count(orders).label('order_count'),
-                func.max(orders.price).label('highest_order')],
-                customers.c.customer_id==orders.c.customer_id,
-                group_by=[c for c in customers.c]
-                ).alias('somealias')
-    class Customer(object):
-        pass
-
-    mapper(Customer, s)
-
-Above, the "customers" table is joined against the "orders" table to produce a full row for each customer row, the total count of related rows in the "orders" table, and the highest price in the "orders" table, grouped against the full set of columns in the "customers" table.  That query is then mapped against the Customer class.  New instances of Customer will contain attributes for each column in the "customers" table as well as an "order_count" and "highest_order" attribute.  Updates to the Customer object will only be reflected in the "customers" table and not the "orders" table.  This is because the primary key columns of the "orders" table are not represented in this mapper and therefore the table is not affected by save or delete operations.
-
-#### Multiple Mappers for One Class {@name=multiple}
-
-The first mapper created for a certain class is known as that class's "primary mapper."  Other mappers can be created as well on the "load side" - these are called **secondary mappers**.   This is a mapper that must be constructed with the keyword argument `non_primary=True`, and represents a load-only mapper.  Objects that are loaded with a secondary mapper will have their save operation processed by the primary mapper.  It is also invalid to add new `relation()`s to a non-primary mapper. To use this mapper with the Session, specify it to the `query` method:
-
-example:
-
-    {python}
-    # primary mapper
-    mapper(User, users_table)
-
-    # make a secondary mapper to load User against a join
-    othermapper = mapper(User, users_table.join(someothertable), non_primary=True)
-
-    # select
-    result = session.query(othermapper).select()
-
-The "non primary mapper" is a rarely needed feature of SQLAlchemy; in most cases, the `Query` object can produce any kind of query that's desired.  It's recommended that a straight `Query` be used in place of a non-primary mapper unless the mapper approach is absolutely needed.  Current use cases for the "non primary mapper" are when you want to map the class to a particular select statement or view to which additional query criterion can be added, and for when the particular mapped select statement or view is to be placed in a `relation()` of a parent mapper.
-
-Versions of SQLAlchemy previous to 0.5 included another mapper flag called "entity_name", as of version 0.5.0 this feature has been removed (it never worked very well).
-
-#### Constructors and Object Initialization {@name=reconstructor}
-
-Mapping imposes no restrictions or requirements on the constructor
-(`__init__`) method for the class.  You are free to require any
-arguments for the function that you wish, assign attributes to the
-instance that are unknown to the ORM, and generally do anything else
-you would normally do when writing a constructor for a Python class.
-
-The SQLAlchemy ORM does not call `__init__` when recreating objects
-from database rows.  The ORM's process is somewhat akin to the Python
-standard library's `pickle` module, invoking the low level `__new__`
-method and then quietly restoring attributes directly on the instance
-rather than calling `__init__`.
-
-If you need to do some setup on database-loaded instances before
-they're ready to use, you can use the `@reconstructor` decorator to
-tag a method as the ORM counterpart to `__init__`.  SQLAlchemy will
-call this method with no arguments every time it loads or reconstructs
-one of your instances.  This is useful for recreating transient
-properties that are normally assigned in your `__init__`.
-
-    {python}
-    from sqlalchemy import orm
-
-    class MyMappedClass(object):
-        def __init__(self, data):
-            self.data = data
-            # we need stuff on all instances, but not in the database.
-            self.stuff = []
-
-        @orm.reconstructor
-        def init_on_load(self):
-            self.stuff = []
-
-When `obj = MyMappedClass()` is executed, Python calls the `__init__`
-method as normal and the `data` argument is required.  When instances
-are loaded during a `Query` operation as in
-`query(MyMappedClass).one()`, `init_on_load` is called instead.
-
-Any method may be tagged as the `reconstructor`, even the `__init__`
-method.  SQLAlchemy will call the reconstructor method with no
-arguments.  Scalar (non-collection) database-mapped attributes of the
-instance will be available for use within the function.
-Eagerly-loaded collections are generally not yet available and will
-usually only contain the first element.  ORM state changes made to
-objects at this stage will not be recorded for the next flush()
-operation, so the activity within a reconstructor should be
-conservative.
-
-While the ORM does not call your `__init__` method, it will modify the
-class's `__init__` slightly.  The method is lightly wrapped to act as
-a trigger for the ORM, allowing mappers to be compiled automatically
-and will fire a `init_instance` event that `MapperExtension`s may
-listen for.  `MapperExtension`s can also listen for a
-`reconstruct_instance` event, analogous to the `reconstructor`
-decorator above.
-
-#### Extending Mapper {@name=extending}
-
-Mappers can have functionality augmented or replaced at many points in its execution via the usage of the MapperExtension class.  This class is just a series of "hooks" where various functionality takes place.  An application can make its own MapperExtension objects, overriding only the methods it needs.  Methods that are not overridden return the special value `sqlalchemy.orm.EXT_CONTINUE` to allow processing to continue to the next MapperExtension or simply proceed normally if there are no more extensions.
-
-API documentation for MapperExtension: [docstrings_sqlalchemy.orm_MapperExtension](rel:docstrings_sqlalchemy.orm_MapperExtension)
-
-To use MapperExtension, make your own subclass of it and just send it off to a mapper:
-
-    {python}
-    m = mapper(User, users_table, extension=MyExtension())
-
-Multiple extensions will be chained together and processed in order; they are specified as a list:
-
-    {python}
-    m = mapper(User, users_table, extension=[ext1, ext2, ext3])
-
-### Relation Configuration {@name=relation}
-
-The full list of options for the `relation()` function:
-
-[docstrings_sqlalchemy.orm_modfunc_relation](rel:docstrings_sqlalchemy.orm_modfunc_relation)
-
-#### Basic Relational Patterns {@name=patterns}
-
-A quick walkthrough of the basic relational patterns.
-
-##### One To Many {@name=onetomany}
-
-A one to many relationship places a foreign key in the child table referencing the parent.   SQLAlchemy creates the relationship as a collection on the parent object containing instances of the child object.
-
-    {python}
-    parent_table = Table('parent', metadata,
-        Column('id', Integer, primary_key=True))
-
-    child_table = Table('child', metadata,
-        Column('id', Integer, primary_key=True),
-        Column('parent_id', Integer, ForeignKey('parent.id')))
-
-    class Parent(object):
-        pass
-
-    class Child(object):
-        pass
-
-    mapper(Parent, parent_table, properties={
-        'children': relation(Child)
-    })
-
-    mapper(Child, child_table)
-
-To establish a bi-directional relationship in one-to-many, where the "reverse" side is a many to one, specify the `backref` option:
-
-    {python}
-    mapper(Parent, parent_table, properties={
-        'children': relation(Child, backref='parent')
-    })
-
-    mapper(Child, child_table)
-
-`Child` will get a `parent` attribute with many-to-one semantics.
-
-##### Many To One {@name=manytoone}
-
-Many to one places a foreign key in the parent table referencing the child.  The mapping setup is identical to one-to-many, however SQLAlchemy creates the relationship as a scalar attribute on the parent object referencing a single instance of the child object.
-
-    {python}
-    parent_table = Table('parent', metadata,
-        Column('id', Integer, primary_key=True),
-        Column('child_id', Integer, ForeignKey('child.id')))
-
-    child_table = Table('child', metadata,
-        Column('id', Integer, primary_key=True),
-        )
-
-    class Parent(object):
-        pass
-
-    class Child(object):
-        pass
-
-    mapper(Parent, parent_table, properties={
-        'child': relation(Child)
-    })
-
-    mapper(Child, child_table)
-
-Backref behavior is available here as well, where `backref="parents"` will place a one-to-many collection on the `Child` class.
-
-##### One To One {@name=onetoone}
-
-One To One is essentially a bi-directional relationship with a scalar attribute on both sides.  To achieve this, the `uselist=False` flag indicates the placement of a scalar attribute instead of a collection on the "many" side of the relationship.  To convert one-to-many into one-to-one:
-
-    {python}
-    mapper(Parent, parent_table, properties={
-        'child': relation(Child, uselist=False, backref='parent')
-    })
-
-Or to turn many-to-one into one-to-one:
-
-    {python}
-    mapper(Parent, parent_table, properties={
-        'child': relation(Child, backref=backref('parent', uselist=False))
-    })
-
-##### Many To Many {@name=manytomany}
-
-Many to Many adds an association table between two classes.  The association table is indicated by the `secondary` argument to `relation()`.
-
-    {python}
-    left_table = Table('left', metadata,
-        Column('id', Integer, primary_key=True))
-
-    right_table = Table('right', metadata,
-        Column('id', Integer, primary_key=True))
-
-    association_table = Table('association', metadata,
-        Column('left_id', Integer, ForeignKey('left.id')),
-        Column('right_id', Integer, ForeignKey('right.id')),
-        )
-
-    mapper(Parent, left_table, properties={
-        'children': relation(Child, secondary=association_table)
-    })
-
-    mapper(Child, right_table)
-
-For a bi-directional relationship, both sides of the relation contain a collection by default, which can be modified on either side via the `uselist` flag to be scalar.  The `backref` keyword will automatically use the same `secondary` argument for the reverse relation:
-
-    {python}
-    mapper(Parent, left_table, properties={
-        'children': relation(Child, secondary=association_table, backref='parents')
-    })
-
-##### Association Object
-
-The association object pattern is a variant on many-to-many:  it specifically is used when your association table contains additional columns beyond those which are foreign keys to the left and right tables.  Instead of using the `secondary` argument, you map a new class directly to the association table.  The left side of the relation references the association object via one-to-many, and the association class references the right side via many-to-one.
-
-    {python}
-    left_table = Table('left', metadata,
-        Column('id', Integer, primary_key=True))
-
-    right_table = Table('right', metadata,
-        Column('id', Integer, primary_key=True))
-
-    association_table = Table('association', metadata,
-        Column('left_id', Integer, ForeignKey('left.id'), primary_key=True),
-        Column('right_id', Integer, ForeignKey('right.id'), primary_key=True),
-        Column('data', String(50))
-        )
-
-    mapper(Parent, left_table, properties={
-        'children':relation(Association)
-    })
-
-    mapper(Association, association_table, properties={
-        'child':relation(Child)
-    })
-
-    mapper(Child, right_table)
-
-The bi-directional version adds backrefs to both relations:
-
-    {python}
-    mapper(Parent, left_table, properties={
-        'children':relation(Association, backref="parent")
-    })
-
-    mapper(Association, association_table, properties={
-        'child':relation(Child, backref="parent_assocs")
-    })
-
-    mapper(Child, right_table)
-
-Working with the association pattern in its direct form requires that child objects are associated with an association instance before being appended to the parent; similarly, access from parent to child goes through the association object:
-
-    {python}
-    # create parent, append a child via association
-    p = Parent()
-    a = Association()
-    a.child = Child()
-    p.children.append(a)
-
-    # iterate through child objects via association, including association
-    # attributes
-    for assoc in p.children:
-        print assoc.data
-        print assoc.child
-
-To enhance the association object pattern such that direct access to the `Association` object is optional, SQLAlchemy provides the [plugins_associationproxy](rel:plugins_associationproxy).
-
-**Important Note**:  it is strongly advised that the `secondary` table argument not be combined with the Association Object pattern, unless the `relation()` which contains the `secondary` argument is marked `viewonly=True`.  Otherwise, SQLAlchemy may persist conflicting data to the underlying association table since it is represented by two conflicting mappings.  The Association Proxy pattern should be favored in the case where access to the underlying association data is only sometimes needed.
-
-#### Adjacency List Relationships {@name=selfreferential}
-
-The **adjacency list** pattern is a common relational pattern whereby a table contains a foreign key reference to itself.  This is the most common and simple way to represent hierarchical data in flat tables.  The other way is the "nested sets" model, sometimes called "modified preorder".  Despite what many online articles say about modified preorder, the adjacency list model is probably the most appropriate pattern for the large majority of hierarchical storage needs, for reasons of concurrency, reduced complexity, and that modified preorder has little advantage over an application which can fully load subtrees into the application space.
-
-SQLAlchemy commonly refers to an adjacency list relation as a **self-referential mapper**.  In this example, we'll work with a single table called `treenodes` to represent a tree structure:
-
-    {python}
-    nodes = Table('treenodes', metadata,
-        Column('id', Integer, primary_key=True),
-        Column('parent_id', Integer, ForeignKey('treenodes.id')),
-        Column('data', String(50)),
-        )
-
-A graph such as the following:
-
-    {diagram}
-    root --+---> child1
-           +---> child2 --+--> subchild1
-           |              +--> subchild2
-           +---> child3
-
-Would be represented with data such as:
-
-    {diagram}
-    id       parent_id     data
-    ---      -------       ----
-    1        NULL          root
-    2        1             child1
-    3        1             child2
-    4        3             subchild1
-    5        3             subchild2
-    6        1             child3
-
-SQLAlchemy's `mapper()` configuration for a self-referential one-to-many relationship is exactly like a "normal" one-to-many relationship.  When SQLAlchemy encounters the foreign key relation from `treenodes` to `treenodes`, it assumes one-to-many unless told otherwise:
-
-    {python}
-    # entity class
-    class Node(object):
-        pass
-
-    mapper(Node, nodes, properties={
-        'children': relation(Node)
-    })
-
-To create a many-to-one relationship from child to parent, an extra indicator of the "remote side" is added, which contains the `Column` object or objects indicating the remote side of the relation:
-
-    {python}
-    mapper(Node, nodes, properties={
-        'parent': relation(Node, remote_side=[nodes.c.id])
-    })
-
-And the bi-directional version combines both:
-
-    {python}
-    mapper(Node, nodes, properties={
-        'children': relation(Node, backref=backref('parent', remote_side=[nodes.c.id]))
-    })
-
-There are several examples included with SQLAlchemy illustrating self-referential strategies; these include [basic_tree.py](http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/examples/adjacencytree/basic_tree.py) and [optimized_al.py](http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/examples/elementtree/optimized_al.py), the latter of which illustrates how to persist and search XML documents in conjunction with [ElementTree](http://effbot.org/zone/element-index.htm).
-
-##### Self-Referential Query Strategies {@name=query}
-
-Querying self-referential structures is done in the same way as any other query in SQLAlchemy, such as below, we query for any node whose `data` attribute stores the value `child2`:
-
-    {python}
-    # get all nodes named 'child2'
-    session.query(Node).filter(Node.data=='child2')
-
-On the subject of joins, i.e. those described in [datamapping_joins](rel:datamapping_joins), self-referential structures require the usage of aliases so that the same table can be referenced multiple times within the FROM clause of the query.   Aliasing can be done either manually using the `nodes` `Table` object as a source of aliases:
-
-    {python}
-    # get all nodes named 'subchild1' with a parent named 'child2'
-    nodealias = nodes.alias()
-    {sql}session.query(Node).filter(Node.data=='subchild1').\
-        filter(and_(Node.parent_id==nodealias.c.id, nodealias.c.data=='child2')).all()
-    SELECT treenodes.id AS treenodes_id, treenodes.parent_id AS treenodes_parent_id, treenodes.data AS treenodes_data
-    FROM treenodes, treenodes AS treenodes_1
-    WHERE treenodes.data = ? AND treenodes.parent_id = treenodes_1.id AND treenodes_1.data = ?
-    ['subchild1', 'child2']
-
-or automatically, using `join()` with `aliased=True`:
-
-    {python}
-    # get all nodes named 'subchild1' with a parent named 'child2'
-    {sql}session.query(Node).filter(Node.data=='subchild1').\
-        join('parent', aliased=True).filter(Node.data=='child2').all()
-    SELECT treenodes.id AS treenodes_id, treenodes.parent_id AS treenodes_parent_id, treenodes.data AS treenodes_data
-    FROM treenodes JOIN treenodes AS treenodes_1 ON treenodes_1.id = treenodes.parent_id
-    WHERE treenodes.data = ? AND treenodes_1.data = ?
-    ['subchild1', 'child2']
-
-To add criterion to multiple points along a longer join, use `from_joinpoint=True`:
-
-    {python}
-    # get all nodes named 'subchild1' with a parent named 'child2' and a grandparent 'root'
-    {sql}session.query(Node).filter(Node.data=='subchild1').\
-        join('parent', aliased=True).filter(Node.data=='child2').\
-        join('parent', aliased=True, from_joinpoint=True).filter(Node.data=='root').all()
-    SELECT treenodes.id AS treenodes_id, treenodes.parent_id AS treenodes_parent_id, treenodes.data AS treenodes_data
-    FROM treenodes JOIN treenodes AS treenodes_1 ON treenodes_1.id = treenodes.parent_id JOIN treenodes AS treenodes_2 ON treenodes_2.id = treenodes_1.parent_id
-    WHERE treenodes.data = ? AND treenodes_1.data = ? AND treenodes_2.data = ?
-    ['subchild1', 'child2', 'root']
-
-##### Configuring Eager Loading {@name=eagerloading}
-
-Eager loading of relations occurs using joins or outerjoins from parent to child table during a normal query operation, such that the parent and its child collection can be populated from a single SQL statement.  SQLAlchemy's eager loading uses aliased tables in all cases when joining to related items, so it is compatible with self-referential joining.  However, to use eager loading with a self-referential relation, SQLAlchemy needs to be told how many levels deep it should join; otherwise the eager load will not take place.  This depth setting is configured via `join_depth`:
-
-    {python}
-    mapper(Node, nodes, properties={
-        'children': relation(Node, lazy=False, join_depth=2)
-    })
-
-    {sql}session.query(Node).all()
-    SELECT treenodes_1.id AS treenodes_1_id, treenodes_1.parent_id AS treenodes_1_parent_id, treenodes_1.data AS treenodes_1_data, treenodes_2.id AS treenodes_2_id, treenodes_2.parent_id AS treenodes_2_parent_id, treenodes_2.data AS treenodes_2_data, treenodes.id AS treenodes_id, treenodes.parent_id AS treenodes_parent_id, treenodes.data AS treenodes_data
-    FROM treenodes LEFT OUTER JOIN treenodes AS treenodes_2 ON treenodes.id = treenodes_2.parent_id LEFT OUTER JOIN treenodes AS treenodes_1 ON treenodes_2.id = treenodes_1.parent_id
-    []
-
-#### Specifying Alternate Join Conditions to relation() {@name=customjoin}
-
-The `relation()` function uses the foreign key relationship between the parent and child tables to formulate the **primary join condition** between parent and child; in the case of a many-to-many relationship it also formulates the **secondary join condition**.  If you are working with a `Table` which has no `ForeignKey` objects on it (which can be the case when using reflected tables with MySQL), or if the join condition cannot be expressed by a simple foreign key relationship, use the `primaryjoin` and possibly `secondaryjoin` conditions to create the appropriate relationship.
-
-In this example we create a relation `boston_addresses` which will only load the user addresses with a city of "Boston":
-
-    {python}
-    class User(object):
-        pass
-    class Address(object):
-        pass
-
-    mapper(Address, addresses_table)
-    mapper(User, users_table, properties={
-        'boston_addresses': relation(Address, primaryjoin=
-                    and_(users_table.c.user_id==addresses_table.c.user_id,
-                    addresses_table.c.city=='Boston'))
-    })
-
-Many to many relationships can be customized by one or both of `primaryjoin` and `secondaryjoin`, shown below with just the default many-to-many relationship explicitly set:
-
-    {python}
-    class User(object):
-        pass
-    class Keyword(object):
-        pass
-    mapper(Keyword, keywords_table)
-    mapper(User, users_table, properties={
-        'keywords': relation(Keyword, secondary=userkeywords_table,
-            primaryjoin=users_table.c.user_id==userkeywords_table.c.user_id,
-            secondaryjoin=userkeywords_table.c.keyword_id==keywords_table.c.keyword_id
-            )
-    })
-
-##### Specifying Foreign Keys {@name=fks}
-
-When using `primaryjoin` and `secondaryjoin`, SQLAlchemy also needs to be aware of which columns in the relation reference the other.  In most cases, a `Table` construct will have `ForeignKey` constructs which take care of this; however, in the case of reflected tables on a database that does not report FKs (like MySQL ISAM) or when using join conditions on columns that don't have foreign keys, the `relation()` needs to be told specifically which columns are "foreign" using the `foreign_keys` collection:
-
-    {python}
-    mapper(Address, addresses_table)
-    mapper(User, users_table, properties={
-        'addresses': relation(Address, primaryjoin=
-                    users_table.c.user_id==addresses_table.c.user_id,
-                    foreign_keys=[addresses_table.c.user_id])
-    })
-
-##### Building Query-Enabled Properties {@name=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 the equation, use the flag `viewonly=True` on the `relation()`, which establishes it as a read-only attribute (data written to the collection will be ignored on flush()).  However, in extreme cases, consider using a regular Python property in conjunction with `Query` as follows:
-
-    {python}
-    class User(object):
-        def _get_addresses(self):
-            return object_session(self).query(Address).with_parent(self).filter(...).all()
-        addresses = property(_get_addresses)
-
-##### Multiple Relations against the Same Parent/Child {@name=multiplejoin}
-
-Theres no restriction on how many times you can relate from parent to child.  SQLAlchemy can usually figure out what you want, particularly if the join conditions are straightforward.  Below we add a `newyork_addresses` attribute to complement the `boston_addresses` attribute:
-
-    {python}
-    mapper(User, users_table, properties={
-        'boston_addresses': relation(Address, primaryjoin=
-                    and_(users_table.c.user_id==addresses_table.c.user_id,
-                    addresses_table.c.city=='Boston')),
-        'newyork_addresses': relation(Address, primaryjoin=
-                    and_(users_table.c.user_id==addresses_table.c.user_id,
-                    addresses_table.c.city=='New York')),
-    })
-
-#### Alternate Collection Implementations {@name=collections}
-
-Mapping a one-to-many or many-to-many relationship results in a collection of values accessible through an attribute on the parent instance.  By default, this collection is a `list`:
-
-    {python}
-    mapper(Parent, properties={
-        children = relation(Child)
-    })
-
-    parent = Parent()
-    parent.children.append(Child())
-    print parent.children[0]
-
-Collections are not limited to lists.  Sets, mutable sequences and almost any other Python object that can act as a container can be used in place of the default list.
-
-    {python}
-    # use a set
-    mapper(Parent, properties={
-        children = relation(Child, collection_class=set)
-    })
-
-    parent = Parent()
-    child = Child()
-    parent.children.add(child)
-    assert child in parent.children
-
-##### Custom Collection Implementations {@name=custom}
-
-You can use your own types for collections as well.  For most cases, simply inherit from `list` or `set` and add the custom behavior.
-
-Collections in SQLAlchemy are transparently *instrumented*.  Instrumentation means that normal operations on the collection are tracked and result in changes being written to the database at flush time.  Additionally, collection operations can fire *events* which indicate some secondary operation must take place.  Examples of a secondary operation include saving the child item in the parent's `Session` (i.e. the `save-update` cascade), as well as synchronizing the state of a bi-directional relationship (i.e. a `backref`).
-
-The collections package understands the basic interface of lists, sets and dicts and will automatically apply instrumentation to those built-in types and their subclasses.  Object-derived types that implement a basic collection interface are detected and instrumented via duck-typing:
-
-    {python}
-    class ListLike(object):
-        def __init__(self):
-            self.data = []
-        def append(self, item):
-            self.data.append(item)
-        def remove(self, item):
-            self.data.remove(item)
-        def extend(self, items):
-            self.data.extend(items)
-        def __iter__(self):
-            return iter(self.data)
-        def foo(self):
-            return 'foo'
-
-`append`, `remove`, and `extend` are known list-like methods, and will be instrumented automatically.  `__iter__` is not a mutator method and won't be instrumented, and `foo` won't be either.
-
-Duck-typing (i.e. guesswork) isn't rock-solid, of course, so you can be explicit about the interface you are implementing by providing an `__emulates__` class attribute:
-
-    {python}
-    class SetLike(object):
-        __emulates__ = set
-
-        def __init__(self):
-            self.data = set()
-        def append(self, item):
-            self.data.add(item)
-        def remove(self, item):
-            self.data.remove(item)
-        def __iter__(self):
-            return iter(self.data)
-
-This class looks list-like because of `append`, but `__emulates__` forces it to set-like.  `remove` is known to be part of the set interface and will be instrumented.
-
-But this class won't work quite yet: a little glue is needed to adapt it for use by SQLAlchemy.  The ORM needs to know which methods to use to append, remove and iterate over members of the collection.  When using a type like `list` or `set`, the appropriate methods are well-known and used automatically when present. This set-like class does not provide the expected `add` method, so we must supply an explicit mapping for the ORM via a decorator.
-
-##### Annotating Custom Collections via Decorators {@name=decorators}
-
-Decorators can be used to tag the individual methods the ORM needs to manage collections.  Use them when your class doesn't quite meet the regular interface for its container type, or you simply would like to use a different method to get the job done.
-
-    {python}
-    from sqlalchemy.orm.collections import collection
-
-    class SetLike(object):
-        __emulates__ = set
-
-        def __init__(self):
-            self.data = set()
-
-        @collection.appender
-        def append(self, item):
-            self.data.add(item)
-
-        def remove(self, item):
-            self.data.remove(item)
-
-        def __iter__(self):
-            return iter(self.data)
-
-And that's all that's needed to complete the example.  SQLAlchemy will add instances via the `append` method.  `remove` and `__iter__` are the default methods for sets and will be used for removing and iteration.  Default methods can be changed as well:
-
-    {python}
-    from sqlalchemy.orm.collections import collection
-
-    class MyList(list):
-        @collection.remover
-        def zark(self, item):
-            # do something special...
-
-        @collection.iterator
-        def hey_use_this_instead_for_iteration(self):
-            # ...
-
-There is no requirement to be list-, or set-like at all.  Collection classes can be any shape, so long as they have the append, remove and iterate interface marked for SQLAlchemy's use.  Append and remove methods will be called with a mapped entity as the single argument, and iterator methods are called with no arguments and must return an iterator.
-
-##### Dictionary-Based Collections {@name=dictcollections}
-
-A `dict` can be used as a collection, but a keying strategy is needed to map entities loaded by the ORM to key, value pairs.  The [collections](rel:docstrings_sqlalchemy.orm.collections) package provides several built-in types for dictionary-based collections:
-
-    {python}
-    from sqlalchemy.orm.collections import column_mapped_collection, attribute_mapped_collection, mapped_collection
-
-    mapper(Item, items_table, properties={
-        # key by column
-        'notes': relation(Note, collection_class=column_mapped_collection(notes_table.c.keyword)),
-        # or named attribute
-        'notes2': relation(Note, collection_class=attribute_mapped_collection('keyword')),
-        # or any callable
-        'notes3': relation(Note, collection_class=mapped_collection(lambda entity: entity.a + entity.b))
-    })
-
-    # ...
-    item = Item()
-    item.notes['color'] = Note('color', 'blue')
-    print item.notes['color']
-
-These functions each provide a `dict` subclass with decorated `set` and `remove` methods and the keying strategy of your choice.
-
-The [collections.MappedCollection](rel:docstrings_sqlalchemy.orm.collections.MappedCollection) class can be used as a base class for your custom types or as a mix-in to quickly add `dict` collection support to other classes.  It uses a keying function to delegate to `__setitem__` and `__delitem__`:
-
-    {python}
-    from sqlalchemy.util import OrderedDict
-    from sqlalchemy.orm.collections import MappedCollection
-
-    class NodeMap(OrderedDict, MappedCollection):
-        """Holds 'Node' objects, keyed by the 'name' attribute with insert order maintained."""
-
-        def __init__(self, *args, **kw):
-            MappedCollection.__init__(self, keyfunc=lambda node: node.name)
-            OrderedDict.__init__(self, *args, **kw)
-
-The ORM understands the `dict` interface just like lists and sets, and will automatically instrument all dict-like methods if you choose to subclass `dict` or provide dict-like collection behavior in a duck-typed class.  You must decorate appender and remover methods, however- there are no compatible methods in the basic dictionary interface for SQLAlchemy to use by default.  Iteration will go through `itervalues()` unless otherwise decorated.
-
-##### Instrumentation and Custom Types {@name=adv_collections}
-
-Many custom types and existing library classes can be used as a entity collection type as-is without further ado.  However, it is important to note that the instrumentation process _will_ modify the type, adding decorators around methods automatically.
-
-The decorations are lightweight and no-op outside of relations, but they do add unneeded overhead when triggered elsewhere.  When using a library class as a collection, it can be good practice to use the "trivial subclass" trick to restrict the decorations to just your usage in relations.  For example:
-
-    {python}
-    class MyAwesomeList(some.great.library.AwesomeList):
-        pass
-
-    # ... relation(..., collection_class=MyAwesomeList)
-
-The ORM uses this approach for built-ins, quietly substituting a trivial subclass when a `list`, `set` or `dict` is used directly.
-
-The collections package provides additional decorators and support for authoring custom types.  See the [package documentation](rel:docstrings_sqlalchemy.orm.collections) for more information and discussion of advanced usage and Python 2.3-compatible decoration options.
-
-#### Configuring Loader Strategies: Lazy Loading, Eager Loading {@name=strategies}
-
-In the [datamapping](rel:datamapping), we introduced the concept of **Eager Loading**.  We used an `option` in conjunction with the `Query` object in order to indicate that a relation should be loaded at the same time as the parent, within a single SQL query:
-
-    {python}
-    {sql}>>> jack = session.query(User).options(eagerload('addresses')).filter_by(name='jack').all() #doctest: +NORMALIZE_WHITESPACE
-    SELECT addresses_1.id AS addresses_1_id, addresses_1.email_address AS addresses_1_email_address,
-    addresses_1.user_id AS addresses_1_user_id, users.id AS users_id, users.name AS users_name,
-    users.fullname AS users_fullname, users.password AS users_password
-    FROM users LEFT OUTER JOIN addresses AS addresses_1 ON users.id = addresses_1.user_id
-    WHERE users.name = ?
-    ['jack']
-
-By default, all relations are **lazy loading**.  The scalar or collection attribute associated with a `relation()` contains a trigger which fires the first time the attribute is accessed, which issues a SQL call at that point:
-
-    {python}
-    {sql}>>> jack.addresses
-    SELECT addresses.id AS addresses_id, addresses.email_address AS addresses_email_address, addresses.user_id AS addresses_user_id
-    FROM addresses
-    WHERE ? = addresses.user_id
-    [5]
-    {stop}[<Address(u'jack@google.com')>, <Address(u'j25@yahoo.com')>]
-
-The default **loader strategy** for any `relation()` is configured by the `lazy` keyword argument, which defaults to `True`.  Below we set it as `False` so that the `children` relation is eager loading:
-
-    {python}
-    # eager load 'children' attribute
-    mapper(Parent, parent_table, properties={
-        'children': relation(Child, lazy=False)
-    })
-
-The loader strategy can be changed from lazy to eager as well as eager to lazy using the `eagerload()` and `lazyload()` query options:
-
-    {python}
-    # set children to load lazily
-    session.query(Parent).options(lazyload('children')).all()
-
-    # set children to load eagerly
-    session.query(Parent).options(eagerload('children')).all()
-
-To reference a relation that is deeper than one level, separate the names by periods:
-
-    {python}
-    session.query(Parent).options(eagerload('foo.bar.bat')).all()
-
-When using dot-separated names with `eagerload()`, option applies **only** to the actual attribute named, and **not** its ancestors.  For example, suppose a mapping from `A` to `B` to `C`, where the relations, named `atob` and `btoc`, are both lazy-loading.  A statement like the following:
-
-    {python}
-    session.query(A).options(eagerload('atob.btoc')).all()
-
-will load only `A` objects to start.  When the `atob` attribute on each `A` is accessed, the returned `B` objects will *eagerly* load their `C` objects.
-
-Therefore, to modify the eager load to load both `atob` as well as `btoc`, place eagerloads for both:
-
-    {python}
-    session.query(A).options(eagerload('atob'), eagerload('atob.btoc')).all()
-
-or more simply just use `eagerload_all()`:
-
-    {python}
-    session.query(A).options(eagerload_all('atob.btoc')).all()
-
-There are two other loader strategies available, **dynamic loading** and **no loading**; these are described in [advdatamapping_relation_largecollections](rel:advdatamapping_relation_largecollections).
-
-##### Routing Explicit Joins/Statements into Eagerly Loaded Collections {@name=containseager}
-
-When full statement loads are used with `Query`, the user defined SQL is used verbatim and the `Query` does not play any role in generating it.  In this scenario, if eager loading is desired, the `Query` should be informed as to what collections should also be loaded from the result set.  Similarly, Queries which compile their statement in the usual way may also have user-defined joins built in which are synonymous with what eager loading would normally produce, and it improves performance to utilize those same JOINs for both purposes, instead of allowing the eager load mechanism to generate essentially the same JOIN redundantly.   Yet another use case for such a feature is a Query which returns instances with a filtered view of their collections loaded, in which case the default eager load mechanisms need to be bypassed.
-
-The single option `Query` provides to control this is the `contains_eager()` option, which specifies the path of a single relationship to be eagerly loaded.  Like all relation-oriented options, it takes a string or Python descriptor as an argument.  Below it's used with a `from_statement` load:
-
-    {python}
-    # mapping is the users->addresses mapping
-    mapper(User, users_table, properties={
-        'addresses': relation(Address, addresses_table)
-    })
-
-    # define a query on USERS with an outer join to ADDRESSES
-    statement = users_table.outerjoin(addresses_table).select().apply_labels()
-
-    # construct a Query object which expects the "addresses" results
-    query = session.query(User).options(contains_eager('addresses'))
-
-    # get results normally
-    r = query.from_statement(statement)
-
-It works just as well with an inline `Query.join()` or `Query.outerjoin()`:
-
-    {python}
-    session.query(User).outerjoin(User.addresses).options(contains_eager(User.addresses)).all()
-
-If the "eager" portion of the statement is "aliased", the `alias` keyword argument to `contains_eager()` may be used to indicate it.  This is a string alias name or reference to an actual `Alias` object:
-
-    {python}
-    # use an alias of the Address entity
-    adalias = aliased(Address)
-
-    # construct a Query object which expects the "addresses" results
-    query = session.query(User).outerjoin((adalias, User.addresses)).options(contains_eager(User.addresses, alias=adalias))
-
-    # get results normally
-    {sql}r = query.all()
-    SELECT users.user_id AS users_user_id, users.user_name AS users_user_name, adalias.address_id AS adalias_address_id,
-    adalias.user_id AS adalias_user_id, adalias.email_address AS adalias_email_address, (...other columns...)
-    FROM users LEFT OUTER JOIN email_addresses AS email_addresses_1 ON users.user_id = email_addresses_1.user_id
-
-The path given as the argument to `contains_eager()` needs to be a full path from the starting entity.  For example if we were loading `Users->orders->Order->items->Item`, the string version would look like:
-
-    {python}
-    query(User).options(contains_eager('orders', 'items'))
-
-The descriptor version like:
-
-    {python}
-    query(User).options(contains_eager(User.orders, Order.items))
-
-A variant on `contains_eager()` is the `contains_alias()` option, which is used in the rare case that the parent object is loaded from an alias within a user-defined SELECT statement:
-
-    {python}
-    # define an aliased UNION called 'ulist'
-    statement = users.select(users.c.user_id==7).union(users.select(users.c.user_id>7)).alias('ulist')
-
-    # add on an eager load of "addresses"
-    statement = statement.outerjoin(addresses).select().apply_labels()
-
-    # create query, indicating "ulist" is an alias for the main table, "addresses" property should
-    # be eager loaded
-    query = session.query(User).options(contains_alias('ulist'), contains_eager('addresses'))
-
-    # results
-    r = query.from_statement(statement)
-
-#### Working with Large Collections {@name=largecollections}
-
-The default behavior of `relation()` is to fully load the collection of items in, as according to the loading strategy of the relation.  Additionally, the Session by default only knows how to delete objects which are actually present within the session.  When a parent instance is marked for deletion and flushed, the Session loads its full list of child items in so that they may either be deleted as well, or have their foreign key value set to null; this is to avoid constraint violations.  For large collections of child items, there are several strategies to bypass full loading of child items both at load time as well as deletion time.
-
-##### Dynamic Relation Loaders {@name=dynamic}
-
-The most useful by far is the `dynamic_loader()` relation.  This is a variant of `relation()` which returns a `Query` object in place of a collection when accessed.  `filter()` criterion may be applied as well as limits and offsets, either explicitly or via array slices:
-
-    {python}
-    mapper(User, users_table, properties={
-        'posts': dynamic_loader(Post)
-    })
-
-    jack = session.query(User).get(id)
-
-    # filter Jack's blog posts
-    posts = jack.posts.filter(Post.headline=='this is a post')
-
-    # apply array slices
-    posts = jack.posts[5:20]
-
-The dynamic relation supports limited write operations, via the `append()` and `remove()` methods.  Since the read side of the dynamic relation always queries the database, changes to the underlying collection will not be visible until the data has been flushed:
-
-    {python}
-    oldpost = jack.posts.filter(Post.headline=='old post').one()
-    jack.posts.remove(oldpost)
-
-    jack.posts.append(Post('new post'))
-
-To place a dynamic relation on a backref, use `lazy='dynamic'`:
-
-    {python}
-    mapper(Post, posts_table, properties={
-        'user': relation(User, backref=backref('posts', lazy='dynamic'))
-    })
-
-Note that eager/lazy loading options cannot be used in conjunction dynamic relations at this time.
-
-##### Setting Noload {@name=noload}
-
-The opposite of the dynamic relation is simply "noload", specified using `lazy=None`:
-
-    {python}
-    mapper(MyClass, table, properties={
-        'children': relation(MyOtherClass, lazy=None)
-    })
-
-Above, the `children` collection is fully writeable, and changes to it will be persisted to the database as well as locally available for reading at the time they are added.  However when instances of  `MyClass` are freshly loaded from the database, the `children` collection stays empty.
-
-##### Using Passive Deletes {@name=passivedelete}
-
-Use `passive_deletes=True` to disable child object loading on a DELETE operation, in conjunction with "ON DELETE (CASCADE|SET NULL)" on your database to automatically cascade deletes to child objects.   Note that "ON DELETE" is not supported on SQLite, and requires `InnoDB` tables when using MySQL:
-
-        {python}
-        mytable = Table('mytable', meta,
-            Column('id', Integer, primary_key=True),
-            )
-
-        myothertable = Table('myothertable', meta,
-            Column('id', Integer, primary_key=True),
-            Column('parent_id', Integer),
-            ForeignKeyConstraint(['parent_id'], ['mytable.id'], ondelete="CASCADE"),
-            )
-
-        mapper(MyOtherClass, myothertable)
-
-        mapper(MyClass, mytable, properties={
-            'children': relation(MyOtherClass, cascade="all, delete-orphan", passive_deletes=True)
-        })
-
-When `passive_deletes` is applied, the `children` relation will not be loaded into memory when an instance of `MyClass` is marked for deletion.  The `cascade="all, delete-orphan"` *will* take effect for instances of `MyOtherClass` which are currently present in the session; however for instances of `MyOtherClass` which are not loaded, SQLAlchemy assumes that "ON DELETE CASCADE" rules will ensure that those rows are deleted by the database and that no foreign key violation will occur.
-
-#### Mutable Primary Keys / Update Cascades {@name=mutablepks}
-
-As of SQLAlchemy 0.4.2, the primary key attributes of an instance can be changed freely, and will be persisted upon flush.  When the primary key of an entity changes, related items which reference the primary key must also be updated as well.  For databases which enforce referential integrity, it's required to use the database's ON UPDATE CASCADE functionality in order to propagate primary key changes.  For those which don't, the `passive_cascades` flag can be set to `False` which instructs SQLAlchemy to issue UPDATE statements individually.  The `passive_cascades` flag can also be `False` in conjunction with ON UPDATE CASCADE functionality, although in that case it issues UPDATE statements unnecessarily.
-
-A typical mutable primary key setup might look like:
-
-    {python}
-    users = Table('users', metadata,
-        Column('username', String(50), primary_key=True),
-        Column('fullname', String(100)))
-
-    addresses = Table('addresses', metadata,
-        Column('email', String(50), primary_key=True),
-        Column('username', String(50), ForeignKey('users.username', onupdate="cascade")))
-
-    class User(object):
-        pass
-    class Address(object):
-        pass
-
-    mapper(User, users, properties={
-        'addresses': relation(Address, passive_updates=False)
-    })
-    mapper(Address, addresses)
-
-passive_updates is set to `True` by default.  Foreign key references to non-primary key columns are supported as well.
-
diff --git a/doc/build/oldcontent/metadata.txt b/doc/build/oldcontent/metadata.txt
deleted file mode 100644 (file)
index bc92baf..0000000
+++ /dev/null
@@ -1,532 +0,0 @@
-[alpha_api]: javascript:alphaApi()
-[alpha_implementation]: javascript:alphaImplementation()
-
-Database Meta Data {@name=metadata}
-==================
-
-### Describing Databases with MetaData {@name=tables}    
-
-The core of SQLAlchemy's query and object mapping operations are supported by **database metadata**, which is comprised of Python objects that describe tables and other schema-level objects.  These objects can be created by explicitly naming the various components and their properties, using the Table, Column, ForeignKey, Index, and Sequence objects imported from `sqlalchemy.schema`.  There is also support for **reflection** of some entities, which means you only specify the *name* of the entities and they are recreated from the database automatically.
-
-A collection of metadata entities is stored in an object aptly named `MetaData`:
-
-    {python}
-    from sqlalchemy import *
-    
-    metadata = MetaData()
-
-To represent a Table, use the `Table` class:
-
-    {python}
-    users = Table('users', metadata, 
-        Column('user_id', Integer, primary_key = True),
-        Column('user_name', String(16), nullable = False),
-        Column('email_address', String(60), key='email'),
-        Column('password', String(20), nullable = False)
-    )
-    
-    user_prefs = Table('user_prefs', metadata, 
-        Column('pref_id', Integer, primary_key=True),
-        Column('user_id', Integer, ForeignKey("users.user_id"), nullable=False),
-        Column('pref_name', String(40), nullable=False),
-        Column('pref_value', String(100))
-    )
-
-The specific datatypes for each Column, such as Integer, String, etc. are described in [types](rel:types), and exist within the module `sqlalchemy.types` as well as the global `sqlalchemy` namespace.
-
-Foreign keys are most easily specified by the `ForeignKey` object within a `Column` object.  For a composite foreign key, i.e. a foreign key that contains multiple columns referencing multiple columns to a composite primary key, an explicit syntax is provided which allows the correct table CREATE statements to be generated:
-
-    {python}
-    # a table with a composite primary key
-    invoices = Table('invoices', metadata, 
-        Column('invoice_id', Integer, primary_key=True),
-        Column('ref_num', Integer, primary_key=True),
-        Column('description', String(60), nullable=False)
-    )
-    
-    # a table with a composite foreign key referencing the parent table
-    invoice_items = Table('invoice_items', metadata, 
-        Column('item_id', Integer, primary_key=True),
-        Column('item_name', String(60), nullable=False),
-        Column('invoice_id', Integer, nullable=False),
-        Column('ref_num', Integer, nullable=False),
-        ForeignKeyConstraint(['invoice_id', 'ref_num'], ['invoices.invoice_id', 'invoices.ref_num'])
-    )
-    
-Above, the `invoice_items` table will have `ForeignKey` objects automatically added to the `invoice_id` and `ref_num` `Column` objects as a result of the additional `ForeignKeyConstraint` object.
-
-The `MetaData` object supports some handy methods, such as getting a list of Tables in the order (or reverse) of their dependency:
-
-    {python}
-    >>> for t in metadata.table_iterator(reverse=False):
-    ...    print t.name
-    users
-    user_prefs
-        
-And `Table` provides an interface to the table's properties as well as that of its columns:
-        
-    {python}
-    employees = Table('employees', metadata, 
-        Column('employee_id', Integer, primary_key=True),
-        Column('employee_name', String(60), nullable=False, key='name'),
-        Column('employee_dept', Integer, ForeignKey("departments.department_id"))
-    )
-    
-    # access the column "EMPLOYEE_ID":
-    employees.columns.employee_id
-    
-    # or just
-    employees.c.employee_id
-    
-    # via string
-    employees.c['employee_id']
-    
-    # iterate through all columns
-    for c in employees.c:
-        # ...
-        
-    # get the table's primary key columns
-    for primary_key in employees.primary_key:
-        # ...
-    
-    # get the table's foreign key objects:
-    for fkey in employees.foreign_keys:
-        # ...
-        
-    # access the table's MetaData:
-    employees.metadata
-    
-    # access the table's bound Engine or Connection, if its MetaData is bound:
-    employees.bind
-    
-    # access a column's name, type, nullable, primary key, foreign key
-    employees.c.employee_id.name
-    employees.c.employee_id.type
-    employees.c.employee_id.nullable
-    employees.c.employee_id.primary_key
-    employees.c.employee_dept.foreign_key
-    
-    # get the "key" of a column, which defaults to its name, but can 
-    # be any user-defined string:
-    employees.c.name.key
-    
-    # access a column's table:
-    employees.c.employee_id.table is employees
-    >>> True
-    
-    # get the table related by a foreign key
-    fcolumn = employees.c.employee_dept.foreign_key.column.table
-
-#### Binding MetaData to an Engine or Connection {@name=binding}
-
-A `MetaData` object can be associated with an `Engine` or an individual `Connection`; this process is called **binding**.  The term used to describe "an engine or a connection" is often referred to as a **connectable**.  Binding allows the `MetaData` and the elements which it contains to perform operations against the database directly, using the connection resources to which it's bound.   Common operations which are made more convenient through binding include being able to generate SQL constructs which know how to execute themselves, creating `Table` objects which query the database for their column and constraint information, and issuing CREATE or DROP statements.
-
-To bind `MetaData` to an `Engine`, use the `bind` attribute:
-
-    {python}
-    engine = create_engine('sqlite://', **kwargs)
-    
-    # create MetaData 
-    meta = MetaData()
-
-    # bind to an engine
-    meta.bind = engine
-
-Once this is done, the `MetaData` and its contained `Table` objects can access the database directly:
-
-    {python}
-    meta.create_all()  # issue CREATE statements for all tables
-    
-    # describe a table called 'users', query the database for its columns
-    users_table = Table('users', meta, autoload=True)
-    
-    # generate a SELECT statement and execute
-    result = users_table.select().execute()
-
-Note that the feature of binding engines is **completely optional**.  All of the operations which take advantage of "bound" `MetaData` also can be given an `Engine` or `Connection` explicitly with which to perform the operation.   The equivalent "non-bound" of the above would be:
-
-    {python}
-    meta.create_all(engine)  # issue CREATE statements for all tables
-    
-    # describe a table called 'users',  query the database for its columns
-    users_table = Table('users', meta, autoload=True, autoload_with=engine)
-    
-    # generate a SELECT statement and execute
-    result = engine.execute(users_table.select())
-
-#### Reflecting Tables
-
-A `Table` object can be created without specifying any of its contained attributes, using the argument `autoload=True` in conjunction with the table's name and possibly its schema (if not the databases "default" schema).  (You can also specify a list or set of column names to autoload as the kwarg include_columns, if you only want to load a subset of the columns in the actual database.)  This will issue the appropriate queries to the database in order to locate all properties of the table required for SQLAlchemy to use it effectively, including its column names and datatypes, foreign and primary key constraints, and in some cases its default-value generating attributes.   To use `autoload=True`, the table's `MetaData` object need be bound to an `Engine` or `Connection`, or alternatively the `autoload_with=<some connectable>` argument can be passed.  Below we illustrate autoloading a table and then iterating through the names of its columns:
-
-    {python}
-    >>> messages = Table('messages', meta, autoload=True)
-    >>> [c.name for c in messages.columns]
-    ['message_id', 'message_name', 'date']
-
-Note that if a reflected table has a foreign key referencing another table, the related `Table` object  will be automatically created within the `MetaData` object if it does not exist already.  Below, suppose table `shopping_cart_items` references a table `shopping_carts`.  After reflecting, the `shopping carts` table is present:
-        
-    {python}
-    >>> shopping_cart_items = Table('shopping_cart_items', meta, autoload=True)
-    >>> 'shopping_carts' in meta.tables:
-    True
-        
-To get direct access to 'shopping_carts', simply instantiate it via the `Table` constructor.  `Table` uses a special constructor that will return the already created `Table` instance if it's already present:
-
-    {python}
-    shopping_carts = Table('shopping_carts', meta)
-
-Of course, it's a good idea to use `autoload=True` with the above table regardless.  This is so that if it hadn't been loaded already, the operation will load the table.  The autoload operation only occurs for the table if it hasn't already been loaded; once loaded, new calls to `Table` will not re-issue any reflection queries.
-
-##### Overriding Reflected Columns {@name=overriding}
-
-Individual columns can be overridden with explicit values when reflecting tables; this is handy for specifying custom datatypes, constraints such as primary keys that may not be configured within the database, etc.
-
-    {python}
-    >>> mytable = Table('mytable', meta,
-    ... Column('id', Integer, primary_key=True),   # override reflected 'id' to have primary key
-    ... Column('mydata', Unicode(50)),    # override reflected 'mydata' to be Unicode
-    ... autoload=True)
-
-##### Reflecting All Tables at Once {@name=reflectall}
-
-The `MetaData` object can also get a listing of tables and reflect the full set.  This is achieved by using the `reflect()` method.  After calling it, all located tables are present within the `MetaData`s dictionary of tables:
-
-    {python}
-    meta = MetaData()
-    meta.reflect(bind=someengine)
-    users_table = meta.tables['users']
-    addresses_table = meta.tables['addresses']
-    
-`metadata.reflect()` is also a handy way to clear or drop all tables in a database:
-
-    {python}
-    meta = MetaData()
-    meta.reflect(bind=someengine)
-    for table in reversed(meta.sorted_tables):
-        someengine.execute(table.delete())
-
-#### Specifying the Schema Name {@name=schema}
-
-Some databases support the concept of multiple schemas.  A `Table` can reference this by specifying the `schema` keyword argument:
-
-    {python}
-    financial_info = Table('financial_info', meta,
-        Column('id', Integer, primary_key=True),
-        Column('value', String(100), nullable=False),
-        schema='remote_banks'
-    )
-
-Within the `MetaData` collection, this table will be identified by the combination of `financial_info` and `remote_banks`.  If another table called `financial_info` is referenced without the `remote_banks` schema, it will refer to a different `Table`.  `ForeignKey` objects can reference columns in this table using the form `remote_banks.financial_info.id`.
-
-#### ON UPDATE and ON DELETE {@name=onupdate}
-
-`ON UPDATE` and `ON DELETE` clauses to a table create are specified within the `ForeignKeyConstraint` object, using the `onupdate` and `ondelete` keyword arguments:
-
-    {python}
-    foobar = Table('foobar', meta,
-        Column('id', Integer, primary_key=True),
-        Column('lala', String(40)),
-        ForeignKeyConstraint(['lala'],['hoho.lala'], onupdate="CASCADE", ondelete="CASCADE"))
-
-Note that these clauses are not supported on SQLite, and require `InnoDB` tables when used with MySQL.  They may also not be supported on other databases.
-
-#### Other Options {@name=options}
-
-`Tables` may support database-specific options, such as MySQL's `engine` option that can specify "MyISAM", "InnoDB", and other backends for the table:
-
-    {python}
-    addresses = Table('engine_email_addresses', meta,
-        Column('address_id', Integer, primary_key = True),
-        Column('remote_user_id', Integer, ForeignKey(users.c.user_id)),
-        Column('email_address', String(20)),
-        mysql_engine='InnoDB'
-    )
-    
-### Creating and Dropping Database Tables {@name=creating}    
-
-Creating and dropping individual tables can be done via the `create()` and `drop()` methods of `Table`; these methods take an optional `bind` parameter which references an `Engine` or a `Connection`.  If not supplied, the `Engine` bound to the `MetaData` will be used, else an error is raised:
-
-    {python}
-    meta = MetaData()
-    meta.bind = 'sqlite:///:memory:'
-
-    employees = Table('employees', meta, 
-        Column('employee_id', Integer, primary_key=True),
-        Column('employee_name', String(60), nullable=False, key='name'),
-        Column('employee_dept', Integer, ForeignKey("departments.department_id"))
-    )
-    {sql}employees.create()
-    CREATE TABLE employees(
-    employee_id SERIAL NOT NULL PRIMARY KEY,
-    employee_name VARCHAR(60) NOT NULL,
-    employee_dept INTEGER REFERENCES departments(department_id)
-    )
-    {}            
-
-`drop()` method:
-    
-    {python}
-    {sql}employees.drop(bind=e)
-    DROP TABLE employees
-    {}            
-
-The `create()` and `drop()` methods also support an optional keyword argument `checkfirst` which will issue the database's appropriate pragma statements to check if the table exists before creating or dropping:
-
-    {python}
-    employees.create(bind=e, checkfirst=True)
-    employees.drop(checkfirst=False)
-    
-Entire groups of Tables can be created and dropped directly from the `MetaData` object with `create_all()` and `drop_all()`.  These methods always check for the existence of each table before creating or dropping.  Each method takes an optional `bind` keyword argument which can reference an `Engine` or a `Connection`.  If no engine is specified, the underlying bound `Engine`,  if any, is used:
-
-    {python}
-    engine = create_engine('sqlite:///:memory:')
-    
-    metadata = MetaData()
-    
-    users = Table('users', metadata, 
-        Column('user_id', Integer, primary_key = True),
-        Column('user_name', String(16), nullable = False),
-        Column('email_address', String(60), key='email'),
-        Column('password', String(20), nullable = False)
-    )
-    
-    user_prefs = Table('user_prefs', metadata, 
-        Column('pref_id', Integer, primary_key=True),
-        Column('user_id', Integer, ForeignKey("users.user_id"), nullable=False),
-        Column('pref_name', String(40), nullable=False),
-        Column('pref_value', String(100))
-    )
-    
-    {sql}metadata.create_all(bind=engine)
-    PRAGMA table_info(users){}
-    CREATE TABLE users(
-            user_id INTEGER NOT NULL PRIMARY KEY, 
-            user_name VARCHAR(16) NOT NULL, 
-            email_address VARCHAR(60), 
-            password VARCHAR(20) NOT NULL
-    )
-    PRAGMA table_info(user_prefs){}
-    CREATE TABLE user_prefs(
-            pref_id INTEGER NOT NULL PRIMARY KEY, 
-            user_id INTEGER NOT NULL REFERENCES users(user_id), 
-            pref_name VARCHAR(40) NOT NULL, 
-            pref_value VARCHAR(100)
-    )
-
-### Column Insert/Update Defaults {@name=defaults}    
-
-SQLAlchemy includes several constructs which provide default values provided during INSERT and UPDATE statements.  The defaults may be provided as Python constants, Python functions, or SQL expressions, and the SQL expressions themselves may be "pre-executed", executed inline within the insert/update statement itself, or can be created as a SQL level "default" placed on the table definition itself.  A "default" value by definition is only invoked if no explicit value is passed into the INSERT or UPDATE statement.
-
-#### Pre-Executed Python Functions {@name=preexecute_functions}
-
-The "default" keyword argument on Column can reference a Python value or callable which is invoked at the time of an insert:
-
-    {python}
-    # a function which counts upwards
-    i = 0
-    def mydefault():
-        global i
-        i += 1
-        return i
-
-    t = Table("mytable", meta, 
-        # function-based default
-        Column('id', Integer, primary_key=True, default=mydefault),
-    
-        # a scalar default
-        Column('key', String(10), default="default")
-    )
-
-Similarly, the "onupdate" keyword does the same thing for update statements:
-
-    {python}
-    import datetime
-    
-    t = Table("mytable", meta, 
-        Column('id', Integer, primary_key=True),
-    
-        # define 'last_updated' to be populated with datetime.now()
-        Column('last_updated', DateTime, onupdate=datetime.datetime.now),
-    )
-
-#### Pre-executed and Inline SQL Expressions {@name=sqlexpression}
-
-The "default" and "onupdate" keywords may also be passed SQL expressions, including select statements or direct function calls:
-
-    {python}
-    t = Table("mytable", meta, 
-        Column('id', Integer, primary_key=True),
-    
-        # define 'create_date' to default to now()
-        Column('create_date', DateTime, default=func.now()),
-    
-        # define 'key' to pull its default from the 'keyvalues' table
-        Column('key', String(20), default=keyvalues.select(keyvalues.c.type='type1', limit=1))
-
-        # define 'last_modified' to use the current_timestamp SQL function on update
-        Column('last_modified', DateTime, onupdate=func.current_timestamp())
-        )
-
-The above SQL functions are usually executed "inline" with the INSERT or UPDATE statement being executed.  In some cases, the function is "pre-executed" and its result pre-fetched explicitly.  This happens under the following circumstances:
-
-* the column is a primary key column
-
-* the database dialect does not support a usable `cursor.lastrowid` accessor (or equivalent); this currently includes Postgres, Oracle, and Firebird.
-
-* the statement is a single execution, i.e. only supplies one set of parameters and doesn't use "executemany" behavior
-
-* the `inline=True` flag is not set on the `Insert()` or `Update()` construct.
-
-For a statement execution which is not an executemany, the returned `ResultProxy` will contain a collection accessible via `result.postfetch_cols()` which contains a list of all `Column` objects which had an inline-executed default.  Similarly, all parameters which were bound to the statement, including all Python and SQL expressions which were pre-executed, are present in the `last_inserted_params()` or `last_updated_params()` collections on `ResultProxy`.  The `last_inserted_ids()` collection contains a list of primary key values for the row inserted.  
-
-#### DDL-Level Defaults {@name=passive}
-
-A variant on a SQL expression default is the `server_default`, which gets placed in the CREATE TABLE statement during a `create()` operation:
-
-    {python}
-    t = Table('test', meta,
-        Column('abc', String(20), server_default='abc'),
-        Column('created_at', DateTime, server_default=text("sysdate"))
-    )
-
-A create call for the above table will produce:
-
-    {code}
-    CREATE TABLE test (
-        abc varchar(20) default 'abc',
-        created_at datetime default sysdate
-    )
-
-The behavior of `server_default` is similar to that of a regular SQL default; if it's placed on a primary key column for a database which doesn't have a way to "postfetch" the ID, and the statement is not "inlined", the SQL expression is pre-executed; otherwise, SQLAlchemy lets the default fire off on the database side normally.
-
-#### Triggered Columns {@name=triggered}
-
-Columns with values set by a database trigger or other external process may be called out with a marker:
-
-    {python}
-    t = Table('test', meta,
-        Column('abc', String(20), server_default=FetchedValue())
-        Column('def', String(20), server_onupdate=FetchedValue())
-    )
-
-These markers do not emit a ``default`` clause when the table is created, however they do set the same internal flags as a static `server_default` clause, providing hints to higher-level tools that a "post-fetch" of these rows should be performed after an insert or update.
-
-#### Defining Sequences {@name=sequences}
-
-A table with a sequence looks like:
-
-    {python}
-    table = Table("cartitems", meta, 
-        Column("cart_id", Integer, Sequence('cart_id_seq'), primary_key=True),
-        Column("description", String(40)),
-        Column("createdate", DateTime())
-    )
-
-The `Sequence` object works a lot like the `default` keyword on `Column`, except that it only takes effect on a database which supports sequences.  When used with a database that does not support sequences, the `Sequence` object has no effect; therefore it's safe to place on a table which is used against multiple database backends.  The same rules for pre- and inline execution apply.
-
-When the `Sequence` is associated with a table, CREATE and DROP statements issued for that table will also issue CREATE/DROP for the sequence object as well, thus "bundling" the sequence object with its parent table.
-
-The flag `optional=True` on `Sequence` will produce a sequence that is only used on databases which have no "autoincrementing" capability.  For example, Postgres supports primary key generation using the SERIAL keyword, whereas Oracle has no such capability.  Therefore, a `Sequence` placed on a primary key column with `optional=True` will only be used with an Oracle backend but not Postgres.
-
-A sequence can also be executed standalone, using an `Engine` or `Connection`, returning its next value in a database-independent fashion:
-
-    {python}
-    seq = Sequence('some_sequence')
-    nextid = connection.execute(seq)
-
-### Defining Constraints and Indexes {@name=constraints}
-
-#### UNIQUE Constraint
-
-Unique constraints can be created anonymously on a single column using the `unique` keyword on `Column`.  Explicitly named unique constraints and/or those with multiple columns are created via the `UniqueConstraint` table-level construct.
-
-    {python}
-    meta = MetaData()
-    mytable = Table('mytable', meta,
-    
-        # per-column anonymous unique constraint
-        Column('col1', Integer, unique=True),
-        
-        Column('col2', Integer),
-        Column('col3', Integer),
-        
-        # explicit/composite unique constraint.  'name' is optional.
-        UniqueConstraint('col2', 'col3', name='uix_1')
-        )
-
-#### CHECK Constraint
-
-Check constraints can be named or unnamed and can be created at the Column or Table level, using the `CheckConstraint` construct.  The text of the check constraint is passed directly through to the database, so there is limited "database independent" behavior.  Column level check constraints generally should only refer to the column to which they are placed, while table level constraints can refer to any columns in the table.
-
-Note that some databases do not actively support check constraints such as MySQL and SQLite.
-
-    {python}
-    meta = MetaData()
-    mytable = Table('mytable', meta,
-    
-        # per-column CHECK constraint
-        Column('col1', Integer, CheckConstraint('col1>5')),
-        
-        Column('col2', Integer),
-        Column('col3', Integer),
-        
-        # table level CHECK constraint.  'name' is optional.
-        CheckConstraint('col2 > col3 + 5', name='check1')
-        )
-    
-#### Indexes
-
-Indexes can be created anonymously (using an auto-generated name "ix_&lt;column label&gt;") for a single column using the inline `index` keyword on `Column`, which also modifies the usage of `unique` to apply the uniqueness to the index itself, instead of adding a separate UNIQUE constraint.  For indexes with specific names or which encompass more than one column, use the `Index` construct, which requires a name.  
-
-Note that the `Index` construct is created **externally** to the table which it corresponds, using `Column` objects and not strings.
-
-    {python}
-    meta = MetaData()
-    mytable = Table('mytable', meta,
-        # an indexed column, with index "ix_mytable_col1"
-        Column('col1', Integer, index=True),
-
-        # a uniquely indexed column with index "ix_mytable_col2"
-        Column('col2', Integer, index=True, unique=True),
-
-        Column('col3', Integer),
-        Column('col4', Integer),
-
-        Column('col5', Integer),
-        Column('col6', Integer),
-        )
-
-    # place an index on col3, col4
-    Index('idx_col34', mytable.c.col3, mytable.c.col4)
-
-    # place a unique index on col5, col6
-    Index('myindex', mytable.c.col5, mytable.c.col6, unique=True)
-
-The `Index` objects will be created along with the CREATE statements for the table itself.  An index can also be created on its own independently of the table:
-
-    {python}
-    # create a table
-    sometable.create()
-
-    # define an index
-    i = Index('someindex', sometable.c.col5)
-
-    # create the index, will use the table's bound connectable if the `bind` keyword argument not specified
-    i.create()
-
-### Adapting Tables to Alternate Metadata {@name=adapting}
-
-A `Table` object created against a specific `MetaData` object can be re-created against a new MetaData using the `tometadata` method:
-
-    {python}
-    # create two metadata
-    meta1 = MetaData('sqlite:///querytest.db')
-    meta2 = MetaData()
-                        
-    # load 'users' from the sqlite engine
-    users_table = Table('users', meta1, autoload=True)
-    
-    # create the same Table object for the plain metadata
-    users_table_2 = users_table.tometadata(meta2)
-    
-    
diff --git a/doc/build/oldcontent/ormtutorial.txt b/doc/build/oldcontent/ormtutorial.txt
deleted file mode 100644 (file)
index 7cce3f7..0000000
+++ /dev/null
@@ -1,1189 +0,0 @@
-Object Relational Tutorial {@name=datamapping}
-============
-
-In this tutorial we will cover a basic SQLAlchemy object-relational mapping scenario, where we store and retrieve Python objects from a database representation.  The tutorial is in doctest format, meaning each `>>>` line represents something you can type at a Python command prompt, and the following text represents the expected return value.
-
-## Version Check
-
-A quick check to verify that we are on at least **version 0.5** of SQLAlchemy:
-
-    {python}
-    >>> import sqlalchemy
-    >>> sqlalchemy.__version__ # doctest:+SKIP
-    0.5.0
-    
-## Connecting
-
-For this tutorial we will use an in-memory-only SQLite database.  To connect we use `create_engine()`:
-
-    {python}
-    >>> from sqlalchemy import create_engine
-    >>> engine = create_engine('sqlite:///:memory:', echo=True)
-    
-The `echo` flag is a shortcut to setting up SQLAlchemy logging, which is accomplished via Python's standard `logging` module.  With it enabled, we'll see all the generated SQL produced.  If you are working through this tutorial and want less output generated, set it to `False`.   This tutorial will format the SQL behind a popup window so it doesn't get in our way; just click the "SQL" links to see what's being generated.
-    
-## Define and Create a Table {@name=tables}
-
-Next we want to tell SQLAlchemy about our tables.  We will start with just a single table called `users`, which will store records for the end-users using our application (lets assume it's a website).  We define our tables within a catalog called `MetaData`, using the `Table` construct, which is used in a manner similar to SQL's CREATE TABLE syntax:
-
-    {python}
-    >>> from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey    
-    >>> metadata = MetaData()
-    >>> users_table = Table('users', metadata,
-    ...     Column('id', Integer, primary_key=True),
-    ...     Column('name', String),
-    ...     Column('fullname', String),
-    ...     Column('password', String)
-    ... )
-
-All about how to define `Table` objects, as well as how to load their definition from an existing database (known as **reflection**), is described in [metadata](rel:metadata).
-
-Next, we can issue CREATE TABLE statements derived from our table metadata, by calling `create_all()` and passing it the `engine` instance which points to our database.  This will check for the presence of a table first before creating, so it's safe to call multiple times:
-
-    {python}
-    {sql}>>> metadata.create_all(engine) # doctest:+ELLIPSIS,+NORMALIZE_WHITESPACE
-    PRAGMA table_info("users")
-    {}
-    CREATE TABLE users (
-        id INTEGER NOT NULL, 
-        name VARCHAR, 
-        fullname VARCHAR, 
-        password VARCHAR, 
-        PRIMARY KEY (id)
-    )
-    {}
-    COMMIT
-
-Users familiar with the syntax of CREATE TABLE may notice that the VARCHAR columns were generated without a length; on SQLite, this is a valid datatype, but on most databases it's not allowed.  So if running this tutorial on a database such as Postgres or MySQL, and you wish to use SQLAlchemy to generate the tables, a "length" may be provided to the `String` type as below:
-
-    {python}
-    Column('name', String(50))
-    
-The length field on `String`, as well as similar precision/scale fields available on `Integer`, `Numeric`, etc. are not referenced by SQLAlchemy other than when creating tables.
-
-## Define a Python Class to be Mapped {@name=mapping}
-
-While the `Table` object defines information about our database, it does not say anything about the definition or behavior of the business objects used by our application;  SQLAlchemy views this as a separate concern.  To correspond to our `users` table, let's create a rudimentary `User` class.  It only need subclass Python's built-in `object` class (i.e. it's a new style class):
-
-    {python}
-    >>> class User(object):
-    ...     def __init__(self, name, fullname, password):
-    ...         self.name = name
-    ...         self.fullname = fullname
-    ...         self.password = password
-    ...
-    ...     def __repr__(self):
-    ...        return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)
-
-The class has an `__init__()` and a `__repr__()` method for convenience.  These methods are both entirely optional, and can be of any form.  SQLAlchemy never calls `__init__()` directly.
-
-## Setting up the Mapping
-
-With our `users_table` and `User` class, we now want to map the two together.  That's where the SQLAlchemy ORM package comes in.  We'll use the `mapper` function to create a **mapping** between `users_table` and `User`:
-
-    {python}
-    >>> from sqlalchemy.orm import mapper
-    >>> mapper(User, users_table) # doctest:+ELLIPSIS,+NORMALIZE_WHITESPACE
-    <Mapper at 0x...; User>
-    
-The `mapper()` function creates a new `Mapper` object and stores it away for future reference, associated with our class.  Let's now create and inspect a `User` object:
-
-    {python}
-    >>> ed_user = User('ed', 'Ed Jones', 'edspassword')
-    >>> ed_user.name
-    'ed'
-    >>> ed_user.password
-    'edspassword'
-    >>> str(ed_user.id)
-    'None'
-    
-The `id` attribute, which while not defined by our `__init__()` method, exists due to the `id` column present within the `users_table` object.  By default, the `mapper` creates class attributes for all columns present within the `Table`.  These class attributes exist as Python descriptors, and define **instrumentation** for the mapped class.  The functionality of this instrumentation is very rich and includes the ability to track modifications and automatically load new data from the database when needed.
-
-Since we have not yet told SQLAlchemy to persist `Ed Jones` within the database, its id is `None`.  When we persist the object later, this attribute will be populated with a newly generated value.
-
-## Creating Table, Class and Mapper All at Once Declaratively {@name=declarative}
-
-The preceding approach to configuration involving a `Table`, user-defined class, and `mapper()` call illustrate classical SQLAlchemy usage, which values the highest separation of concerns possible.  A large number of applications don't require this degree of separation, and for those SQLAlchemy offers an alternate "shorthand" configurational style called **declarative**.  For many applications, this is the only style of configuration needed.  Our above example using this style is as follows:
-
-    {python}
-    >>> from sqlalchemy.ext.declarative import declarative_base
-    
-    >>> Base = declarative_base()
-    >>> class User(Base):
-    ...     __tablename__ = 'users'
-    ...
-    ...     id = Column(Integer, primary_key=True)
-    ...     name = Column(String)
-    ...     fullname = Column(String)
-    ...     password = Column(String)
-    ...
-    ...     def __init__(self, name, fullname, password):
-    ...         self.name = name
-    ...         self.fullname = fullname
-    ...         self.password = password
-    ...
-    ...     def __repr__(self):
-    ...        return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)
-
-Above, the `declarative_base()` function defines a new class which we name `Base`, from which all of our ORM-enabled classes will derive.  Note that we define `Column` objects with no "name" field, since it's inferred from the given attribute name.
-
-The underlying `Table` object created by our `declarative_base()` version of `User` is accessible via the `__table__` attribute:
-
-    {python}
-    >>> users_table = User.__table__
-    
-and the owning `MetaData` object is available as well:
-
-    {python}
-    >>> metadata = Base.metadata
-
-Yet another "declarative" method is available for SQLAlchemy as a third party library called [Elixir](http://elixir.ematia.de/).  This is a full-featured configurational product which also includes many higher level mapping configurations built in.  Like declarative, once classes and mappings are defined, ORM usage is the same as with a classical SQLAlchemy configuration.
-
-## Creating a Session
-
-We're now ready to start talking to the database.  The ORM's "handle" to the database is the `Session`.  When we first set up the application, at the same level as our `create_engine()` statement, we define a `Session` class which will serve as a factory for new `Session` objects:
-
-    {python}
-    >>> from sqlalchemy.orm import sessionmaker
-    >>> Session = sessionmaker(bind=engine)
-
-In the case where your application does not yet have an `Engine` when you define your module-level objects, just set it up like this:
-
-    {python}
-    >>> Session = sessionmaker()
-
-Later, when you create your engine with `create_engine()`, connect it to the `Session` using `configure()`:
-
-    {python}
-    >>> Session.configure(bind=engine)  # once engine is available
-    
-This custom-made `Session` class will create new `Session` objects which are bound to our database.  Other transactional characteristics may be defined when calling `sessionmaker()` as well; these are described in a later chapter.  Then, whenever you need to have a conversation with the database, you instantiate a `Session`:
-
-    {python}
-    >>> session = Session()
-    
-The above `Session` is associated with our SQLite `engine`, but it hasn't opened any connections yet.  When it's first used, it retrieves a connection from a pool of connections maintained by the `engine`, and holds onto it until we commit all changes and/or close the session object.
-
-## Adding new Objects
-
-To persist our `User` object, we `add()` it to our `Session`:
-
-    {python}
-    >>> ed_user = User('ed', 'Ed Jones', 'edspassword')
-    >>> session.add(ed_user)
-    
-At this point, the instance is **pending**; no SQL has yet been issued.  The `Session` will issue the SQL to persist `Ed Jones` as soon as is needed, using a process known as a **flush**.  If we query the database for `Ed Jones`, all pending information will first be flushed, and the query is issued afterwards.
-
-For example, below we create a new `Query` object which loads instances of `User`.  We "filter by" the `name` attribute of `ed`, and indicate that we'd like only the first result in the full list of rows.  A `User` instance is returned which is equivalent to that which we've added:
-
-    {python}
-    {sql}>>> our_user = session.query(User).filter_by(name='ed').first() # doctest:+ELLIPSIS,+NORMALIZE_WHITESPACE
-    BEGIN
-    INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
-    ['ed', 'Ed Jones', 'edspassword']
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name = ?
-     LIMIT 1 OFFSET 0
-    ['ed']
-    {stop}>>> our_user
-    <User('ed','Ed Jones', 'edspassword')>
-
-In fact, the `Session` has identified that the row returned is the **same** row as one already represented within its internal map of objects, so we actually got back the identical instance as that which we just added:
-
-    {python}
-    >>> ed_user is our_user
-    True
-
-The ORM concept at work here is known as an **identity map** and ensures that all operations upon a particular row within a `Session` operate upon the same set of data.  Once an object with a particular primary key is present in the `Session`, all SQL queries on that `Session` will always return the same Python object for that particular primary key; it also will raise an error if an attempt is made to place a second, already-persisted object with the same primary key within the session.
-
-We can add more `User` objects at once using `add_all()`:
-
-    {python}
-    >>> session.add_all([
-    ...     User('wendy', 'Wendy Williams', 'foobar'),
-    ...     User('mary', 'Mary Contrary', 'xxg527'),
-    ...     User('fred', 'Fred Flinstone', 'blah')])
-
-Also, Ed has already decided his password isn't too secure, so lets change it:
-    
-    {python}
-    >>> ed_user.password = 'f8s7ccs'
-
-The `Session` is paying attention.  It knows, for example, that `Ed Jones` has been modified:
-    
-    {python}
-    >>> session.dirty
-    IdentitySet([<User('ed','Ed Jones', 'f8s7ccs')>])
-    
-and that three new `User` objects are pending:
-
-    {python}
-    >>> session.new  # doctest: +NORMALIZE_WHITESPACE
-    IdentitySet([<User('wendy','Wendy Williams', 'foobar')>, 
-    <User('mary','Mary Contrary', 'xxg527')>, 
-    <User('fred','Fred Flinstone', 'blah')>])
-    
-We tell the `Session` that we'd like to issue all remaining changes to the database and commit the transaction, which has been in progress throughout.  We do this via `commit()`:
-
-    {python}
-    {sql}>>> session.commit()
-    UPDATE users SET password=? WHERE users.id = ?
-    ['f8s7ccs', 1]
-    INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
-    ['wendy', 'Wendy Williams', 'foobar']
-    INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
-    ['mary', 'Mary Contrary', 'xxg527']
-    INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
-    ['fred', 'Fred Flinstone', 'blah']
-    COMMIT
-
-`commit()` flushes whatever remaining changes remain to the database, and commits the transaction.  The connection resources referenced by the session are now returned to the connection pool.  Subsequent operations with this session will occur in a **new** transaction, which will again re-acquire connection resources when first needed.
-
-If we look at Ed's `id` attribute, which earlier was `None`, it now has a value:
-
-    {python}
-    {sql}>>> ed_user.id # doctest: +NORMALIZE_WHITESPACE
-    BEGIN
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.id = ?
-    [1]
-    {stop}1
-
-After the `Session` inserts new rows in the database, all newly generated identifiers and database-generated defaults become available on the instance, either immediately or via load-on-first-access.  In this case, the entire row was re-loaded on access because a new transaction was begun after we issued `commit()`.  SQLAlchemy by default refreshes data from a previous transaction the first time it's accessed within a new transaction, so that the most recent state is available.  The level of reloading is configurable as is described in the chapter on Sessions.
-
-## Rolling Back
-
-Since the `Session` works within a transaction, we can roll back changes made too.   Let's make two changes that we'll revert; `ed_user`'s user name gets set to `Edwardo`:
-
-    {python}
-    >>> ed_user.name = 'Edwardo'
-
-and we'll add another erroneous user, `fake_user`:
-
-    {python}
-    >>> fake_user = User('fakeuser', 'Invalid', '12345')
-    >>> session.add(fake_user)
-    
-Querying the session, we can see that they're flushed into the current transaction:
-
-    {python}
-    {sql}>>> session.query(User).filter(User.name.in_(['Edwardo', 'fakeuser'])).all()
-    UPDATE users SET name=? WHERE users.id = ?
-    ['Edwardo', 1]
-    INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
-    ['fakeuser', 'Invalid', '12345']
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name IN (?, ?)
-    ['Edwardo', 'fakeuser']
-    {stop}[<User('Edwardo','Ed Jones', 'f8s7ccs')>, <User('fakeuser','Invalid', '12345')>]
-    
-Rolling back, we can see that `ed_user`'s name is back to `ed`, and `fake_user` has been kicked out of the session:
-
-    {python}
-    {sql}>>> session.rollback()
-    ROLLBACK
-
-
-    {sql}>>> ed_user.name
-    BEGIN
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.id = ?
-    [1]
-    {stop}u'ed'
-    >>> fake_user in session
-    False
-    
-issuing a SELECT illustrates the changes made to the database:
-
-    {python}
-    {sql}>>> session.query(User).filter(User.name.in_(['ed', 'fakeuser'])).all()
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name IN (?, ?)
-    ['ed', 'fakeuser']
-    {stop}[<User('ed','Ed Jones', 'f8s7ccs')>]
-
-## Querying
-
-A `Query` is created using the `query()` function on `Session`.  This function takes a variable number of arguments, which can be any combination of classes and class-instrumented descriptors.  Below, we indicate a `Query` which loads `User` instances.  When evaluated in an iterative context, the list of `User` objects present is returned:
-
-    {python}
-    {sql}>>> for instance in session.query(User).order_by(User.id): # doctest: +NORMALIZE_WHITESPACE
-    ...     print instance.name, instance.fullname 
-    SELECT users.id AS users_id, users.name AS users_name, 
-    users.fullname AS users_fullname, users.password AS users_password 
-    FROM users ORDER BY users.id
-    []
-    {stop}ed Ed Jones
-    wendy Wendy Williams
-    mary Mary Contrary
-    fred Fred Flinstone
-
-The `Query` also accepts ORM-instrumented descriptors as arguments.  Any time multiple class entities or column-based entities are expressed as arguments to the `query()` function, the return result is expressed as tuples:
-
-    {python}
-    {sql}>>> for name, fullname in session.query(User.name, User.fullname): # doctest: +NORMALIZE_WHITESPACE
-    ...     print name, fullname
-    SELECT users.name AS users_name, users.fullname AS users_fullname
-    FROM users
-    []
-    {stop}ed Ed Jones
-    wendy Wendy Williams
-    mary Mary Contrary
-    fred Fred Flinstone
-
-The tuples returned by `Query` are *named* tuples, and can be treated much like an ordinary Python object.  The names are the same as the attribute's name for an attribute, and the class name for a class:
-
-    {python}
-    {sql}>>> for row in session.query(User, User.name).all():
-    ...    print row.User, row.name
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users
-    []
-    {stop}<User('ed','Ed Jones', 'f8s7ccs')> ed
-    <User('wendy','Wendy Williams', 'foobar')> wendy
-    <User('mary','Mary Contrary', 'xxg527')> mary
-    <User('fred','Fred Flinstone', 'blah')> fred
-        
-You can control the names using the `label()` construct for scalar attributes and `aliased()` for class constructs:
-
-    {python}
-    >>> from sqlalchemy.orm import aliased
-    >>> user_alias = aliased(User, name='user_alias')
-    {sql}>>> for row in session.query(user_alias, user_alias.name.label('name_label')).all():
-    ...    print row.user_alias, row.name_label
-    SELECT users_1.id AS users_1_id, users_1.name AS users_1_name, users_1.fullname AS users_1_fullname, users_1.password AS users_1_password, users_1.name AS name_label 
-    FROM users AS users_1
-    []
-    <User('ed','Ed Jones', 'f8s7ccs')> ed
-    <User('wendy','Wendy Williams', 'foobar')> wendy
-    <User('mary','Mary Contrary', 'xxg527')> mary
-    <User('fred','Fred Flinstone', 'blah')> fred
-
-Basic operations with `Query` include issuing LIMIT and OFFSET, most conveniently using Python array slices and typically in conjunction with ORDER BY:
-
-    {python}
-    {sql}>>> for u in session.query(User).order_by(User.id)[1:3]: #doctest: +NORMALIZE_WHITESPACE
-    ...    print u
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users ORDER BY users.id 
-    LIMIT 2 OFFSET 1
-    []
-    {stop}<User('wendy','Wendy Williams', 'foobar')>
-    <User('mary','Mary Contrary', 'xxg527')>
-
-and filtering results, which is accomplished either with `filter_by()`, which uses keyword arguments:
-
-    {python}
-    {sql}>>> for name, in session.query(User.name).filter_by(fullname='Ed Jones'): # doctest: +NORMALIZE_WHITESPACE
-    ...    print name
-    SELECT users.name AS users_name FROM users 
-    WHERE users.fullname = ?
-    ['Ed Jones']
-    {stop}ed
-
-...or `filter()`, which uses more flexible SQL expression language constructs.  These allow you to use regular Python operators with the class-level attributes on your mapped class:
-
-    {python}
-    {sql}>>> for name, in session.query(User.name).filter(User.fullname=='Ed Jones'): # doctest: +NORMALIZE_WHITESPACE
-    ...    print name
-    SELECT users.name AS users_name FROM users 
-    WHERE users.fullname = ?
-    ['Ed Jones']
-    {stop}ed
-
-The `Query` object is fully *generative*, meaning that most method calls return a new `Query` object upon which further criteria may be added.  For example, to query for users named "ed" with a full name of "Ed Jones", you can call `filter()` twice, which joins criteria using `AND`:
-
-    {python}
-    {sql}>>> for user in session.query(User).filter(User.name=='ed').filter(User.fullname=='Ed Jones'): # doctest: +NORMALIZE_WHITESPACE
-    ...    print user
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name = ? AND users.fullname = ?
-    ['ed', 'Ed Jones']
-    {stop}<User('ed','Ed Jones', 'f8s7ccs')>
-
-
-### Common Filter Operators
-
-Here's a rundown of some of the most common operators used in `filter()`:
-
-  * equals
-
-        {python}
-        query.filter(User.name == 'ed')
-    
-  * not equals
-    
-        {python}
-        query.filter(User.name != 'ed')
-    
-  * LIKE
-    
-        {python}
-        query.filter(User.name.like('%ed%'))
-        
-  * IN
-    
-        {python}
-        query.filter(User.name.in_(['ed', 'wendy', 'jack']))
-        
-  * IS NULL
-    
-        {python}
-        filter(User.name == None)
-        
-  * AND
-    
-        {python}
-        from sqlalchemy import and_
-        filter(and_(User.name == 'ed', User.fullname == 'Ed Jones'))
-        
-        # or call filter()/filter_by() multiple times
-        filter(User.name == 'ed').filter(User.fullname == 'Ed Jones')
-    
-  * OR
-        
-        {python}
-        from sqlalchemy import or_
-        filter(or_(User.name == 'ed', User.name == 'wendy'))
-
-  * match
-        
-        {python}
-        query.filter(User.name.match('wendy'))
-
-    The contents of the match parameter are database backend specific.
-        
-### Returning Lists and Scalars {@name=scalars}
-
-The `all()`, `one()`, and `first()` methods of `Query` immediately issue SQL and return a non-iterator value.  `all()` returns a list:
-
-    {python}
-    >>> query = session.query(User).filter(User.name.like('%ed')).order_by(User.id)
-    {sql}>>> query.all()
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name LIKE ? ORDER BY users.id
-    ['%ed']
-    {stop}[<User('ed','Ed Jones', 'f8s7ccs')>, <User('fred','Fred Flinstone', 'blah')>]
-
-`first()` applies a limit of one and returns the first result as a scalar:
-
-    {python}
-    {sql}>>> query.first()
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name LIKE ? ORDER BY users.id 
-     LIMIT 1 OFFSET 0
-    ['%ed']
-    {stop}<User('ed','Ed Jones', 'f8s7ccs')>
-
-`one()`, applies a limit of *two*, and if not exactly one row returned, raises an error:
-
-    {python}
-    {sql}>>> try:  
-    ...     user = query.one() 
-    ... except Exception, e: 
-    ...     print e
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name LIKE ? ORDER BY users.id 
-     LIMIT 2 OFFSET 0
-    ['%ed']
-    {stop}Multiple rows were found for one()
-
-    {python}
-    {sql}>>> try:
-    ...     user = query.filter(User.id == 99).one() 
-    ... except Exception, e: 
-    ...     print e
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name LIKE ? AND users.id = ? ORDER BY users.id 
-     LIMIT 2 OFFSET 0
-    ['%ed', 99]
-    {stop}No row was found for one()
-
-### Using Literal SQL {@naqme=literal}
-
-Literal strings can be used flexibly with `Query`.  Most methods accept strings in addition to SQLAlchemy clause constructs.  For example, `filter()` and `order_by()`:
-
-    {python}
-    {sql}>>> for user in session.query(User).filter("id<224").order_by("id").all():
-    ...     print user.name
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE id<224 ORDER BY id
-    []
-    {stop}ed
-    wendy
-    mary
-    fred
-    
-Bind parameters can be specified with string-based SQL, using a colon.  To specify the values, use the `params()` method:
-
-    {python}
-    {sql}>>> session.query(User).filter("id<:value and name=:name").\
-    ...     params(value=224, name='fred').order_by(User.id).one() # doctest: +NORMALIZE_WHITESPACE
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE id<? and name=? ORDER BY users.id 
-    LIMIT 2 OFFSET 0
-    [224, 'fred']
-    {stop}<User('fred','Fred Flinstone', 'blah')>
-
-To use an entirely string-based statement, using `from_statement()`; just ensure that the columns clause of the statement contains the column names normally used by the mapper (below illustrated using an asterisk):
-
-    {python}
-    {sql}>>> session.query(User).from_statement("SELECT * FROM users where name=:name").params(name='ed').all()
-    SELECT * FROM users where name=?
-    ['ed']
-    {stop}[<User('ed','Ed Jones', 'f8s7ccs')>]
-
-## Building a Relation {@name=relation}
-
-Now let's consider a second table to be dealt with.  Users in our system also can store any number of email addresses associated with their username.  This implies a basic one to many association from the `users_table` to a new table which stores email addresses, which we will call `addresses`.  Using declarative, we define this table along with its mapped class, `Address`:
-
-    {python}
-    >>> from sqlalchemy import ForeignKey
-    >>> from sqlalchemy.orm import relation, backref
-    >>> class Address(Base):
-    ...     __tablename__ = 'addresses'
-    ...     id = Column(Integer, primary_key=True)
-    ...     email_address = Column(String, nullable=False)
-    ...     user_id = Column(Integer, ForeignKey('users.id'))
-    ...
-    ...     user = relation(User, backref=backref('addresses', order_by=id))
-    ...
-    ...     def __init__(self, email_address):
-    ...         self.email_address = email_address
-    ...
-    ...     def __repr__(self):
-    ...         return "<Address('%s')>" % self.email_address
-
-The above class introduces a **foreign key** constraint which references the `users` table.  This defines for SQLAlchemy the relationship between the two tables at the database level.  The relationship between the `User` and `Address` classes is defined separately using the `relation()` function, which defines an attribute `user` to be placed on the `Address` class, as well as an `addresses` collection to be placed on the `User` class.  Such a relation is known as a **bidirectional** relationship.   Because of the placement of the foreign key, from `Address` to `User` it is **many to one**, and from `User` to `Address` it is **one to many**.  SQLAlchemy is automatically aware of many-to-one/one-to-many based on foreign keys.
-
-The `relation()` function is extremely flexible, and could just have easily been defined on the `User` class:
-
-    {python}
-    class User(Base):
-        ....
-        addresses = relation(Address, order_by=Address.id, backref="user")
-
-We are also free to not define a backref, and to define the `relation()` only on one class and not the other.   It is also possible to define two separate `relation()`s for either direction, which is generally safe for many-to-one and one-to-many relations, but not for many-to-many relations.
-
-When using the `declarative` extension, `relation()` gives us the option to use strings for most arguments that concern the target class, in the case that the target class has not yet been defined.  This **only** works in conjunction with `declarative`:
-
-    {python}
-    class User(Base):
-        ....
-        addresses = relation("Address", order_by="Address.id", backref="user")
-
-When `declarative` is not in use, you typically define your `mapper()` well after the target classes and `Table` objects have been defined, so string expressions are not needed.
-
-We'll need to create the `addresses` table in the database, so we will issue another CREATE from our metadata, which will skip over tables which have already been created:
-
-    {python}
-    {sql}>>> metadata.create_all(engine) # doctest: +NORMALIZE_WHITESPACE
-    PRAGMA table_info("users")
-    {}
-    PRAGMA table_info("addresses")
-    {}
-    CREATE TABLE addresses (
-        id INTEGER NOT NULL, 
-        email_address VARCHAR NOT NULL, 
-        user_id INTEGER, 
-        PRIMARY KEY (id), 
-         FOREIGN KEY(user_id) REFERENCES users (id)
-    )
-    {}
-    COMMIT
-
-## Working with Related Objects {@name=related_objects}
-
-Now when we create a `User`, a blank `addresses` collection will be present.  By default, the collection is a Python list.  Other collection types, such as sets and dictionaries, are available as well:
-
-    {python}
-    >>> jack = User('jack', 'Jack Bean', 'gjffdd')
-    >>> jack.addresses
-    []
-    
-We are free to add `Address` objects on our `User` object.  In this case we just assign a full list directly:
-
-    {python}
-    >>> jack.addresses = [Address(email_address='jack@google.com'), Address(email_address='j25@yahoo.com')]
-
-When using a bidirectional relationship, elements added in one direction automatically become visible in the other direction.  This is the basic behavior of the **backref** keyword, which maintains the relationship purely in memory, without using any SQL:
-
-    {python}
-    >>> jack.addresses[1]
-    <Address('j25@yahoo.com')>
-    
-    >>> jack.addresses[1].user
-    <User('jack','Jack Bean', 'gjffdd')>
-
-Let's add and commit `Jack Bean` to the database.  `jack` as well as the two `Address` members in his `addresses` collection are both added to the session at once, using a process known as **cascading**:
-
-    {python}
-    >>> session.add(jack)
-    {sql}>>> session.commit()
-    INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)
-    ['jack', 'Jack Bean', 'gjffdd']
-    INSERT INTO addresses (email_address, user_id) VALUES (?, ?)
-    ['jack@google.com', 5]
-    INSERT INTO addresses (email_address, user_id) VALUES (?, ?)
-    ['j25@yahoo.com', 5]
-    COMMIT
-    
-Querying for Jack, we get just Jack back.  No SQL is yet issued for Jack's addresses:
-
-    {python}
-    {sql}>>> jack = session.query(User).filter_by(name='jack').one()
-    BEGIN
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name = ? 
-     LIMIT 2 OFFSET 0
-    ['jack']
-    
-    >>> jack
-    <User('jack','Jack Bean', 'gjffdd')>
-    
-Let's look at the `addresses` collection.  Watch the SQL:
-
-    {python}
-    {sql}>>> jack.addresses
-    SELECT addresses.id AS addresses_id, addresses.email_address AS addresses_email_address, addresses.user_id AS addresses_user_id 
-    FROM addresses 
-    WHERE ? = addresses.user_id ORDER BY addresses.id
-    [5]
-    {stop}[<Address('jack@google.com')>, <Address('j25@yahoo.com')>]
-    
-When we accessed the `addresses` collection, SQL was suddenly issued.  This is an example of a **lazy loading relation**.  The `addresses` collection is now loaded and behaves just like an ordinary list.  
-    
-If you want to reduce the number of queries (dramatically, in many cases), we can apply an **eager load** to the query operation.   With the same query, we may apply an **option** to the query, indicating that we'd like `addresses` to load "eagerly".  SQLAlchemy then constructs an outer join between the `users` and `addresses` tables, and loads them at once, populating the `addresses` collection on each `User` object if it's not already populated:
-
-    {python}
-    >>> from sqlalchemy.orm import eagerload
-    
-    {sql}>>> jack = session.query(User).options(eagerload('addresses')).filter_by(name='jack').one() #doctest: +NORMALIZE_WHITESPACE
-    SELECT anon_1.users_id AS anon_1_users_id, anon_1.users_name AS anon_1_users_name, 
-    anon_1.users_fullname AS anon_1_users_fullname, anon_1.users_password AS anon_1_users_password, 
-    addresses_1.id AS addresses_1_id, addresses_1.email_address AS addresses_1_email_address, 
-    addresses_1.user_id AS addresses_1_user_id 
-        FROM (SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, 
-        users.password AS users_password
-        FROM users WHERE users.name = ? 
-         LIMIT 2 OFFSET 0) AS anon_1 LEFT OUTER JOIN addresses AS addresses_1 
-         ON anon_1.users_id = addresses_1.user_id ORDER BY addresses_1.id
-        ['jack']
-    
-    >>> jack
-    <User('jack','Jack Bean', 'gjffdd')>
-    
-    >>> jack.addresses
-    [<Address('jack@google.com')>, <Address('j25@yahoo.com')>]
-
-SQLAlchemy has the ability to control exactly which attributes and how many levels deep should be joined together in a single SQL query.  More information on this feature is available in [advdatamapping_relation](rel:advdatamapping_relation).
-
-## Querying with Joins {@name=joins}
-
-While the eager load created a JOIN specifically to populate a collection, we can also work explicitly with joins in many ways.  For example, to construct a simple inner join between `User` and `Address`, we can just `filter()` their related columns together.  Below we load the `User` and `Address` entities at once using this method:
-
-    {python}
-    {sql}>>> for u, a in session.query(User, Address).filter(User.id==Address.user_id).\
-    ...         filter(Address.email_address=='jack@google.com').all():   # doctest: +NORMALIZE_WHITESPACE
-    ...     print u, a
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, 
-    users.password AS users_password, addresses.id AS addresses_id, 
-    addresses.email_address AS addresses_email_address, addresses.user_id AS addresses_user_id 
-    FROM users, addresses 
-    WHERE users.id = addresses.user_id AND addresses.email_address = ?
-    ['jack@google.com']
-    {stop}<User('jack','Jack Bean', 'gjffdd')> <Address('jack@google.com')>
-
-Or we can make a real JOIN construct; one way to do so is to use the ORM `join()` function, and tell `Query` to "select from" this join:
-
-    {python}
-    >>> from sqlalchemy.orm import join
-    {sql}>>> session.query(User).select_from(join(User, Address)).\
-    ...         filter(Address.email_address=='jack@google.com').all()
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users JOIN addresses ON users.id = addresses.user_id 
-    WHERE addresses.email_address = ?
-    ['jack@google.com']
-    {stop}[<User('jack','Jack Bean', 'gjffdd')>]
-
-`join()` knows how to join between `User` and `Address` because there's only one foreign key between them.  If there were no foreign keys, or several, `join()` would require a third argument indicating the ON clause of the join, in one of the following forms:
-
-    {python}
-    join(User, Address, User.id==Address.user_id)  # explicit condition
-    join(User, Address, User.addresses)            # specify relation from left to right
-    join(User, Address, 'addresses')               # same, using a string
-    
-The functionality of `join()` is also available generatively from `Query` itself using `Query.join`.  This is most easily used with just the "ON" clause portion of the join, such as:
-
-    {python}
-    {sql}>>> session.query(User).join(User.addresses).\
-    ...     filter(Address.email_address=='jack@google.com').all()
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users JOIN addresses ON users.id = addresses.user_id 
-    WHERE addresses.email_address = ?
-    ['jack@google.com']
-    {stop}[<User('jack','Jack Bean', 'gjffdd')>]
-
-To explicitly specify the target of the join, use tuples to form an argument list similar to the standalone join.  This becomes more important when using aliases and similar constructs:
-
-    {python}
-    session.query(User).join((Address, User.addresses))
-    
-Multiple joins can be created by passing a list of arguments:
-
-    {python}
-    session.query(Foo).join(Foo.bars, Bar.bats, (Bat, 'widgets'))
-    
-The above would produce SQL something like `foo JOIN bars ON <onclause> JOIN bats ON <onclause> JOIN widgets ON <onclause>`.
-    
-### Using Aliases {@name=aliases}
-
-When querying across multiple tables, if the same table needs to be referenced more than once, SQL typically requires that the table be *aliased* with another name, so that it can be distinguished against other occurrences of that table.  The `Query` supports this most explicitly using the `aliased` construct.  Below we join to the `Address` entity twice, to locate a user who has two distinct email addresses at the same time:
-
-    {python}
-    >>> from sqlalchemy.orm import aliased
-    >>> adalias1 = aliased(Address)
-    >>> adalias2 = aliased(Address)
-    {sql}>>> for username, email1, email2 in session.query(User.name, adalias1.email_address, adalias2.email_address).\
-    ...     join((adalias1, User.addresses), (adalias2, User.addresses)).\
-    ...     filter(adalias1.email_address=='jack@google.com').\
-    ...     filter(adalias2.email_address=='j25@yahoo.com'):
-    ...     print username, email1, email2      # doctest: +NORMALIZE_WHITESPACE
-    SELECT users.name AS users_name, addresses_1.email_address AS addresses_1_email_address, 
-    addresses_2.email_address AS addresses_2_email_address 
-    FROM users JOIN addresses AS addresses_1 ON users.id = addresses_1.user_id 
-    JOIN addresses AS addresses_2 ON users.id = addresses_2.user_id 
-    WHERE addresses_1.email_address = ? AND addresses_2.email_address = ?
-    ['jack@google.com', 'j25@yahoo.com']
-    {stop}jack jack@google.com j25@yahoo.com
-
-### Using Subqueries {@name=subqueries}
-
-The `Query` is suitable for generating statements which can be used as subqueries.  Suppose we wanted to load `User` objects along with a count of how many `Address` records each user has.  The best way to generate SQL like this is to get the count of addresses grouped by user ids, and JOIN to the parent.  In this case we use a LEFT OUTER JOIN so that we get rows back for those users who don't have any addresses, e.g.:
-
-    {code}
-    SELECT users.*, adr_count.address_count FROM users LEFT OUTER JOIN
-        (SELECT user_id, count(*) AS address_count FROM addresses GROUP BY user_id) AS adr_count
-        ON users.id=adr_count.user_id
-
-Using the `Query`, we build a statement like this from the inside out.  The `statement` accessor returns a SQL expression representing the statement generated by a particular `Query` - this is an instance of a `select()` construct, which are described in [sql](rel:sql):
-    
-    {python}
-    >>> from sqlalchemy.sql import func
-    >>> stmt = session.query(Address.user_id, func.count('*').label('address_count')).group_by(Address.user_id).subquery()
-    
-The `func` keyword generates SQL functions, and the `subquery()` method on `Query` produces a SQL expression construct representing a SELECT statement embedded within an alias (it's actually shorthand for `query.statement.alias()`).
-
-Once we have our statement, it behaves like a `Table` construct, such as the one we created for `users` at the start of this tutorial.  The columns on the statement are accessible through an attribute called `c`:
-
-    {python}
-    {sql}>>> for u, count in session.query(User, stmt.c.address_count).\
-    ...     outerjoin((stmt, User.id==stmt.c.user_id)).order_by(User.id): # doctest: +NORMALIZE_WHITESPACE
-    ...     print u, count
-    SELECT users.id AS users_id, users.name AS users_name, 
-    users.fullname AS users_fullname, users.password AS users_password, 
-    anon_1.address_count AS anon_1_address_count 
-    FROM users LEFT OUTER JOIN (SELECT addresses.user_id AS user_id, count(?) AS address_count 
-    FROM addresses GROUP BY addresses.user_id) AS anon_1 ON users.id = anon_1.user_id 
-    ORDER BY users.id
-    ['*']
-    {stop}<User('ed','Ed Jones', 'f8s7ccs')> None
-    <User('wendy','Wendy Williams', 'foobar')> None
-    <User('mary','Mary Contrary', 'xxg527')> None
-    <User('fred','Fred Flinstone', 'blah')> None
-    <User('jack','Jack Bean', 'gjffdd')> 2
-
-### Using EXISTS
-
-The EXISTS keyword in SQL is a boolean operator which returns True if the given expression contains any rows.  It may be used in many scenarios in place of joins, and is also useful for locating rows which do not have a corresponding row in a related table.
-
-There is an explicit EXISTS construct, which looks like this:
-
-    {python}
-    >>> from sqlalchemy.sql import exists
-    >>> stmt = exists().where(Address.user_id==User.id)
-    {sql}>>> for name, in session.query(User.name).filter(stmt):   # doctest: +NORMALIZE_WHITESPACE
-    ...     print name
-    SELECT users.name AS users_name 
-    FROM users 
-    WHERE EXISTS (SELECT * 
-    FROM addresses 
-    WHERE addresses.user_id = users.id)
-    []
-    {stop}jack
-
-The `Query` features several operators which make usage of EXISTS automatically.  Above, the statement can be expressed along the `User.addresses` relation using `any()`:
-
-    {python}
-    {sql}>>> for name, in session.query(User.name).filter(User.addresses.any()):   # doctest: +NORMALIZE_WHITESPACE
-    ...     print name
-    SELECT users.name AS users_name 
-    FROM users 
-    WHERE EXISTS (SELECT 1 
-    FROM addresses 
-    WHERE users.id = addresses.user_id)
-    []
-    {stop}jack
-
-`any()` takes criterion as well, to limit the rows matched:
-
-    {python}
-    {sql}>>> for name, in session.query(User.name).filter(User.addresses.any(Address.email_address.like('%google%'))):   # doctest: +NORMALIZE_WHITESPACE
-    ...     print name
-    SELECT users.name AS users_name 
-    FROM users 
-    WHERE EXISTS (SELECT 1 
-    FROM addresses 
-    WHERE users.id = addresses.user_id AND addresses.email_address LIKE ?)
-    ['%google%']
-    {stop}jack
-
-`has()` is the same operator as `any()` for many-to-one relations (note the `~` operator here too, which means "NOT"):
-
-    {python}
-    {sql}>>> session.query(Address).filter(~Address.user.has(User.name=='jack')).all() # doctest: +NORMALIZE_WHITESPACE
-    SELECT addresses.id AS addresses_id, addresses.email_address AS addresses_email_address, 
-    addresses.user_id AS addresses_user_id 
-    FROM addresses 
-    WHERE NOT (EXISTS (SELECT 1 
-    FROM users 
-    WHERE users.id = addresses.user_id AND users.name = ?))
-    ['jack']
-    {stop}[]
-    
-### Common Relation Operators {@name=relationop}
-
-Here's all the operators which build on relations:
-
-  * equals (used for many-to-one)
-    
-        {python}
-        query.filter(Address.user == someuser)
-    
-  * not equals (used for many-to-one)
-
-        {python}
-        query.filter(Address.user != someuser)
-
-  * IS NULL (used for many-to-one)
-    
-        {python}
-        query.filter(Address.user == None)
-        
-  * contains (used for one-to-many and many-to-many collections)
-    
-        {python}
-        query.filter(User.addresses.contains(someaddress))
-    
-  * any (used for one-to-many and many-to-many collections)
-    
-        {python}
-        query.filter(User.addresses.any(Address.email_address == 'bar'))
-        
-        # also takes keyword arguments:
-        query.filter(User.addresses.any(email_address='bar'))
-    
-  * has (used for many-to-one)
-    
-        {python}
-        query.filter(Address.user.has(name='ed'))
-    
-  * with_parent (used for any relation)
-    
-        {python}
-        session.query(Address).with_parent(someuser, 'addresses')
-
-## Deleting
-
-Let's try to delete `jack` and see how that goes.  We'll mark as deleted in the session, then we'll issue a `count` query to see that no rows remain:
-
-    {python}
-    >>> session.delete(jack)
-    {sql}>>> session.query(User).filter_by(name='jack').count() # doctest: +NORMALIZE_WHITESPACE
-    UPDATE addresses SET user_id=? WHERE addresses.id = ?
-    [None, 1]
-    UPDATE addresses SET user_id=? WHERE addresses.id = ?
-    [None, 2]
-    DELETE FROM users WHERE users.id = ?
-    [5]
-    SELECT count(1) AS count_1 
-    FROM users 
-    WHERE users.name = ?
-    ['jack']
-    {stop}0
-    
-So far, so good.  How about Jack's `Address` objects ?
-
-    {python}
-    {sql}>>> session.query(Address).filter(
-    ...     Address.email_address.in_(['jack@google.com', 'j25@yahoo.com'])
-    ...  ).count() # doctest: +NORMALIZE_WHITESPACE
-    SELECT count(1) AS count_1
-    FROM addresses 
-    WHERE addresses.email_address IN (?, ?)
-    ['jack@google.com', 'j25@yahoo.com']
-    {stop}2
-    
-Uh oh, they're still there !  Analyzing the flush SQL, we can see that the `user_id` column of each address was set to NULL, but the rows weren't deleted.  SQLAlchemy doesn't assume that deletes cascade, you have to tell it to do so.
-
-### Configuring delete/delete-orphan Cascade {@name=cascade}
-
-We will configure **cascade** options on the `User.addresses` relation to change the behavior.  While SQLAlchemy allows you to add new attributes and relations to mappings at any point in time, in this case the existing relation needs to be removed, so we need to tear down the mappings completely and start again.  This is not a typical operation and is here just for illustrative purposes.
-
-Removing all ORM state is as follows:
-
-    {python}
-    >>> session.close()  # roll back and close the transaction
-    >>> from sqlalchemy.orm import clear_mappers
-    >>> clear_mappers() # clear mappers
-    
-Below, we use `mapper()` to reconfigure an ORM mapping for `User` and `Address`, on our existing but currently un-mapped classes.  The `User.addresses` relation now has `delete, delete-orphan` cascade on it, which indicates that DELETE operations will cascade to attached `Address` objects as well as `Address` objects which are removed from their parent:
-
-    {python}
-    >>> mapper(User, users_table, properties={    # doctest: +ELLIPSIS
-    ...     'addresses':relation(Address, backref='user', cascade="all, delete, delete-orphan")
-    ... })
-    <Mapper at 0x...; User>
-    
-    >>> addresses_table = Address.__table__
-    >>> mapper(Address, addresses_table) # doctest: +ELLIPSIS
-    <Mapper at 0x...; Address>
-
-Now when we load Jack (below using `get()`, which loads by primary key), removing an address from his `addresses` collection will result in that `Address` being deleted:
-
-    {python}
-    # load Jack by primary key
-    {sql}>>> jack = session.query(User).get(5)    #doctest: +NORMALIZE_WHITESPACE
-    BEGIN
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.id = ?
-    [5]
-    {stop}
-    
-    # remove one Address (lazy load fires off)
-    {sql}>>> del jack.addresses[1]  
-    SELECT addresses.id AS addresses_id, addresses.email_address AS addresses_email_address, addresses.user_id AS addresses_user_id 
-    FROM addresses 
-    WHERE ? = addresses.user_id
-    [5]
-    {stop}
-
-    # only one address remains
-    {sql}>>> session.query(Address).filter(
-    ...     Address.email_address.in_(['jack@google.com', 'j25@yahoo.com'])
-    ... ).count() # doctest: +NORMALIZE_WHITESPACE
-    DELETE FROM addresses WHERE addresses.id = ?
-    [2]
-    SELECT count(1) AS count_1
-    FROM addresses 
-    WHERE addresses.email_address IN (?, ?)
-    ['jack@google.com', 'j25@yahoo.com']
-    {stop}1
-    
-Deleting Jack will delete both Jack and his remaining `Address`:
-
-    {python}
-    >>> session.delete(jack)
-    
-    {sql}>>> session.query(User).filter_by(name='jack').count() # doctest: +NORMALIZE_WHITESPACE
-    DELETE FROM addresses WHERE addresses.id = ?
-    [1]
-    DELETE FROM users WHERE users.id = ?
-    [5]
-    SELECT count(1) AS count_1
-    FROM users 
-    WHERE users.name = ?
-    ['jack']
-    {stop}0
-    
-    {sql}>>> session.query(Address).filter(
-    ...    Address.email_address.in_(['jack@google.com', 'j25@yahoo.com'])
-    ... ).count() # doctest: +NORMALIZE_WHITESPACE
-    SELECT count(1) AS count_1
-    FROM addresses 
-    WHERE addresses.email_address IN (?, ?)
-    ['jack@google.com', 'j25@yahoo.com']
-    {stop}0
-
-## Building a Many To Many Relation {@name=manytomany}
-
-We're moving into the bonus round here, but lets show off a many-to-many relationship.  We'll sneak in some other features too, just to take a tour.  We'll make our application a blog application, where users can write `BlogPost`s, which have `Keywords` associated with them.
-
-The declarative setup is as follows:
-
-    {python}
-    >>> from sqlalchemy import Text
-
-    >>> # association table
-    >>> post_keywords = Table('post_keywords', metadata,
-    ...     Column('post_id', Integer, ForeignKey('posts.id')),
-    ...     Column('keyword_id', Integer, ForeignKey('keywords.id'))
-    ... )
-
-    >>> class BlogPost(Base):
-    ...     __tablename__ = 'posts'
-    ...
-    ...     id = Column(Integer, primary_key=True)
-    ...     user_id = Column(Integer, ForeignKey('users.id'))
-    ...     headline = Column(String(255), nullable=False)
-    ...     body = Column(Text)
-    ...
-    ...     # many to many BlogPost<->Keyword
-    ...     keywords = relation('Keyword', secondary=post_keywords, backref='posts')
-    ...
-    ...     def __init__(self, headline, body, author):
-    ...         self.author = author
-    ...         self.headline = headline
-    ...         self.body = body
-    ...
-    ...     def __repr__(self):
-    ...         return "BlogPost(%r, %r, %r)" % (self.headline, self.body, self.author)
-
-    >>> class Keyword(Base):
-    ...     __tablename__ = 'keywords'
-    ...
-    ...     id = Column(Integer, primary_key=True)
-    ...     keyword = Column(String(50), nullable=False, unique=True)
-    ...
-    ...     def __init__(self, keyword):
-    ...         self.keyword = keyword
-
-Above, the many-to-many relation above is `BlogPost.keywords`.  The defining feature of a many to many relation is the `secondary` keyword argument which references a `Table` object representing the association table.  This table only contains columns which reference the two sides of the relation; if it has *any* other columns, such as its own primary key, or foreign keys to other tables, SQLAlchemy requires a different usage pattern called the "association object", described at [advdatamapping_relation_patterns_association](rel:advdatamapping_relation_patterns_association).
-
-The many-to-many relation is also bi-directional using the `backref` keyword.  This is the one case where usage of `backref` is generally required, since if a separate `posts` relation were added to the `Keyword` entity, both relations would independently add and remove rows from the `post_keywords` table and produce conflicts.
-
-We would also like our `BlogPost` class to have an `author` field.  We will add this as another bidirectional relationship, except one issue we'll have is that a single user might have lots of blog posts.  When we access `User.posts`, we'd like to be able to filter results further so as not to load the entire collection.  For this we use a setting accepted by `relation()` called `lazy='dynamic'`, which configures an alternate **loader strategy** on the attribute.  To use it on the "reverse" side of a `relation()`, we use the `backref()` function:
-
-    {python}
-    >>> from sqlalchemy.orm import backref
-    >>> # "dynamic" loading relation to User
-    >>> BlogPost.author = relation(User, backref=backref('posts', lazy='dynamic'))
-
-Create new tables:
-    
-    {python}
-    {sql}>>> metadata.create_all(engine) # doctest: +NORMALIZE_WHITESPACE
-    PRAGMA table_info("users")
-    {}
-    PRAGMA table_info("addresses")
-    {}
-    PRAGMA table_info("posts")
-    {}
-    PRAGMA table_info("keywords")
-    {}
-    PRAGMA table_info("post_keywords")
-    {}
-    CREATE TABLE posts (
-        id INTEGER NOT NULL, 
-        user_id INTEGER, 
-        headline VARCHAR(255) NOT NULL, 
-        body TEXT, 
-        PRIMARY KEY (id), 
-         FOREIGN KEY(user_id) REFERENCES users (id)
-    )
-    {}
-    COMMIT
-    CREATE TABLE keywords (
-        id INTEGER NOT NULL, 
-        keyword VARCHAR(50) NOT NULL, 
-        PRIMARY KEY (id), 
-         UNIQUE (keyword)
-    )
-    {}
-    COMMIT
-    CREATE TABLE post_keywords (
-        post_id INTEGER, 
-        keyword_id INTEGER, 
-         FOREIGN KEY(post_id) REFERENCES posts (id), 
-         FOREIGN KEY(keyword_id) REFERENCES keywords (id)
-    )
-    {}
-    COMMIT
-
-Usage is not too different from what we've been doing.  Let's give Wendy some blog posts:
-
-    {python}
-    {sql}>>> wendy = session.query(User).filter_by(name='wendy').one()
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, users.password AS users_password 
-    FROM users 
-    WHERE users.name = ? 
-     LIMIT 2 OFFSET 0
-    ['wendy']
-    
-    >>> post = BlogPost("Wendy's Blog Post", "This is a test", wendy)
-    >>> session.add(post)
-    
-We're storing keywords uniquely in the database, but we know that we don't have any yet, so we can just create them:
-
-    {python}
-    >>> post.keywords.append(Keyword('wendy'))
-    >>> post.keywords.append(Keyword('firstpost'))
-    
-We can now look up all blog posts with the keyword 'firstpost'.   We'll use the `any` operator to locate "blog posts where any of its keywords has the keyword string 'firstpost'":
-
-    {python}
-    {sql}>>> session.query(BlogPost).filter(BlogPost.keywords.any(keyword='firstpost')).all()
-    INSERT INTO posts (user_id, headline, body) VALUES (?, ?, ?)
-    [2, "Wendy's Blog Post", 'This is a test']
-    INSERT INTO keywords (keyword) VALUES (?)
-    ['wendy']
-    INSERT INTO keywords (keyword) VALUES (?)
-    ['firstpost']
-    INSERT INTO post_keywords (post_id, keyword_id) VALUES (?, ?)
-    [[1, 1], [1, 2]]
-    SELECT posts.id AS posts_id, posts.user_id AS posts_user_id, posts.headline AS posts_headline, posts.body AS posts_body 
-    FROM posts 
-    WHERE EXISTS (SELECT 1 
-    FROM post_keywords, keywords 
-    WHERE posts.id = post_keywords.post_id AND keywords.id = post_keywords.keyword_id AND keywords.keyword = ?)
-    ['firstpost']
-    {stop}[BlogPost("Wendy's Blog Post", 'This is a test', <User('wendy','Wendy Williams', 'foobar')>)]
-    
-If we want to look up just Wendy's posts, we can tell the query to narrow down to her as a parent:
-
-    {python}
-    {sql}>>> session.query(BlogPost).filter(BlogPost.author==wendy).\
-    ... filter(BlogPost.keywords.any(keyword='firstpost')).all()
-    SELECT posts.id AS posts_id, posts.user_id AS posts_user_id, posts.headline AS posts_headline, posts.body AS posts_body 
-    FROM posts 
-    WHERE ? = posts.user_id AND (EXISTS (SELECT 1 
-    FROM post_keywords, keywords 
-    WHERE posts.id = post_keywords.post_id AND keywords.id = post_keywords.keyword_id AND keywords.keyword = ?))
-    [2, 'firstpost']
-    {stop}[BlogPost("Wendy's Blog Post", 'This is a test', <User('wendy','Wendy Williams', 'foobar')>)]
-
-Or we can use Wendy's own `posts` relation, which is a "dynamic" relation, to query straight from there:
-
-    {python}
-    {sql}>>> wendy.posts.filter(BlogPost.keywords.any(keyword='firstpost')).all()
-    SELECT posts.id AS posts_id, posts.user_id AS posts_user_id, posts.headline AS posts_headline, posts.body AS posts_body 
-    FROM posts 
-    WHERE ? = posts.user_id AND (EXISTS (SELECT 1 
-    FROM post_keywords, keywords 
-    WHERE posts.id = post_keywords.post_id AND keywords.id = post_keywords.keyword_id AND keywords.keyword = ?))
-    [2, 'firstpost']
-    {stop}[BlogPost("Wendy's Blog Post", 'This is a test', <User('wendy','Wendy Williams', 'foobar')>)]
-
-## Further Reference 
-
-Generated Documentation for Query: [docstrings_sqlalchemy.orm.query_Query](rel:docstrings_sqlalchemy.orm.query_Query)
-
-ORM Generated Docs: [docstrings_sqlalchemy.orm](rel:docstrings_sqlalchemy.orm)
-
-Further information on mapping setups are in [advdatamapping](rel:advdatamapping).
-
-Further information on working with Sessions: [unitofwork](rel:unitofwork).
diff --git a/doc/build/oldcontent/plugins.txt b/doc/build/oldcontent/plugins.txt
deleted file mode 100644 (file)
index b0e6eed..0000000
+++ /dev/null
@@ -1,628 +0,0 @@
-Plugins  {@name=plugins}
-======================
-
-SQLAlchemy has a variety of extensions available which provide extra functionality to SA, either via explicit usage or by augmenting the core behavior.  Several of these extensions are designed to work together.
-
-### declarative
-
-**Author:** Mike Bayer<br/>
-**Version:** 0.4.4 or greater
-
-`declarative` intends to be a fully featured replacement for the very old `activemapper` extension.  Its goal is to redefine the organization of class, `Table`, and `mapper()` constructs such that they can all be defined "at once" underneath a class declaration.   Unlike `activemapper`, it does not redefine normal SQLAlchemy configurational semantics - regular `Column`, `relation()` and other schema or ORM constructs are used in almost all cases.
-
-`declarative` is a so-called "micro declarative layer"; it does not generate table or column names and requires almost as fully verbose a configuration as that of straight tables and mappers.  As an alternative, the [Elixir](http://elixir.ematia.de/) project is a full community-supported declarative layer for SQLAlchemy, and is recommended for its active-record-like semantics, its convention-based configuration, and plugin capabilities.
-
-SQLAlchemy object-relational configuration involves the usage of Table, mapper(), and class objects to define the three areas of configuration.
-declarative moves these three types of configuration underneath the individual mapped class. Regular SQLAlchemy schema and ORM constructs are used
-in most cases:
-
-    {python}
-    from sqlalchemy.ext.declarative import declarative_base
-    
-    Base = declarative_base()
-    
-    class SomeClass(Base):
-        __tablename__ = 'some_table'
-        id = Column('id', Integer, primary_key=True)
-        name =  Column('name', String(50))
-
-Above, the `declarative_base` callable produces a new base class from which all mapped classes inherit from. When the class definition is
-completed, a new `Table` and `mapper()` have been generated, accessible via the `__table__` and `__mapper__` attributes on the
-`SomeClass` class.
-
-You may omit the names from the Column definitions.  Declarative will fill
-them in for you:
-
-    {python}
-    class SomeClass(Base):
-        __tablename__ = 'some_table'
-        id = Column(Integer, primary_key=True)
-        name = Column(String(50))
-
-Attributes may be added to the class after its construction, and they will be added to the underlying `Table` and `mapper()` definitions as
-appropriate:
-
-    {python}
-    SomeClass.data = Column('data', Unicode)
-    SomeClass.related = relation(RelatedInfo)
-
-Classes which are mapped explicitly using `mapper()` can interact freely with declarative classes. 
-
-The `declarative_base` base class contains a `MetaData` object where newly defined `Table` objects are collected.  This is accessed via the ``metadata`` class level accessor, so to create tables we can say:
-
-    {python}
-    engine = create_engine('sqlite://')
-    Base.metadata.create_all(engine)
-
-The `Engine` created above may also be directly associated with the declarative base class using the `bind` keyword argument, where it will be associated with the underlying `MetaData` object and allow SQL operations involving that metadata and its tables to make use of that engine automatically:
-
-    {python}
-    Base = declarative_base(bind=create_engine('sqlite://'))
-
-Or, as `MetaData` allows, at any time using the `bind` attribute:
-
-    {python}
-    Base.metadata.bind = create_engine('sqlite://')
-The `declarative_base` can also receive a pre-created `MetaData` object, which allows a declarative setup to be associated with an already existing traditional collection of `Table` objects:
-
-    {python}
-    mymetadata = MetaData()
-    Base = declarative_base(metadata=mymetadata)
-
-Relations to other classes are done in the usual way, with the added feature that the class specified to `relation()` may be a string name. The
-"class registry" associated with `Base` is used at mapper compilation time to resolve the name into the actual class object, which is expected to
-have been defined once the mapper configuration is used:
-
-    {python}
-    class User(Base):
-        __tablename__ = 'users'
-
-        id = Column('id', Integer, primary_key=True)
-        name = Column('name', String(50))
-        addresses = relation("Address", backref="user")
-    
-    class Address(Base):
-        __tablename__ = 'addresses'
-
-        id = Column('id', Integer, primary_key=True)
-        email = Column('email', String(50))
-        user_id = Column('user_id', Integer, ForeignKey('users.id'))
-
-Column constructs, since they are just that, are immediately usable, as below where we define a primary join condition on the `Address` class
-using them:
-
-    {python}
-    class Address(Base)
-        __tablename__ = 'addresses'
-
-        id = Column('id', Integer, primary_key=True)
-        email = Column('email', String(50))
-        user_id = Column('user_id', Integer, ForeignKey('users.id'))
-        user = relation(User, primaryjoin=user_id==User.id)
-
-In addition to the main argument for `relation`, other arguments
-which depend upon the columns present on an as-yet undefined class
-may also be specified as strings.  These strings are evaluated as
-Python expressions.  The full namespace available within this 
-evaluation includes all classes mapped for this declarative base,
-as well as the contents of the `sqlalchemy` package, including 
-expression functions like `desc` and `func`:
-
-    {python}
-    class User(Base):
-        # ....
-        addresses = relation("Address", order_by="desc(Address.email)", 
-            primaryjoin="Address.user_id==User.id")
-
-As an alternative to string-based attributes, attributes may also be 
-defined after all classes have been created.  Just add them to the target
-class after the fact:
-
-    {python}
-    User.addresses = relation(Address, primaryjoin=Address.user_id==User.id)
-
-Synonyms are one area where `declarative` needs to slightly change the usual SQLAlchemy configurational syntax. To define a
-getter/setter which proxies to an underlying attribute, use `synonym` with the `descriptor` argument:
-
-    {python}
-    class MyClass(Base):
-        __tablename__ = 'sometable'
-        
-        _attr = Column('attr', String)
-        
-        def _get_attr(self):
-            return self._some_attr
-        def _set_attr(self, attr):
-            self._some_attr = attr
-        attr = synonym('_attr', descriptor=property(_get_attr, _set_attr))
-        
-The above synonym is then usable as an instance attribute as well as a class-level expression construct:
-
-    {python}
-    x = MyClass()
-    x.attr = "some value"
-    session.query(MyClass).filter(MyClass.attr == 'some other value').all()
-
-The `synonym_for` decorator can accomplish the same task:
-
-    {python}
-    class MyClass(Base):
-        __tablename__ = 'sometable'
-        
-        _attr = Column('attr', String)
-
-        @synonym_for('_attr')
-        @property
-        def attr(self):
-            return self._some_attr
-
-Similarly, `comparable_using` is a front end for the `comparable_property` ORM function:
-
-    {python}
-    class MyClass(Base):
-        __tablename__ = 'sometable'
-
-        name = Column('name', String)
-
-        @comparable_using(MyUpperCaseComparator)
-        @property
-        def uc_name(self):
-            return self.name.upper()
-
-As an alternative to `__tablename__`, a direct `Table` construct may be used.  The `Column` objects, which in this case require their names, will be added to the mapping just like a regular mapping to a table:
-
-
-    {python}
-    class MyClass(Base):
-        __table__ = Table('my_table', Base.metadata,
-            Column('id', Integer, primary_key=True),
-            Column('name', String(50))
-        )
-
-Other table-based attributes include `__table_args__`, which is
-either a dictionary as in:
-
-    {python}
-    class MyClass(Base)
-        __tablename__ = 'sometable'
-        __table_args__ = {'mysql_engine':'InnoDB'}
-
-or a dictionary-containing tuple in the form 
-`(arg1, arg2, ..., {kwarg1:value, ...})`, as in:
-
-    {python}
-    class MyClass(Base)
-        __tablename__ = 'sometable'
-        __table_args__ = (ForeignKeyConstraint(['id'], ['remote_table.id']), {'autoload':True})
-
-Mapper arguments are specified using the `__mapper_args__` class variable. Note that the column objects declared on the class are immediately
-usable, as in this joined-table inheritance example:
-
-    {python}
-    class Person(Base):
-        __tablename__ = 'people'
-        id = Column('id', Integer, primary_key=True)
-        discriminator = Column('type', String(50))
-        __mapper_args__ = {'polymorphic_on':discriminator}
-    
-    class Engineer(Person):
-        __tablename__ = 'engineers'
-        __mapper_args__ = {'polymorphic_identity':'engineer'}
-        id = Column('id', Integer, ForeignKey('people.id'), primary_key=True)
-        primary_language = Column('primary_language', String(50))
-        
-For single-table inheritance, the `__tablename__` and `__table__` class variables are optional on a class when the class inherits from another
-mapped class.
-
-As a convenience feature, the `declarative_base()` sets a default constructor on classes which takes keyword arguments, and assigns them to the
-named attributes:
-
-    {python}
-    e = Engineer(primary_language='python')
-
-Note that `declarative` has no integration built in with sessions, and is only intended as an optional syntax for the regular usage of mappers
-and Table objects. A typical application setup using `scoped_session` might look like:
-
-    {python}
-    engine = create_engine('postgres://scott:tiger@localhost/test')
-    Session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
-    Base = declarative_base()
-    
-Mapped instances then make usage of `Session` in the usual way.
-
-
-### associationproxy
-
-**Author:** Mike Bayer and Jason Kirtland<br/>
-**Version:** 0.3.1 or greater
-
-`associationproxy` is used to create a simplified, read/write view of a relationship.  It can be used to cherry-pick fields from a collection of related objects or to greatly simplify access to associated objects in an association relationship.
-
-#### Simplifying Relations
-
-Consider this "association object" mapping:
-
-    {python}
-    users_table = Table('users', metadata,
-        Column('id', Integer, primary_key=True),
-        Column('name', String(64)),
-    )
-
-    keywords_table = Table('keywords', metadata,
-        Column('id', Integer, primary_key=True),
-        Column('keyword', String(64))
-    )
-
-    userkeywords_table = Table('userkeywords', metadata,
-        Column('user_id', Integer, ForeignKey("users.id"),
-               primary_key=True),
-        Column('keyword_id', Integer, ForeignKey("keywords.id"),
-               primary_key=True)
-    )
-
-    class User(object):
-        def __init__(self, name):
-            self.name = name
-
-    class Keyword(object):
-        def __init__(self, keyword):
-            self.keyword = keyword
-
-    mapper(User, users_table, properties={
-        'kw': relation(Keyword, secondary=userkeywords_table)
-        })
-    mapper(Keyword, keywords_table)
-
-Above are three simple tables, modeling users, keywords and a many-to-many relationship between the two.  These ``Keyword`` objects are little more than a container for a name, and accessing them via the relation is awkward:
-
-    {python}
-    user = User('jek')
-    user.kw.append(Keyword('cheese inspector'))
-    print user.kw
-    # [<__main__.Keyword object at 0xb791ea0c>]
-    print user.kw[0].keyword
-    # 'cheese inspector'
-    print [keyword.keyword for keyword in user.kw]
-    # ['cheese inspector']
-
-With ``association_proxy`` you have a "view" of the relation that contains just the `.keyword` of the related objects.  The proxy is a Python property, and unlike the mapper relation, is defined in your class:
-
-    {python}
-    from sqlalchemy.ext.associationproxy import association_proxy
-
-    class User(object):
-        def __init__(self, name):
-            self.name = name
-
-        # proxy the 'keyword' attribute from the 'kw' relation
-        keywords = association_proxy('kw', 'keyword')
-
-    # ...
-    >>> user.kw
-    [<__main__.Keyword object at 0xb791ea0c>]
-    >>> user.keywords
-    ['cheese inspector']
-    >>> user.keywords.append('snack ninja')
-    >>> user.keywords
-    ['cheese inspector', 'snack ninja']
-    >>> user.kw
-    [<__main__.Keyword object at 0x9272a4c>, <__main__.Keyword object at 0xb7b396ec>]
-
-The proxy is read/write.  New associated objects are created on demand when values are added to the proxy, and modifying or removing an entry through the proxy also affects the underlying collection.
-
-- The association proxy property is backed by a mapper-defined relation, either a collection or scalar.
-- You can access and modify both the proxy and the backing relation. Changes in one are immediate in the other.
-- The proxy acts like the type of the underlying collection.  A list gets a list-like proxy, a dict a dict-like proxy, and so on.
-- Multiple proxies for the same relation are fine.
-- Proxies are lazy, and won't trigger a load of the backing relation until they are accessed.
-- The relation is inspected to determine the type of the related objects.
-- To construct new instances, the type is called with the value being assigned, or key and value for dicts.
-- A ``creator`` function can be used to create instances instead.
-
-Above, the ``Keyword.__init__`` takes a single argument ``keyword``, which maps conveniently to the value being set through the proxy.  A ``creator`` function could have been used instead if more flexibility was required.
-
-Because the proxies are backed a regular relation collection, all of the usual hooks and patterns for using collections are still in effect.  The most convenient behavior is the automatic setting of "parent"-type relationships on assignment.  In the example above, nothing special had to be done to associate the Keyword to the User.  Simply adding it to the collection is sufficient.
-
-#### Simplifying Association Object Relations
-
-Association proxies are also useful for keeping [association objects](rel:datamapping_association) out the way during regular use.  For example, the  ``userkeywords`` table might have a bunch of auditing columns that need to get updated when changes are made- columns that are updated but seldom, if ever, accessed in your application.  A proxy can provide a very natural access pattern for the relation.
-
-    {python}
-    from sqlalchemy.ext.associationproxy import association_proxy
-
-    # users_table and keywords_table tables as above, then:
-
-    def get_current_uid():
-        """Return the uid of the current user."""
-        return 1  # hardcoded for this example
-
-    userkeywords_table = Table('userkeywords', metadata,
-        Column('user_id', Integer, ForeignKey("users.id"), primary_key=True),
-        Column('keyword_id', Integer, ForeignKey("keywords.id"), primary_key=True),
-        # add some auditing columns
-        Column('updated_at', DateTime, default=datetime.now),
-        Column('updated_by', Integer, default=get_current_uid, onupdate=get_current_uid),
-    )
-
-    def _create_uk_by_keyword(keyword):
-        """A creator function."""
-        return UserKeyword(keyword=keyword)
-
-    class User(object):
-        def __init__(self, name):
-            self.name = name
-        keywords = association_proxy('user_keywords', 'keyword', creator=_create_uk_by_keyword)
-
-    class Keyword(object):
-        def __init__(self, keyword):
-            self.keyword = keyword
-        def __repr__(self):
-            return 'Keyword(%s)' % repr(self.keyword)
-
-    class UserKeyword(object):
-        def __init__(self, user=None, keyword=None):
-            self.user = user
-            self.keyword = keyword
-
-    mapper(User, users_table)
-    mapper(Keyword, keywords_table)
-    mapper(UserKeyword, userkeywords_table, properties={
-        'user': relation(User, backref='user_keywords'),
-        'keyword': relation(Keyword),
-    })
-
-    user = User('log')
-    kw1  = Keyword('new_from_blammo')
-
-    # Adding a Keyword requires creating a UserKeyword association object
-    user.user_keywords.append(UserKeyword(user, kw1))
-
-    # And accessing Keywords requires traversing UserKeywords
-    print user.user_keywords[0]
-    # <__main__.UserKeyword object at 0xb79bbbec>
-
-    print user.user_keywords[0].keyword
-    # Keyword('new_from_blammo')
-
-    # Lots of work.
-
-    # It's much easier to go through the association proxy!
-    for kw in (Keyword('its_big'), Keyword('its_heavy'), Keyword('its_wood')):
-        user.keywords.append(kw)
-
-    print user.keywords
-    # [Keyword('new_from_blammo'), Keyword('its_big'), Keyword('its_heavy'), Keyword('its_wood')]
-
-
-#### Building Complex Views
-
-    {python}
-    stocks = Table("stocks", meta,
-       Column('symbol', String(10), primary_key=True),
-       Column('description', String(100), nullable=False),
-       Column('last_price', Numeric)
-    )
-
-    brokers = Table("brokers", meta,
-       Column('id', Integer,primary_key=True),
-       Column('name', String(100), nullable=False)
-    )
-
-    holdings = Table("holdings", meta,
-      Column('broker_id', Integer, ForeignKey('brokers.id'), primary_key=True),
-      Column('symbol', String(10), ForeignKey('stocks.symbol'), primary_key=True),
-      Column('shares', Integer)
-    )
-
-Above are three tables, modeling stocks, their brokers and the number of shares of a stock held by each broker.  This situation is quite different from the association example above.  `shares` is a _property of the relation_, an important one that we need to use all the time.
-
-For this example, it would be very convenient if `Broker` objects had a dictionary collection that mapped `Stock` instances to the shares held for each.  That's easy.
-
-    {python}
-    from sqlalchemy.ext.associationproxy import association_proxy
-    from sqlalchemy.orm.collections import attribute_mapped_collection
-
-    def _create_holding(stock, shares):
-        """A creator function, constructs Holdings from Stock and share quantity."""
-        return Holding(stock=stock, shares=shares)
-
-    class Broker(object):
-        def __init__(self, name):
-            self.name = name
-
-        holdings = association_proxy('by_stock', 'shares', creator=_create_holding)
-
-    class Stock(object):
-        def __init__(self, symbol, description=None):
-            self.symbol = symbol
-            self.description = description
-            self.last_price = 0
-
-    class Holding(object):
-        def __init__(self, broker=None, stock=None, shares=0):
-            self.broker = broker
-            self.stock = stock
-            self.shares = shares
-
-    mapper(Stock, stocks_table)
-    mapper(Broker, brokers_table, properties={
-        'by_stock': relation(Holding,
-            collection_class=attribute_mapped_collection('stock'))
-    })
-    mapper(Holding, holdings_table, properties={
-        'stock': relation(Stock),
-        'broker': relation(Broker)
-    })
-
-Above, we've set up the 'by_stock' relation collection to act as a dictionary, using the `.stock` property of each Holding as a key.
-
-Populating and accessing that dictionary manually is slightly inconvenient because of the complexity of the Holdings association object:
-
-    {python}
-    stock = Stock('ZZK')
-    broker = Broker('paj')
-
-    broker.holdings[stock] = Holding(broker, stock, 10)
-    print broker.holdings[stock].shares
-    # 10
-
-The `by_stock` proxy we've added to the `Broker` class hides the details of the `Holding` while also giving access to `.shares`:
-
-    {python}
-    for stock in (Stock('JEK'), Stock('STPZ')):
-        broker.holdings[stock] = 123
-
-    for stock, shares in broker.holdings.items():
-        print stock, shares
-
-    # lets take a peek at that holdings_table after committing changes to the db
-    print list(holdings_table.select().execute())
-    # [(1, 'ZZK', 10), (1, 'JEK', 123), (1, 'STEPZ', 123)]
-
-Further examples can be found in the `examples/` directory in the SQLAlchemy distribution.
-
-The `association_proxy` convenience function is not present in SQLAlchemy versions 0.3.1 through 0.3.7, instead instantiate the class directly:
-
-    {python}
-    from sqlalchemy.ext.associationproxy import AssociationProxy
-
-    class Article(object):
-       keywords = AssociationProxy('keyword_associations', 'keyword')
-
-
-### orderinglist
-
-**Author:** Jason Kirtland
-
-`orderinglist` is a helper for mutable ordered relations.  It will intercept
-list operations performed on a relation collection and automatically
-synchronize changes in list position with an attribute on the related objects.
-(See [advdatamapping_properties_entitycollections](rel:advdatamapping_properties_customcollections) for more information on the general pattern.)
-
-Example: Two tables that store slides in a presentation.  Each slide
-has a number of bullet points, displayed in order by the 'position'
-column on the bullets table.  These bullets can be inserted and re-ordered
-by your end users, and you need to update the 'position' column of all
-affected rows when changes are made.
-
-    {python}
-    slides_table = Table('Slides', metadata,
-                         Column('id', Integer, primary_key=True),
-                         Column('name', String))
-
-    bullets_table = Table('Bullets', metadata,
-                          Column('id', Integer, primary_key=True),
-                          Column('slide_id', Integer, ForeignKey('Slides.id')),
-                          Column('position', Integer),
-                          Column('text', String))
-
-     class Slide(object):
-         pass
-     class Bullet(object):
-         pass
-
-     mapper(Slide, slides_table, properties={
-           'bullets': relation(Bullet, order_by=[bullets_table.c.position])
-     })
-     mapper(Bullet, bullets_table)
-
-The standard relation mapping will produce a list-like attribute on each Slide
-containing all related Bullets, but coping with changes in ordering is totally
-your responsibility.  If you insert a Bullet into that list, there is no
-magic- it won't have a position attribute unless you assign it it one, and
-you'll need to manually renumber all the subsequent Bullets in the list to
-accommodate the insert.
-
-An `orderinglist` can automate this and manage the 'position' attribute on all
-related bullets for you.
-
-    {python}        
-    mapper(Slide, slides_table, properties={
-           'bullets': relation(Bullet,
-                               collection_class=ordering_list('position'),
-                               order_by=[bullets_table.c.position])
-    })
-    mapper(Bullet, bullets_table)
-
-    s = Slide()
-    s.bullets.append(Bullet())
-    s.bullets.append(Bullet())
-    s.bullets[1].position
-    >>> 1
-    s.bullets.insert(1, Bullet())
-    s.bullets[2].position
-    >>> 2
-
-Use the `ordering_list` function to set up the `collection_class` on relations
-(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 relation.
-
-`ordering_list` takes the name of the related object's ordering attribute as
-an argument.  By default, the zero-based integer index of the object's
-position in the `ordering_list` is synchronized with the ordering attribute:
-index 0 will get position 0, index 1 position 1, etc.  To start numbering at 1
-or some other integer, provide `count_from=1`.
-
-Ordering values are not limited to incrementing integers.  Almost any scheme
-can implemented by supplying a custom `ordering_func` that maps a Python list
-index to any value you require.  See the [module
-documentation](rel:docstrings_sqlalchemy.ext.orderinglist) for more
-information, and also check out the unit tests for examples of stepped
-numbering, alphabetical and Fibonacci numbering.
-
-### serializer
-
-**Author:** Mike Bayer
-
-Serializer/Deserializer objects for usage with SQLAlchemy structures.
-
-Any SQLAlchemy structure, including Tables, Columns, expressions, mappers,
-Query objects etc. can be serialized in a minimally-sized format,
-and deserialized when given a Metadata and optional ScopedSession object
-to use as context on the way out.
-
-Usage is nearly the same as that of the standard Python pickle module:
-
-    {python}
-    from sqlalchemy.ext.serializer import loads, dumps
-    metadata = MetaData(bind=some_engine)
-    Session = scoped_session(sessionmaker())
-    
-    # ... define mappers
-    
-    query = Session.query(MyClass).filter(MyClass.somedata=='foo').order_by(MyClass.sortkey)
-    
-    # pickle the query
-    serialized = dumps(query)
-    
-    # unpickle.  Pass in metadata + scoped_session
-    query2 = loads(serialized, metadata, Session)
-    
-    print query2.all()
-
-Similar restrictions as when using raw pickle apply; mapped classes must be 
-themselves be pickleable, meaning they are importable from a module-level
-namespace.
-
-Note that instances of user-defined classes do not require this extension
-in order to be pickled; these contain no references to engines, sessions
-or expression constructs in the typical case and can be serialized directly.
-This module is specifically for ORM and expression constructs.
-
-### SqlSoup
-
-**Author:** Jonathan Ellis
-
-SqlSoup creates mapped classes on the fly from tables, which are automatically reflected from the database based on name.  It is essentially a nicer version of the "row data gateway" pattern.
-
-    {python}
-    >>> from sqlalchemy.ext.sqlsoup import SqlSoup
-    >>> soup = SqlSoup('sqlite:///')
-
-    >>> db.users.select(order_by=[db.users.c.name])
-    [MappedUsers(name='Bhargan Basepair',email='basepair@example.edu',password='basepair',classname=None,admin=1),
-     MappedUsers(name='Joe Student',email='student@example.edu',password='student',classname=None,admin=0)]
-
-Full SqlSoup documentation is on the [SQLAlchemy Wiki](http://www.sqlalchemy.org/trac/wiki/SqlSoup).
-
diff --git a/doc/build/oldcontent/pooling.txt b/doc/build/oldcontent/pooling.txt
deleted file mode 100644 (file)
index d12e029..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-.. _pooling:
-
-==================
-Connection Pooling
-==================
-
-This section describes the connection pool module of SQLAlchemy.  The `Pool` object it provides is normally embedded within an `Engine` instance.  For most cases, explicit access to the pool module is not required.  However, the `Pool` object can be used on its own, without the rest of SA, to manage DBAPI connections; this section describes that usage.  Also, this section will describe in more detail how to customize the pooling strategy used by an `Engine`.
-
-At the base of any database helper library is a system of efficiently acquiring connections to the database.  Since the establishment of a database connection is typically a somewhat expensive operation, an application needs a way to get at database connections repeatedly without incurring the full overhead each time.  Particularly for server-side web applications, a connection pool is the standard way to maintain a "pool" of database connections which are used over and over again among many requests.  Connection pools typically are configured to maintain a certain "size", which represents how many connections can be used simultaneously without resorting to creating more newly-established connections.
-
-### Establishing a Transparent Connection Pool {@name=establishing}
-
-Any DBAPI module can be "proxied" through the connection pool using the following technique (note that the usage of 'psycopg2' is **just an example**; substitute whatever DBAPI module you'd like):
-    
-    {python}
-    import sqlalchemy.pool as pool
-    import psycopg2 as psycopg
-    psycopg = pool.manage(psycopg)
-    
-    # then connect normally
-    connection = psycopg.connect(database='test', username='scott', password='tiger')
-
-This produces a `sqlalchemy.pool.DBProxy` object which supports the same `connect()` function as the original DBAPI module.  Upon connection, a connection proxy object is returned, which delegates its calls to a real DBAPI connection object.  This connection object is stored persistently within a connection pool (an instance of `sqlalchemy.pool.Pool`) that corresponds to the exact connection arguments sent to the `connect()` function.  
-
-The connection proxy supports all of the methods on the original connection object, most of which are proxied via `__getattr__()`.  The `close()` method will return the connection to the pool, and the `cursor()` method will return a proxied cursor object.  Both the connection proxy and the cursor proxy will also return the underlying connection to the pool after they have both been garbage collected, which is detected via the `__del__()` method.
-
-Additionally, when connections are returned to the pool, a `rollback()` is issued on the connection unconditionally.  This is to release any locks still held by the connection that may have resulted from normal activity.
-
-By default, the `connect()` method will return the same connection that is already checked out in the current thread.  This allows a particular connection to be used in a given thread without needing to pass it around between functions.  To disable this behavior, specify `use_threadlocal=False` to the `manage()` function.
-
-### Connection Pool Configuration {@name=configuration}
-
-For all types of Pool construction, which includes the "transparent proxy" described in the previous section, using an `Engine` via `create_engine()`, or constructing a pool through direct class instantiation, the options are generally the same.  Additional options may be available based on the specific subclass of `Pool` being used.
-
-For a description of all pool classes, see the [generated documentation](rel:docstrings_sqlalchemy.pool).
-
-Common options include:
-
- * echo=False : if set to True, connections being pulled and retrieved from/to the pool will
-   be logged to the standard output, as well as pool sizing information.  Echoing can also
-   be achieved by enabling logging for the "sqlalchemy.pool" namespace.  When using create_engine(), 
-   this option is specified as `echo_pool`.
- * use_threadlocal=False : if set to True, repeated calls to connect() within the same
-   application thread will be guaranteed to return the same connection object, if one has
-   already been retrieved from the pool and has not been returned yet. This allows code to
-   retrieve a connection from the pool, and then while still holding on to that connection,
-   to call other functions which also ask the pool for a connection of the same arguments;
-   those functions will act upon the same connection that the calling method is using.
-   This option is overridden during `create_engine()`, corresponding to the "plain" or 
-   "threadlocal" connection strategy.
- * recycle=-1 : if set to non -1, a number of seconds between connection recycling, which
-   means upon checkout, if this timeout is surpassed the connection will be closed and replaced
-   with a newly opened connection.
-
-QueuePool options include:
-
- * pool_size=5 : the size of the pool to be maintained. This is the
- largest number of connections that will be kept persistently in the pool. Note that the
- pool begins with no connections; once this number of connections is requested, that
- number of connections will remain.
- * max_overflow=10 : the maximum overflow size of the pool. When the number of checked-out
- connections reaches the size set in pool_size, additional connections will be returned up
- to this limit. When those additional connections are returned to the pool, they are
- disconnected and discarded. It follows then that the total number of simultaneous
- connections the pool will allow is pool_size + max_overflow, and the total number of
- "sleeping" connections the pool will allow is pool_size. max_overflow can be set to -1 to
- indicate no overflow limit; no limit will be placed on the total number of concurrent
- connections.
- * timeout=30 : the number of seconds to wait before giving up on returning a connection
-### Custom Pool Construction {@name=custom}
-
-Besides using the transparent proxy, instances of `sqlalchemy.pool.Pool` can be created directly.  Constructing your own pool involves passing a callable used to create a connection.  Through this method, custom connection schemes can be made, such as a connection that automatically executes some initialization commands to start.  
-
-    {python title="Constructing a QueuePool"}
-    import sqlalchemy.pool as pool
-    import psycopg2
-    
-    def getconn():
-        c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
-        # execute an initialization function on the connection before returning
-        c.cursor.execute("setup_encodings()")
-        return c
-        
-    p = pool.QueuePool(getconn, max_overflow=10, pool_size=5, use_threadlocal=True)
-    
-Or with SingletonThreadPool:
-
-    {python title="Constructing a SingletonThreadPool"}
-    import sqlalchemy.pool as pool
-    import sqlite
-    
-    def getconn():
-        return sqlite.connect(filename='myfile.db')
-    
-    # SQLite connections require the SingletonThreadPool    
-    p = pool.SingletonThreadPool(getconn)
-    
diff --git a/doc/build/oldcontent/session.txt b/doc/build/oldcontent/session.txt
deleted file mode 100644 (file)
index 41b167e..0000000
+++ /dev/null
@@ -1,680 +0,0 @@
-Using the Session {@name=unitofwork}
-============
-
-The [Mapper](rel:advdatamapping) is the entrypoint to the configurational API of the SQLAlchemy object relational mapper.  But the primary object one works with when using the ORM is the [Session](rel:docstrings_sqlalchemy.orm.session_Session).
-
-## What does the Session do ?
-
-In the most general sense, the `Session` establishes all conversations with the database and represents a "holding zone" for all the mapped instances which you've loaded or created during its lifespan.  It implements the [Unit of Work](http://martinfowler.com/eaaCatalog/unitOfWork.html) pattern, which means it keeps track of all changes which occur, and is capable of **flushing** those changes to the database as appropriate.   Another important facet of the `Session` is that it's also maintaining **unique** copies of each instance, where "unique" means "only one object with a particular primary key" - this pattern is called the [Identity Map](http://martinfowler.com/eaaCatalog/identityMap.html).
-
-Beyond that, the `Session` implements an interface which lets you move objects in or out of the session in a variety of ways, it provides the entryway to a `Query` object which is used to query the database for data, and it also provides a transactional context for SQL operations which rides on top of the transactional capabilities of `Engine` and `Connection` objects.
-
-## Getting a Session
-
-`Session` is a regular Python class which can be directly instantiated.  However, to standardize how sessions are configured and acquired, the `sessionmaker()` function is normally used to create a top level `Session` configuration which can then be used throughout an application without the need to repeat the configurational arguments.
-
-### Using a sessionmaker() Configuration {@name=sessionmaker}
-
-The usage of `sessionmaker()` is illustrated below:
-
-    {python}
-    from sqlalchemy.orm import sessionmaker
-    
-    # create a configured "Session" class
-    Session = sessionmaker(bind=some_engine)
-
-    # create a Session
-    session = Session()
-    
-    # work with sess
-    myobject = MyObject('foo', 'bar')
-    session.add(myobject)
-    session.commit()
-    
-    # close when finished
-    session.close()
-
-Above, the `sessionmaker` call creates a class for us, which we assign to the name `Session`.  This class is a subclass of the actual `sqlalchemy.orm.session.Session` class, which will instantiate with a particular bound engine.
-
-When you write your application, place the call to `sessionmaker()` somewhere global, and then make your new `Session` class available to the rest of your application.
-
-### Binding Session to an Engine {@name=binding}
-
-In our previous example regarding `sessionmaker()`, we specified a `bind` for a particular `Engine`.  If we'd like to construct a `sessionmaker()` without an engine available and bind it later on, or to specify other options to an existing `sessionmaker()`, we may use the `configure()` method:
-
-    {python}
-    # configure Session class with desired options
-    Session = sessionmaker()
-
-    # later, we create the engine
-    engine = create_engine('postgres://...')
-    
-    # associate it with our custom Session class
-    Session.configure(bind=engine)
-
-    # work with the session
-    session = Session()
-
-It's actually entirely optional to bind a Session to an engine.  If the underlying mapped `Table` objects use "bound" metadata, the `Session` will make use of the bound engine instead (or will even use multiple engines if multiple binds are present within the mapped tables).  "Bound" metadata is described at [metadata_tables_binding](rel:metadata_tables_binding).
-
-The `Session` also has the ability to be bound to multiple engines explicitly.   Descriptions of these scenarios are described in [unitofwork_partitioning](rel:unitofwork_partitioning).
-
-### Binding Session to a Connection {@name=connection}
-
-The `Session` can also be explicitly bound to an individual database `Connection`.  Reasons for doing this may include to join a `Session` with an ongoing transaction local to a specific `Connection` object, or to bypass connection pooling by just having connections persistently checked out and associated with distinct, long running sessions:
-
-    {python}
-    # global application scope.  create Session class, engine
-    Session = sessionmaker()
-
-    engine = create_engine('postgres://...')
-    
-    ...
-    
-    # local scope, such as within a controller function
-    
-    # connect to the database
-    connection = engine.connect()
-    
-    # bind an individual Session to the connection
-    session = Session(bind=connection)
-
-### Using create_session() {@name=createsession}
-
-As an alternative to `sessionmaker()`, `create_session()` is a function which calls the normal `Session` constructor directly.  All arguments are passed through and the new `Session` object is returned:
-
-    {python}
-    session = create_session(bind=myengine, autocommit=True, autoflush=False)
-
-Note that `create_session()` disables all optional "automation" by default.  Called with no arguments, the session produced is not autoflushing, does not auto-expire, and does not maintain a transaction (i.e. it begins and commits a new transaction for each `flush()`).  SQLAlchemy uses `create_session()` extensively within its own unit tests.
-
-### Configurational Arguments {@name=configuration}
-
-Configurational arguments accepted by `sessionmaker()` and `create_session()` are the same as that of the `Session` class itself, and are described at [docstrings_sqlalchemy.orm_modfunc_sessionmaker](rel:docstrings_sqlalchemy.orm_modfunc_sessionmaker).
-
-Note that the defaults of `create_session()` are the opposite of that of `sessionmaker()`: autoflush and expire_on_commit are False, autocommit is True. It is recommended to use the `sessionmaker()` function instead of `create_session()`. `create_session()` is used to get a session with no automation turned on and is useful for testing.
-
-## Using the Session 
-
-### Quickie Intro to Object States {@name=states}
-
-It's helpful to know the states which an instance can have within a session:
-
-* *Transient* - an instance that's not in a session, and is not saved to the database; i.e. it has no database identity.  The only relationship such an object has to the ORM is that its class has a `mapper()` associated with it.
-
-* *Pending* - when you `add()` a transient instance, it becomes pending.  It still wasn't actually flushed to the database yet, but it will be when the next flush occurs.
-
-* *Persistent* - An instance which is present in the session and has a record in the database.  You get persistent instances by either flushing so that the pending instances become persistent, or by querying the database for existing instances (or moving persistent instances from other sessions into your local session).
-
-* *Detached* - an instance which has a record in the database, but is not in any session.  There's nothing wrong with this, and you can use objects normally when they're detached, **except** they will not be able to issue any SQL in order to load collections or attributes which are not yet loaded, or were marked as "expired".
-
-Knowing these states is important, since the `Session` tries to be strict about ambiguous operations (such as trying to save the same object to two different sessions at the same time).
-
-### Frequently Asked Questions {@name=faq}
-
-* When do I make a `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 application has three .py files in a package, you could, for example, place the `sessionmaker` line in your `__init__.py` file; from that point on your other modules say "from mypackage import Session".   That way, everyone else just uses `Session()`, and the configuration of that session is controlled by that central point.
-
-    If your application starts up, does imports, but does not know what database it's going to be connecting to, you can bind the `Session` at the "class" level to the engine later on, using `configure()`.
-
-    In the examples in this section, we will frequently show the `sessionmaker` being created right above the line where we actually invoke `Session()`.  But that's just for example's sake !  In reality, the `sessionmaker` would be somewhere at the module level, and your individual `Session()` calls would be sprinkled all throughout your app, such as in a web application within each controller method.
-
-* When do I make a `Session` ? 
-
-    You typically invoke `Session()` when you first need to talk to your database, and want to save some objects or load some existing ones.  Then, you work with it, save your changes, and then dispose of it....or at the very least `close()` it.  It's not a "global" kind of object, and should be handled more like a "local variable", as it's generally **not** safe to use with concurrent threads.  Sessions are very inexpensive to make, and don't use any resources whatsoever until they are first used...so create some !
-
-    There is also a pattern whereby you're using a **contextual session**, this is described later in [unitofwork_contextual](rel:unitofwork_contextual).  In this pattern, a helper object is maintaining a `Session` for you, most commonly one that is local to the current thread (and sometimes also local to an application instance).  SQLAlchemy has worked this pattern out such that it still *looks* like you're creating a new session as you need one...so in that case, it's still a guaranteed win to just say `Session()` whenever you want a session.  
-
-* Is the Session a cache ? 
-
-    Yeee...no.  It's somewhat used as a cache, in that it implements the identity map pattern, and stores objects keyed to their primary key.  However, it doesn't do any kind of query caching.  This means, if you say `session.query(Foo).filter_by(name='bar')`, even if `Foo(name='bar')` is right there, in the identity map, the session has no idea about that.  It has to issue SQL to the database, get the rows back, and then when it sees the primary key in the row, *then* it can look in the local identity map and see that the object is already there.  It's only when you say `query.get({some primary key})` that the `Session` doesn't have to issue a query.
-    
-    Additionally, the Session stores object instances using a weak reference by default.  This also defeats the purpose of using the Session as a cache, unless the `weak_identity_map` flag is set to `False`.
-
-    The `Session` is not designed to be a global object from which everyone consults as a "registry" of objects.  That is the job of a **second level cache**.  A good library for implementing second level caching is [Memcached](http://www.danga.com/memcached/).  It *is* possible to "sort of" use the `Session` in this manner, if you set it to be non-transactional and it never flushes any SQL, but it's not a terrific solution,  since if concurrent threads load the same objects at the same time, you may have multiple copies of the same objects present in collections.
-
-* How can I get the `Session` for a certain object ?
-
-    Use the `object_session()` classmethod available on `Session`:
-    
-        {python}
-        session = Session.object_session(someobject)
-
-* Is the session threadsafe ?
-
-    Nope.  It has no thread synchronization of any kind built in, and particularly when you do a flush operation, it definitely is not open to concurrent threads accessing it, because it holds onto a single database connection at that point.  If you use a session which is non-transactional for read operations only, it's still not thread-"safe", but you also wont get any catastrophic failures either, since it opens and closes connections on an as-needed basis; it's just that different threads might load the same objects independently of each other, but only one will wind up in the identity map (however, the other one might still live in a collection somewhere).
-
-    But the bigger point here is, you should not *want* to use the session with multiple concurrent threads.  That would be like having everyone at a restaurant all eat from the same plate.  The session is a local "workspace" that you use for a specific set of tasks; you don't want to, or need to, share that session with other threads who are doing some other task.  If, on the other hand, there are other threads  participating in the same task you are, such as in a desktop graphical application, then you would be sharing the session with those threads, but you also will have implemented a proper locking scheme (or your graphical framework does) so that those threads do not collide.
-  
-### Querying
-
-The `query()` function takes one or more *entities* and returns a new `Query` object which will issue mapper queries within the context of this Session.  An entity is defined as a mapped class, a `Mapper` object, an orm-enabled *descriptor*, or an `AliasedClass` object.
-
-    {python}
-    # query from a class
-    session.query(User).filter_by(name='ed').all()
-
-    # query with multiple classes, returns tuples
-    session.query(User, Address).join('addresses').filter_by(name='ed').all()
-
-    # query using orm-enabled descriptors
-    session.query(User.name, User.fullname).all()
-    
-    # query from a mapper
-    user_mapper = class_mapper(User)
-    session.query(user_mapper)
-
-When `Query` returns results, each object instantiated is stored within the identity map.   When a row matches an object which is already present, the same object is returned.  In the latter case, whether or not the row is populated onto an existing object depends upon whether the attributes of the instance have been *expired* or not.  As of 0.5, a default-configured `Session` automatically expires all instances along transaction boundaries, so that with a normally isolated transaction, there shouldn't be any issue of instances representing data which is stale with regards to the current transaction.
-
-### Adding New or Existing Items
-
-`add()` is used to place instances in the session.  For *transient* (i.e. brand new) instances, this will have the effect of an INSERT taking place for those instances upon the next flush.  For instances which are *persistent* (i.e. were loaded by this session), they are already present and do not need to be added.  Instances which are *detached* (i.e. have been removed from a session) may be re-associated with a session using this method:
-
-    {python}
-    user1 = User(name='user1')
-    user2 = User(name='user2')
-    session.add(user1)
-    session.add(user2)
-    
-    session.commit()     # write changes to the database
-
-To add a list of items to the session at once, use `add_all()`:
-
-    {python}
-    session.add_all([item1, item2, item3])
-
-The `add()` operation **cascades** along the `save-update` cascade.  For more details see the section [unitofwork_cascades](rel:unitofwork_cascades).
-
-### Merging
-
-`merge()` reconciles the current state of an instance and its associated children with existing data in the database, and returns a copy of the instance associated with the session.  Usage is as follows:
-
-    {python}
-    merged_object = session.merge(existing_object)
-
-When given an instance, it follows these steps:
-
-  * It examines the primary key of the instance.  If it's present, it attempts to load an instance with that primary key (or pulls from the local identity map).
-  * If there's no primary key on the given instance, or the given primary key does not exist in the database, a new instance is created.
-  * The state of the given instance is then copied onto the located/newly created instance.
-  * The operation is cascaded to associated child items along the `merge` cascade.  Note that all changes present on the given instance, including changes to collections, are merged.
-  * The new instance is returned.
-
-With `merge()`, the given instance is not placed within the session, and can be associated with a different session or detached.  `merge()` is very useful for taking the state of any kind of object structure without regard for its origins or current session associations and placing that state within a session.   Here's two examples:
-
-  * An application which reads an object structure from a file and wishes to save it to the database might parse the file, build up the structure, and then use `merge()` to save it to the database, ensuring that the data within the file is used to formulate the primary key of each element of the structure.  Later, when the file has changed, the same process can be re-run, producing a slightly different object structure, which can then be `merged()` in again, and the `Session` will automatically update the database to reflect those changes.
-  * A web application stores mapped entities within an HTTP session object.  When each request starts up, the serialized data can be merged into the session, so that the original entity may be safely shared among requests and threads.
-
-`merge()` is frequently used by applications which implement their own second level caches.  This refers to an application which uses an in memory dictionary, or an tool like Memcached to store objects over long running spans of time.  When such an object needs to exist within a `Session`, `merge()` is a good choice since it leaves the original cached object untouched.  For this use case, merge provides a keyword option called `dont_load=True`.  When this boolean flag is set to `True`, `merge()` will not issue any SQL to reconcile the given object against the current state of the database, thereby reducing query overhead.   The limitation is that the given object and all of its children may not contain any pending changes, and it's also of course possible that newer information in the database will not be present on the merged object, since no load is issued.
-
-### Deleting
-
-The `delete` method places an instance into the Session's list of objects to be marked as deleted:
-
-    {python}
-    # mark two objects to be deleted
-    session.delete(obj1)
-    session.delete(obj2)
-
-    # commit (or flush)
-    session.commit()
-
-The big gotcha with `delete()` is that **nothing is removed from collections**.  Such as, if a `User` has a collection of three `Addresses`, deleting an `Address` will not remove it from `user.addresses`:
-
-    {python}
-    >>> address = user.addresses[1]
-    >>> session.delete(address)
-    >>> session.flush()
-    >>> address in user.addresses
-    True
-
-The solution is to use proper cascading:
-
-    {python}
-    mapper(User, users_table, properties={
-        'addresses':relation(Address, cascade="all, delete, delete-orphan")
-    })
-    del user.addresses[1]
-    session.flush()
-
-### Flushing
-
-When the `Session` is used with its default configuration, the flush step is nearly always done transparently.  Specifically, the flush occurs before any individual `Query` is issued, as well as within the `commit()` call before the transaction is committed.  It also occurs before a SAVEPOINT is issued when `begin_nested()` is used.  The "flush-on-Query" aspect of the behavior can be disabled by constructing `sessionmaker()` with the flag `autoflush=False`.
-
-Regardless of the autoflush setting, a flush can always be forced by issuing `flush()`:
-    
-    {python}
-    session.flush()
-    
-`flush()` also supports the ability to flush a subset of objects which are present in the session, by passing a list of objects:
-
-    {python}
-    # saves only user1 and address2.  all other modified
-    # objects remain present in the session.
-    session.flush([user1, address2])
-    
-This second form of flush should be used carefully as it currently does not cascade, meaning that it will not necessarily affect other objects directly associated with the objects given.
-
-The flush process *always* occurs within a transaction, even if the `Session` has been configured with `autocommit=True`, a setting that disables the session's persistent transactional state.  If no transaction is present, `flush()` creates its own transaction and commits it.  Any failures during flush will always result in a rollback of whatever transaction is present.
-
-### Committing
-
-`commit()` is used to commit the current transaction.  It always issues `flush()` beforehand to flush any remaining state to the database; this is independent of the "autoflush" setting.   If no transaction is present, it raises an error.  Note that the default behavior of the `Session` is that a transaction is always present; this behavior can be disabled by setting `autocommit=True`.  In autocommit mode, a transaction can be initiated by calling the `begin()` method.
-
-Another behavior of `commit()` is that by default it expires the state of all instances present after the commit is complete.  This is so that when the instances are next accessed, either through attribute access or by them being present in a `Query` result set, they receive the most recent state.  To disable this behavior, configure `sessionmaker()` with `expire_on_commit=False`.
-
-Normally, instances loaded into the `Session` are never changed by subsequent queries; the assumption is that the current transaction is isolated so the state most recently loaded is correct as long as the transaction continues.  Setting `autocommit=True` works against this model to some degree since the `Session` behaves in exactly the same way with regard to attribute state, except no transaction is present.
-
-### Rolling Back
-
-`rollback()` rolls back the current transaction.   With a default configured session, the post-rollback state of the session is as follows:
-
-  * All connections are rolled back and returned to the connection pool, unless the Session was bound directly to 
-  a Connection, in which case the connection is still maintained (but still rolled back).
-  * Objects which were initially in the *pending* state when they were added to the `Session` within the lifespan of the transaction are expunged, corresponding to their INSERT statement being rolled back.  The state of their attributes remains unchanged.
-  * Objects which were marked as *deleted* within the lifespan of the transaction are promoted back to the *persistent* state, corresponding to their DELETE statement being rolled back.  Note that if those objects were first *pending* within the transaction, that operation takes precedence instead.
-  * All objects not expunged are fully expired.  
-
-With that state understood, the `Session` may safely continue usage after a rollback occurs (note that this is a new feature as of version 0.5).
-
-When a `flush()` fails, typically for reasons like primary key, foreign key, or "not nullable" constraint violations, a `rollback()` is issued automatically (it's currently not possible for a flush to continue after a partial failure).  However, the flush process always uses its own transactional demarcator called a *subtransaction*, which is described more fully in the docstrings for `Session`.  What it means here is that even though the database transaction has been rolled back, the end user must still issue `rollback()` to fully reset the state of the `Session`.
-
-### Expunging
-
-Expunge removes an object from the Session, sending persistent instances to the detached state, and pending instances to the transient state:
-
-    {python}
-    session.expunge(obj1)
-    
-To remove all items, call `session.expunge_all()` (this method was formerly known as `clear()`).
-
-### Closing
-
-The `close()` method issues a `expunge_all()`, and releases any transactional/connection resources.  When connections are returned to the connection pool, transactional state is rolled back as well.
-
-### Refreshing / Expiring
-
-To assist with the Session's "sticky" behavior of instances which are present, individual objects can have all of their attributes immediately re-loaded from the database, or marked as "expired" which will cause a re-load to occur upon the next access of any of the object's mapped attributes.  This includes all relationships, so lazy-loaders will be re-initialized, eager relationships will be repopulated.  Any changes marked on the object are discarded:
-
-    {python}
-    # immediately re-load attributes on obj1, obj2
-    session.refresh(obj1)
-    session.refresh(obj2)
-    
-    # expire objects obj1, obj2, attributes will be reloaded
-    # on the next access:
-    session.expire(obj1)
-    session.expire(obj2)
-
-`refresh()` and `expire()` also support being passed a list of individual attribute names in which to be refreshed.  These names can reference any attribute, column-based or relation based:
-
-    {python}
-    # immediately re-load the attributes 'hello', 'world' on obj1, obj2
-    session.refresh(obj1, ['hello', 'world'])
-    session.refresh(obj2, ['hello', 'world'])
-    
-    # expire the attributes 'hello', 'world' objects obj1, obj2, attributes will be reloaded
-    # on the next access:
-    session.expire(obj1, ['hello', 'world'])
-    session.expire(obj2, ['hello', 'world'])
-
-The full contents of the session may be expired at once using `expire_all()`:
-
-    {python}
-    session.expire_all()
-
-`refresh()` and `expire()` are usually not needed when working with a default-configured `Session`.  The usual need is when an UPDATE or DELETE has been issued manually within the transaction using `Session.execute()`.
-
-### Session Attributes {@name=attributes} 
-
-The `Session` itself acts somewhat like a set-like collection.  All items present may be accessed using the iterator interface:
-
-    {python}
-    for obj in session:
-        print obj
-
-And presence may be tested for using regular "contains" semantics:
-
-    {python}
-    if obj in session:
-        print "Object is present"
-
-The session is also keeping track of all newly created (i.e. pending) objects, all objects which have had changes since they were last loaded or saved (i.e. "dirty"), and everything that's been marked as deleted.  
-
-    {python}
-    # pending objects recently added to the Session
-    session.new
-
-    # persistent objects which currently have changes detected
-    # (this collection is now created on the fly each time the property is called)
-    session.dirty
-
-    # persistent objects that have been marked as deleted via session.delete(obj)
-    session.deleted
-
-Note that objects within the session are by default *weakly referenced*.  This means that when they are dereferenced in the outside application, they fall out of scope from within the `Session` as well and are subject to garbage collection by the Python interpreter.  The exceptions to this include objects which are pending, objects which are marked as deleted, or persistent objects which have pending changes on them.  After a full flush, these collections are all empty, and all objects are again weakly referenced.  To disable the weak referencing behavior and force all objects within the session to remain until explicitly expunged, configure `sessionmaker()` with the `weak_identity_map=False` setting.
-
-## Cascades
-
-Mappers support the concept of configurable *cascade* behavior on `relation()`s.  This behavior controls how the Session should treat the instances that have a parent-child relationship with another instance that is operated upon by the Session.  Cascade is indicated as a comma-separated list of string keywords, with the possible values `all`, `delete`, `save-update`, `refresh-expire`, `merge`, `expunge`, and `delete-orphan`.
-
-Cascading is configured by setting the `cascade` keyword argument on a `relation()`:
-
-    {python}
-    mapper(Order, order_table, properties={
-        'items' : relation(Item, items_table, cascade="all, delete-orphan"),
-        'customer' : relation(User, users_table, user_orders_table, cascade="save-update"),
-    })
-
-The above mapper specifies two relations, `items` and `customer`.  The `items` relationship specifies "all, delete-orphan" as its `cascade` value, indicating that all  `add`, `merge`, `expunge`, `refresh` `delete` and `expire` operations performed on a parent `Order` instance should also be performed on the child `Item` instances attached to it.  The `delete-orphan` cascade value additionally indicates that if an `Item` instance is no longer associated with an `Order`, it should also be deleted.  The "all, delete-orphan" cascade argument allows a so-called *lifecycle* relationship between an `Order` and an `Item` object.
-
-The `customer` relationship specifies only the "save-update" cascade value, indicating most operations will not be cascaded from a parent `Order` instance to a child `User` instance except for the `add()` operation.  "save-update" cascade indicates that an `add()` on the parent will cascade to all child items, and also that items added to a parent which is already present in the session will also be added.
-
-The default value for `cascade` on `relation()`s is `save-update, merge`.
-
-## Managing Transactions
-
-The `Session` manages transactions across all engines associated with it.  As the `Session` receives requests to execute SQL statements using a particular `Engine` or `Connection`, it adds each individual `Engine` encountered to its transactional state and maintains an open connection for each one (note that a simple application normally has just one `Engine`).  At commit time, all unflushed data is flushed, and each individual transaction is committed.  If the underlying databases support two-phase semantics, this may be used by the Session as well if two-phase transactions are enabled.
-
-Normal operation ends the transactional state using the `rollback()` or `commit()` methods.  After either is called, the `Session` starts a new transaction.
-
-    {python}
-    Session = sessionmaker()
-    session = Session()
-    try:
-        item1 = session.query(Item).get(1)
-        item2 = session.query(Item).get(2)
-        item1.foo = 'bar'
-        item2.bar = 'foo'
-    
-        # commit- will immediately go into a new transaction afterwards
-        session.commit()
-    except:
-        # rollback - will immediately go into a new transaction afterwards.
-        session.rollback()
-
-A session which is configured with `autocommit=True` may be placed into a transaction using `begin()`.  With an `autocommit=True` session that's been placed into a transaction using `begin()`, the session releases all connection resources after a `commit()` or `rollback()` and remains transaction-less (with the exception of flushes) until the next `begin()` call:
-
-    {python}
-    Session = sessionmaker(autocommit=True)
-    session = Session()
-    session.begin()
-    try:
-        item1 = session.query(Item).get(1)
-        item2 = session.query(Item).get(2)
-        item1.foo = 'bar'
-        item2.bar = 'foo'
-        session.commit()
-    except:
-        session.rollback()
-        raise
-
-The `begin()` method also returns a transactional token which is compatible with the Python 2.6 `with` statement:
-
-    {python}
-    Session = sessionmaker(autocommit=True)
-    session = Session()
-    with session.begin():
-        item1 = session.query(Item).get(1)
-        item2 = session.query(Item).get(2)
-        item1.foo = 'bar'
-        item2.bar = 'foo'
-
-### Using SAVEPOINT {@name=savepoint}
-
-SAVEPOINT transactions, if supported by the underlying engine, may be delineated using the `begin_nested()` method:
-
-    {python}
-    Session = sessionmaker()
-    session = Session()
-    session.add(u1)
-    session.add(u2)
-
-    session.begin_nested() # establish a savepoint
-    session.add(u3)
-    session.rollback()  # rolls back u3, keeps u1 and u2
-
-    session.commit() # commits u1 and u2
-
-`begin_nested()` may be called any number of times, which will issue a new SAVEPOINT with a unique identifier for each call.  For each `begin_nested()` call, a corresponding `rollback()` or `commit()` must be issued.  
-
-When `begin_nested()` is called, a `flush()` is unconditionally issued (regardless of the `autoflush` setting).  This is so that when a `rollback()` occurs, the full state of the session is expired, thus causing all subsequent attribute/instance access to reference the full state of the `Session` right before `begin_nested()` was called.
-
-### Enabling Two-Phase Commit {@name=twophase}
-
-Finally, for MySQL, PostgreSQL, and soon Oracle as well, the session can be instructed to use two-phase commit semantics. This will coordinate the committing of transactions across databases so that the transaction is either committed or rolled back in all databases. You can also `prepare()` the session for interacting with transactions not managed by SQLAlchemy. To use two phase transactions set the flag `twophase=True` on the session:
-
-    {python}
-    engine1 = create_engine('postgres://db1')
-    engine2 = create_engine('postgres://db2')
-    
-    Session = sessionmaker(twophase=True)
-
-    # bind User operations to engine 1, Account operations to engine 2
-    Session.configure(binds={User:engine1, Account:engine2})
-
-    session = Session()
-    
-    # .... work with accounts and users
-    
-    # commit.  session will issue a flush to all DBs, and a prepare step to all DBs,
-    # before committing both transactions
-    session.commit()
-
-## Embedding SQL Insert/Update Expressions into a Flush {@name=flushsql}
-
-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 updates, calling stored procedures, etc.  All you do is assign an expression to an attribute:
-
-    {python}
-    class SomeClass(object):
-        pass
-    mapper(SomeClass, some_table)
-    
-    someobject = session.query(SomeClass).get(5)
-    
-    # set 'value' attribute to a SQL expression adding one
-    someobject.value = some_table.c.value + 1
-    
-    # issues "UPDATE some_table SET value=value+1"
-    session.commit()
-    
-This technique works both for INSERT and UPDATE statements.  After the flush/commit operation, the `value` attribute on `someobject` above is expired, so that when next accessed the newly generated value will be loaded from the database. 
-
-## Using SQL Expressions with Sessions {@name=sql}
-
-SQL expressions and strings can be executed via the `Session` within its transactional context.  This is most easily accomplished using the `execute()` method, which returns a `ResultProxy` in the same manner as an `Engine` or `Connection`:
-
-    {python}
-    Session = sessionmaker(bind=engine)
-    session = Session()
-    
-    # execute a string statement
-    result = session.execute("select * from table where id=:id", {'id':7})
-    
-    # execute a SQL expression construct
-    result = session.execute(select([mytable]).where(mytable.c.id==7))
-
-The current `Connection` held by the `Session` is accessible using the `connection()` method:
-
-    {python}
-    connection = session.connection()
-
-The examples above deal with a `Session` that's bound to a single `Engine` or `Connection`.  To execute statements using a `Session` which is bound either to multiple engines, or none at all (i.e. relies upon bound metadata), both `execute()` and `connection()` accept a `mapper` keyword argument, which is passed a mapped class or `Mapper` instance, which is used to locate the proper context for the desired engine:
-    
-    {python}
-    Session = sessionmaker()
-    session = Session()
-    
-    # need to specify mapper or class when executing
-    result = session.execute("select * from table where id=:id", {'id':7}, mapper=MyMappedClass)
-
-    result = session.execute(select([mytable], mytable.c.id==7), mapper=MyMappedClass)
-
-    connection = session.connection(MyMappedClass)
-
-## Joining a Session into an External Transaction {@name=joining}
-
-If a `Connection` is being used which is already in a transactional state (i.e. has a `Transaction`), a `Session` can be made to participate within that transaction by just binding the `Session` to that `Connection`:
-
-    {python}
-    Session = sessionmaker()
-    
-    # non-ORM connection + transaction
-    conn = engine.connect()
-    trans = conn.begin()
-    
-    # create a Session, bind to the connection
-    session = Session(bind=conn)
-    
-    # ... work with session
-    
-    session.commit() # commit the session
-    session.close()  # close it out, prohibit further actions
-    
-    trans.commit() # commit the actual transaction
-
-Note that above, we issue a `commit()` both on the `Session` as well as the `Transaction`.  This is an example of where we take advantage of `Connection`'s ability to maintain *subtransactions*, or nested begin/commit pairs.  The `Session` is used exactly as though it were managing the transaction on its own; its `commit()` method issues its `flush()`, and commits the subtransaction.   The subsequent transaction the `Session` starts after commit will not begin until it's next used.  Above we issue a `close()` to prevent this from occurring.  Finally, the actual transaction is committed using `Transaction.commit()`.
-
-When using the `threadlocal` engine context, the process above is simplified; the `Session` uses the same connection/transaction as everyone else in the current thread, whether or not you explicitly bind it:
-
-    {python}
-    engine = create_engine('postgres://mydb', strategy="threadlocal")
-    engine.begin()
-    
-    session = Session()  # session takes place in the transaction like everyone else
-    
-    # ... go nuts
-    
-    engine.commit() # commit the transaction
-
-## Contextual/Thread-local Sessions {@name=contextual}
-
-A common need in applications, particularly those built around web frameworks, is the ability to "share" a `Session` object among disparate parts of an application, without needing to pass the object explicitly to all method and function calls.  What you're really looking for is some kind of "global" session object, or at least "global" to all the parts of an application which are tasked with servicing the current request.  For this pattern, SQLAlchemy provides the ability to enhance the `Session` class generated by `sessionmaker()` to provide auto-contextualizing support.  This means that whenever you create a `Session` instance with its constructor, you get an *existing* `Session` object which is bound to some "context".  By default, this context is the current thread.  This feature is what previously was accomplished using the `sessioncontext` SQLAlchemy extension.
-
-### Creating a Thread-local Context {@name=creating}
-
-The `scoped_session()` function wraps around the `sessionmaker()` function, and produces an object which behaves the same as the `Session` subclass returned by `sessionmaker()`:
-
-    {python}
-    from sqlalchemy.orm import scoped_session, sessionmaker
-    Session = scoped_session(sessionmaker())
-    
-However, when you instantiate this `Session` "class", in reality the object is pulled from a threadlocal variable, or if it doesn't exist yet, it's created using the underlying class generated by `sessionmaker()`:
-
-    {python}
-    >>> # call Session() the first time.  the new Session instance is created.
-    >>> session = Session()
-    
-    >>> # later, in the same application thread, someone else calls Session()
-    >>> session2 = Session()
-    
-    >>> # the two Session objects are *the same* object
-    >>> session is session2
-    True
-
-Since the `Session()` constructor now returns the same `Session` object every time within the current thread, the object returned by `scoped_session()` also implements most of the `Session` methods and properties at the "class" level, such that you don't even need to instantiate `Session()`:
-
-    {python}
-    # create some objects
-    u1 = User()
-    u2 = User()
-    
-    # save to the contextual session, without instantiating
-    Session.add(u1)
-    Session.add(u2)
-    
-    # view the "new" attribute
-    assert u1 in Session.new
-    
-    # commit changes
-    Session.commit()
-
-The contextual session may be disposed of by calling `Session.remove()`:
-
-    {python}
-    # remove current contextual session
-    Session.remove()
-
-After `remove()` is called, the next operation with the contextual session will start a new `Session` for the current thread.
-
-### Lifespan of a Contextual Session {@name=lifespan}
-
-A (really, really) common question is when does the contextual session get created, when does it get disposed ?  We'll consider a typical lifespan as used in a web application:
-
-    {diagram}
-    Web Server          Web Framework        User-defined Controller Call
-    --------------      --------------       ------------------------------
-    web request    -> 
-                        call controller ->   # call Session().  this establishes a new,
-                                             # contextual Session.
-                                             session = Session()
-                                             
-                                             # load some objects, save some changes
-                                             objects = session.query(MyClass).all()
-                                             
-                                             # some other code calls Session, it's the 
-                                             # same contextual session as "sess"
-                                             session2 = Session()
-                                             session2.add(foo)
-                                             session2.commit()
-                                             
-                                             # generate content to be returned
-                                             return generate_content()
-                        Session.remove() <-
-    web response   <-  
-
-The above example illustrates an explicit call to `Session.remove()`.  This has the effect such that each web request starts fresh with a brand new session.   When integrating with a web framework, there's actually many options on how to proceed for this step, particularly as of version 0.5:
-
- * Session.remove() - this is the most cut and dry approach; the `Session` is thrown away, all of its transactional/connection resources are closed out, everything within it is explicitly gone.  A new `Session` will be used on the next request.
- * Session.close() - Similar to calling `remove()`, in that all objects are explicitly expunged and all transactional/connection resources closed, except the actual `Session` object hangs around.  It doesn't make too much difference here unless the start of the web request would like to pass specific options to the initial construction of `Session()`, such as a specific `Engine` to bind to.
- * Session.commit() - In this case, the behavior is that any remaining changes pending are flushed, and the transaction is committed.  The full state of the session is expired, so that when the next web request is started, all data will be reloaded.  In reality, the contents of the `Session` are weakly referenced anyway so its likely that it will be empty on the next request in any case.
- * Session.rollback() - Similar to calling commit, except we assume that the user would have called commit explicitly if that was desired; the `rollback()` ensures that no transactional state remains and expires all data, in the case that the request was aborted and did not roll back itself.
- * do nothing - this is a valid option as well.  The controller code is responsible for doing one of the above steps at the end of the request.
-
-[Generated docstrings for scoped_session()](rel:docstrings_sqlalchemy.orm_modfunc_scoped_session)
-
-## Partitioning Strategies
-
-this section is TODO
-
-### Vertical Partitioning
-
-Vertical partitioning places different kinds of objects, or different tables, across multiple databases.
-
-    {python}
-    engine1 = create_engine('postgres://db1')
-    engine2 = create_engine('postgres://db2')
-
-    Session = sessionmaker(twophase=True)
-
-    # bind User operations to engine 1, Account operations to engine 2
-    Session.configure(binds={User:engine1, Account:engine2})
-
-    session = Session()
-
-### Horizontal Partitioning
-
-Horizontal partitioning partitions the rows of a single table (or a set of tables) across multiple databases.
-
-See the "sharding" example in [attribute_shard.py](http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/examples/sharding/attribute_shard.py)
-
-## Extending Session
-
-Extending the session can be achieved through subclassing as well as through a simple extension class, which resembles the style of [advdatamapping_mapper_extending](rel:advdatamapping_mapper_extending) called [SessionExtension](rel:docstrings_sqlalchemy.orm.session_SessionExtension).  See the docstrings for more information on this class' methods.
-
-Basic usage is similar to `MapperExtension`:
-
-    {python}
-    class MySessionExtension(SessionExtension):
-        def before_commit(self, session):
-            print "before commit!"
-            
-    Session = sessionmaker(extension=MySessionExtension())
-    
-or with `create_session()`:
-
-    {python}
-    session = create_session(extension=MySessionExtension())
-    
-The same `SessionExtension` instance can be used with any number of sessions.
diff --git a/doc/build/oldcontent/sqlexpression.txt b/doc/build/oldcontent/sqlexpression.txt
deleted file mode 100644 (file)
index cf37943..0000000
+++ /dev/null
@@ -1,940 +0,0 @@
-SQL Expression Language Tutorial {@name=sql}
-===============================================
-
-This tutorial will cover SQLAlchemy SQL Expressions, which are Python constructs that represent SQL statements.  The tutorial is in doctest format, meaning each `>>>` line represents something you can type at a Python command prompt, and the following text represents the expected return value.  The tutorial has no prerequisites.
-
-## Version Check
-
-A quick check to verify that we are on at least **version 0.5** of SQLAlchemy:
-
-    {python}
-    >>> import sqlalchemy
-    >>> sqlalchemy.__version__ # doctest:+SKIP
-    0.5.0
-    
-## Connecting
-
-For this tutorial we will use an in-memory-only SQLite database.   This is an easy way to test things without needing to have an actual database defined anywhere.  To connect we use `create_engine()`:
-
-    {python}
-    >>> from sqlalchemy import create_engine
-    >>> engine = create_engine('sqlite:///:memory:', echo=True)
-    
-The `echo` flag is a shortcut to setting up SQLAlchemy logging, which is accomplished via Python's standard `logging` module.  With it enabled, we'll see all the generated SQL produced.  If you are working through this tutorial and want less output generated, set it to `False`.   This tutorial will format the SQL behind a popup window so it doesn't get in our way; just click the "SQL" links to see what's being generated.
-    
-## Define and Create Tables {@name=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 called `Column`, and in all cases a `Column` is associated with a `Table`.  A collection of `Table` objects and their associated child objects is referred to as **database metadata**.  In this tutorial we will explicitly lay out several `Table` objects, but note that SA can also "import" whole sets of `Table` objects automatically from an existing database (this process is called **table reflection**).
-
-We define our tables all within a catalog called `MetaData`, using the `Table` construct, which resembles regular SQL CREATE TABLE statements.  We'll make two tables, one of which represents "users" in an application, and another which represents zero or more "email addreses" for each row in the "users" table:
-
-    {python}
-    >>> from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
-    >>> metadata = MetaData()
-    >>> users = Table('users', metadata,
-    ...     Column('id', Integer, primary_key=True),
-    ...     Column('name', String),
-    ...     Column('fullname', String),
-    ... )
-
-    >>> addresses = Table('addresses', metadata, 
-    ...   Column('id', Integer, primary_key=True),
-    ...   Column('user_id', None, ForeignKey('users.id')),
-    ...   Column('email_address', String, nullable=False)
-    ...  )
-
-All about how to define `Table` objects, as well as how to create them from an existing database automatically, is described in [metadata](rel:metadata).
-
-Next, to tell the `MetaData` we'd actually like to create our selection of tables for real inside the SQLite database, we use `create_all()`, passing it the `engine` instance which points to our database.  This will check for the presence of each table first before creating, so it's safe to call multiple times:
-
-    {python}
-    {sql}>>> metadata.create_all(engine) #doctest: +NORMALIZE_WHITESPACE
-    PRAGMA table_info("users")
-    {}
-    PRAGMA table_info("addresses")
-    {}
-    CREATE TABLE users (
-        id INTEGER NOT NULL, 
-        name VARCHAR, 
-        fullname VARCHAR, 
-        PRIMARY KEY (id)
-    )
-    {}
-    COMMIT
-    CREATE TABLE addresses (
-        id INTEGER NOT NULL, 
-        user_id INTEGER, 
-        email_address VARCHAR NOT NULL, 
-        PRIMARY KEY (id), 
-         FOREIGN KEY(user_id) REFERENCES users (id)
-    )
-    {}
-    COMMIT
-
-Users familiar with the syntax of CREATE TABLE may notice that the VARCHAR columns were generated without a length; on SQLite, this is a valid datatype, but on most databases it's not allowed.  So if running this tutorial on a database such as PostgreSQL or MySQL, and you wish to use SQLAlchemy to generate the tables, a "length" may be provided to the `String` type as below:
-
-    {python}
-    Column('name', String(50))
-
-The length field on `String`, as well as similar fields available on `Integer`, `Numeric`, etc. are not referenced by SQLAlchemy other than when creating tables.
-
-## Insert Expressions
-
-The first SQL expression we'll create is the `Insert` construct, which represents an INSERT statement.   This is typically created relative to its target table:
-
-    {python}
-    >>> ins = users.insert()
-
-To see a sample of the SQL this construct produces, use the `str()` function:
-
-    {python}
-    >>> str(ins)
-    'INSERT INTO users (id, name, fullname) VALUES (:id, :name, :fullname)'
-    
-Notice above that the INSERT statement names every column in the `users` table.  This can be limited by using the `values` keyword, which establishes the VALUES clause of the INSERT explicitly:
-
-    {python}
-    >>> ins = users.insert(values={'name':'jack', 'fullname':'Jack Jones'})
-    >>> str(ins)
-    'INSERT INTO users (name, fullname) VALUES (:name, :fullname)'
-    
-Above, while the `values` keyword limited the VALUES clause to just two columns, the actual data we placed in `values` didn't get rendered into the string; instead we got named bind parameters.  As it turns out, our data *is* stored within our `Insert` construct, but it typically only comes out when the statement is actually executed; since the data consists of literal values, SQLAlchemy automatically generates bind parameters for them.  We can peek at this data for now by looking at the compiled form of the statement:
-
-    {python}
-    >>> ins.compile().params #doctest: +NORMALIZE_WHITESPACE
-    {'fullname': 'Jack Jones', 'name': 'jack'}    
-
-## Executing {@name=executing}
-
-The interesting part of an `Insert` is executing it.  In this tutorial, we will generally focus on the most explicit method of executing a SQL construct, and later touch upon some "shortcut" ways to do it.  The `engine` object we created is a repository for database connections capable of issuing SQL to the database.  To acquire a connection, we use the `connect()` method:
-
-    {python}
-    >>> conn = engine.connect()
-    >>> conn #doctest: +ELLIPSIS
-    <sqlalchemy.engine.base.Connection object at 0x...>
-
-The `Connection` object represents an actively checked out DBAPI connection resource.  Lets feed it our `Insert` object and see what happens:
-
-    {python}
-    >>> result = conn.execute(ins)
-    {opensql}INSERT INTO users (name, fullname) VALUES (?, ?)
-    ['jack', 'Jack Jones']
-    COMMIT
-
-So the INSERT statement was now issued to the database.  Although we got positional "qmark" bind parameters instead of "named" bind parameters in the output.  How come ?  Because when executed, the `Connection` used the SQLite **dialect** to help generate the statement; when we use the `str()` function, the statement isn't aware of this dialect, and falls back onto a default which uses named parameters. We can view this manually as follows:
-
-    {python}
-    >>> ins.bind = engine
-    >>> str(ins)
-    'INSERT INTO users (name, fullname) VALUES (?, ?)'
-
-What about the `result` variable we got when we called `execute()` ?  As the SQLAlchemy `Connection` object references a DBAPI connection, the result, known as a `ResultProxy` object, is analogous to the DBAPI cursor object.  In the case of an INSERT, we can get important information from it, such as the primary key values which were generated from our statement:
-
-    {python}
-    >>> result.last_inserted_ids()
-    [1]
-    
-The value of `1` was automatically generated by SQLite, but only because we did not specify the `id` column in our `Insert` statement; otherwise, our explicit value would have been used.   In either case, SQLAlchemy always knows how to get at a newly generated primary key value, even though the method of generating them is different across different databases; each databases' `Dialect` knows the specific steps needed to determine the correct value (or values; note that `last_inserted_ids()` returns a list so that it supports composite primary keys).
-
-## Executing Multiple Statements {@name=execmany}
-
-Our insert example above was intentionally a little drawn out to show some various behaviors of expression language constructs.  In the usual case, an `Insert` statement is usually compiled against the parameters sent to the `execute()` method on `Connection`, so that there's no need to use the `values` keyword with `Insert`.  Lets create a generic `Insert` statement again and use it in the "normal" way:
-
-    {python}
-    >>> ins = users.insert()
-    >>> conn.execute(ins, id=2, name='wendy', fullname='Wendy Williams') # doctest: +ELLIPSIS
-    {opensql}INSERT INTO users (id, name, fullname) VALUES (?, ?, ?)
-    [2, 'wendy', 'Wendy Williams']
-    COMMIT
-    {stop}<sqlalchemy.engine.base.ResultProxy object at 0x...>
-
-Above, because we specified all three columns in the the `execute()` method, the compiled `Insert` included all three columns.  The `Insert` statement is compiled at execution time based on the parameters we specified; if we specified fewer parameters, the `Insert` would have fewer entries in its VALUES clause.
-
-To issue many inserts using DBAPI's `executemany()` method, we can send in a list of dictionaries each containing a distinct set of parameters to be inserted, as we do here to add some email addresses:
-
-    {python}
-    >>> conn.execute(addresses.insert(), [ # doctest: +ELLIPSIS
-    ...    {'user_id': 1, 'email_address' : 'jack@yahoo.com'},
-    ...    {'user_id': 1, 'email_address' : 'jack@msn.com'},
-    ...    {'user_id': 2, 'email_address' : 'www@www.org'},
-    ...    {'user_id': 2, 'email_address' : 'wendy@aol.com'},
-    ... ])
-    {opensql}INSERT INTO addresses (user_id, email_address) VALUES (?, ?)
-    [[1, 'jack@yahoo.com'], [1, 'jack@msn.com'], [2, 'www@www.org'], [2, 'wendy@aol.com']]
-    COMMIT
-    {stop}<sqlalchemy.engine.base.ResultProxy object at 0x...>
-
-Above, we again relied upon SQLite's automatic generation of primary key identifiers for each `addresses` row.
-
-When executing multiple sets of parameters, each dictionary must have the **same** set of keys; i.e. you cant have fewer keys in some dictionaries than others.  This is because the `Insert` statement is compiled against the **first** dictionary in the list, and it's assumed that all subsequent argument dictionaries are compatible with that statement.
-
-## Connectionless / Implicit Execution {@name=connectionless}
-
-We're executing our `Insert` using a `Connection`.  There's two options that allow you to not have to deal with the connection part.  You can execute in the **connectionless** style, using the engine, which opens and closes a connection for you:
-
-    {python}
-    {sql}>>> result = engine.execute(users.insert(), name='fred', fullname="Fred Flintstone")
-    INSERT INTO users (name, fullname) VALUES (?, ?)
-    ['fred', 'Fred Flintstone']
-    COMMIT
-    
-and you can save even more steps than that, if you connect the `Engine` to the `MetaData` object we created earlier.  When this is done, all SQL expressions which involve tables within the `MetaData` object will be automatically **bound** to the `Engine`.  In this case, we call it  **implicit execution**:
-
-    {python}
-    >>> metadata.bind = engine
-    {sql}>>> result = users.insert().execute(name="mary", fullname="Mary Contrary")
-    INSERT INTO users (name, fullname) VALUES (?, ?)
-    ['mary', 'Mary Contrary']
-    COMMIT
-
-When the `MetaData` is bound, statements will also compile against the engine's dialect.  Since a lot of the examples here assume the default dialect, we'll detach the engine from the metadata which we just attached:
-
-    {python}
-    >>> metadata.bind = None
-
-Detailed examples of connectionless and implicit execution are available in the "Engines" chapter: [dbengine_implicit](rel:dbengine_implicit).
-    
-## Selecting {@name=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 DELETE statements later.  The primary construct used to generate SELECT statements is the `select()` function:
-
-    {python}
-    >>> from sqlalchemy.sql import select
-    >>> s = select([users])
-    {opensql}>>> result = conn.execute(s)
-    SELECT users.id, users.name, users.fullname 
-    FROM users
-    []
-
-Above, we issued a basic `select()` call, placing the `users` table within the COLUMNS clause of the select, and then executing.  SQLAlchemy expanded the `users` table into the set of each of its columns, and also generated a FROM clause for us.  The result returned is again a `ResultProxy` object, which acts much like a DBAPI cursor, including methods such as `fetchone()` and `fetchall()`.  The easiest way to get rows from it is to just iterate:
-
-    {python}
-    >>> for row in result:
-    ...     print row
-    (1, u'jack', u'Jack Jones')
-    (2, u'wendy', u'Wendy Williams')
-    (3, u'fred', u'Fred Flintstone')
-    (4, u'mary', u'Mary Contrary')
-
-Above, we see that printing each row produces a simple tuple-like result.  We have more options at accessing the data in each row.  One very common way is through dictionary access, using the string names of columns:
-
-    {python}
-    {sql}>>> result = conn.execute(s)
-    SELECT users.id, users.name, users.fullname 
-    FROM users
-    []
-    
-    >>> row = result.fetchone()
-    >>> print "name:", row['name'], "; fullname:", row['fullname']
-    name: jack ; fullname: Jack Jones
-
-Integer indexes work as well:
-
-    {python}
-    >>> row = result.fetchone()
-    >>> print "name:", row[1], "; fullname:", row[2]
-    name: wendy ; fullname: Wendy Williams
-
-But another way, whose usefulness will become apparent later on, is to use the `Column` objects directly as keys:
-
-    {python}
-    {sql}>>> for row in conn.execute(s):
-    ...     print "name:", row[users.c.name], "; fullname:", row[users.c.fullname]
-    SELECT users.id, users.name, users.fullname 
-    FROM users
-    []
-    {stop}name: jack ; fullname: Jack Jones
-    name: wendy ; fullname: Wendy Williams
-    name: fred ; fullname: Fred Flintstone
-    name: mary ; fullname: Mary Contrary
-
-Result sets which have pending rows remaining should be explicitly closed before discarding.  While the resources referenced by the `ResultProxy` will be closed when the object is garbage collected, it's better to make it explicit as some database APIs are very picky about such things:
-
-    {python}
-    >>> result.close()
-
-If we'd like to more carefully control the columns which are placed in the COLUMNS clause of the select, we reference individual `Column` objects from our `Table`.  These are available as named attributes off the `c` attribute of the `Table` object:
-
-    {python}
-    >>> s = select([users.c.name, users.c.fullname])
-    {sql}>>> result = conn.execute(s)
-    SELECT users.name, users.fullname 
-    FROM users
-    []
-    {stop}>>> for row in result:  #doctest: +NORMALIZE_WHITESPACE
-    ...     print row
-    (u'jack', u'Jack Jones')
-    (u'wendy', u'Wendy Williams')
-    (u'fred', u'Fred Flintstone')
-    (u'mary', u'Mary Contrary')
-    
-Lets observe something interesting about the FROM clause.  Whereas the generated statement contains two distinct sections, a "SELECT columns" part and a "FROM table" part, our `select()` construct only has a list containing columns.  How does this work ?  Let's try putting *two* tables into our `select()` statement:
-
-    {python}
-    {sql}>>> for row in conn.execute(select([users, addresses])):
-    ...     print row
-    SELECT users.id, users.name, users.fullname, addresses.id, addresses.user_id, addresses.email_address 
-    FROM users, addresses
-    []
-    {stop}(1, u'jack', u'Jack Jones', 1, 1, u'jack@yahoo.com')
-    (1, u'jack', u'Jack Jones', 2, 1, u'jack@msn.com')
-    (1, u'jack', u'Jack Jones', 3, 2, u'www@www.org')
-    (1, u'jack', u'Jack Jones', 4, 2, u'wendy@aol.com')
-    (2, u'wendy', u'Wendy Williams', 1, 1, u'jack@yahoo.com')
-    (2, u'wendy', u'Wendy Williams', 2, 1, u'jack@msn.com')
-    (2, u'wendy', u'Wendy Williams', 3, 2, u'www@www.org')
-    (2, u'wendy', u'Wendy Williams', 4, 2, u'wendy@aol.com')
-    (3, u'fred', u'Fred Flintstone', 1, 1, u'jack@yahoo.com')
-    (3, u'fred', u'Fred Flintstone', 2, 1, u'jack@msn.com')
-    (3, u'fred', u'Fred Flintstone', 3, 2, u'www@www.org')
-    (3, u'fred', u'Fred Flintstone', 4, 2, u'wendy@aol.com')
-    (4, u'mary', u'Mary Contrary', 1, 1, u'jack@yahoo.com')
-    (4, u'mary', u'Mary Contrary', 2, 1, u'jack@msn.com')
-    (4, u'mary', u'Mary Contrary', 3, 2, u'www@www.org')
-    (4, u'mary', u'Mary Contrary', 4, 2, u'wendy@aol.com')
-
-It placed **both** tables into the FROM clause.  But also, it made a real mess.  Those who are familiar with SQL joins know that this is a **Cartesian product**; each row from the `users` table is produced against each row from the `addresses` table.  So to put some sanity into this statement, we need a WHERE clause.  Which brings us to the second argument of `select()`:
-
-    {python}
-    >>> s = select([users, addresses], users.c.id==addresses.c.user_id)
-    {sql}>>> for row in conn.execute(s):
-    ...     print row
-    SELECT users.id, users.name, users.fullname, addresses.id, addresses.user_id, addresses.email_address 
-    FROM users, addresses 
-    WHERE users.id = addresses.user_id
-    []
-    {stop}(1, u'jack', u'Jack Jones', 1, 1, u'jack@yahoo.com')
-    (1, u'jack', u'Jack Jones', 2, 1, u'jack@msn.com')
-    (2, u'wendy', u'Wendy Williams', 3, 2, u'www@www.org')
-    (2, u'wendy', u'Wendy Williams', 4, 2, u'wendy@aol.com')
-
-So that looks a lot better, we added an expression to our `select()` which had the effect of adding `WHERE users.id = addresses.user_id` to our statement, and our results were managed down so that the join of `users` and `addresses` rows made sense.  But let's look at that expression?  It's using just a Python equality operator between two different `Column` objects.  It should be clear that something is up.  Saying `1==1` produces `True`, and `1==2` produces `False`, not a WHERE clause.  So lets see exactly what that expression is doing:
-
-    {python}
-    >>> users.c.id==addresses.c.user_id #doctest: +ELLIPSIS
-    <sqlalchemy.sql.expression._BinaryExpression object at 0x...>
-
-Wow, surprise !  This is neither a `True` nor a `False`.  Well what is it ?
-
-    {python}
-    >>> str(users.c.id==addresses.c.user_id)
-    'users.id = addresses.user_id'
-
-As you can see, the `==` operator is producing an object that is very much like the `Insert` and `select()` objects we've made so far, thanks to Python's `__eq__()` builtin; you call `str()` on it and it produces SQL.  By now, one can that everything we are working with is ultimately the same type of object.  SQLAlchemy terms the base class of all of these expressions as `sqlalchemy.sql.ClauseElement`.
-
-## Operators {@name=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:
-
-    {python}
-    >>> print users.c.id==addresses.c.user_id
-    users.id = addresses.user_id
-    
-If we use a literal value (a literal meaning, not a SQLAlchemy clause object), we get a bind parameter:
-
-    {python}
-    >>> print users.c.id==7
-    users.id = :id_1
-    
-The `7` literal is embedded in `ClauseElement`; we can use the same trick we did with the `Insert` object to see it:
-
-    {python}
-    >>> (users.c.id==7).compile().params
-    {'id_1': 7}
-    
-Most Python operators, as it turns out, produce a SQL expression here, like equals, not equals, etc.:
-
-    {python}
-    >>> print users.c.id != 7
-    users.id != :id_1
-    
-    >>> # None converts to IS NULL
-    >>> print users.c.name == None
-    users.name IS NULL
-     
-    >>> # reverse works too 
-    >>> print 'fred' > users.c.name
-    users.name < :name_1
-    
-If we add two integer columns together, we get an addition expression:
-
-    {python}
-    >>> print users.c.id + addresses.c.id
-    users.id + addresses.id
-    
-Interestingly, the type of the `Column` is important !  If we use `+` with two string based columns (recall we put types like `Integer` and `String` on our `Column` objects at the beginning), we get something different:
-
-    {python}
-    >>> print users.c.name + users.c.fullname
-    users.name || users.fullname
-
-Where `||` is the string concatenation operator used on most databases.  But not all of them.  MySQL users, fear not:
-
-    {python}
-    >>> print (users.c.name + users.c.fullname).compile(bind=create_engine('mysql://'))
-    concat(users.name, users.fullname)
-
-The above illustrates the SQL that's generated for an `Engine` that's connected to a MySQL database; the `||` operator now compiles as MySQL's `concat()` function.
-
-If you have come across an operator which really isn't available, you can always use the `op()` method; this generates whatever operator you need:
-
-    {python}
-    >>> print users.c.name.op('tiddlywinks')('foo')
-    users.name tiddlywinks :name_1
-    
-## Conjunctions {@name=conjunctions}
-
-We'd like to show off some of our operators inside of `select()` constructs.  But we need to lump them together a little more, so let's first introduce some conjunctions.  Conjunctions are those little words like AND and OR that put things together.  We'll also hit upon NOT.  AND, OR and NOT can work from the corresponding functions SQLAlchemy provides (notice we also throw in a LIKE):
-
-    {python}
-    >>> from sqlalchemy.sql import and_, or_, not_
-    >>> print and_(users.c.name.like('j%'), users.c.id==addresses.c.user_id, #doctest: +NORMALIZE_WHITESPACE  
-    ...     or_(addresses.c.email_address=='wendy@aol.com', addresses.c.email_address=='jack@yahoo.com'),
-    ...     not_(users.c.id>5))
-    users.name LIKE :name_1 AND users.id = addresses.user_id AND 
-    (addresses.email_address = :email_address_1 OR addresses.email_address = :email_address_2) 
-    AND users.id <= :id_1
-
-And you can also use the re-jiggered bitwise AND, OR and NOT operators, although because of Python operator precedence you have to watch your parenthesis:
-
-    {python}
-    >>> print users.c.name.like('j%') & (users.c.id==addresses.c.user_id) &  \
-    ...     ((addresses.c.email_address=='wendy@aol.com') | (addresses.c.email_address=='jack@yahoo.com')) \
-    ...     & ~(users.c.id>5) # doctest: +NORMALIZE_WHITESPACE
-    users.name LIKE :name_1 AND users.id = addresses.user_id AND 
-    (addresses.email_address = :email_address_1 OR addresses.email_address = :email_address_2) 
-    AND users.id <= :id_1
-
-So with all of this vocabulary, let's select all users who have an email address at AOL or MSN, whose name starts with a letter between "m" and "z", and we'll also generate a column containing their full name combined with their email address.  We will add two new constructs to this statement, `between()` and `label()`.  `between()` produces a BETWEEN clause, and `label()` is used in a column expression to produce labels using the `AS` keyword; it's recommended when selecting from expressions that otherwise would not have a name:
-
-    {python}
-    >>> s = select([(users.c.fullname + ", " + addresses.c.email_address).label('title')], 
-    ...        and_( 
-    ...            users.c.id==addresses.c.user_id, 
-    ...            users.c.name.between('m', 'z'), 
-    ...           or_(
-    ...              addresses.c.email_address.like('%@aol.com'), 
-    ...              addresses.c.email_address.like('%@msn.com')
-    ...           )
-    ...        )
-    ...    ) 
-    >>> print conn.execute(s).fetchall() #doctest: +NORMALIZE_WHITESPACE
-    SELECT users.fullname || ? || addresses.email_address AS title 
-    FROM users, addresses 
-    WHERE users.id = addresses.user_id AND users.name BETWEEN ? AND ? AND 
-    (addresses.email_address LIKE ? OR addresses.email_address LIKE ?)
-    [', ', 'm', 'z', '%@aol.com', '%@msn.com']
-    [(u'Wendy Williams, wendy@aol.com',)]
-
-Once again, SQLAlchemy figured out the FROM clause for our statement.  In fact it will determine the FROM clause based on all of its other bits; the columns clause, the where clause, and also some other elements which we haven't covered yet, which include ORDER BY, GROUP BY, and HAVING. 
-
-## Using Text {@name=text}
-
-Our last example really became a handful to type.  Going from what one understands to be a textual SQL expression into a Python construct which groups components together in a programmatic style can be hard.  That's why SQLAlchemy lets you just use strings too.  The `text()` construct represents any textual statement.  To use bind parameters with `text()`, always use the named colon format.  Such as below, we create a `text()` and execute it, feeding in the bind parameters to the `execute()` method:
-
-    {python}
-    >>> from sqlalchemy.sql import text
-    >>> s = text("""SELECT users.fullname || ', ' || addresses.email_address AS title 
-    ...            FROM users, addresses 
-    ...            WHERE users.id = addresses.user_id AND users.name BETWEEN :x AND :y AND 
-    ...            (addresses.email_address LIKE :e1 OR addresses.email_address LIKE :e2)
-    ...        """)
-    {sql}>>> print conn.execute(s, x='m', y='z', e1='%@aol.com', e2='%@msn.com').fetchall() # doctest:+NORMALIZE_WHITESPACE
-    SELECT users.fullname || ', ' || addresses.email_address AS title 
-    FROM users, addresses 
-    WHERE users.id = addresses.user_id AND users.name BETWEEN ? AND ? AND 
-    (addresses.email_address LIKE ? OR addresses.email_address LIKE ?)
-    ['m', 'z', '%@aol.com', '%@msn.com']
-    {stop}[(u'Wendy Williams, wendy@aol.com',)]
-
-To gain a "hybrid" approach, any of SA's SQL constructs can have text freely intermingled wherever you like - the `text()` construct can be placed within any other `ClauseElement` construct, and when used in a non-operator context, a direct string may be placed which converts to `text()` automatically.  Below we combine the usage of `text()` and strings with our constructed `select()` object, by using the `select()` object to structure the statement, and the `text()`/strings to provide all the content within the structure.  For this example, SQLAlchemy is not given any `Column` or `Table` objects in any of its expressions, so it cannot generate a FROM clause.  So we also give it the `from_obj` keyword argument, which is a list of `ClauseElements` (or strings) to be placed within the FROM clause:
-
-    {python}
-    >>> s = select([text("users.fullname || ', ' || addresses.email_address AS title")], 
-    ...        and_( 
-    ...            "users.id = addresses.user_id", 
-    ...             "users.name BETWEEN 'm' AND 'z'",
-    ...             "(addresses.email_address LIKE :x OR addresses.email_address LIKE :y)"
-    ...        ),
-    ...         from_obj=['users', 'addresses']
-    ...    )
-    {sql}>>> print conn.execute(s, x='%@aol.com', y='%@msn.com').fetchall() #doctest: +NORMALIZE_WHITESPACE
-    SELECT users.fullname || ', ' || addresses.email_address AS title 
-    FROM users, addresses 
-    WHERE users.id = addresses.user_id AND users.name BETWEEN 'm' AND 'z' AND (addresses.email_address LIKE ? OR addresses.email_address LIKE ?)
-    ['%@aol.com', '%@msn.com']
-    {stop}[(u'Wendy Williams, wendy@aol.com',)]
-
-Going from constructed SQL to text, we lose some capabilities.  We lose the capability for SQLAlchemy to compile our expression to a specific target database; above, our expression won't work with MySQL since it has no `||` construct.  It also becomes more tedious for SQLAlchemy to be made aware of the datatypes in use; for example, if our bind parameters required UTF-8 encoding before going in, or conversion from a Python `datetime` into a string (as is required with SQLite), we would have to add extra information to our `text()` construct.  Similar issues arise on the result set side, where SQLAlchemy also performs type-specific data conversion in some cases; still more information can be added to `text()` to work around this.  But what we really lose from our statement is the ability to manipulate it, transform it, and analyze it.  These features are critical when using the ORM, which makes heavy usage of relational transformations.  To show off what we mean, we'll first introduce the ALIAS construct and the JOIN construct, just so we have some juicier bits to play with.
-
-## Using Aliases {@name=aliases}
-
-The alias corresponds to a "renamed" version of a table or arbitrary relation, which occurs anytime you say "SELECT  .. FROM sometable AS someothername".  The `AS` creates a new name for the table.  Aliases are super important in SQL as they allow you to reference the same table more than once.  Scenarios where you need to do this include when you self-join a table to itself, or more commonly when you need to join from a parent table to a child table multiple times.  For example, we know that our user `jack` has two email addresses.  How can we locate jack based on the combination of those two addresses?  We need to join twice to it.  Let's construct two distinct aliases for the `addresses` table and join:
-
-    {python}
-    >>> a1 = addresses.alias('a1')
-    >>> a2 = addresses.alias('a2')
-    >>> s = select([users], and_(
-    ...        users.c.id==a1.c.user_id, 
-    ...        users.c.id==a2.c.user_id, 
-    ...        a1.c.email_address=='jack@msn.com', 
-    ...        a2.c.email_address=='jack@yahoo.com'
-    ...   ))
-    {sql}>>> print conn.execute(s).fetchall()
-    SELECT users.id, users.name, users.fullname 
-    FROM users, addresses AS a1, addresses AS a2 
-    WHERE users.id = a1.user_id AND users.id = a2.user_id AND a1.email_address = ? AND a2.email_address = ?
-    ['jack@msn.com', 'jack@yahoo.com']
-    {stop}[(1, u'jack', u'Jack Jones')]
-
-Easy enough.  One thing that we're going for with the SQL Expression Language is the melding of programmatic behavior with SQL generation.  Coming up with names like `a1` and `a2` is messy; we really didn't need to use those names anywhere, it's just the database that needed them.  Plus, we might write some code that uses alias objects that came from several different places, and it's difficult to ensure that they all have unique names.  So instead, we just let SQLAlchemy make the names for us, using "anonymous" aliases:
-
-    {python}
-    >>> a1 = addresses.alias()
-    >>> a2 = addresses.alias()
-    >>> s = select([users], and_(
-    ...        users.c.id==a1.c.user_id, 
-    ...        users.c.id==a2.c.user_id, 
-    ...        a1.c.email_address=='jack@msn.com', 
-    ...        a2.c.email_address=='jack@yahoo.com'
-    ...   ))
-    {sql}>>> print conn.execute(s).fetchall()
-    SELECT users.id, users.name, users.fullname 
-    FROM users, addresses AS addresses_1, addresses AS addresses_2 
-    WHERE users.id = addresses_1.user_id AND users.id = addresses_2.user_id AND addresses_1.email_address = ? AND addresses_2.email_address = ?
-    ['jack@msn.com', 'jack@yahoo.com']
-    {stop}[(1, u'jack', u'Jack Jones')]
-
-One super-huge advantage of anonymous aliases is that not only did we not have to guess up a random name, but we can also be guaranteed that the above SQL string is **deterministically** generated to be the same every time.  This is important for databases such as Oracle which cache compiled "query plans" for their statements, and need to see the same SQL string in order to make use of it.
-
-Aliases can of course be used for anything which you can SELECT from, including SELECT statements themselves.  We can self-join the `users` table back to the `select()` we've created by making an alias of the entire statement.  The `correlate(None)` directive is to avoid SQLAlchemy's attempt to "correlate" the inner `users` table with the outer one:
-
-    {python}
-    >>> a1 = s.correlate(None).alias()
-    >>> s = select([users.c.name], users.c.id==a1.c.id)
-    {sql}>>> print conn.execute(s).fetchall()
-    SELECT users.name 
-    FROM users, (SELECT users.id AS id, users.name AS name, users.fullname AS fullname 
-    FROM users, addresses AS addresses_1, addresses AS addresses_2 
-    WHERE users.id = addresses_1.user_id AND users.id = addresses_2.user_id AND addresses_1.email_address = ? AND addresses_2.email_address = ?) AS anon_1 
-    WHERE users.id = anon_1.id
-    ['jack@msn.com', 'jack@yahoo.com']
-    {stop}[(u'jack',)]
-    
-## Using Joins {@name=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 joins in our examples, by just placing two tables in either the columns clause or the where clause of the `select()` construct.  But if we want to make a real "JOIN" or "OUTERJOIN" construct, we use the `join()` and `outerjoin()` methods, most commonly accessed from the left table in the join:
-
-    {python}
-    >>> print users.join(addresses)
-    users JOIN addresses ON users.id = addresses.user_id
-    
-The alert reader will see more surprises; SQLAlchemy figured out how to JOIN the two tables !  The ON condition of the join, as it's called, was automatically generated based on the `ForeignKey` object which we placed on the `addresses` table way at the beginning of this tutorial.  Already the `join()` construct is looking like a much better way to join tables.
-
-Of course you can join on whatever expression you want, such as if we want to join on all users who use the same name in their email address as their username:
-
-    {python}
-    >>> print users.join(addresses, addresses.c.email_address.like(users.c.name + '%'))
-    users JOIN addresses ON addresses.email_address LIKE users.name || :name_1
-
-When we create a `select()` construct, SQLAlchemy looks around at the tables we've mentioned and then places them in the FROM clause of the statement.  When we use JOINs however, we know what FROM clause we want, so here we make usage of the `from_obj` keyword argument:
-
-    {python}
-    >>> s = select([users.c.fullname], from_obj=[
-    ...    users.join(addresses, addresses.c.email_address.like(users.c.name + '%'))
-    ...    ])
-    {sql}>>> print conn.execute(s).fetchall()
-    SELECT users.fullname 
-    FROM users JOIN addresses ON addresses.email_address LIKE users.name || ?
-    ['%']
-    {stop}[(u'Jack Jones',), (u'Jack Jones',), (u'Wendy Williams',)]
-
-The `outerjoin()` function just creates `LEFT OUTER JOIN` constructs.  It's used just like `join()`:
-
-    {python}
-    >>> s = select([users.c.fullname], from_obj=[users.outerjoin(addresses)])
-    >>> print s
-    SELECT users.fullname 
-    FROM users LEFT OUTER JOIN addresses ON users.id = addresses.user_id
-
-That's the output `outerjoin()` produces, unless, of course, you're stuck in a gig using Oracle prior to version 9, and you've set up your engine (which would be using `OracleDialect`) to use Oracle-specific SQL:
-
-    {python}
-    >>> from sqlalchemy.databases.oracle import OracleDialect
-    >>> print s.compile(dialect=OracleDialect(use_ansi=False))
-    SELECT users.fullname 
-    FROM users, addresses 
-    WHERE users.id = addresses.user_id(+)
-
-If you don't know what that SQL means, don't worry !  The secret tribe of Oracle DBAs don't want their black magic being found out ;).
-
-## Intro to Generative Selects and Transformations {@name=transform}
-
-We've now gained the ability to construct very sophisticated statements.  We can use all kinds of operators, table constructs, text, joins, and aliases.  The point of all of this, as mentioned earlier, is not that it's an "easier" or "better" way to write SQL than just writing a SQL statement yourself; the point is that it's better for writing *programmatically generated* SQL which can be morphed and adapted as needed in automated scenarios.
-
-To support this, the `select()` construct we've been working with supports piecemeal construction, in addition to the "all at once" method we've been doing.  Suppose you're writing a search function, which receives criterion and then must construct a select from it.  To accomplish this, upon each criterion encountered, you apply "generative" criterion to an existing `select()` construct with new elements, one at a time.  We start with a basic `select()` constructed with the shortcut method available on the `users` table:
-
-    {python}
-    >>> query = users.select()
-    >>> print query
-    SELECT users.id, users.name, users.fullname 
-    FROM users
-    
-We encounter search criterion of "name='jack'".  So we apply WHERE criterion stating such:
-
-    {python}
-    >>> query = query.where(users.c.name=='jack')
-    
-Next, we encounter that they'd like the results in descending order by full name.  We apply ORDER BY, using an extra modifier `desc`:
-
-    {python}
-    >>> query = query.order_by(users.c.fullname.desc())
-    
-We also come across that they'd like only users who have an address at MSN.  A quick way to tack this on is by using an EXISTS clause, which we correlate to the `users` table in the enclosing SELECT:
-
-    {python}
-    >>> from sqlalchemy.sql import exists
-    >>> query = query.where(
-    ...    exists([addresses.c.id], 
-    ...        and_(addresses.c.user_id==users.c.id, addresses.c.email_address.like('%@msn.com'))
-    ...    ).correlate(users))
-    
-And finally, the application also wants to see the listing of email addresses at once; so to save queries, we outerjoin the `addresses` table (using an outer join so that users with no addresses come back as well; since we're programmatic, we might not have kept track that we used an EXISTS clause against the `addresses` table too...).  Additionally, since the `users` and `addresses` table both have a column named `id`, let's isolate their names from each other in the COLUMNS clause by using labels:
-
-    {python}
-    >>> query = query.column(addresses).select_from(users.outerjoin(addresses)).apply_labels()
-    
-Let's bake for .0001 seconds and see what rises:
-
-    {python}
-    {opensql}>>> conn.execute(query).fetchall()
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, addresses.id AS addresses_id, addresses.user_id AS addresses_user_id, addresses.email_address AS addresses_email_address 
-    FROM users LEFT OUTER JOIN addresses ON users.id = addresses.user_id 
-    WHERE users.name = ? AND (EXISTS (SELECT addresses.id 
-    FROM addresses 
-    WHERE addresses.user_id = users.id AND addresses.email_address LIKE ?)) ORDER BY users.fullname DESC
-    ['jack', '%@msn.com']
-    {stop}[(1, u'jack', u'Jack Jones', 1, 1, u'jack@yahoo.com'), (1, u'jack', u'Jack Jones', 2, 1, u'jack@msn.com')]
-
-So we started small, added one little thing at a time, and at the end we have a huge statement..which actually works.  Now let's do one more thing; the searching function wants to add another `email_address` criterion on, however it doesn't want to construct an alias of the `addresses` table; suppose many parts of the application are written to deal specifically with the `addresses` table, and to change all those functions to support receiving an arbitrary alias of the address would be cumbersome.  We can actually *convert* the `addresses` table within the *existing* statement to be an alias of itself, using `replace_selectable()`:
-
-    {python}
-    >>> a1 = addresses.alias()
-    >>> query = query.replace_selectable(addresses, a1)
-    >>> print query
-    {opensql}SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, addresses_1.id AS addresses_1_id, addresses_1.user_id AS addresses_1_user_id, addresses_1.email_address AS addresses_1_email_address 
-    FROM users LEFT OUTER JOIN addresses AS addresses_1 ON users.id = addresses_1.user_id 
-    WHERE users.name = :name_1 AND (EXISTS (SELECT addresses_1.id 
-    FROM addresses AS addresses_1 
-    WHERE addresses_1.user_id = users.id AND addresses_1.email_address LIKE :email_address_1)) ORDER BY users.fullname DESC
-
-One more thing though, with automatic labeling applied as well as anonymous aliasing, how do we retrieve the columns from the rows for this thing ?  The label for the `email_addresses` column is now the generated name `addresses_1_email_address`; and in another statement might be something different !  This is where accessing by result columns by `Column` object becomes very useful:
-
-    {python}    
-    {sql}>>> for row in conn.execute(query):
-    ...     print "Name:", row[users.c.name], "; Email Address", row[a1.c.email_address]
-    SELECT users.id AS users_id, users.name AS users_name, users.fullname AS users_fullname, addresses_1.id AS addresses_1_id, addresses_1.user_id AS addresses_1_user_id, addresses_1.email_address AS addresses_1_email_address 
-    FROM users LEFT OUTER JOIN addresses AS addresses_1 ON users.id = addresses_1.user_id 
-    WHERE users.name = ? AND (EXISTS (SELECT addresses_1.id 
-    FROM addresses AS addresses_1 
-    WHERE addresses_1.user_id = users.id AND addresses_1.email_address LIKE ?)) ORDER BY users.fullname DESC
-    ['jack', '%@msn.com']
-    {stop}Name: jack ; Email Address jack@yahoo.com
-    Name: jack ; Email Address jack@msn.com
-
-The above example, by its end, got significantly more intense than the typical end-user constructed SQL will usually be.  However when writing higher-level tools such as ORMs, they become more significant.  SQLAlchemy's ORM relies very heavily on techniques like this.
-
-## Everything Else {@name=everythingelse}
-
-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 important things we'll need to know.
-
-### Bind Parameter Objects {@name=bindparams}
-
-Throughout all these examples, SQLAlchemy is busy creating bind parameters wherever literal expressions occur.  You can also specify your own bind parameters with your own names, and use the same statement repeatedly.  The database dialect converts to the appropriate named or positional style, as here where it converts to positional for SQLite:
-
-    {python}
-    >>> from sqlalchemy.sql import bindparam
-    >>> s = users.select(users.c.name==bindparam('username'))
-    {sql}>>> conn.execute(s, username='wendy').fetchall()
-    SELECT users.id, users.name, users.fullname 
-    FROM users 
-    WHERE users.name = ?
-    ['wendy']
-    {stop}[(2, u'wendy', u'Wendy Williams')]
-
-Another important aspect of bind parameters is that they may be assigned a type.  The type of the bind parameter will determine its behavior within expressions and also how the data bound to it is processed before being sent off to the database:
-
-    {python}
-    >>> s = users.select(users.c.name.like(bindparam('username', type_=String) + text("'%'")))
-    {sql}>>> conn.execute(s, username='wendy').fetchall()
-    SELECT users.id, users.name, users.fullname 
-    FROM users 
-    WHERE users.name LIKE ? || '%'
-    ['wendy']
-    {stop}[(2, u'wendy', u'Wendy Williams')]
-    
-    
-Bind parameters of the same name can also be used multiple times, where only a single named value is needed in the execute parameters:
-
-    {python}
-    >>> s = select([users, addresses], 
-    ...    users.c.name.like(bindparam('name', type_=String) + text("'%'")) | 
-    ...    addresses.c.email_address.like(bindparam('name', type_=String) + text("'@%'")), 
-    ...    from_obj=[users.outerjoin(addresses)])
-    {sql}>>> conn.execute(s, name='jack').fetchall()
-    SELECT users.id, users.name, users.fullname, addresses.id, addresses.user_id, addresses.email_address 
-    FROM users LEFT OUTER JOIN addresses ON users.id = addresses.user_id 
-    WHERE users.name LIKE ? || '%' OR addresses.email_address LIKE ? || '@%'
-    ['jack', 'jack']
-    {stop}[(1, u'jack', u'Jack Jones', 1, 1, u'jack@yahoo.com'), (1, u'jack', u'Jack Jones', 2, 1, u'jack@msn.com')]
-
-### Functions {@name=functions}
-
-SQL functions are created using the `func` keyword, which generates functions using attribute access:
-
-    {python}
-    >>> from sqlalchemy.sql import func
-    >>> print func.now()
-    now()
-
-    >>> print func.concat('x', 'y')
-    concat(:param_1, :param_2)
-    
-Certain functions are marked as "ANSI" functions, which mean they don't get the parenthesis added after them, such as CURRENT_TIMESTAMP:
-
-    {python}
-    >>> print func.current_timestamp()
-    CURRENT_TIMESTAMP
-    
-Functions are most typically used in the columns clause of a select statement, and can also be labeled as well as given a type.  Labeling a function is recommended so that the result can be targeted in a result row based on a string name, and assigning it a type is required when you need result-set processing to occur, such as for Unicode conversion and date conversions.  Below, we use the result function `scalar()` to just read the first column of the first row and then close the result; the label, even though present, is not important in this case:
-
-    {python}
-    >>> print conn.execute(
-    ...     select([func.max(addresses.c.email_address, type_=String).label('maxemail')])
-    ... ).scalar()
-    {opensql}SELECT max(addresses.email_address) AS maxemail 
-    FROM addresses
-    []
-    {stop}www@www.org
-    
-Databases such as PostgreSQL and Oracle which support functions that return whole result sets can be assembled into selectable units, which can be used in statements.   Such as, a database function `calculate()` which takes the parameters `x` and `y`, and returns three columns which we'd like to name `q`, `z` and `r`, we can construct using "lexical" column objects as well as bind parameters:
-
-    {python}
-    >>> from sqlalchemy.sql import column
-    >>> calculate = select([column('q'), column('z'), column('r')], 
-    ...     from_obj=[func.calculate(bindparam('x'), bindparam('y'))])
-    
-    >>> print select([users], users.c.id > calculate.c.z)
-    SELECT users.id, users.name, users.fullname 
-    FROM users, (SELECT q, z, r 
-    FROM calculate(:x, :y)) 
-    WHERE users.id > z
-    
-If we wanted to use our `calculate` statement twice with different bind parameters, the `unique_params()` function will create copies for us, and mark the bind parameters as "unique" so that conflicting names are isolated.  Note we also make two separate aliases of our selectable:
-
-    {python}
-    >>> s = select([users], users.c.id.between(
-    ...    calculate.alias('c1').unique_params(x=17, y=45).c.z, 
-    ...    calculate.alias('c2').unique_params(x=5, y=12).c.z))
-    
-    >>> print s
-    SELECT users.id, users.name, users.fullname 
-    FROM users, (SELECT q, z, r 
-    FROM calculate(:x_1, :y_1)) AS c1, (SELECT q, z, r 
-    FROM calculate(:x_2, :y_2)) AS c2 
-    WHERE users.id BETWEEN c1.z AND c2.z
-
-    >>> s.compile().params
-    {'x_2': 5, 'y_2': 12, 'y_1': 45, 'x_1': 17}
-    
-### Unions and Other Set Operations {@name=unions}
-
-Unions come in two flavors, UNION and UNION ALL, which are available via module level functions:
-
-    {python}
-    >>> from sqlalchemy.sql import union
-    >>> u = union(
-    ...     addresses.select(addresses.c.email_address=='foo@bar.com'),
-    ...    addresses.select(addresses.c.email_address.like('%@yahoo.com')),
-    ... ).order_by(addresses.c.email_address)
-
-    {sql}>>> print conn.execute(u).fetchall()
-    SELECT addresses.id, addresses.user_id, addresses.email_address 
-    FROM addresses 
-    WHERE addresses.email_address = ? UNION SELECT addresses.id, addresses.user_id, addresses.email_address 
-    FROM addresses 
-    WHERE addresses.email_address LIKE ? ORDER BY addresses.email_address
-    ['foo@bar.com', '%@yahoo.com']
-    {stop}[(1, 1, u'jack@yahoo.com')]
-    
-Also available, though not supported on all databases, are `intersect()`, `intersect_all()`, `except_()`, and `except_all()`:
-
-    {python}
-    >>> from sqlalchemy.sql import except_
-    >>> u = except_(
-    ...    addresses.select(addresses.c.email_address.like('%@%.com')),
-    ...    addresses.select(addresses.c.email_address.like('%@msn.com'))
-    ... )
-
-    {sql}>>> print conn.execute(u).fetchall()
-    SELECT addresses.id, addresses.user_id, addresses.email_address 
-    FROM addresses 
-    WHERE addresses.email_address LIKE ? EXCEPT SELECT addresses.id, addresses.user_id, addresses.email_address 
-    FROM addresses 
-    WHERE addresses.email_address LIKE ?
-    ['%@%.com', '%@msn.com']
-    {stop}[(1, 1, u'jack@yahoo.com'), (4, 2, u'wendy@aol.com')]
-
-### Scalar Selects {@name=scalar}
-
-To embed a SELECT in a column expression, use `as_scalar()`:
-
-    {python}
-    {sql}>>> print conn.execute(select([   # doctest: +NORMALIZE_WHITESPACE
-    ...       users.c.name, 
-    ...       select([func.count(addresses.c.id)], users.c.id==addresses.c.user_id).as_scalar()
-    ...    ])).fetchall()
-    SELECT users.name, (SELECT count(addresses.id) AS count_1
-    FROM addresses 
-    WHERE users.id = addresses.user_id) AS anon_1 
-    FROM users
-    []
-    {stop}[(u'jack', 2), (u'wendy', 2), (u'fred', 0), (u'mary', 0)]
-
-Alternatively, applying a `label()` to a select evaluates it as a scalar as well:
-
-    {python}
-    {sql}>>> print conn.execute(select([    # doctest: +NORMALIZE_WHITESPACE
-    ...       users.c.name, 
-    ...       select([func.count(addresses.c.id)], users.c.id==addresses.c.user_id).label('address_count')
-    ...    ])).fetchall()
-    SELECT users.name, (SELECT count(addresses.id) AS count_1
-    FROM addresses 
-    WHERE users.id = addresses.user_id) AS address_count 
-    FROM users
-    []
-    {stop}[(u'jack', 2), (u'wendy', 2), (u'fred', 0), (u'mary', 0)]
-
-### Correlated Subqueries {@name=correlated}
-
-Notice in the examples on "scalar selects", the FROM clause of each embedded select did not contain the `users` table in its FROM clause.  This is because SQLAlchemy automatically attempts to correlate embedded FROM objects to that of an enclosing query.  To disable this, or to specify explicit FROM clauses to be correlated, use `correlate()`:
-
-    {python}
-    >>> s = select([users.c.name], users.c.id==select([users.c.id]).correlate(None))
-    >>> print s
-    SELECT users.name 
-    FROM users 
-    WHERE users.id = (SELECT users.id 
-    FROM users)
-
-    {python}
-    >>> s = select([users.c.name, addresses.c.email_address], users.c.id==
-    ...        select([users.c.id], users.c.id==addresses.c.user_id).correlate(addresses)
-    ...    )
-    >>> print s
-    SELECT users.name, addresses.email_address 
-    FROM users, addresses 
-    WHERE users.id = (SELECT users.id 
-    FROM users 
-    WHERE users.id = addresses.user_id)
-
-### Ordering, Grouping, Limiting, Offset...ing... {@name=ordering}
-
-The `select()` function can take keyword arguments `order_by`, `group_by` (as well as `having`), `limit`, and `offset`.  There's also `distinct=True`.  These are all also available as generative functions.  `order_by()` expressions can use the modifiers `asc()` or `desc()` to indicate ascending or descending.  
-
-    {python}
-    >>> s = select([addresses.c.user_id, func.count(addresses.c.id)]).\
-    ...     group_by(addresses.c.user_id).having(func.count(addresses.c.id)>1)
-    {opensql}>>> print conn.execute(s).fetchall()
-    SELECT addresses.user_id, count(addresses.id) AS count_1 
-    FROM addresses GROUP BY addresses.user_id 
-    HAVING count(addresses.id) > ?
-    [1]
-    {stop}[(1, 2), (2, 2)]
-    
-    >>> s = select([addresses.c.email_address, addresses.c.id]).distinct().\
-    ...     order_by(addresses.c.email_address.desc(), addresses.c.id)
-    {opensql}>>> conn.execute(s).fetchall()
-    SELECT DISTINCT addresses.email_address, addresses.id 
-    FROM addresses ORDER BY addresses.email_address DESC, addresses.id
-    []
-    {stop}[(u'www@www.org', 3), (u'wendy@aol.com', 4), (u'jack@yahoo.com', 1), (u'jack@msn.com', 2)]
-    
-    >>> s = select([addresses]).offset(1).limit(1)
-    {opensql}>>> print conn.execute(s).fetchall() # doctest: +NORMALIZE_WHITESPACE
-    SELECT addresses.id, addresses.user_id, addresses.email_address 
-    FROM addresses 
-    LIMIT 1 OFFSET 1
-    []
-    {stop}[(2, 1, u'jack@msn.com')]
-    
-## Updates {@name=update}
-
-Finally, we're back to UPDATE.  Updates work a lot like INSERTS, except there is an additional WHERE clause that can be specified.
-
-    {python}
-    >>> # change 'jack' to 'ed'
-    {sql}>>> conn.execute(users.update(users.c.name=='jack'), name='ed') #doctest: +ELLIPSIS
-    UPDATE users SET name=? WHERE users.name = ?
-    ['ed', 'jack']
-    COMMIT
-    {stop}<sqlalchemy.engine.base.ResultProxy object at 0x...>
-    
-    >>> # use bind parameters
-    >>> u = users.update(users.c.name==bindparam('oldname'), values={'name':bindparam('newname')})
-    {sql}>>> conn.execute(u, oldname='jack', newname='ed') #doctest: +ELLIPSIS
-    UPDATE users SET name=? WHERE users.name = ?
-    ['ed', 'jack']
-    COMMIT
-    {stop}<sqlalchemy.engine.base.ResultProxy object at 0x...>
-
-    >>> # update a column to an expression
-    {sql}>>> conn.execute(users.update(values={users.c.fullname:"Fullname: " + users.c.name})) #doctest: +ELLIPSIS
-    UPDATE users SET fullname=(? || users.name)
-    ['Fullname: ']
-    COMMIT
-    {stop}<sqlalchemy.engine.base.ResultProxy object at 0x...>
-
-### Correlated Updates {@name=correlated}
-
-A correlated update lets you update a table using selection from another table, or the same table:
-
-    {python}
-    >>> s = select([addresses.c.email_address], addresses.c.user_id==users.c.id).limit(1)
-    {sql}>>> conn.execute(users.update(values={users.c.fullname:s})) #doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
-    UPDATE users SET fullname=(SELECT addresses.email_address 
-    FROM addresses 
-    WHERE addresses.user_id = users.id 
-    LIMIT 1 OFFSET 0)
-    []
-    COMMIT
-    {stop}<sqlalchemy.engine.base.ResultProxy object at 0x...>
-
-## Deletes {@name=delete}
-
-Finally, a delete.  Easy enough:
-
-    {python}
-    {sql}>>> conn.execute(addresses.delete()) #doctest: +ELLIPSIS
-    DELETE FROM addresses
-    []
-    COMMIT
-    {stop}<sqlalchemy.engine.base.ResultProxy object at 0x...>
-    
-    {sql}>>> conn.execute(users.delete(users.c.name > 'm')) #doctest: +ELLIPSIS
-    DELETE FROM users WHERE users.name > ?
-    ['m']
-    COMMIT
-    {stop}<sqlalchemy.engine.base.ResultProxy object at 0x...>
-
-## Further Reference {@name=reference}
-
-The best place to get every possible name you can use in constructed SQL is the [Generated Documentation](rel:docstrings_sqlalchemy.sql.expression).
-
-Table Metadata Reference: [metadata](rel:metadata)
-
-Engine/Connection/Execution Reference: [dbengine](rel:dbengine)
-
-SQL Types: [types](rel:types)
-
-    
diff --git a/doc/build/oldcontent/tutorial.txt b/doc/build/oldcontent/tutorial.txt
deleted file mode 100644 (file)
index 5689ee2..0000000
+++ /dev/null
@@ -1,523 +0,0 @@
-Tutorial
-========
-This tutorial provides a relatively simple walking tour through the basic concepts of SQLAlchemy.  You may wish to skip it and dive into the [main manual][manual] which is more reference-oriented.  The examples in this tutorial comprise a fully working interactive Python session, and are guaranteed to be functioning courtesy of [doctest][].
-
-[doctest]: http://www.python.org/doc/lib/module-doctest.html
-[manual]: rel:metadata
-
-Installation
-------------
-
-### Installing SQLAlchemy {@name=sqlalchemy}
-
-Installing SQLAlchemy from scratch is most easily achieved with [setuptools][].  ([setuptools installation][install setuptools]). Just run this from the command-line:
-    
-    # easy_install SQLAlchemy
-
-This command will download the latest version of SQLAlchemy from the [Python Cheese Shop][cheese] and install it to your system.
-
-[setuptools]: http://peak.telecommunity.com/DevCenter/setuptools
-[install setuptools]: http://peak.telecommunity.com/DevCenter/EasyInstall#installation-instructions
-[cheese]: http://cheeseshop.python.org/pypi/SQLAlchemy
-
-Otherwise, you can install from the distribution using the `setup.py` script:
-
-    # python setup.py install
-
-### Installing a Database API {@name=dbms}
-
-SQLAlchemy is designed to operate with a [DBAPI](http://www.python.org/doc/peps/pep-0249/) implementation built for a particular database, and includes support for the most popular databases. If you have one of the [supported DBAPI implementations](rel:dbengine_supported), you can proceed to the following section. Otherwise [SQLite][] is an easy-to-use database to get started with, which works with plain files or in-memory databases.
-
-SQLite is included with Python 2.5 and greater.
-
-If you are working with Python 2.3 or 2.4, SQLite and the Python API for SQLite can be installed from the following packages:
-
-  * [pysqlite][] - Python interface for SQLite
-  * [SQLite library](http://sqlite.org)
-
-Note that the SQLite library download is not required with Windows, as the Windows Pysqlite library already includes it linked in.  Pysqlite and SQLite can also be installed on Linux or FreeBSD via pre-made [packages][pysqlite packages] or [from sources][pysqlite].
-
-[sqlite]: http://sqlite.org/
-[pysqlite]: http://pysqlite.org/
-[pysqlite packages]: http://initd.org/tracker/pysqlite/wiki/PysqlitePackages
-
-Getting Started {@name=gettingstarted}
---------------------------
-### Checking the Version
-**Note:  This tutorial is oriented towards version 0.4 of SQLAlchemy. ** Check the version of SQLAlchemy you have installed via:
-
-     {python}
-     >>> import sqlalchemy
-     >>> sqlalchemy.__version__ # doctest: +SKIP
-     0.4.0
-
-### Imports
-
-To start connecting to databases and begin issuing queries, we want to import the base of SQLAlchemy's functionality, which is provided under the module name of `sqlalchemy`.  For the purposes of this tutorial, we will import its full list of symbols into our own local namespace.  
-
-    {python}
-    >>> from sqlalchemy import *
-
-Note that importing using the `*` operator pulls all the names from `sqlalchemy` into the local module namespace, which in a real application can produce name conflicts.  Therefore it's recommended in practice to either import the individual symbols desired (i.e. `from sqlalchemy import Table, Column`) or to import under a distinct namespace (i.e. `import sqlalchemy as sa`).
-
-### Connecting to the Database
-
-After our imports, the next thing we need is a handle to the desired database, represented by an `Engine` object.  This object handles the business of managing connections and dealing with the specifics of a particular database.  Below, we will make a SQLite connection to a file-based database called "tutorial.db".
-
-    {python}
-    >>> db = create_engine('sqlite:///tutorial.db')
-    
-Technically, the above statement did not make an actual connection to the SQLite database just yet.  As soon as we begin working with the engine, it will start creating connections.  In the case of SQLite, the `tutorial.db` file will actually be created at the moment it is first used, if the file does not exist already.
-
-For full information on creating database engines, including those for SQLite and others, see [dbengine](rel:dbengine).
-
-SQLAlchemy is Two Libraries in One {@name=twoinone}
-----------------------------------------------------
-
-Now that the basics of installing SQLAlchemy and connecting to our database are established, we can start getting in to actually doing something.  But first, a little bit of explanation is required.
-
-A central concept of SQLAlchemy is that it actually contains two distinct areas of functionality, one of which builds upon the other.  One is a **SQL Construction Language** and the other is an **Object Relational Mapper** ("ORM" for short).  The SQL construction language allows you to construct objects called `ClauseElements` which represent SQL expressions.  These ClauseElements can then be executed against any database, where they are **compiled** into strings that are appropriate for the target database, and return an object called a `ResultProxy`, which is essentially a result set object that acts very much like a deluxe version of the dbapi `cursor` object.
-
-The Object Relational Mapper (ORM) is a set of tools completely distinct from the SQL Construction Language which serve the purpose of mapping Python object instances into database rows, providing a rich selection interface with which to retrieve instances from tables as well as a comprehensive solution to persisting changes on those instances back into the database.  When working with the ORM, its underlying workings as well as its public API make extensive use of the SQL Construction Language, however the general theory of operation is slightly different.  Instead of working with database rows directly, you work with your own user-defined classes and object instances.  Additionally, the method of issuing queries to the database is different, as the ORM handles the job of generating most of the SQL required, and instead requires more information about what kind of class instances you'd like to load and where you'd like to put them.
-
-Where SA is somewhat unique, more powerful, and slightly more complicated is that the two areas of functionality can be mixed together in many ways.  A key strategy to working with SA effectively is to have a solid awareness of these two distinct toolsets, and which concepts of SA belong to each - even some publications have confused the SQL Construction Language with the ORM.  The key difference between the two is that when you're working with cursor-like result sets it's the SQL Construction Language, and when working with collections of your own class instances it's the Object Relational Mapper.
-
-This tutorial will first focus on the basic configuration that is common to using both the SQL Construction Language as well as the ORM, which is to declare information about your database called **table metadata**.  This will be followed by some constructed SQL examples, and then into usage of the ORM utilizing the same data we established in the SQL construction examples.
-
-Working with Database Objects {@name=schemasql}
------------------------------------------------
-
-### Defining Metadata, Binding to Engines {@name=metadata}
-
-Configuring SQLAlchemy for your database consists of creating objects called `Tables`, each of which represent an actual table in the database.  A collection of `Table` objects resides in a `MetaData` object which is essentially a table collection.  We will create a `MetaData` and connect it to our `Engine` (connecting a schema object to an Engine is called *binding*):
-
-    {python}
-    >>> metadata = MetaData()
-    >>> metadata.bind = db
-
-An equivalent operation is to create the `MetaData` object directly with the Engine:
-
-    {python}
-    >>> metadata = MetaData(db)
-    
-Now, when we tell "metadata" about the tables in our database, we can issue CREATE statements for those tables, as well as execute SQL statements derived from them, without needing to open or close any connections; that will be all done automatically.
-
-Note that SQLALchemy allows us to use explicit connection objects for everything, if we wanted to, and there are reasons why you might want to do this.  But for the purposes of this tutorial, using `bind` removes the need for us to deal with explicit connections.
-
-### Creating a Table {@name=table_creating}
-
-With `metadata` as our established home for tables, lets make a Table for it:
-
-    {python}
-    >>> users_table = Table('users', metadata,
-    ...     Column('user_id', Integer, primary_key=True),
-    ...     Column('user_name', String(40)),
-    ...     Column('password', String(15))
-    ... )
-
-As you might have guessed, we have just defined a table named `users` which has three columns: `user_id` (which is a primary key column), `user_name` and `password`. Currently it is just an object that doesn't necessarily correspond to an existing table in our database.  To actually create the table, we use the `create()` method.  To make it interesting, we will have SQLAlchemy echo the SQL statements it sends to the database, by setting the `echo` flag on the `Engine` associated with our `MetaData`:
-
-    {python}
-    >>> metadata.bind.echo = True
-    >>> users_table.create() # doctest:+ELLIPSIS,+NORMALIZE_WHITESPACE
-    CREATE TABLE users (
-        user_id INTEGER NOT NULL,
-        user_name VARCHAR(40),
-        password VARCHAR(15),
-        PRIMARY KEY (user_id)
-    )
-    ...
-
-Alternatively, the `users` table might already exist (such as, if you're running examples from this tutorial for the second time), in which case you can just skip the `create()` method call. You can even skip defining the individual columns in the `users` table and ask SQLAlchemy to load its definition from the database:
-
-    {python}
-    >>> users_table = Table('users', metadata, autoload=True)
-    >>> list(users_table.columns)[0].name
-    'user_id'
-
-Loading a table's columns from the database is called **reflection**.  Documentation on table metadata, including reflection, is available in [metadata](rel:metadata).
-
-### Inserting Rows
-
-Inserting is achieved via the `insert()` method, which defines a *clause object* (known as a `ClauseElement`) representing an INSERT statement:
-
-    {python}
-    >>> i = users_table.insert()
-    >>> i # doctest:+ELLIPSIS
-    <sqlalchemy.sql.Insert object at 0x...>
-    >>> # the string form of the Insert object is a generic SQL representation
-    >>> print i
-    INSERT INTO users (user_id, user_name, password) VALUES (?, ?, ?)
-
-Since we created this insert statement object from the `users` table which is bound to our `Engine`, the statement itself is also bound to the `Engine`, and supports executing itself.  The `execute()` method of the clause object will *compile* the object into a string according to the underlying *dialect* of the Engine to which the statement is bound, and will then execute the resulting statement.  
-
-    {python}
-    >>> # insert a single row
-    >>> i.execute(user_name='Mary', password='secure') # doctest:+ELLIPSIS,+NORMALIZE_WHITESPACE
-    INSERT INTO users (user_name, password) VALUES (?, ?)
-    ['Mary', 'secure']
-    COMMIT
-    <sqlalchemy.engine.base.ResultProxy object at 0x...>
-
-    >>> # insert multiple rows simultaneously
-    >>> i.execute({'user_name':'Tom'}, {'user_name':'Fred'}, {'user_name':'Harry'}) # doctest:+ELLIPSIS,+NORMALIZE_WHITESPACE
-    INSERT INTO users (user_name) VALUES (?)
-    [['Tom'], ['Fred'], ['Harry']]
-    COMMIT
-    <sqlalchemy.engine.base.ResultProxy object at 0x...>
-
-
-Note that the `VALUES` clause of each `INSERT` statement was automatically adjusted to correspond to the parameters sent to the `execute()` method.  This is because the compilation step of a `ClauseElement` takes into account not just the constructed SQL object and the specifics of the type of database being used, but the execution parameters sent along as well.
-
-When constructing clause objects, SQLAlchemy will bind all literal values into bind parameters.  On the construction side, bind parameters are always treated as named parameters.  At compilation time, SQLAlchemy will convert them into their proper format, based on the paramstyle of the underlying DBAPI.  This works equally well for all named and positional bind parameter formats described in the DBAPI specification.
-
-Documentation on inserting: [sql_insert](rel:sql_insert).
-
-### Selecting
-
-Let's check that the data we have put into `users` table is actually there. The procedure is analogous to the insert example above, except you now call the `select()` method off the `users` table:
-
-    {python}
-    >>> s = users_table.select()
-    >>> print s
-    SELECT users.user_id, users.user_name, users.password 
-    FROM users
-    >>> r = s.execute()
-    SELECT users.user_id, users.user_name, users.password 
-    FROM users
-    []
-    
-This time, we won't ignore the return value of `execute()`.  Its an instance of `ResultProxy`, which is a result-holding object that behaves very similarly to the `cursor` object one deals with directly with a database API:
-
-    {python}
-    >>> r # doctest:+ELLIPSIS
-    <sqlalchemy.engine.base.ResultProxy object at 0x...>
-    >>> r.fetchone()
-    (1, u'Mary', u'secure')
-    >>> r.fetchall()
-    [(2, u'Tom', None), (3, u'Fred', None), (4, u'Harry', None)]
-
-Query criterion for the select is specified using Python expressions, using the `Column` objects in the `Table` as a base.  All expressions constructed from `Column` objects are themselves instances of `ClauseElements`, just like the `Select`, `Insert`, and `Table` objects themselves.
-
-    {python}
-    >>> r = users_table.select(users_table.c.user_name=='Harry').execute()
-    SELECT users.user_id, users.user_name, users.password 
-    FROM users 
-    WHERE users.user_name = ?
-    ['Harry']
-    >>> row = r.fetchone()
-    >>> print row
-    (4, u'Harry', None)
-    
-Pretty much the full range of standard SQL operations are supported as constructed Python expressions, including joins, ordering, grouping, functions, correlated subqueries, unions, etc. Documentation on selecting: [sql_select](rel:sql_select).
-
-### Working with Rows
-
-You can see that when we print out the rows returned by an execution result, it prints the rows as tuples.  These rows support both the list and dictionary interfaces.  The dictionary interface allows the addressing of columns by string column name, or even the original `Column` object:
-
-    {python}
-    >>> row.keys()
-    [u'user_id', u'user_name', u'password']
-    >>> row['user_id'], row[1], row[users_table.c.password] 
-    (4, u'Harry', None)
-
-Addressing the columns in a row based on the original `Column` object is especially handy, as it eliminates the need to work with literal column names altogether.
-
-Result sets also support iteration.  We'll show this with a slightly different form of `select` that allows you to specify the specific columns to be selected:
-
-    {python}
-    >>> for row in select([users_table.c.user_id, users_table.c.user_name]).execute(): # doctest:+NORMALIZE_WHITESPACE
-    ...     print row
-    SELECT users.user_id, users.user_name
-    FROM users
-    []
-    (1, u'Mary')
-    (2, u'Tom')
-    (3, u'Fred')
-    (4, u'Harry')
-
-### Table Relationships {@name=table_relationships}
-
-Lets create a second table, `email_addresses`, which references the `users` table.  To define the relationship between the two tables, we will use the `ForeignKey` construct.  We will also issue the `CREATE` statement for the table:
-
-    {python}
-    >>> email_addresses_table = Table('email_addresses', metadata,
-    ...     Column('address_id', Integer, primary_key=True),
-    ...     Column('email_address', String(100), nullable=False),
-    ...     Column('user_id', Integer, ForeignKey('users.user_id')))
-    >>> email_addresses_table.create() # doctest:+ELLIPSIS,+NORMALIZE_WHITESPACE
-    CREATE TABLE email_addresses (
-        address_id INTEGER NOT NULL,
-        email_address VARCHAR(100) NOT NULL,
-        user_id INTEGER,
-        PRIMARY KEY (address_id),
-        FOREIGN KEY(user_id) REFERENCES users (user_id)
-    )
-    ...
-
-Above, the `email_addresses` table is related to the `users` table via the `ForeignKey('users.user_id')`.  The `ForeignKey` constructor can take a `Column` object or a string representing the table and column name.  When using the string argument, the referenced table must exist within the same `MetaData` object; thats where it looks for the other table!
-
-Next, lets put a few rows in:
-
-    {python}
-    >>> email_addresses_table.insert().execute(
-    ...     {'email_address':'tom@tom.com', 'user_id':2},
-    ...     {'email_address':'mary@mary.com', 'user_id':1}) #doctest:+ELLIPSIS
-    INSERT INTO email_addresses (email_address, user_id) VALUES (?, ?)
-    [['tom@tom.com', 2], ['mary@mary.com', 1]]
-    COMMIT
-    <sqlalchemy.engine.base.ResultProxy object at 0x...>
-
-With two related tables, we can now construct a join amongst them using the `join` method:
-
-    {python}
-    >>> r = users_table.join(email_addresses_table).select(order_by=users_table.c.user_id).execute()
-    SELECT users.user_id, users.user_name, users.password, email_addresses.address_id, email_addresses.email_address, email_addresses.user_id 
-    FROM users JOIN email_addresses ON users.user_id = email_addresses.user_id ORDER BY users.user_id
-    []
-    >>> print [row for row in r]
-    [(1, u'Mary', u'secure', 2, u'mary@mary.com', 1), (2, u'Tom', None, 1, u'tom@tom.com', 2)]
-    
-The `join` method is also a standalone function in the `sqlalchemy` namespace.  The join condition is figured out from the foreign keys of the Table objects given.  The condition (also called the "ON clause") can be specified explicitly, such as in this example which creates a join representing all users that used their email address as their password:
-
-    {python}
-    >>> print join(users_table, email_addresses_table, 
-    ...     and_(users_table.c.user_id==email_addresses_table.c.user_id, 
-    ...     users_table.c.password==email_addresses_table.c.email_address)
-    ...     )
-    users JOIN email_addresses ON users.user_id = email_addresses.user_id AND users.password = email_addresses.email_address
-
-Working with Object Mappers {@name=orm}
------------------------------------------------
-
-Now that we have a little bit of Table and SQL operations covered, lets look into SQLAlchemy's ORM (object relational mapper).  With the ORM, you associate Tables (and other *Selectable* units, like queries and table aliases) with Python classes, into units called **Mappers**.  Then you can execute queries that return lists of object instances, instead of result sets.  The object instances themselves are associated with an object called a **Session**, which automatically tracks changes on each object and supports a "save all at once" operation called a **flush**.
-
-To start, we will import the names necessary to use SQLAlchemy's ORM, again using `import *` for simplicities sake, even though we all know that in real life we should be importing individual names via "`from sqlalchemy.orm import symbol1, symbol2, ...`" or "`import sqlalchemy.orm as orm`":
-
-    {python}
-    >>> from sqlalchemy.orm import *
-    
-It should be noted that the above step is technically not needed when working with the 0.3 series of SQLAlchemy; all symbols from the `orm` package are also included in the `sqlalchemy` package.  However, a future release (most likely the 0.4 series) will make the separate `orm` import required in order to use the object relational mapper, so it's a good practice for now.
-
-### Creating a Mapper {@name=mapper}
-
-A Mapper is usually created once per Python class, and at its core primarily means to say, "objects of this class are to be stored as rows in this table".  Lets create a class called `User`, which will represent a user object that is stored in our `users` table:
-
-    {python}
-    >>> class User(object):
-    ...     def __repr__(self):
-    ...        return "%s(%r,%r)" % (
-    ...            self.__class__.__name__, self.user_name, self.password)
-    
-The class is a new style class (i.e. it extends `object`) and does not require a constructor (although one may be provided if desired).  We just have one `__repr__` method on it which will display basic information about the User.  Note that the `__repr__` method references the instance variables `user_name` and `password` which otherwise aren't defined.  While we are free to explicitly define these attributes and treat them normally, this is optional; as SQLAlchemy's `Mapper` construct will manage them for us, since their names correspond to the names of columns in the `users` table.  Lets create a mapper, and observe that these attributes are now defined:
-
-    {python}
-    >>> mapper(User, users_table) # doctest: +ELLIPSIS
-    <sqlalchemy.orm.mapper.Mapper object at 0x...>
-    >>> u1 = User()
-    >>> print u1.user_name
-    None
-    >>> print u1.password
-    None
-    
-The `mapper` function returns a new instance of `Mapper`.  As it is the first Mapper we have created for the `User` class, it is known as the classes' *primary mapper*.  We generally don't need to hold onto the return value of the `mapper` function; SA can automatically locate this Mapper as needed when it deals with the `User` class.  
-
-### Obtaining a Session {@name=session}
-
-After you create a Mapper, all operations with that Mapper require the usage of an important object called a `Session`.  All objects loaded or saved by the Mapper must be *attached* to a `Session` object, which represents a kind of "workspace" of objects that are loaded into memory.  A particular object instance can only be attached to one `Session` at a time (but of course can be moved around or detached altogether).
-
-By default, you have to create a `Session` object explicitly before you can load or save objects.  There are several ways to manage sessions, but the most straightforward is to just create one, which we will do by saying, `create_session()`:
-
-    {python}
-    >>> session = create_session()
-    >>> session # doctest:+ELLIPSIS
-    <sqlalchemy.orm.session.Session object at 0x...>
-
-### The Query Object {@name=query}
-
-The Session has all kinds of methods on it to manage and inspect its collection of objects.  The Session also provides an easy interface which can be used to query the database, by giving you an instance to a `Query` object corresponding to a particular Python class:
-
-    {python}
-    >>> query = session.query(User)
-    >>> print query.filter_by(user_name='Harry').all()
-    SELECT users.user_id AS users_user_id, users.user_name AS users_user_name, users.password AS users_password 
-    FROM users 
-    WHERE users.user_name = ? ORDER BY users.oid
-    ['Harry']
-    [User(u'Harry',None)]
-    
-All querying for objects is performed via an instance of `Query`.  The various `select` methods on an instance of `Mapper` also use an underlying `Query` object to perform the operation.  A `Query` is always bound to a specific `Session`.
-
-Lets turn off the database echoing for a moment, and try out a few methods on `Query`.  The two methods used to narrow results are `filter()` and `filter_by()`, and the two most common methods used to load results are `all()` and `first()`.   The `get()` method is used for a quick lookup by primary key.  `filter_by()` works with keyword arguments, and `filter()` works with `ClauseElement` objects, which are constructed by using `Column` objects inside of Python expressions, in the same way as we did with our SQL select example in the previous section of this tutorial.  Using `ClauseElement` structures to query objects is more verbose but more flexible:
-
-    {python}
-    >>> metadata.bind.echo = False
-    >>> print query.filter(User.c.user_id==3).all()
-    [User(u'Fred',None)]
-    >>> print query.get(2)
-    User(u'Tom',None)
-    >>> print query.filter_by(user_name='Mary').first()
-    User(u'Mary',u'secure')
-    >>> print query.filter(User.c.password==None).first()
-    User(u'Tom',None)
-    >>> print query.count()
-    4
-
-Notice that our `User` class has a special attribute `c` attached to it.  This 'c' represents the columns on the User's mapper's Table object.  Saying `User.c.user_name` is synonymous with saying `users_table.c.user_name`, recalling that `User` is the Python class and `users_table` is our `Table` object.
-
-### Making Changes {@name=changes}
-
-With a little experience in loading objects, lets see what it's like to make changes.  First, lets create a new user "Ed".  We do this by just constructing the new object.  Then, we just add it to the session:
-
-    {python}
-    >>> ed = User()
-    >>> ed.user_name = 'Ed'
-    >>> ed.password = 'edspassword'
-    >>> session.save(ed)
-    >>> ed in session
-    True
-
-Lets also make a few changes on some of the objects in the database.  We will load them with our `Query` object, and then change some things.
-
-    {python}
-    >>> mary = query.filter_by(user_name='Mary').first()
-    >>> harry = query.filter_by(user_name='Harry').first()
-    >>> mary.password = 'marysnewpassword'
-    >>> harry.password = 'harrysnewpassword'
-    
-At the moment, nothing has been saved to the database; all of our changes are in memory only.  What happens if some other part of the application also tries to load 'Mary' from the database and make some changes before we had a chance to save it ?  Assuming that the same `Session` is used, loading 'Mary' from the database a second time will issue a second query in order locate the primary key of 'Mary', but will *return the same object instance as the one already loaded*.  This behavior is due to an important property of the `Session` known as the **identity map**:
-
-    {python}
-    >>> mary2 = query.filter_by(user_name='Mary').first()
-    >>> mary is mary2
-    True
-    
-With the identity map, a single `Session` can be relied upon to keep all loaded instances straight.
-
-As far as the issue of the same object being modified in two different Sessions, that's an issue of concurrency detection; SQLAlchemy does some basic concurrency checks when saving objects, with the option for a stronger check using version ids.  See [advdatamapping_arguments](rel:advdatamapping_arguments) for more details.
-
-### Saving {@name=saving}
-
-With a new user "ed" and some changes made on "Mary" and "Harry", lets also mark "Fred" as deleted:
-
-    {python}
-    >>> fred = query.filter_by(user_name='Fred').first()
-    >>> session.delete(fred)
-    
-Then to send all of our changes to the database, we `flush()` the Session.  Lets turn echo back on to see this happen!:
-
-    {python}
-    >>> metadata.bind.echo = True
-    >>> session.flush()
-    BEGIN
-    UPDATE users SET password=? WHERE users.user_id = ?
-    ['marysnewpassword', 1]
-    UPDATE users SET password=? WHERE users.user_id = ?
-    ['harrysnewpassword', 4]
-    INSERT INTO users (user_name, password) VALUES (?, ?)
-    ['Ed', 'edspassword']
-    DELETE FROM users WHERE users.user_id = ?
-    [3]
-    COMMIT
-
-### Relationships
-
-When our User object contains relationships to other kinds of information, such as a list of email addresses, we can indicate this by using a function when creating the `Mapper` called `relation()`.  While there is a lot you can do with relations, we'll cover a simple one here.  First, recall that our `users` table has a foreign key relationship to another table called `email_addresses`.  A single row in `email_addresses` has a column `user_id` that references a row in the `users` table; since many rows in the `email_addresses` table can reference a single row in `users`, this is called a *one to many* relationship.
-
-To illustrate this relationship, we will start with a new mapper configuration.  Since our `User` class has a mapper assigned to it, we want to discard it and start over again.  So we issue the `clear_mappers()` function first, which removes all mapping associations from classes:
-
-    {python}
-    >>> clear_mappers()
-    
-When removing mappers, it is usually best to remove all mappings at the same time, since mappers usually have relationships to each other which will become invalid if only part of the mapper collection is removed.  In practice, a particular mapping setup will usually remain throughout the lifetime of an application.  Clearing out the mappers and making new ones is a practice that is generally limited to writing mapper unit tests and experimenting from the console.
-    
-Next, we want to create a class/mapping that corresponds to the `email_addresses` table.  We will create a new class `Address` which represents a single row in the `email_addresses` table, and a corresponding `Mapper` which will associate the `Address` class with the `email_addresses` table:
-
-    {python}
-    >>> class Address(object):
-    ...     def __init__(self, email_address):
-    ...         self.email_address = email_address
-    ...     def __repr__(self):
-    ...         return "%s(%r)" % (
-    ...            self.__class__.__name__, self.email_address)    
-    >>> mapper(Address, email_addresses_table) # doctest: +ELLIPSIS
-    <sqlalchemy.orm.mapper.Mapper object at 0x...>
-    
-We then create a mapper for the `User` class which contains a relationship to the `Address` class using the `relation()` function:
-
-    {python}
-    >>> mapper(User, users_table, properties={ # doctest: +ELLIPSIS
-    ...    'addresses':relation(Address)
-    ... })
-    <sqlalchemy.orm.mapper.Mapper object at 0x...>
-
-Since we've made new mappers, we have to throw away the old `Query` object and get a new one:
-
-    >>> query = session.query(User)
-    
-The `relation()` function takes either a class or a Mapper as its first argument, and has many options to further control its behavior.  When this mapping relationship is used, each new `User` instance will contain an attribute called `addresses`.  SQLAlchemy will automatically determine that this relationship is a one-to-many relationship, and will subsequently create `addresses` as a list.  When a new `User` is created, this list will begin as empty.
-
-The order in which the mapping definitions for `User` and `Address` is created is *not significant*.  When the `mapper()` function is called, it creates an *uncompiled* mapping record corresponding to the given class/table combination.  When the mappers are first used, the entire collection of mappers created up until that point will be compiled, which involves the establishment of class instrumentation as well as the resolution of all mapping relationships.  
-
-Lets try out this new mapping configuration, and see what we get for the email addresses already in the database.  Since we have made a new mapping configuration, it's best that we clear out our `Session`, which is currently holding onto every `User` object we have already loaded:
-
-    {python}
-    >>> session.clear()
-
-We can then treat the `addresses` attribute on each `User` object like a regular list:
-
-    {python}
-    >>> mary = query.filter_by(user_name='Mary').first() # doctest: +NORMALIZE_WHITESPACE
-    SELECT users.user_id AS users_user_id, users.user_name AS users_user_name, users.password AS users_password 
-    FROM users 
-    WHERE users.user_name = ? ORDER BY users.oid 
-    LIMIT 1 OFFSET 0
-    ['Mary']
-    >>> print [a for a in mary.addresses]
-    SELECT email_addresses.address_id AS email_addresses_address_id, email_addresses.email_address AS email_addresses_email_address, email_addresses.user_id AS email_addresses_user_id 
-    FROM email_addresses 
-    WHERE ? = email_addresses.user_id ORDER BY email_addresses.oid
-    [1]
-    [Address(u'mary@mary.com')]
-
-Adding to the list is just as easy.  New `Address` objects will be detected and saved when we `flush` the Session:
-
-    {python}
-    >>> mary.addresses.append(Address('mary2@gmail.com'))
-    >>> session.flush() # doctest: +NORMALIZE_WHITESPACE
-    BEGIN
-    INSERT INTO email_addresses (email_address, user_id) VALUES (?, ?)
-    ['mary2@gmail.com', 1]
-    COMMIT
-
-
-
-Main documentation for using mappers:  [datamapping](rel:datamapping)
-
-### Transactions
-
-You may have noticed from the example above that when we say `session.flush()`, SQLAlchemy indicates the names `BEGIN` and `COMMIT` to indicate a transaction with the database.  The `flush()` method, since it may execute many statements in a row, will automatically use a transaction in order to execute these instructions.  But what if we want to use `flush()` inside of a larger transaction?  The easiest way is to use a "transactional" session; that is, when the session is created, you're automatically in a transaction which you can commit or rollback at any time.  As a bonus, it offers the ability to call `flush()` for you, whenever a query is issued; that way whatever changes you've made can be returned right back (and since it's all in a transaction, nothing gets committed until you tell it so).
-
-Below, we create a session with `autoflush=True`, which implies that it's transactional.  We can query for things as soon as they are created without the need for calling `flush()`.  At the end, we call `commit()` to persist everything permanently.
-
-    {python}
-    >>> metadata.bind.echo = False
-    >>> session = create_session(autoflush=True)
-    >>> (ed, harry, mary) = session.query(User).filter(
-    ...         User.c.user_name.in_(['Ed', 'Harry', 'Mary'])
-    ...     ).order_by(User.c.user_name).all()  # doctest: +NORMALIZE_WHITESPACE
-    >>> del mary.addresses[1]
-    >>> harry_address = Address('harry2@gmail.com')
-    >>> harry.addresses.append(harry_address) 
-    >>> session.query(User).join('addresses').filter_by(email_address='harry2@gmail.com').first() # doctest: +NORMALIZE_WHITESPACE
-    User(u'Harry',u'harrysnewpassword')
-    >>> session.commit()
-
-Main documentation:  [unitofwork](rel:unitofwork)
-
-Next Steps
-----------
-
-That covers a quick tour through the basic idea of SQLAlchemy, in its simplest form.  Beyond that, one should familiarize oneself with the basics of Sessions, the various patterns that can be used to define different kinds of Mappers and relations among them, the rudimentary SQL types that are available when constructing Tables, and the basics of Engines, SQL statements, and database Connections. 
-
diff --git a/doc/build/oldcontent/types.txt b/doc/build/oldcontent/types.txt
deleted file mode 100644 (file)
index cee82a6..0000000
+++ /dev/null
@@ -1,167 +0,0 @@
-The Types System {@name=types}
-================
-
-The package `sqlalchemy.types` defines the datatype identifiers which may be used when defining [metadata](rel:table metadata).  This package includes a set of generic types, a set of SQL-specific subclasses of those types, and a small extension system used by specific database connectors to adapt these generic types into database-specific type objects.
-
-### Built-in Types {@name=standard}
-
-SQLAlchemy comes with a set of standard generic datatypes, which are defined as classes.  Types are usually used when defining tables, and can be left as a class or instantiated, for example:
-
-    {python}
-    mytable = Table('mytable', metadata,
-        Column('myid', Integer, primary_key=True),
-        Column('data', String(30)),
-        Column('info', Unicode(100)),
-        Column('value', Number(7,4)) 
-        )
-
-Following is a rundown of the standard types.
-
-#### String
-
-This type is the base class for all string and character types.  `String` includes a `length` parameter, which will be used as the "length" when generating DDL for types such as `CHAR` and `VARCHAR`.  The base `String` type will usually generate the DDL of `VARCHAR`.  `length` has no other usage and can be omitted if DDL is not being generated.
-
-#### Unicode
-
-The `Unicode` type is a `String` which converts Python unicode objects (i.e., strings that are defined as `u'somevalue'`) into encoded bytestrings when passing the value to the database, and similarly decodes values from the database back into Python unicode objects.  The encoding used is configured on the dialect using the `encoding` parameter, which defaults to utf-8.
-
-When using the `Unicode` type, it is only appropriate to pass Python unicode objects, and not plain strings.   If a bytestring is passed, a warning is issued.  If you notice your application raising these warnings but you're not sure where, the Python `warnings` filter can be used to turn these warnings into exceptions which will illustrate a stack trace:
-
-    {python}
-    import warnings
-    warnings.simplefilter('error')
-
-Any `String` type or subtype can be turned into a `Unicode` type by passing the flags `convert_unicode=True, assert_unicode='warn'` to the constructor.  The `Unicode` type itself is shorthand for this notation.   The `create_engine()` call also accepts these flags which when passed will establish their settings as the default setting for all `String` types.
-
-#### Text / UnicodeText
-
-The `Text` and `UnicodeText` types are the same as `String` and `Unicode` except they do not take a length parameter.  They differ only in that they generate DDL of `TEXT` or `CLOB` instead of `VARCHAR`.
-
-#### Numeric
-
-Numeric types return `decimal.Decimal` objects by default.  The flag `asdecimal=False` may be specified which causes data to be passed straight from the DBAPI's preferred return type, which may be either `Decimal` or `float`.   Numeric also takes "precision" and "scale" arguments which are used when generating DDL.
-
-#### Float
-
-Float types return Python floats.  Float also takes a "precision" argument which is used when generating DDL.
-
-#### DateTime/Date/Time
-
-Date and time types return objects from the Python `datetime` module.  Most DBAPIs have built in support for the datetime module, with the noted exception of SQLite.  In the case of SQLite, date and time types are stored as strings which are then converted back to datetime objects when rows are returned.
-
-#### Interval
-
-The Interval type deals with `datetime.timedelta` objects.  In PostgreSQL, the native INTERVAL type is used; for others, the value is stored as a date which is relative to the "epoch" (Jan. 1, 1970).
-
-#### Binary
-
-The Binary type generates BLOB or BYTEA when tables are created, and also converts incoming values using the `Binary` callable provided by each DBAPI.  
-
-#### Boolean
-
-Boolean typically uses BOOLEAN or SMALLINT on the DDL side, and on the Python side deals in `True` or `False`.
-
-#### PickleType
-
-PickleType builds upon the Binary type to apply Python's `pickle.dumps()` to incoming objects, and `pickle.loads()` on the way out, allowing any pickleable Python object to be stored as a serialized binary field.
-
-#### SQL-Specific Types {@name=sqlspecific}
-
-These are subclasses of the generic types and include:
-
-    {python}
-    class FLOAT(Numeric)
-    class TEXT(String)
-    class DECIMAL(Numeric)
-    class INT(Integer)
-    INTEGER = INT
-    class TIMESTAMP(DateTime)
-    class DATETIME(DateTime)
-    class CLOB(String)
-    class VARCHAR(String)
-    class CHAR(String)
-    class BLOB(Binary)
-    class BOOLEAN(Boolean)
-
-The idea behind the SQL-specific types is that DDL (i.e. during a CREATE TABLE statement) would generate the exact type specified in all cases.   This also implies that some of these types may not be supported by all dialects.
-
-### Dialect Specific Types {@name=dialect}
-
-Each dialect has its own set of types, many of which are available only within that dialect.  For example, MySQL has a `BigInteger` type and PostgreSQL has an `Inet` type.  To use these, import them from the module explicitly:
-
-    {python}
-    from sqlalchemy.databases.mysql import MSEnum, MSBigInteger
-    
-    table = Table('foo', meta,
-        Column('enumerates', MSEnum('a', 'b', 'c')),
-        Column('id', MSBigInteger)
-    )
-        
-Or some PostgreSQL types:
-
-    {python}
-    from sqlalchemy.databases.postgres import PGInet, PGArray
-    
-    table = Table('foo', meta,
-        Column('ipaddress', PGInet),
-        Column('elements', PGArray(str))
-        )
-
-
-### Creating your Own Types {@name=custom}
-
-User-defined types can be created which can augment the bind parameter and result processing capabilities of the built in types.  This is usually achieved using the `TypeDecorator` class, which "decorates" the behavior of any existing type.  
-
-    {python}
-    import sqlalchemy.types as types
-
-    class MyType(types.TypeDecorator):
-        """a type that decorates Unicode, prefixes values with "PREFIX:" on 
-        the way in and strips it off on the way out."""
-        
-        impl = types.Unicode
-        
-        def process_bind_param(self, value, dialect):
-            return "PREFIX:" + value
-            
-        def process_result_value(self, value, dialect):
-            return value[7:]
-        
-        def copy(self):
-            return MyType(self.impl.length)
-
-The reason that type behavior is modified using class decoration instead of subclassing is due to the way dialect specific types are used.  Such as with the example above, when using the mysql dialect, the actual type in use will be a `sqlalchemy.databases.mysql.MSString` instance.  `TypeDecorator` handles the mechanics of passing the values between user-defined `process_` methods and the current dialect-specific type in use.
-
-To build a type object from scratch, which will not have a corresponding database-specific implementation, subclass `TypeEngine`:
-
-    {python}
-    import sqlalchemy.types as types
-
-    class MyType(types.TypeEngine):
-        def __init__(self, precision = 8):
-            self.precision = precision
-
-        def get_col_spec(self):
-            return "MYTYPE(%s)" % self.precision
-
-        def bind_processor(self, dialect):
-            def process(value):
-                return value
-            return process
-
-        def result_processor(self, dialect):
-            def process(value):
-                return value
-            return process
-
-The `bind_processor` and `result_processor` methods return a callable which will be used to process data at the bind parameter and result row level.  If processing is not necessary, the method should return `None`.
-
-Once you make your type, it's immediately useable:
-
-    {python}
-    table = Table('foo', meta,
-        Column('id', Integer, primary_key=True),
-        Column('data', MyType(16))
-        )
-        
-