SQLAlchemy 0.4 Documentation
Table of Contents
(view full table)- Overview / Installation
- Object Relational Tutorial
- SQL Expression Language Tutorial
- Mapper Configuration
- Using the Session
- Database Engines
- Database Meta Data
- The Types System
- Connection Pooling
- Plugins
- API Documentation
- Appendix: Copyright
Table of Contents: Full
(view brief table)- Overview / Installation
-
- Overview
- Tutorials
- Reference Documentation
- Installing SQLAlchemy
- 0.3 to 0.4 Migration
-
- ORM Package is now sqlalchemy.orm
- BoundMetaData is now MetaData
- "Magic" Global MetaData removed
- Some existing select() methods become generative
- collection_class behavior is changed
- All "engine", "bind_to", "connectable" Keyword Arguments Changed to "bind"
- All "type" Keyword Arguments Changed to "type_"
- Mapper Extensions must return EXT_CONTINUE to continue execution to the next mapper
- Object Relational Tutorial
-
- Version Check
- Connecting
- Define and Create a Table
- Define a Python Class to be Mapped
- Setting up the Mapping
- Too Verbose ? There are alternatives
- Creating a Session
- Saving Objects
- Querying
- Building a One-to-Many Relation
- Working with Related Objects and Backreferences
- Querying with Joins
- Deleting
- Building a Many To Many Relation
- Further Reference
- SQL Expression Language Tutorial
-
- Version Check
- Connecting
- Define and Create Tables
- Insert Expressions
- Executing
- Executing Multiple Statements
- Connectionless / Implicit Execution
- Selecting
- Operators
- Conjunctions
- Using Text
- Using Aliases
- Using Joins
- Intro to Generative Selects and Transformations
- Everything Else
- Updates
- Deletes
- Further Reference
- Mapper Configuration
-
- Mapper Configuration
-
- Customizing Column Properties
- Deferred Column Loading
- SQL Expressions as Mapped Attributes
- Overriding Attribute Behavior with Synonyms
- Composite Column Types
- Controlling Ordering
- Mapping Class Inheritance Hierarchies
- Mapping a Class against Multiple Tables
- Mapping a Class against Arbitrary Selects
- Multiple Mappers for One Class
- Extending Mapper
- Relation Configuration
- Using the Session
- Database Engines
- Database Meta Data
- The Types System
- Connection Pooling
- Plugins
- API Documentation
-
- module sqlalchemy.engine
-
- Module Functions
- class BufferedColumnResultProxy(ResultProxy)
- class BufferedColumnRow(RowProxy)
- class BufferedRowResultProxy(ResultProxy)
- class Compiled(object)
- class Connectable(object)
- class Connection(Connectable)
- class DefaultRunner(SchemaVisitor)
- class Dialect(object)
- class Engine(Connectable)
- class ExecutionContext(object)
- class NestedTransaction(Transaction)
- class ResultProxy(object)
- class RootTransaction(Transaction)
- class RowProxy(object)
- class SchemaIterator(SchemaVisitor)
- class Transaction(object)
- class TwoPhaseTransaction(Transaction)
- module sqlalchemy.engine.default
- module sqlalchemy.engine.strategies
- module sqlalchemy.engine.threadlocal
- module sqlalchemy.engine.url
- module sqlalchemy.exceptions
-
- class ArgumentError()
- class AssertionError()
- class CircularDependencyError()
- class CompileError()
- class ConcurrentModificationError()
- class DBAPIError()
- class DataError()
- class DatabaseError()
- class DisconnectionError()
- class FlushError()
- class IntegrityError()
- class InterfaceError()
- class InternalError()
- class InvalidRequestError()
- class NoReferencedTableError()
- class NoSuchColumnError()
- class NoSuchTableError()
- class NotSupportedError()
- class OperationalError()
- class ProgrammingError()
- class SADeprecationWarning()
- class SAPendingDeprecationWarning()
- class SAWarning()
- class SQLAlchemyError()
- class TimeoutError()
- class UnboundExecutionError()
- class UnmappedColumnError()
- module sqlalchemy.interfaces
- module sqlalchemy.pool
- module sqlalchemy.schema
-
- class CheckConstraint(Constraint)
- class Column(SchemaItem,_ColumnClause)
- class ColumnDefault(DefaultGenerator)
- class Constraint(SchemaItem)
- class DDL(object)
- class DefaultGenerator(SchemaItem)
- class ForeignKey(SchemaItem)
- class ForeignKeyConstraint(Constraint)
- class Index(SchemaItem)
- class MetaData(SchemaItem)
- class PassiveDefault(DefaultGenerator)
- class PrimaryKeyConstraint(Constraint)
- class SchemaItem(object)
- class SchemaVisitor(ClauseVisitor)
- class Sequence(DefaultGenerator)
- class Table(SchemaItem,TableClause)
- class ThreadLocalMetaData(MetaData)
- class UniqueConstraint(Constraint)
- module sqlalchemy.sql.compiler
- module sqlalchemy.sql.expression
-
- Module Functions
-
- alias()
- and_()
- asc()
- between()
- bindparam()
- case()
- cast()
- collate()
- column()
- delete()
- desc()
- distinct()
- except_()
- except_all()
- exists()
- extract()
- insert()
- intersect()
- intersect_all()
- is_column()
- join()
- label()
- literal()
- literal_column()
- not_()
- null()
- or_()
- outerjoin()
- outparam()
- select()
- subquery()
- table()
- text()
- union()
- union_all()
- update()
- class Alias(FromClause)
- class _BinaryExpression(ColumnElement)
- class _BindParamClause(ClauseElement,_CompareMixin)
- class _CalculatedClause(ColumnElement)
- class _Cast(ColumnElement)
- class ClauseElement(object)
- class ClauseList(ClauseElement)
- class _ColumnClause(ColumnElement)
- class ColumnCollection(OrderedProperties)
- class ColumnElement(ClauseElement,_CompareMixin)
- class _ColumnElementAdapter(ColumnElement)
- class ColumnOperators(Operators)
- class ColumnSet(OrderedSet)
- class _CompareMixin(ColumnOperators)
- class CompoundSelect(_SelectBaseMixin,FromClause)
- class Delete(_UpdateBase)
- class _Exists(_UnaryExpression)
- class _FigureVisitName(type)
- class FromClause(Selectable)
- class _FromGrouping(FromClause)
- class _Function(_CalculatedClause,FromClause)
- class _FunctionGenerator(object)
- class _Grouping(_ColumnElementAdapter)
- class _IdentifiedClause(ClauseElement)
- class Insert(_ValuesBase)
- class Join(FromClause)
- class _Label(ColumnElement)
- class _Null(ColumnElement)
- class Operators(object)
- class ReleaseSavepointClause(_IdentifiedClause)
- class RollbackToSavepointClause(_IdentifiedClause)
- class SavepointClause(_IdentifiedClause)
- class _ScalarSelect(_Grouping)
- class Select(_SelectBaseMixin,FromClause)
- class _SelectBaseMixin(object)
- class Selectable(ClauseElement)
- class TableClause(FromClause)
- class _TextClause(ClauseElement)
- class _TypeClause(ClauseElement)
- class _UnaryExpression(ColumnElement)
- class Update(_ValuesBase)
- class _UpdateBase(ClauseElement)
- class _ValuesBase(_UpdateBase)
- module sqlalchemy.types
-
- class AbstractType(object)
- class BLOB(Binary)
- class BOOLEAN(Boolean)
- class Binary(TypeEngine)
- class Boolean(TypeEngine)
- class CHAR(String)
- class CLOB(Text)
- class DATE(Date)
- class DATETIME(DateTime)
- class DECIMAL(Numeric)
- class Date(TypeEngine)
- class DateTime(TypeEngine)
- class FLOAT(Float)
- class Float(Numeric)
- class INT(Integer)
- class Integer(TypeEngine)
- class Interval(TypeDecorator)
- class NCHAR(Unicode)
- class NUMERIC(Numeric)
- class Numeric(TypeEngine)
- class PickleType(MutableType,TypeDecorator)
- class SMALLINT(SmallInteger)
- class SmallInteger(Integer)
- class String(Concatenable,TypeEngine)
- class TIME(Time)
- class TIMESTAMP(DateTime)
- class Text(String)
- class Time(TypeEngine)
- class TypeDecorator(AbstractType)
- class TypeEngine(AbstractType)
- class Unicode(String)
- class UnicodeText(Text)
- class VARCHAR(String)
- module sqlalchemy.orm
-
- Module Functions
-
- backref()
- class_mapper()
- clear_mappers()
- column_property()
- comparable_property()
- compile_mappers()
- composite()
- contains_alias()
- contains_eager()
- create_session()
- defer()
- deferred()
- dynamic_loader()
- eagerload()
- eagerload_all()
- extension()
- lazyload()
- mapper()
- noload()
- object_mapper()
- object_session()
- polymorphic_union()
- relation()
- scoped_session()
- sessionmaker()
- synonym()
- undefer()
- undefer_group()
- class AliasedClass(object)
- class MapperExtension(object)
- class PropComparator(ColumnOperators)
- class Query(object)
- module sqlalchemy.orm.collections
- module sqlalchemy.orm.interfaces
-
- Module Functions
- class AttributeExtension(object)
- class ExtensionOption(MapperOption)
- class LoaderStrategy(object)
- class MapperExtension(object)
- class MapperOption(object)
- class MapperProperty(object)
- class PropComparator(ColumnOperators)
- class PropertyOption(MapperOption)
- class StrategizedOption(PropertyOption)
- class StrategizedProperty(MapperProperty)
- module sqlalchemy.orm.mapper
- module sqlalchemy.orm.properties
- module sqlalchemy.orm.query
- module sqlalchemy.orm.session
- module sqlalchemy.orm.shard
- module sqlalchemy.ext.declarative
- module sqlalchemy.ext.associationproxy
- module sqlalchemy.ext.orderinglist
- module sqlalchemy.ext.sqlsoup
- module sqlalchemy.databases.sqlite
-
- Module Functions
- class DateTimeMixin(object)
- class PassiveDefault(DefaultGenerator)
- class SLBinary(Binary)
- class SLBoolean(Boolean)
- class SLChar(CHAR)
- class SLDate(DateTimeMixin,Date)
- class SLDateTime(DateTimeMixin,DateTime)
- class SLInteger(Integer)
- class SLNumeric(Numeric)
- class SLSmallInteger(SmallInteger)
- class SLString(String)
- class SLText(Text)
- class SLTime(DateTimeMixin,Time)
- class SQLiteCompiler(DefaultCompiler)
- class SQLiteDialect(DefaultDialect)
- class SQLiteExecutionContext(DefaultExecutionContext)
- class SQLiteIdentifierPreparer(IdentifierPreparer)
- class SQLiteSchemaDropper(SchemaDropper)
- class SQLiteSchemaGenerator(SchemaGenerator)
- module sqlalchemy.databases.postgres
-
- Module Functions
- class PGArray(MutableType,Concatenable,TypeEngine)
- class PGBigInteger(PGInteger)
- class PGBinary(Binary)
- class PGBoolean(Boolean)
- class PGChar(CHAR)
- class PGCompiler(DefaultCompiler)
- class PGDate(Date)
- class PGDateTime(DateTime)
- class PGDefaultRunner(DefaultRunner)
- class PGDialect(DefaultDialect)
- class PGExecutionContext(DefaultExecutionContext)
- class PGFloat(Float)
- class PGIdentifierPreparer(IdentifierPreparer)
- class PGInet(TypeEngine)
- class PGInteger(Integer)
- class PGInterval(TypeEngine)
- class PGMacAddr(TypeEngine)
- class PGNumeric(Numeric)
- class PGSchemaDropper(SchemaDropper)
- class PGSchemaGenerator(SchemaGenerator)
- class PGSmallInteger(SmallInteger)
- class PGString(String)
- class PGText(Text)
- class PGTime(Time)
- module sqlalchemy.databases.mysql
-
- class MSBigInteger(MSInteger)
- class MSBinary(_BinaryType)
- class MSBit(TypeEngine)
- class MSBlob(_BinaryType)
- class MSBoolean(Boolean)
- class MSChar(_StringType,CHAR)
- class MSDate(Date)
- class MSDateTime(DateTime)
- class MSDecimal(MSNumeric)
- class MSDouble(Float,_NumericType)
- class MSEnum(MSString)
- class MSFloat(Float,_NumericType)
- class MSInteger(Integer,_NumericType)
- class MSLongBlob(MSBlob)
- class MSLongText(MSText)
- class MSMediumBlob(MSBlob)
- class MSMediumText(MSText)
- class MSNChar(_StringType,CHAR)
- class MSNVarChar(_StringType,String)
- class MSNumeric(Numeric,_NumericType)
- class MSSet(MSString)
- class MSSmallInteger(SmallInteger,MSInteger)
- class MSString(_StringType,String)
- class MSText(_StringType,Text)
- class MSTime(Time)
- class MSTimeStamp(TIMESTAMP)
- class MSTinyBlob(MSBlob)
- class MSTinyInteger(MSInteger)
- class MSTinyText(MSText)
- class MSVarBinary(_BinaryType)
- class MSYear(TypeEngine)
- module sqlalchemy.databases.oracle
-
- Module Functions
- class OracleBinary(Binary)
- class OracleBoolean(Boolean)
- class OracleChar(CHAR)
- class OracleCompiler(DefaultCompiler)
- class OracleDate(Date)
- class OracleDateTime(DateTime)
- class OracleDefaultRunner(DefaultRunner)
- class OracleDialect(DefaultDialect)
- class OracleExecutionContext(DefaultExecutionContext)
- class OracleIdentifierPreparer(IdentifierPreparer)
- class OracleInteger(Integer)
- class OracleNumeric(Numeric)
- class OracleRaw(OracleBinary)
- class OracleSchemaDropper(SchemaDropper)
- class OracleSchemaGenerator(SchemaGenerator)
- class OracleSmallInteger(SmallInteger)
- class OracleString(String)
- class OracleText(Text)
- class OracleTimestamp(TIMESTAMP)
- module sqlalchemy.databases.mssql
-
- Module Functions
- class AdoMSNVarchar(MSNVarchar)
- class Decimal(object)
- class MSBigInteger(MSInteger)
- class MSBinary(Binary)
- class MSBoolean(Boolean)
- class MSChar(CHAR)
- class MSDate(Date)
- class MSDateTime(DateTime)
- class MSDateTime_adodbapi(MSDateTime)
- class MSDateTime_pyodbc(MSDateTime)
- class MSDate_pyodbc(MSDate)
- class MSFloat(Float)
- class MSInteger(Integer)
- class MSMoney(TypeEngine)
- class MSNChar(NCHAR)
- class MSNVarchar(Unicode)
- class MSNumeric(Numeric)
- class MSSQLCompiler(DefaultCompiler)
- class MSSQLDefaultRunner(DefaultRunner)
- class MSSQLDialect(DefaultDialect)
- class MSSQLDialect_adodbapi(MSSQLDialect)
- class MSSQLDialect_pymssql(MSSQLDialect)
- class MSSQLDialect_pyodbc(MSSQLDialect)
- class MSSQLExecutionContext(DefaultExecutionContext)
- class MSSQLExecutionContext_pyodbc(MSSQLExecutionContext)
- class MSSQLIdentifierPreparer(IdentifierPreparer)
- class MSSQLSchemaDropper(SchemaDropper)
- class MSSQLSchemaGenerator(SchemaGenerator)
- class MSSmallDate(Date)
- class MSSmallInteger(MSInteger)
- class MSSmallMoney(MSMoney)
- class MSString(String)
- class MSText(Text)
- class MSTime(Time)
- class MSTimeStamp(TIMESTAMP)
- class MSTinyInteger(MSInteger)
- class MSUniqueIdentifier(TypeEngine)
- class MSVariant(TypeEngine)
- module sqlalchemy.databases.firebird
-
- Module Functions
- class FBBinary(Binary)
- class FBBoolean(Boolean)
- class FBChar(CHAR)
- class FBCompiler(DefaultCompiler)
- class FBDate(DateTime)
- class FBDateTime(DateTime)
- class FBDefaultRunner(DefaultRunner)
- class FBDialect(DefaultDialect)
- class FBExecutionContext(DefaultExecutionContext)
- class FBFloat(Float)
- class FBIdentifierPreparer(IdentifierPreparer)
- class FBInteger(Integer)
- class FBNumeric(Numeric)
- class FBSchemaDropper(SchemaDropper)
- class FBSchemaGenerator(SchemaGenerator)
- class FBSmallInteger(SmallInteger)
- class FBString(String)
- class FBText(Text)
- class FBTime(Time)
- module sqlalchemy.databases.sybase
-
- class SybaseBigInteger(SybaseInteger)
- class SybaseBinary(Binary)
- class SybaseBoolean(Boolean)
- class SybaseChar(CHAR)
- class SybaseDateTime_mxodbc(DateTime)
- class SybaseDateTime_pyodbc(DateTime)
- class SybaseDate_mxodbc(Date)
- class SybaseDate_pyodbc(Date)
- class SybaseFloat(FLOAT,SybaseNumeric)
- class SybaseInteger(Integer)
- class SybaseMoney(TypeEngine)
- class SybaseSmallInteger(SybaseInteger)
- class SybaseSmallMoney(SybaseMoney)
- class SybaseString(String)
- class SybaseText(Text)
- class SybaseTimeStamp(TIMESTAMP)
- class SybaseTime_mxodbc(Time)
- class SybaseTime_pyodbc(Time)
- class SybaseTinyInteger(SybaseInteger)
- class SybaseUniqueIdentifier(TypeEngine)
- module sqlalchemy.databases.access
-
- Module Functions
- class AcBinary(Binary)
- class AcBoolean(Boolean)
- class AcChar(CHAR)
- class AcDate(Date)
- class AcDateTime(DateTime)
- class AcFloat(Float)
- class AcInteger(Integer)
- class AcNumeric(Numeric)
- class AcSmallInteger(SmallInteger)
- class AcString(String)
- class AcText(Text)
- class AcTimeStamp(TIMESTAMP)
- class AcTinyInteger(Integer)
- class AcUnicode(Unicode)
- class AccessCompiler(DefaultCompiler)
- class AccessDefaultRunner(DefaultRunner)
- class AccessDialect(DefaultDialect)
- class AccessExecutionContext(DefaultExecutionContext)
- class AccessIdentifierPreparer(IdentifierPreparer)
- class AccessSchemaDropper(SchemaDropper)
- class AccessSchemaGenerator(SchemaGenerator)
- module sqlalchemy.databases.maxdb
-
- class MaxBlob(Binary)
- class MaxBoolean(Boolean)
- class MaxChar(_StringType)
- class MaxDate(Date)
- class MaxFloat(Float)
- class MaxInteger(Integer)
- class MaxNumeric(Numeric)
- class MaxSmallInteger(MaxInteger)
- class MaxString(_StringType)
- class MaxText(_StringType)
- class MaxTime(Time)
- class MaxTimestamp(DateTime)
- class MaxUnicode(_StringType)
- Appendix: Copyright
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:
+-----------------------------------------------------------+
| Object Relational Mapper (ORM) |
| [tutorial] [docs] |
+-----------------------------------------------------------+
+---------+ +------------------------------------+ +--------+
| | | SQL Expression Language | | |
| | | [tutorial] [docs] | | |
| | +------------------------------------+ | |
| +-----------------------+ +--------------+ |
| Dialect/Execution | | Schema Management |
| [docs] | | [docs] |
+---------------------------------+ +-----------------------+
+----------------------+ +----------------------------------+
| Connection Pooling | | Types |
| [docs] | | [docs] |
+----------------------+ +----------------------------------+
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.
back to section topTutorials
- Object Relational Tutorial - 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 - 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 - A comprehensive walkthrough of major ORM patterns and techniques.
- Session - A detailed description of SQLAlchemy's Session object
- Engines - Describes SQLAlchemy's database-connection facilities, including connection documentation and working with connections and transactions.
- Connection Pools - Further detail about SQLAlchemy's connection pool library.
-
Metadata - All about schema management using
MetaDataandTableobjects; reading database schemas into your application, creating and dropping tables, constraints, defaults, sequences, indexes. - Types - Datatypes included with SQLAlchemy, their functions, as well as how to create your own types.
- Plugins - Included addons for SQLAlchemy
Installing SQLAlchemy
Installing SQLAlchemy from scratch is most easily achieved with setuptools. (setuptools installation). Just run this from the command-line:
# easy_install SQLAlchemy
This command will download the latest version of SQLAlchemy from the Python Cheese Shop and install it to your system.
Otherwise, you can install from the distribution using the setup.py script:
# python setup.py install
Installing a Database API
SQLAlchemy is designed to operate with a DB-API implementation built for a particular database, and includes support for the most popular databases:
- Postgres: psycopg2
- SQLite: pysqlite, sqlite3 (included with Python 2.5 or greater)
- MySQL: MySQLdb
- Oracle: cx_Oracle
- MS-SQL: pyodbc (recommended), adodbapi or pymssql
- Firebird: kinterbasdb
- Informix: informixdb
Checking the Installed SQLAlchemy Version
This documentation covers SQLAlchemy version 0.4. If you're working on a system that already has SQLAlchemy installed, check the version from your Python prompt like this:
>>> import sqlalchemy >>> sqlalchemy.__version__ 0.4.0
0.3 to 0.4 Migration
From version 0.3 to version 0.4 of SQLAlchemy, some conventions have changed. Most of these conventions are available in the most recent releases of the 0.3 series starting with version 0.3.9, so that you can make a 0.3 application compatible with 0.4 in most cases.
This section will detail only those things that have changed in a backwards-incompatible manner. For a full overview of everything that's new and changed, see WhatsNewIn04.
ORM Package is now sqlalchemy.orm
All symbols related to the SQLAlchemy Object Relational Mapper, i.e. names like mapper(), relation(), backref(), create_session() synonym(), eagerload(), etc. are now only in the sqlalchemy.orm package, and not in sqlalchemy. So if you were previously importing everything on an asterisk:
from sqlalchemy import *
You should now import separately from orm:
from sqlalchemy import * from sqlalchemy.orm import *
Or more commonly, just pull in the names you'll need:
from sqlalchemy import create_engine, MetaData, Table, Column, types from sqlalchemy.orm import mapper, relation, backref, create_session
BoundMetaData is now MetaData
The BoundMetaData name is removed. Now, you just use MetaData. Additionally, the engine parameter/attribute is now called bind, and connect() is deprecated:
# plain metadata meta = MetaData() # metadata bound to an engine meta = MetaData(engine) # bind metadata to an engine later meta.bind = engine
Additionally, DynamicMetaData is now known as ThreadLocalMetaData.
"Magic" Global MetaData removed
There was an old way to specify Table objects using an implicit, global MetaData object. To do this you'd omit the second positional argument, and specify Table('tablename', Column(...)). This no longer exists in 0.4 and the second MetaData positional argument is required, i.e. Table('tablename', meta, Column(...)).
Some existing select() methods become generative
The methods correlate(), <
