Modules and Classes
Version: 0.2.5 Last Updated: 07/08/06 13:45:27
View: Paged  |  One Page
Modules and Classes
Module sqlalchemy.sql

defines the base components of SQL expression trees.

Module Functions
def alias(*args, **params)

def and_(*clauses)

joins a list of clauses together by the AND operator. the & operator can be used as well.

def asc(column)

returns an ascending ORDER BY clause element, e.g.:

order_by = [asc(table1.mycol)]

def between(ctest, cleft, cright)

returns BETWEEN predicate clause (clausetest BETWEEN clauseleft AND clauseright).

this is better called off a ColumnElement directly, i.e.

column.between(value1, value2).

def bindparam(key, value=None, type=None)

creates a bind parameter clause with the given key.

An optional default value can be specified by the value parameter, and the optional type parameter is a sqlalchemy.types.TypeEngine object which indicates bind-parameter and result-set translation for this bind parameter.

def case(whens, value=None, else_=None)

SQL CASE statement -- whens are a sequence of pairs to be translated into "when / then" clauses; optional [value] for simple case statements, and [else_] for case defaults

def cast(clause, totype, **kwargs)

returns CAST function CAST(clause AS totype) Use with a sqlalchemy.types.TypeEngine object, i.e cast(table.c.unit_price * table.c.qty, Numeric(10,4)) or cast(table.c.timestamp, DATE)

def column(text, table=None, type=None)

returns a textual column clause, relative to a table. this is also the primitive version of a schema.Column which is a subclass.

def delete(table, whereclause=None, **kwargs)

returns a DELETE clause element.

This can also be called from a table directly via the table's delete() method.

'table' is the table to be updated. 'whereclause' is a ClauseElement describing the WHERE condition of the UPDATE statement.

def desc(column)

returns a descending ORDER BY clause element, e.g.:

order_by = [desc(table1.mycol)]

def exists(*args, **params)

def insert(table, values=None, **kwargs)

returns an INSERT clause element.

This can also be called from a table directly via the table's insert() method.

'table' is the table to be inserted into.

'values' is a dictionary which specifies the column specifications of the INSERT, and is optional. If left as None, the column specifications are determined from the bind parameters used during the compile phase of the INSERT statement. If the bind parameters also are None during the compile phase, then the column specifications will be generated from the full list of table columns.

If both 'values' and compile-time bind parameters are present, the compile-time bind parameters override the information specified within 'values' on a per-key basis.

The keys within 'values' can be either Column objects or their string identifiers. Each key may reference one of: a literal data value (i.e. string, number, etc.), a Column object, or a SELECT statement. If a SELECT statement is specified which references this INSERT statement's table, the statement will be correlated against the INSERT statement.

def join(left, right, onclause=None, **kwargs)

returns a JOIN clause element (regular inner join), given the left and right hand expressions, as well as the ON condition's expression. To chain joins together, use the resulting Join object's "join()" or "outerjoin()" methods.

def literal(value, type=None)

returns a literal clause, bound to a bind parameter.

literal clauses are created automatically when used as the right-hand side of a boolean or math operation against a column object. use this function when a literal is needed on the left-hand side (and optionally on the right as well).

the optional type parameter is a sqlalchemy.types.TypeEngine object which indicates bind-parameter and result-set translation for this literal.

def not_(clause)

returns a negation of the given clause, i.e. NOT(clause). the ~ operator can be used as well.

def null()

returns a Null object, which compiles to NULL in a sql statement.

def or_(*clauses)

joins a list of clauses together by the OR operator. the | operator can be used as well.

def outerjoin(left, right, onclause=None, **kwargs)

returns an OUTER JOIN clause element, given the left and right hand expressions, as well as the ON condition's expression. To chain joins together, use the resulting Join object's "join()" or "outerjoin()" methods.

def select(columns=None, whereclause=None, from_obj=[], **kwargs)

returns a SELECT clause element.

this can also be called via the table's select() method.

'columns' is a list of columns and/or selectable items to select columns from 'whereclause' is a text or ClauseElement expression which will form the WHERE clause 'from_obj' is an list of additional "FROM" objects, such as Join objects, which will extend or override the default "from" objects created from the column list and the whereclause. **kwargs - additional parameters for the Select object.

def subquery(alias, *args, **kwargs)

def table(name, *columns)

returns a table clause. this is a primitive version of the schema.Table object, which is a subclass of this object.

def text(text, engine=None, *args, **kwargs)

creates literal text to be inserted into a query.

When constructing a query from a select(), update(), insert() or delete(), using plain strings for argument values will usually result in text objects being created automatically. Use this function when creating textual clauses outside of other ClauseElement objects, or optionally wherever plain text is to be used.

Arguments include:

text - the text of the SQL statement to be created. use :<param> to specify bind parameters; they will be compiled to their engine-specific format.

engine - an optional engine to be used for this text query.

bindparams - a list of bindparam() instances which can be used to define the types and/or initial values for the bind parameters within the textual statement; the keynames of the bindparams must match those within the text of the statement. The types will be used for pre-processing on bind values.

typemap - a dictionary mapping the names of columns represented in the SELECT clause of the textual statement to type objects, which will be used to perform post-processing on columns within the result set (for textual statements that produce result sets).

def union(*selects, **params)

def union_all(*selects, **params)

def update(table, whereclause=None, values=None, **kwargs)

returns an UPDATE clause element.

This can also be called from a table directly via the table's update() method.

'table' is the table to be updated. 'whereclause' is a ClauseElement describing the WHERE condition of the UPDATE statement. 'values' is a dictionary which specifies the SET conditions of the UPDATE, and is optional. If left as None, the SET conditions are determined from the bind parameters used during the compile phase of the UPDATE statement. If the bind parameters also are None during the compile phase, then the SET conditions will be generated from the full list of table columns.

If both 'values' and compile-time bind parameters are present, the compile-time bind parameters override the information specified within 'values' on a per-key basis.

The keys within 'values' can be either Column objects or their string identifiers. Each key may reference one of: a literal data value (i.e. string, number, etc.), a Column object, or a SELECT statement. If a SELECT statement is specified which references this UPDATE statement's table, the statement will be correlated against the UPDATE statement.

back to section top
Class Engine(object)

represents a 'thing that can produce Compiled objects and execute them'.

def compiler(self, statement, parameters, **kwargs)

def execute_compiled(self, compiled, parameters, echo=None, **kwargs)

back to section top
Class AbstractDialect(object)

represents the behavior of a particular database. Used by Compiled objects.

back to section top
Class ClauseParameters(OrderedDict)

represents a dictionary/iterator of bind parameter key names/values. Includes parameters compiled with a Compiled object as well as additional arguments passed to the Compiled object's get_params() method. Parameter values will be converted as per the TypeEngine objects present in the bind parameter objects. The non-converted value can be retrieved via the get_original method. For Compiled objects that compile positional parameters, the values() iteration of the object will return the parameter values in the correct order.

def __init__(self, dialect)

def get_original(self, key)

returns the given parameter as it was originally placed in this ClauseParameters object, without any Type conversion

def get_original_dict(self)

def get_raw_dict(self)

def set_parameter(self, key, value, bindparam)

def values(self)

back to section top
Class Compiled(ClauseVisitor)

represents a compiled SQL expression. the __str__ method of the Compiled object should produce the actual text of the statement. Compiled objects are specific to the database library that created them, and also may or may not be specific to the columns referenced within a particular set of bind parameters. In no case should the Compiled object be dependent on the actual values of those bind parameters, even though it may reference those values as defaults.

def __init__(self, dialect, statement, parameters, engine=None)

constructs a new Compiled object.

statement - ClauseElement to be compiled

parameters - optional dictionary indicating a set of bind parameters specified with this Compiled object. These parameters are the "default" values corresponding to the ClauseElement's BindParamClauses when the Compiled is executed. In the case of an INSERT or UPDATE statement, these parameters will also result in the creation of new BindParamClause objects for each key and will also affect the generated column list in an INSERT statement and the SET clauses of an UPDATE statement. The keys of the parameter dictionary can either be the string names of columns or ColumnClause objects.

engine - optional Engine to compile this statement against

def compile(self)

def execute(self, *multiparams, **params)

executes this compiled object using the AbstractEngine it is bound to.

def get_params(self, **params)

returns the bind params for this compiled object.

Will start with the default parameters specified when this Compiled object was first constructed, and will override those values with those sent via **params, which are key/value pairs. Each key should match one of the BindParamClause objects compiled into this object; either the "key" or "shortname" property of the BindParamClause.

def scalar(self, *multiparams, **params)

executes this compiled object via the execute() method, then returns the first column of the first row. Useful for executing functions, sequences, rowcounts, etc.

back to section top
Class ClauseElement(object)

base class for elements of a programmatically constructed SQL expression.

def accept_visitor(self, visitor)

accepts a ClauseVisitor and calls the appropriate visit_xxx method.

def compare(self, other)

compares this ClauseElement to the given ClauseElement.

Subclasses should override the default behavior, which is a straight identity comparison.

def compile(self, engine=None, parameters=None, compiler=None, dialect=None)

compiles this SQL expression.

Uses the given Compiler, or the given AbstractDialect or Engine to create a Compiler. If no compiler arguments are given, tries to use the underlying Engine this ClauseElement is bound to to create a Compiler, if any. Finally, if there is no bound Engine, uses an ANSIDialect to create a default Compiler.

bindparams is a dictionary representing the default bind parameters to be used with the statement. if the bindparams is a list, it is assumed to be a list of dictionaries and the first dictionary in the list is used with which to compile against. The bind parameters can in some cases determine the output of the compilation, such as for UPDATE and INSERT statements the bind parameters that are present determine the SET and VALUES clause of those statements.

def copy_container(self)

should return a copy of this ClauseElement, iff this ClauseElement contains other ClauseElements. Otherwise, it should be left alone to return self. This is used to create copies of expression trees that still reference the same "leaf nodes". The new structure can then be restructured without affecting the original.

engine = property()

attempts to locate a Engine within this ClauseElement structure, or returns None if none found.

def execute(self, *multiparams, **params)

def execute_using(self, engine, *multiparams, **params)

def is_selectable(self)

returns True if this ClauseElement is Selectable, i.e. it contains a list of Column objects and can be used as the target of a select statement.

def scalar(self, *multiparams, **params)

def scalar_using(self, engine, *multiparams, **params)

def using(self, abstractengine)

back to section top
Class TableClause(FromClause)

def __init__(self, name, *columns)

def accept_visitor(self, visitor)

def alias(self, name=None)

def append_column(self, c)

c = property()

columns = property()

def count(self, whereclause=None, **params)

def delete(self, whereclause=None)

foreign_keys = property()

indexes = property()

def insert(self, values=None)

def join(self, right, *args, **kwargs)

def named_with_column(self)

original_columns = property()

def outerjoin(self, right, *args, **kwargs)

primary_key = property()

def select(self, whereclause=None, **params)

def update(self, whereclause=None, values=None)

back to section top
Class ColumnClause(ColumnElement)

represents a textual column clause in a SQL statement. May or may not be bound to an underlying Selectable.

def __init__(self, text, selectable=None, type=None, hidden=False)

def accept_visitor(self, visitor)

def to_selectable(self, selectable)

given a Selectable, returns this column's equivalent in that Selectable, if any.

for example, this could translate the column "name" from a Table object to an Alias of a Select off of that Table object.

back to section top
Module sqlalchemy.schema

the schema module provides the building blocks for database metadata. This means all the entities within a SQL database that we might want to look at, modify, or create and delete are described by these objects, in a database-agnostic way.

A structure of SchemaItems also provides a "visitor" interface which is the primary method by which other methods operate upon the schema. The SQL package extends this structure with its own clause-specific objects as well as the visitor interface, so that the schema package "plugs in" to the SQL package.

Class BoundMetaData(MetaData)

builds upon MetaData to provide the capability to bind to an Engine implementation.

def __init__(self, engine_or_url, name=None, **kwargs)

def is_bound(self)

back to section top
Class Column(SchemaItem,ColumnClause)

represents a column in a database table. this is a subclass of sql.ColumnClause and represents an actual existing table in the database, in a similar fashion as TableClause/Table.

def __init__(self, name, type, *args, **kwargs)

constructs a new Column object. Arguments are:

name : the name of this column. this should be the identical name as it appears, or will appear, in the database.

type : this is the type of column. This can be any subclass of types.TypeEngine, including the database-agnostic types defined in the types module, database-specific types defined within specific database modules, or user-defined types.

*args : ForeignKey and Sequence objects should be added as list values.

**kwargs : keyword arguments include:

key=None : an optional "alias name" for this column. The column will then be identified everywhere in an application, including the column list on its Table, by this key, and not the given name. Generated SQL, however, will still reference the column by its actual name.

primary_key=False : True if this column is a primary key column. Multiple columns can have this flag set to specify composite primary keys.

nullable=True : True if this column should allow nulls. Defaults to True unless this column is a primary key column.

default=None : a scalar, python callable, or ClauseElement representing the "default value" for this column, which will be invoked upon insert if this column is not present in the insert list or is given a value of None.

hidden=False : indicates this column should not be listed in the table's list of columns. Used for the "oid" column, which generally isnt in column lists.

index=None : True or index name. Indicates that this column is indexed. Pass true to autogenerate the index name. Pass a string to specify the index name. Multiple columns that specify the same index name will all be included in the index, in the order of their creation.

unique=None : True or index name. Indicates that this column is indexed in a unique index . Pass true to autogenerate the index name. Pass a string to specify the index name. Multiple columns that specify the same index name will all be included in the index, in the order of their creation.

def accept_schema_visitor(self, visitor)

traverses the given visitor to this Column's default and foreign key object, then calls visit_column on the visitor.

def append_item(self, item)

columns = property()

def copy(self)

creates a copy of this Column, unitialized

back to section top
Class ColumnDefault(DefaultGenerator)

A plain default value on a column. this could correspond to a constant, a callable function, or a SQL clause.

def __init__(self, arg, **kwargs)

def accept_schema_visitor(self, visitor)

calls the visit_column_default method on the given visitor.

back to section top
Class DynamicMetaData(MetaData)

builds upon MetaData to provide the capability to bind to multiple Engine implementations on a dynamically alterable, thread-local basis.

def __init__(self, name=None, threadlocal=True)

def connect(self, engine_or_url, **kwargs)

def dispose(self)

disposes all Engines to which this DynamicMetaData has been connected.

engine = property()

def is_bound(self)

back to section top
Class ForeignKey(SchemaItem)

defines a ForeignKey constraint between two columns. ForeignKey is specified as an argument to a Column object.

def __init__(self, column)

Constructs a new ForeignKey object. "column" can be a schema.Column object representing the relationship, or just its string name given as "tablename.columnname". schema can be specified as "schema.tablename.columnname"

def accept_schema_visitor(self, visitor)

calls the visit_foreign_key method on the given visitor.

column = property()

def copy(self)

produces a copy of this ForeignKey object.

def references(self, table)

returns True if the given table is referenced by this ForeignKey.

back to section top
Class Index(SchemaItem)

Represents an index of columns from a database table

def __init__(self, name, *columns, **kw)

Constructs an index object. Arguments are:

name : the name of the index

*columns : columns to include in the index. All columns must belong to the same table, and no column may appear more than once.

**kw : keyword arguments include:

unique=True : create a unique index

def accept_schema_visitor(self, visitor)

def append_column(self, column)

def create(self, engine=None)

def drop(self, engine=None)

back to section top
Class MetaData(SchemaItem)

represents a collection of Tables and their associated schema constructs.

def __init__(self, name=None)

def clear(self)

def create_all(self, engine=None, tables=None)

def drop_all(self, engine=None, tables=None)

def is_bound(self)

def table_iterator(self, reverse=True)

back to section top
Class PassiveDefault(DefaultGenerator)

a default that takes effect on the database side

def __init__(self, arg, **kwargs)

def accept_schema_visitor(self, visitor)

back to section top
Class SchemaItem(object)

base class for items that define a database schema.

engine = property()

metadata = property()

back to section top
Class SchemaVisitor(ClauseVisitor)

defines the visiting for SchemaItem objects

def visit_column(self, column)

visit a Column.

def visit_column_default(self, default)

visit a ColumnDefault.

def visit_column_onupdate(self, onupdate)

visit a ColumnDefault with the "for_update" flag set.

def visit_foreign_key(self, join)

visit a ForeignKey.

def visit_index(self, index)

visit an Index.

def visit_passive_default(self, default)

visit a passive default

def visit_schema(self, schema)

visit a generic SchemaItem

def visit_sequence(self, sequence)

visit a Sequence.

def visit_table(self, table)

visit a Table.

back to section top
Class Sequence(DefaultGenerator)

represents a sequence, which applies to Oracle and Postgres databases.

def __init__(self, name, start=None, increment=None, optional=False, **kwargs)

def accept_schema_visitor(self, visitor)

calls the visit_seauence method on the given visitor.

def create(self)

def drop(self)

back to section top
Class Table(SchemaItem,TableClause)

represents a relational database table. This subclasses sql.TableClause to provide a table that is "wired" to an engine. Whereas TableClause represents a table as its used in a SQL expression, Table represents a table as its created in the database.

Be sure to look at sqlalchemy.sql.TableImpl for additional methods defined on a Table.

def __init__(self, name, metadata, **kwargs)

Table objects can be constructed directly. The init method is actually called via the TableSingleton metaclass. Arguments are:

name : the name of this table, exactly as it appears, or will appear, in the database. This property, along with the "schema", indicates the "singleton identity" of this table. Further tables constructed with the same name/schema combination will return the same Table instance.

*args : should contain a listing of the Column objects for this table.

**kwargs : options include:

schema=None : the "schema name" for this table, which is required if the table resides in a schema other than the default selected schema for the engine's database connection.

autoload=False : the Columns for this table should be reflected from the database. Usually there will be no Column objects in the constructor if this property is set.

redefine=False : if this Table has already been defined in the application, clear out its columns and redefine with new arguments.

mustexist=False : indicates that this Table must already have been defined elsewhere in the application, else an exception is raised.

useexisting=False : indicates that if this Table was already defined elsewhere in the application, disregard the rest of the constructor arguments. If this flag and the "redefine" flag are not set, constructing the same table twice will result in an exception.

def accept_schema_visitor(self, visitor)

traverses the given visitor across the Column objects inside this Table, then calls the visit_table method on the visitor.

def append_column(self, column)

def append_index(self, index)

def append_index_column(self, column, index=None, unique=None)

Add an index or a column to an existing index of the same name.

def append_item(self, item)

appends a Column item or other schema item to this Table.

def create(self, connectable=None)

def deregister(self)

removes this table from it's metadata. this does not issue a SQL DROP statement.

def drop(self, connectable=None)

def reload_values(self, *args)

clears out the columns and other properties of this Table, and reloads them from the given argument list. This is used with the "redefine" keyword argument sent to the metaclass constructor.

def tometadata(self, metadata, schema=None)

returns a singleton instance of this Table with a different Schema

back to section top
Module sqlalchemy.engine

Module Functions
def create_engine(*args, **kwargs)

creates a new Engine instance. Using the given strategy name, locates that strategy and invokes its create() method to produce the Engine. The strategies themselves are instances of EngineStrategy, and the built in ones are present in the sqlalchemy.engine.strategies module. Current implementations include "plain" and "threadlocal". The default used by this function is "threadlocal".

"plain" provides support for a Connection object which can be used to execute SQL queries with a specific underlying DBAPI connection.

"threadlocal" is similar to "plain" except that it adds support for a thread-local connection and transaction context, which allows a group of engine operations to participate using the same connection and transaction without the need for explicit passing of a Connection object.

The standard method of specifying the engine is via URL as the first positional argument, to indicate the appropriate database dialect and connection arguments, with additional keyword arguments sent as options to the dialect and resulting Engine.

The URL is in the form <dialect>://opt1=val1&opt2=val2. Where <dialect> is a name such as "mysql", "oracle", "postgres", and the options indicate username, password, database, etc. Supported keynames include "username", "user", "password", "pw", "db", "database", "host", "filename".

**kwargs represents options to be sent to the Engine itself as well as the components of the Engine, including the Dialect, the ConnectionProvider, and the Pool. A list of common options is as follows:

pool=None : an instance of sqlalchemy.pool.DBProxy or sqlalchemy.pool.Pool to be used as the underlying source for connections (DBProxy/Pool is described in the previous section). If None, a default DBProxy will be created using the engine's own database module with the given arguments.

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. A Engine instances' "echo" data member 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.

logger=None : a file-like object where logging output can be sent, if echo is set to True. This defaults to sys.stdout.

encoding='utf-8' : the encoding to be used when encoding/decoding Unicode strings

convert_unicode=False : True if unicode conversion should be applied to all str types

module=None : used by Oracle and Postgres, this is a reference to a DBAPI2 module to be used instead of the engine's default module. For Postgres, the default is psycopg2, or psycopg1 if 2 cannot be found. For Oracle, its cx_Oracle. For mysql, MySQLdb.

use_ansi=True : used only by Oracle; when False, the Oracle driver attempts to support a particular "quirk" of some Oracle databases, that the LEFT OUTER JOIN SQL syntax is not supported, and the "Oracle join" syntax of using <column1>(+)=<column2> must be used in order to achieve a LEFT OUTER JOIN. Its advised that the Oracle database be configured to have full ANSI support instead of using this feature.

def engine_descriptors()

provides a listing of all the database implementations supported. this data is provided as a list of dictionaries, where each dictionary contains the following key/value pairs:

name : the name of the engine, suitable for use in the create_engine function

description: a plain description of the engine.

arguments : a dictionary describing the name and description of each parameter used to connect to this engine's underlying DBAPI.

This function is meant for usage in automated configuration tools that wish to query the user for database and connection information.

back to section top
Class Connectable(object)

interface for an object that can provide an Engine and a Connection object which correponds to that Engine.

def contextual_connect(self)

returns a Connection object which may be part of an ongoing context.

def create(self, entity, **kwargs)

creates a table or index given an appropriate schema object.

def drop(self, entity, **kwargs)

engine = property()

returns the Engine which this Connectable is associated with.

def execute(self, object, *multiparams, **params)

back to section top
Class ComposedSQLEngine(Engine,Connectable)

Connects a ConnectionProvider, a Dialect and a CompilerFactory together to provide a default implementation of SchemaEngine.

def __init__(self, connection_provider, dialect, echo=False, logger=None, **kwargs)

def compiler(self, statement, parameters, **kwargs)

def connect(self, **kwargs)

returns a newly allocated Connection object.

def contextual_connect(self, close_with_result=False, **kwargs)

returns a Connection object which may be newly allocated, or may be part of some ongoing context. This Connection is meant to be used by the various "auto-connecting" operations.

def create(self, entity, connection=None, **kwargs)

creates a table or index within this engine's database connection given a schema.Table object.

def dispose(self)

def drop(self, entity, connection=None, **kwargs)

drops a table or index within this engine's database connection given a schema.Table object.

engine = property()

def execute(self, statement, *multiparams, **params)

def execute_compiled(self, compiled, *multiparams, **params)

def execute_default(self, default, **kwargs)

func = property()

def has_table(self, table_name)

def log(self, msg)

logs a message using this SQLEngine's logger stream.

name = property()

def raw_connection(self)

returns a DBAPI connection.

def reflecttable(self, table, connection=None)

given a Table object, reflects its columns and properties from the database.

def run_callable(self, callable_, connection=None, *args, **kwargs)

def text(self, text, *args, **kwargs)

returns a sql.text() object for performing literal queries.

def transaction(self, callable_, connection=None, *args, **kwargs)

executes the given function within a transaction boundary. this is a shortcut for explicitly calling begin() and commit() and optionally rollback() when execptions are raised. The given *args and **kwargs will be passed to the function, as well as the Connection used in the transaction.

back to section top
Class Connection(Connectable)

represents a single DBAPI connection returned from the underlying connection pool. Provides execution support for string-based SQL statements as well as ClauseElement, Compiled and DefaultGenerator objects. provides a begin method to return Transaction objects.

def __init__(self, engine, connection=None, close_with_result=False)

def begin(self)

def close(self)

def connect(self)

connect() is implemented to return self so that an incoming Engine or Connection object can be treated similarly.

connection = property()

The underlying DBAPI connection managed by this Connection.

def contextual_connect(self, **kwargs)

contextual_connect() is implemented to return self so that an incoming Engine or Connection object can be treated similarly.

def create(self, entity, **kwargs)

creates a table or index given an appropriate schema object.

def default_schema_name(self)

def drop(self, entity, **kwargs)

drops a table or index given an appropriate schema object.

engine = property()

The Engine with which this Connection is associated (read only)

def execute(self, object, *multiparams, **params)

def execute_clauseelement(self, elem, *multiparams, **params)

def execute_compiled(self, compiled, *multiparams, **params)

executes a sql.Compiled object.

def execute_default(self, default, **kwargs)

def execute_text(self, statement, parameters=None)

def in_transaction(self)

def proxy(self, statement=None, parameters=None)

executes the given statement string and parameter object. the parameter object is expected to be the result of a call to compiled.get_params(). This callable is a generic version of a connection/cursor-specific callable that is produced within the execute_compiled method, and is used for objects that require this style of proxy when outside of an execute_compiled method, primarily the DefaultRunner.

def reflecttable(self, table, **kwargs)

reflects the columns in the given table from the database.

def run_callable(self, callable_)

def scalar(self, object, parameters=None, **kwargs)

should_close_with_result = property()

Indicates if this Connection should be closed when a corresponding ResultProxy is closed; this is essentially an auto-release mode.

back to section top
Class Transaction(object)

represents a Transaction in progress

def __init__(self, connection, parent)

def commit(self)

connection = property()

The Connection object referenced by this Transaction

is_active = property()

def rollback(self)

back to section top
Class Dialect(AbstractDialect)

Adds behavior to the execution of queries to provide support for column defaults, differences between paramstyles, quirks between post-execution behavior, and a general consistentization of the behavior of various DBAPIs.

The Dialect should also implement the following two attributes:

positional - True if the paramstyle for this Dialect is positional

paramstyle - the paramstyle to be used (some DBAPIs support multiple paramstyles)

supports_autoclose_results - usually True; if False, indicates that rows returned by fetchone() might not be just plain tuples, and may be "live" proxy objects which still require the cursor to be open in order to be read (such as pyPgSQL which has active filehandles for BLOBs). in that case, an auto-closing ResultProxy cannot automatically close itself after results are consumed.

convert_unicode - True if unicode conversion should be applied to all str types

encoding - type of encoding to use for unicode, usually defaults to 'utf-8'

def compiler(self, statement, parameters)

returns a sql.ClauseVisitor which will produce a string representation of the given ClauseElement and parameter dictionary. This object is usually a subclass of ansisql.ANSICompiler.

compiler is called within the context of the compile() method.

def convert_compiled_params(self, parameters)

given a sql.ClauseParameters object, returns an array or dictionary suitable to pass directly to this Dialect's DBAPI's execute method.

def create_connect_args(self, opts)

given a dictionary of key-valued connect parameters, returns a tuple consisting of a *args/**kwargs suitable to send directly to the dbapi's connect function. The connect args will have any number of the following keynames: host, hostname, database, dbanme, user,username, password, pw, passwd, filename.

def dbapi(self)

subclasses override this method to provide the DBAPI module used to establish connections.

def defaultrunner(self, engine, proxy, **params)

returns a schema.SchemaVisitor instances that can execute defaults.

def do_begin(self, connection)

provides an implementation of connection.begin()

def do_commit(self, connection)

provides an implementation of connection.commit()

def do_execute(self, cursor, statement, parameters)

def do_executemany(self, cursor, statement, parameters)

def do_rollback(self, connection)

provides an implementation of connection.rollback()

def execution_context(self)

returns a new ExecutionContext object.

def get_default_schema_name(self, connection)

returns the currently selected schema given an connection

def has_table(self, connection, table_name)

def oid_column_name(self)

returns the oid column name for this dialect, or None if the dialect cant/wont support OID/ROWID.

def reflecttable(self, connection, table)

given an Connection and a Table object, reflects its columns and properties from the database.

def schemadropper(self, engine, proxy, **params)

returns a schema.SchemaVisitor instance that can drop schemas, when it is invoked to traverse a set of schema objects.

schemagenerator is called via the drop() method on Table, Index, and others.

def schemagenerator(self, engine, proxy, **params)

returns a schema.SchemaVisitor instance that can generate schemas, when it is invoked to traverse a set of schema objects.

schemagenerator is called via the create() method on Table, Index, and others.

def supports_sane_rowcount(self)

Provided to indicate when MySQL is being used, which does not have standard behavior for the "rowcount" function on a statement handle.

def type_descriptor(self, typeobj)

provides a database-specific TypeEngine object, given the generic object which comes from the types module. Subclasses will usually use the adapt_type() method in the types module to make this job easy.

back to section top
Class ConnectionProvider(object)

defines an interface that returns raw Connection objects (or compatible).

def dispose(self)

releases all resources corresponding to this ConnectionProvider, such as any underlying connection pools.

def get_connection(self)

this method should return a Connection or compatible object from a DBAPI which also contains a close() method. It is not defined what context this connection belongs to. It may be newly connected, returned from a pool, part of some other kind of context such as thread-local, or can be a fixed member of this object.

back to section top
Class ExecutionContext(object)

a messenger object for a Dialect that corresponds to a single execution. The Dialect should provide an ExecutionContext via the create_execution_context() method. The pre_exec and post_exec methods will be called for compiled statements, afterwhich it is expected that the various methods last_inserted_ids, last_inserted_params, etc. will contain appropriate values, if applicable.

def get_rowcount(self, cursor)

returns the count of rows updated/deleted for an UPDATE/DELETE statement

def last_inserted_ids(self)

returns the list of the primary key values for the last insert statement executed. This does not apply to straight textual clauses; only to sql.Insert objects compiled against a schema.Table object, which are executed via statement.execute(). The order of items in the list is the same as that of the Table's 'primary_key' attribute.

In some cases, this method may invoke a query back to the database to retrieve the data, based on the "lastrowid" value in the cursor.

def last_inserted_params(self)

returns a dictionary of the full parameter dictionary for the last compiled INSERT statement, including any ColumnDefaults or Sequences that were pre-executed. this value is thread-local.

def last_updated_params(self)

returns a dictionary of the full parameter dictionary for the last compiled UPDATE statement, including any ColumnDefaults that were pre-executed. this value is thread-local.

def lastrow_has_defaults(self)

returns True if the last row INSERTED via a compiled insert statement contained PassiveDefaults, indicating that the database inserted data beyond that which we gave it. this value is thread-local.

def post_exec(self, engine, proxy, compiled, parameters)

called after the execution of a compiled statement. proxy is a callable that takes a string statement and a bind parameter list/dictionary.

def pre_exec(self, engine, proxy, compiled, parameters)

called before an execution of a compiled statement. proxy is a callable that takes a string statement and a bind parameter list/dictionary.

def supports_sane_rowcount(self)

Provided to indicate when MySQL is being used, which does not have standard behavior for the "rowcount" function on a statement handle.

back to section top
Class ResultProxy

wraps a DBAPI cursor object to provide access to row columns based on integer position, case-insensitive column name, or by schema.Column object. e.g.:

row = fetchone()

col1 = row[0] # access via integer position

col2 = row['col2'] # access via name

col3 = row[mytable.c.mycol] # access via Column object.

ResultProxy also contains a map of TypeEngine objects and will invoke the appropriate convert_result_value() method before returning columns.

def __init__(self, engine, connection, cursor, executioncontext=None, typemap=None)

ResultProxy objects are constructed via the execute() method on SQLEngine.

def close(self)

def fetchall(self)

fetches all rows, just like DBAPI cursor.fetchall().

def fetchone(self)

fetches one row, just like DBAPI cursor.fetchone().

def last_inserted_ids(self)

def last_inserted_params(self)

def last_updated_params(self)

def lastrow_has_defaults(self)

def supports_sane_rowcount(self)

back to section top
Class RowProxy

proxies a single cursor row for a parent ResultProxy.

def __init__(self, parent, row)

RowProxy objects are constructed by ResultProxy objects.

def close(self)

def has_key(self, key)

def items(self)

def keys(self)

def values(self)

back to section top
Module sqlalchemy.engine.strategies

defines different strategies for creating new instances of sql.Engine. by default there are two, one which is the "thread-local" strategy, one which is the "plain" strategy. new strategies can be added via constructing a new EngineStrategy object which will add itself to the list of available strategies here, or replace one of the existing name. this can be accomplished via a mod; see the sqlalchemy/mods package for details.

Class EngineStrategy(object)

defines a function that receives input arguments and produces an instance of sql.Engine, typically an instance sqlalchemy.engine.base.ComposedSQLEngine or a subclass.

def __init__(self, name)

constructs a new EngineStrategy object and sets it in the list of available strategies under this name.

def create(self, *args, **kwargs)

given arguments, returns a new sql.Engine instance.

back to section top
Class PlainEngineStrategy(EngineStrategy)

def __init__(self)

def create(self, name_or_url, **kwargs)

back to section top
Class ThreadLocalEngineStrategy(EngineStrategy)

def __init__(self)

def create(self, name_or_url, **kwargs)

back to section top
Module sqlalchemy.orm

the mapper package provides object-relational functionality, building upon the schema and sql packages and tying operations to class properties and constructors.

Module Functions
def backref(name, **kwargs)

def cascade_mappers(*classes_or_mappers)

given a list of classes and/or mappers, identifies the foreign key relationships between the given mappers or corresponding class mappers, and creates relation() objects representing those relationships, including a backreference. Attempts to find the "secondary" table in a many-to-many relationship as well. The names of the relations will be a lowercase version of the related class. In the case of one-to-many or many-to-many, the name will be "pluralized", which currently is based on the English language (i.e. an 's' or 'es' added to it).

def class_mapper(class_, entity_name=None, compile=True)

given a ClassKey, returns the primary Mapper associated with the key.

def clear_mappers()

removes all mappers that have been created thus far. when new mappers are created, they will be assigned to their classes as their primary mapper.

def defer(name, **kwargs)

returns a MapperOption that will convert the column property of the given name into a deferred load. Used with mapper.options()

def deferred(*columns, **kwargs)

returns a DeferredColumnProperty, which indicates this object attributes should only be loaded from its corresponding table column when first accessed.

def eagerload(name, **kwargs)

returns a MapperOption that will convert the property of the given name into an eager load. Used with mapper.options()

def extension(ext)

returns a MapperOption that will add the given MapperExtension to the mapper returned by mapper.options().

def lazyload(name, **kwargs)

returns a MapperOption that will convert the property of the given name into a lazy load. Used with mapper.options()

def mapper(class_, table=None, *args, **params)

returns a newMapper object.

def noload(name, **kwargs)

returns a MapperOption that will convert the property of the given name into a non-load. Used with mapper.options()

def object_mapper(object, raiseerror=True)

given an object, returns the primary Mapper associated with the object instance

def polymorphic_union(table_map, typecolname, aliasname='p_union')

def relation(*args, **kwargs)

provides a relationship of a primary Mapper to a secondary Mapper, which corresponds to a parent-child or associative table relationship.

def undefer(name, **kwargs)

returns a MapperOption that will convert the column property of the given name into a non-deferred (regular column) load. Used with mapper.options.

back to section top
Class Mapper(object)

Persists object instances to and from schema.Table objects via the sql package. Instances of this class should be constructed through this package's mapper() or relation() function.

def __init__(self, class_, local_table, properties=None, primary_key=None, is_primary=False, non_primary=False, inherits=None, inherit_condition=None, extension=None, order_by=False, allow_column_override=False, entity_name=None, always_refresh=False, version_id_col=None, polymorphic_on=None, polymorphic_map=None, polymorphic_identity=None, concrete=False, select_table=None)

def add_properties(self, dict_of_properties)

adds the given dictionary of properties to this mapper, using add_property.

def add_property(self, key, prop)

adds an indiviual MapperProperty to this mapper. If the mapper has not been compiled yet, just adds the property to the initial properties dictionary sent to the constructor. if this Mapper has already been compiled, then the given MapperProperty is compiled immediately.

def base_mapper(self)

returns the ultimate base mapper in an inheritance chain

def cascade_callable(self, type, object, callable_, recursive=None)

def cascade_iterator(self, type, object, callable_=None, recursive=None)

def compile(self)

compile this mapper into its final internal format.

this is the 'external' version of the method which is not reentrant.

def copy(self, **kwargs)

def count(self, whereclause=None, params=None, **kwargs)

deprecated. use Query instead.

def count_by(self, *args, **params)

deprecated. use Query instead.

def delete_obj(self, objects, uow)

called by a UnitOfWork object to delete objects, which involves a DELETE statement for each table used by this mapper, for each object in the list.

def get(self, ident, **kwargs)

deprecated. use Query instead.

def get_by(self, *args, **params)

deprecated. use Query instead.

def get_select_mapper(self)

def get_session(self)

returns the contextual session provided by the mapper extension chain

raises InvalidRequestError if a session cannot be retrieved from the extension chain

def has_eager(self)

returns True if one of the properties attached to this Mapper is eager loading

def identity(self, instance)

returns the identity (list of primary key values) for the given instance. The list of values can be fed directly into the get() method as mapper.get(*key).

def identity_key(self, primary_key)

returns the instance key for the given identity value. this is a global tracking object used by the Session, and is usually available off a mapped object as instance._instance_key.

def instance_key(self, instance)

returns the instance key for the given instance. this is a global tracking object used by the Session, and is usually available off a mapped object as instance._instance_key.

def instances(self, cursor, session, *mappers, **kwargs)

given a cursor (ResultProxy) from an SQLEngine, returns a list of object instances corresponding to the rows in the cursor.

def is_assigned(self, instance)

returns True if this mapper handles the given instance. this is dependent not only on class assignment but the optional "entity_name" parameter as well.

def options(self, *options, **kwargs)

uses this mapper as a prototype for a new mapper with different behavior. *options is a list of options directives, which include eagerload(), lazyload(), and noload()

def populate_instance(self, session, instance, row, identitykey, imap, isnew, frommapper=None)

def primary_mapper(self)

returns the primary mapper corresponding to this mapper's class key (class + entity_name)

props = property()

compiles this mapper if needed, and returns the dictionary of MapperProperty objects associated with this mapper.

def query(self, session=None)

deprecated. use Query instead.

def register_dependencies(self, uowcommit, *args, **kwargs)

called by an instance of unitofwork.UOWTransaction to register which mappers are dependent on which, as well as DependencyProcessor objects which will process lists of objects in between saves and deletes.

def save_obj(self, objects, uow, postupdate=False)

called by a UnitOfWork object to save objects, which involves either an INSERT or an UPDATE statement for each table used by this mapper, for each element of the list.

def select(self, arg=None, **kwargs)

deprecated. use Query instead.

def select_by(self, *args, **params)

deprecated. use Query instead.

def select_statement(self, statement, **params)

deprecated. use Query instead.

def select_text(self, text, **params)

deprecated. use Query instead.

def select_whereclause(self, whereclause=None, params=None, **kwargs)

deprecated. use Query instead.

def selectfirst(self, *args, **params)

deprecated. use Query instead.

def selectfirst_by(self, *args, **params)

deprecated. use Query instead.

def selectone(self, *args, **params)

deprecated. use Query instead.

def selectone_by(self, *args, **params)

deprecated. use Query instead.

def translate_row(self, tomapper, row)

attempts to take a row and translate its values to a row that can be understood by another mapper.

def using(self, session)

deprecated. use Query instead.

back to section top
Class MapperExtension(object)

base implementation for an object that provides overriding behavior to various Mapper functions. For each method in MapperExtension, a result of EXT_PASS indicates the functionality is not overridden.

def __init__(self)

def after_delete(self, mapper, connection, instance)

called after an object instance is DELETEed

def after_insert(self, mapper, connection, instance)

called after an object instance has been INSERTed

def after_update(self, mapper, connection, instance)

called after an object instnace is UPDATED

def append_result(self, mapper, session, row, imap, result, instance, isnew, populate_existing=False)

called when an object instance is being appended to a result list.

If this method returns True, it is assumed that the mapper should do the appending, else if this method returns False, it is assumed that the append was handled by this method.

mapper - the mapper doing the operation

row - the result row from the database

imap - a dictionary that is storing the running set of objects collected from the current result set

result - an instance of util.HistoryArraySet(), which may be an attribute on an object if this is a related object load (lazy or eager).

instance - the object instance to be appended to the result

isnew - indicates if this is the first time we have seen this object instance in the current result set. if you are selecting from a join, such as an eager load, you might see the same object instance many times in the same result set.

populate_existing - usually False, indicates if object instances that were already in the main identity map, i.e. were loaded by a previous select(), get their attributes overwritten

def before_delete(self, mapper, connection, instance)

called before an object instance is DELETEed

def before_insert(self, mapper, connection, instance)

called before an object instance is INSERTed into its table.

this is a good place to set up primary key values and such that arent handled otherwise.

def before_update(self, mapper, connection, instance)

called before an object instnace is UPDATED

def chain(self, ext)

def create_instance(self, mapper, session, row, imap, class_)

called when a new object instance is about to be created from a row. the method can choose to create the instance itself, or it can return None to indicate normal object creation should take place.

mapper - the mapper doing the operation

row - the result row from the database

imap - a dictionary that is storing the running set of objects collected from the current result set

class_ - the class we are mapping.

def get_session(self)

called to retrieve a contextual Session instance with which to register a new object. Note: this is not called if a session is provided with the __init__ params (i.e. _sa_session)

def populate_instance(self, mapper, session, instance, row, identitykey, imap, isnew)

called right before the mapper, after creating an instance from a row, passes the row to its MapperProperty objects which are responsible for populating the object's attributes. If this method returns True, it is assumed that the mapper should do the appending, else if this method returns False, it is assumed that the append was handled by this method.

Essentially, this method is used to have a different mapper populate the object:

def populate_instance(self, mapper, session, instance, row, identitykey, imap, isnew): othermapper.populate_instance(session, instance, row, identitykey, imap, isnew, frommapper=mapper) return True

def select(self, query, *args, **kwargs)

overrides the select method of the Query object

def select_by(self, query, *args, **kwargs)

overrides the select_by method of the Query object

back to section top
Module sqlalchemy.orm.query

Class Query(object)

encapsulates the object-fetching operations provided by Mappers.

def __init__(self, class_or_mapper, session=None, entity_name=None, **kwargs)

def compile(self, whereclause=None, **kwargs)

def count(self, whereclause=None, params=None, **kwargs)

def count_by(self, *args, **params)

returns the count of instances based on the given clauses and key/value criterion. The criterion is constructed in the same way as the select_by() method.

def get(self, ident, **kwargs)

returns an instance of the object based on the given identifier, or None if not found. The ident argument is a scalar or tuple of primary key column values in the order of the table def's primary key columns.

def get_by(self, *args, **params)

returns a single object instance based on the given key/value criterion. this is either the first value in the result list, or None if the list is empty.

the keys are mapped to property or column names mapped by this mapper's Table, and the values are coerced into a WHERE clause separated by AND operators. If the local property/column names dont contain the key, a search will be performed against this mapper's immediate list of relations as well, forming the appropriate join conditions if a matching property is located.

e.g. u = usermapper.get_by(user_name = 'fred')

def instances(self, clauseelement, params=None, *args, **kwargs)

def join_by(self, *args, **params)

like select_by, but returns a ClauseElement representing the WHERE clause that would normally be sent to select_whereclause by select_by.

def join_to(self, key)

given the key name of a property, will recursively descend through all child properties from this Query's mapper to locate the property, and will return a ClauseElement representing a join from this Query's mapper to the endmost mapper.

def join_via(self, keys)

given a list of keys that represents a path from this Query's mapper to a related mapper based on names of relations from one mapper to the next, returns a ClauseElement representing a join from this Query's mapper to the endmost mapper.

def load(self, ident, **kwargs)

returns an instance of the object based on the given identifier. If not found, raises an exception. The method will *remove all pending changes* to the object already existing in the Session. The ident argument is a scalar or tuple of primary key column values in the order of the table def's primary key columns.

def options(self, *args, **kwargs)

returns a new Query object using the given MapperOptions.

def select(self, arg=None, **kwargs)

selects instances of the object from the database.

arg can be any ClauseElement, which will form the criterion with which to load the objects.

For more advanced usage, arg can also be a Select statement object, which will be executed and its resulting rowset used to build new object instances. in this case, the developer must insure that an adequate set of columns exists in the rowset with which to build new object instances.

def select_by(self, *args, **params)

returns an array of object instances based on the given clauses and key/value criterion.

*args is a list of zero or more ClauseElements which will be connected by AND operators.

**params is a set of zero or more key/value parameters which are converted into ClauseElements. the keys are mapped to property or column names mapped by this mapper's Table, and the values are coerced into a WHERE clause separated by AND operators. If the local property/column names dont contain the key, a search will be performed against this mapper's immediate list of relations as well, forming the appropriate join conditions if a matching property is located.

e.g. result = usermapper.select_by(user_name = 'fred')

def select_statement(self, statement, **params)

def select_text(self, text, **params)

def select_whereclause(self, whereclause=None, params=None, **kwargs)

def selectfirst(self, *args, **params)

works like select(), but only returns the first result by itself, or None if no objects returned.

def selectfirst_by(self, *args, **params)

works like select_by(), but only returns the first result by itself, or None if no objects returned. Synonymous with get_by()

def selectone(self, *args, **params)

works like selectfirst(), but throws an error if not exactly one result was returned.

def selectone_by(self, *args, **params)

works like selectfirst_by(), but throws an error if not exactly one result was returned.

session = property()

table = property()

back to section top
Module sqlalchemy.orm.session

Module Functions
def class_mapper(class_, **kwargs)

def get_id_key(ident, class_, entity_name=None)

def get_row_key(row, class_, primary_key, entity_name=None)

def get_session(obj=None)

deprecated

def object_mapper(obj)

def object_session(obj)

back to section top
Class Session(object)

encapsulates a set of objects being operated upon within an object-relational operation.

def __init__(self, bind_to=None, hash_key=None, import_session=None, echo_uow=False)

def begin(self, *obj)

deprecated

def bind_mapper(self, mapper, bindto)

binds the given Mapper to the given Engine or Connection. All subsequent operations involving this Mapper will use the given bindto.

def bind_table(self, table, bindto)

binds the given Table to the given Engine or Connection. All subsequent operations involving this Table will use the given bindto.

def clear(self)

removes all object instances from this Session. this is equivalent to calling expunge() for all objects in this Session.

def close(self)

closes this Session.

def commit(self, *obj)

deprecated

def connect(self, mapper=None, **kwargs)

returns a unique connection corresponding to the given mapper. this connection will not be part of any pre-existing transactional context.

def connection(self, mapper, **kwargs)

returns a Connection corresponding to the given mapper. used by the execute() method which performs select operations for Mapper and Query. if this Session is transactional, the connection will be in the context of this session's transaction. otherwise, the connection is returned by the contextual_connect method, which some Engines override to return a thread-local connection, and will have close_with_result set to True.

the given **kwargs will be sent to the engine's contextual_connect() method, if no transaction is in progress.

def create_transaction(self, **kwargs)

returns a new SessionTransaction corresponding to an existing or new transaction. if the transaction is new, the returned SessionTransaction will have commit control over the underlying transaction, else will have rollback control only.

def delete(self, object, entity_name=None)

deleted = property()

a Set of all objects marked as 'deleted' within this Session

dirty = property()

a Set of all objects marked as 'dirty' within this Session

def execute(self, mapper, clause, params, **kwargs)

using the given mapper to identify the appropriate Engine or Connection to be used for statement execution, executes the given ClauseElement using the provided parameter dictionary. Returns a ResultProxy corresponding to the execution's results. If this method allocates a new Connection for the operation, then the ResultProxy's close() method will release the resources of the underlying Connection, otherwise its a no-op.

def expire(self, object)

invalidates the data in the given object and sets them to refresh themselves the next time they are requested.

def expunge(self, object)

removes the given object from this Session. this will free all internal references to the object.

def flush(self, objects=None)

flushes all the object modifications present in this session to the database. 'objects' is a list or tuple of objects specifically to be flushed.

def get(self, class_, ident, **kwargs)

returns an instance of the object based on the given identifier, or None if not found. The ident argument is a scalar or tuple of primary key column values in the order of the table def's primary key columns.

the entity_name keyword argument may also be specified which further qualifies the underlying Mapper used to perform the query.

def get_bind(self, mapper)

given a Mapper, returns the Engine or Connection which is used to execute statements on behalf of this Mapper. Calling connect() on the return result will always result in a Connection object. This method disregards any SessionTransaction that may be in progress.

The order of searching is as follows:

if an Engine or Connection was bound to this Mapper specifically within this Session, returns that Engine or Connection.

if an Engine or Connection was bound to this Mapper's underlying Table within this Session (i.e. not to the Table directly), returns that Engine or Conneciton.

if an Engine or Connection was bound to this Session, returns that Engine or Connection.

finally, returns the Engine which was bound directly to the Table's MetaData object.

If no Engine is bound to the Table, an exception is raised.

def has_key(self, key)

identity_map = property()

a WeakValueDictionary consisting of all objects within this Session keyed to their _instance_key value.

def import_instance(self, *args, **kwargs)

deprecated; a synynom for merge()

def is_expired(self, instance, **kwargs)

def load(self, class_, ident, **kwargs)

returns an instance of the object based on the given identifier. If not found, raises an exception. The method will *remove all pending changes* to the object already existing in the Session. The ident argument is a scalar or tuple of primary key columns in the order of the table def's primary key columns.

the entity_name keyword argument may also be specified which further qualifies the underlying Mapper used to perform the query.

def mapper(self, class_, entity_name=None)

given an Class, returns the primary Mapper responsible for persisting it

def merge(self, object, entity_name=None)

new = property()

a Set of all objects marked as 'new' within this Session.

def query(self, mapper_or_class, entity_name=None)

given a mapper or Class, returns a new Query object corresponding to this Session and the mapper, or the classes' primary mapper.

def refresh(self, object)

reloads the attributes for the given object from the database, clears any changes made.

def save(self, object, entity_name=None)

Adds a transient (unsaved) instance to this Session. This operation cascades the "save_or_update" method to associated instances if the relation is mapped with cascade="save-update".

The 'entity_name' keyword argument will further qualify the specific Mapper used to handle this instance.

def save_or_update(self, object, entity_name=None)

def scalar(self, mapper, clause, params, **kwargs)

works like execute() but returns a scalar result.

sql = property()

def update(self, object, entity_name=None)

Brings the given detached (saved) instance into this Session. If there is a persistent instance with the same identifier (i.e. a saved instance already associated with this Session), an exception is thrown. This operation cascades the "save_or_update" method to associated instances if the relation is mapped with cascade="save-update".

back to section top
Class SessionTransaction(object)

def __init__(self, session, parent=None, autoflush=True)

def add(self, connectable)

def close(self)

def commit(self)

def connection(self, mapper_or_class, entity_name=None)

def get_or_add(self, connectable)

def rollback(self)

back to section top
Module sqlalchemy.pool

provides a connection pool implementation, which optionally manages connections on a thread local basis. Also provides a DBAPI2 transparency layer so that pools can be managed automatically, based on module type and connect arguments, simply by calling regular DBAPI connect() methods.

Module Functions
def clear_managers()

removes all current DBAPI2 managers. all pools and connections are disposed.

def manage(module, **params)

given a DBAPI2 module and pool management parameters, returns a proxy for the module that will automatically pool connections. Options are delivered to an underlying DBProxy object.

Arguments: module : a DBAPI2 database module.

Options: 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.

use_threadlocal=True : 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.

poolclass=QueuePool : the default class used by the pool module to provide pooling. QueuePool uses the Python Queue.Queue class to maintain a list of available connections.

pool_size=5 : used by QueuePool - 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.

back to section top
Class DBProxy(object)

proxies a DBAPI2 connect() call to a pooled connection keyed to the specific connect parameters.

def __init__(self, module, poolclass=, **params)

module is a DBAPI2 module poolclass is a Pool class, defaulting to QueuePool. other parameters are sent to the Pool object's constructor.

def close(self)

def connect(self, *args, **params)

connects to a database using this DBProxy's module and the given connect arguments. if the arguments match an existing pool, the connection will be returned from the pool's current thread-local connection instance, or if there is no thread-local connection instance it will be checked out from the set of pooled connections. If the pool has no available connections and allows new connections to be created, a new database connection will be made.

def dispose(self, *args, **params)

disposes the connection pool referenced by the given connect arguments.

def get_pool(self, *args, **params)

back to section top
Class Pool(object)

def __init__(self, echo=False, use_threadlocal=True, logger=None)

def connect(self)

def do_get(self)

def do_return_conn(self, conn)

def do_return_invalid(self)

def get(self)

def log(self, msg)

def return_conn(self, agent)

def return_invalid(self)

def status(self)

def unique_connection(self)

back to section top
Class QueuePool(Pool)

uses Queue.Queue to maintain a fixed-size list of connections.

def __init__(self, creator, pool_size=5, max_overflow=10, timeout=30, **params)

def checkedin(self)

def checkedout(self)

def dispose(self)

def do_get(self)

def do_return_conn(self, conn)

def do_return_invalid(self)

def overflow(self)

def size(self)

def status(self)

back to section top
Class SingletonThreadPool(Pool)

Maintains one connection per each thread, never moving to another thread. this is used for SQLite.

def __init__(self, creator, **params)

def dispose(self)

def do_get(self)

def do_return_conn(self, conn)

def do_return_invalid(self)

def status(self)

back to section top
Module sqlalchemy.ext.sessioncontext

Class SessionContext(object)

A simple wrapper for ScopedRegistry that provides a "current" property which can be used to get, set, or remove the session in the current scope.

By default this object provides thread-local scoping, which is the default scope provided by sqlalchemy.util.ScopedRegistry.

Usage: engine = create_engine(...) def session_factory(): return Session(bind_to=engine) context = SessionContext(session_factory)

s = context.current # get thread-local session context.current = Session(bind_to=other_engine) # set current session del context.current # discard the thread-local session (a new one will # be created on the next call to context.current)

def __init__(self, session_factory, scopefunc=None)

current = property()

Property used to get/set/del the session in the current scope

def del_current(self)

def get_current(self)

mapper_extension = property()

get a mapper extension that implements get_session using this context

def set_current(self, session)

back to section top
Class SessionContextExt(MapperExtension)

a mapper extionsion that provides sessions to a mapper using SessionContext

def __init__(self, context)

def get_session(self)

back to section top
Module sqlalchemy.mods.threadlocal

Module Functions
def assign_mapper(class_, *args, **kwargs)

back to section top
Class Objectstore(SessionContext)

def get_session(self)

back to section top
Module sqlalchemy.ext.selectresults

Class SelectResults(object)

Builds a query one component at a time via separate method calls, each call transforming the previous SelectResults instance into a new SelectResults instance with further limiting criterion added. When interpreted in an iterator context (such as via calling list(selectresults)), executes the query.

def __init__(self, query, clause=None, ops={})

constructs a new SelectResults using the given Query object and optional WHERE clause. ops is an optional dictionary of bind parameter values.

def avg(self, col)

executes the SQL avg() function against the given column

def clone(self)

creates a copy of this SelectResults.

def count(self)

executes the SQL count() function against the SelectResults criterion.

def filter(self, clause)

applies an additional WHERE clause against the query.

def limit(self, limit)

applies a LIMIT to the query.

def list(self)

returns the results represented by this SelectResults as a list. this results in an execution of the underlying query.

def max(self, col)

executes the SQL max() function against the given column

def min(self, col)

executes the SQL min() function against the given column

def offset(self, offset)

applies an OFFSET to the query.

def order_by(self, order_by)

applies an ORDER BY to the query.

def sum(self, col)

executes the SQL sum() function against the given column

back to section top
Class SelectResultsExt(MapperExtension)

a MapperExtension that provides SelectResults functionality for the results of query.select_by() and query.select()

def select(self, query, arg=None, **kwargs)

def select_by(self, query, *args, **params)

back to section top
Module sqlalchemy.exceptions

Class ArgumentError

raised for all those conditions where invalid arguments are sent to constructed objects. This error generally corresponds to construction time state errors.

back to section top
Class AssertionError

corresponds to internal state being detected in an invalid state

back to section top
Class DBAPIError

something weird happened with a particular DBAPI version

back to section top
Class FlushError

raised when an invalid condition is detected upon a flush()

back to section top
Class InvalidRequestError

sqlalchemy was asked to do something it cant do, return nonexistent data, etc. This error generally corresponds to runtime state errors.

back to section top
Class NoSuchTableError

sqlalchemy was asked to load a table's definition from the database, but the table doesn't exist.

back to section top
Class SQLAlchemyError

generic error class

back to section top
Class SQLError

raised when the execution of a SQL statement fails. includes accessors for the underlying exception, as well as the SQL and bind parameters

def __init__(self, statement, params, orig)

back to section top
Class TimeoutError

raised when a connection pool times out on getting a connection

back to section top
Module sqlalchemy.ext.proxy

Class AutoConnectEngine(BaseProxyEngine)

An SQLEngine proxy that automatically connects when necessary.

def __init__(self, dburi, **kwargs)

def get_engine(self)

back to section top
Class BaseProxyEngine(Engine)

Basis for all proxy engines.

def compiler(self, *args, **kwargs)

this method is required to be present as it overrides the compiler method present in sql.Engine

engine = property()

def execute_compiled(self, *args, **kwargs)

this method is required to be present as it overrides the execute_compiled present in sql.Engine

def get_engine(self)

def set_engine(self, engine)

back to section top
Class ProxyEngine(BaseProxyEngine)

Engine proxy for lazy and late initialization.

This engine will delegate access to a real engine set with connect().

def __init__(self, **kwargs)

def connect(self, *args, **kwargs)

Establish connection to a real engine.

def get_engine(self)

def set_engine(self, engine)

back to section top
Previous: Plugins