SQLAlchemy 0.4 Documentation

Multiple Pages | One Page
Version: 0.4 Last Updated: 08/16/07 11:15:18

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 CheckConstraint(Constraint)

def __init__(self, sqltext, name=None)

Construct a new CheckConstraint.

def copy(self)
__visit_name__ = property()
back to section top

class Column(SchemaItem,_ColumnClause)

Represent 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)

Construct 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_
The TypeEngine for this column. This can be any subclass of types.AbstractType, including the database-agnostic types defined in the types module, database-specific types defined within specific database modules, or user-defined types. If the column contains a ForeignKey, the type can also be None, in which case the type assigned will be that of the referenced column.
*args
Constraint, ForeignKey, ColumnDefault and Sequence objects should be added as list values.
**kwargs

Keyword arguments include:

key
Defaults to 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
Defaults to False: True if this column is a primary key column. Multiple columns can have this flag set to specify composite primary keys. As an alternative, the primary key of a Table can be specified via an explicit PrimaryKeyConstraint instance appended to the Table's list of objects.
nullable
Defaults to True : True if this column should allow nulls. True is the default unless this column is a primary key column.
default
Defaults to 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. The default expression will be converted into a ColumnDefault object upon initialization.
_is_oid
Defaults to False: used internally to indicate that this column is used as the quasi-hidden "oid" column
index
Defaults to False: indicates that this column is indexed. The name of the index is autogenerated. to specify indexes with explicit names or indexes that contain multiple columns, use the Index construct instead.
unique
Defaults to False: indicates that this column contains a unique constraint, or if index is True as well, indicates that the Index should be created with the unique flag. To specify multiple columns in the constraint/index or to specify an explicit name, use the UniqueConstraint or Index constructs instead.
autoincrement
Defaults to True: indicates that integer-based primary key columns should have autoincrementing behavior, if supported by the underlying database. This will affect CREATE TABLE statements such that they will use the databases auto-incrementing keyword (such as SERIAL for Postgres, AUTO_INCREMENT for Mysql) and will also affect the behavior of some dialects during INSERT statement execution such that they will assume primary key values are created in this manner. If a Column has an explicit ColumnDefault object (such as via the default keyword, or a Sequence or PassiveDefault), then the value of autoincrement is ignored and is assumed to be False. autoincrement value is only significant for a column with a type or subtype of Integer.
quote
Defaults to False: indicates that the Column identifier must be properly escaped and quoted before being sent to the database. This flag should normally not be required as dialects can auto-detect conditions where quoting is required.
def append_foreign_key(self, fk)
columns = property()
def copy(self)

Create a copy of this Column, unitialized.

This is used in Table.tometadata.

foreign_keys = property()

A default property accessor.

def get_children(self, schema_visitor=False, **kwargs)
primary_key = property()

A default property accessor.

def references(self, column)

return true if this column references the given column via foreign key

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)

Construct a new ColumnDefault.

__visit_name__ = property()
back to section top

class Constraint(SchemaItem)

Represent a table-level Constraint such as a composite primary key, foreign key, or unique constraint.

Implements a hybrid of dict/setlike behavior with regards to the list of underying columns.

def __init__(self, name=None)

Construct a new Constraint.

def copy(self)
def keys(self)
def __add__(self, other)
def __contains__(self, x)
def __iter__(self)
def __len__(self)
back to section top

class DefaultGenerator(SchemaItem)

Base class for column default values.

def __init__(self, for_update=False, metadata=None)

Construct a new DefaultGenerator.

def execute(self, bind=None, **kwargs)
back to section top

class ForeignKey(SchemaItem)

Defines a column-level ForeignKey constraint between two columns.

ForeignKey is specified as an argument to a Column object.

One or more ForeignKey objects are used within a ForeignKeyConstraint object which represents the table-level constraint definition.

def __init__(self, column, constraint=None, use_alter=False, name=None, onupdate=None, ondelete=None)

Construct 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.
constraint
Is the owning ForeignKeyConstraint object, if any. if not given, then a ForeignKeyConstraint will be automatically created and added to the parent table.
column = property()
def copy(self)

Produce a copy of this ForeignKey object.

def references(self, table)

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

back to section top

class ForeignKeyConstraint(Constraint)

Table-level foreign key constraint, represents a collection of ForeignKey objects.

def __init__(self, columns, refcolumns, name=None, onupdate=None, ondelete=None, use_alter=False)

Construct a new ForeignKeyConstraint.

def append_element(self, col, refcol)
def copy(self)
back to section top

class Index(SchemaItem)

Represent an index of columns from a database table.

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

Construct 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.
**kwargs

Keyword arguments include:

unique
Defaults to False: create a unique index.
def append_column(self, column)
def create(self, bind=None)
def drop(self, bind=None)
back to section top

class MetaData(SchemaItem)

A collection of Tables and their associated schema constructs.

Holds a collection of Tables and an optional binding to an Engine or Connection. If bound, the Table objects in the collection and their columns may participate in implicit SQL execution.

The bind property may be assigned to dynamically. A common pattern is to start unbound and then bind later when an engine is available:

metadata = MetaData()
# define tables
Table('mytable', metadata, ...)
# connect to an engine later, perhaps after loading a URL from a
# configuration file
metadata.bind = an_engine

MetaData is a thread-safe object after tables have been explicitly defined or loaded via reflection.

def __init__(self, bind=None, reflect=False)

Create a new MetaData object.

bind
An Engine or Connection to bind to. May also be a string or URL instance, these are passed to create_engine() and this MetaData will be bound to the resulting engine.
reflect
Optional, automatically load all tables from the bound database. Defaults to False. bind is required when this option is set. For finer control over loaded tables, use the reflect method of MetaData.
bind = property()

An Engine or Connection to which this MetaData is bound.

This property may be assigned an Engine or Connection, or assigned a string or URL to automatically create a basic Engine for this bind with create_engine().

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

Deprecated. Bind this MetaData to an Engine.

Use metadata.bind = <engine> or metadata.bind = <url>.

bind
A string, URL, Engine or Connection instance. If a string or URL, will be passed to create_engine() along with \**kwargs to produce the engine which to connect to. Otherwise connects directly to the given Engine.
def create_all(self, bind=None, tables=None, checkfirst=True)

Create all tables stored in this metadata.

This will conditionally create tables depending on if they do not yet exist in the database.

bind
A Connectable used to access the database; if None, uses the existing bind on this MetaData, if any.
tables
Optional list of Table objects, which is a subset of the total tables in the MetaData (others are ignored).
def drop_all(self, bind=None, tables=None, checkfirst=True)

Drop all tables stored in this metadata.

This will conditionally drop tables depending on if they currently exist in the database.

bind
A Connectable used to access the database; if None, uses the existing bind on this MetaData, if any.
tables
Optional list of Table objects, which is a subset of the total tables in the MetaData (others are ignored).
def is_bound(self)

True if this MetaData is bound to an Engine or Connection.

def reflect(self, bind=None, schema=None, only=None)

Load all available table definitions from the database.

Automatically creates Table entries in this MetaData for any table available in the database but not yet present in the MetaData. May be called multiple times to pick up tables recently added to the database, however no special action is taken if a table in this MetaData no longer exists in the database.

bind
A Connectable used to access the database; if None, uses the existing bind on this MetaData, if any.
schema
Optional, query and reflect tables from an alterate schema.
only

Optional. Load only a sub-set of available named tables. May be specified as a sequence of names or a callable.

If a sequence of names is provided, only those tables will be reflected. An error is raised if a table is requested but not available. Named tables already present in this MetaData are ignored.

If a callable is provided, it will be used as a boolean predicate to filter the list of potential table names. The callable is called with a table name and this MetaData instance as positional arguments and should return a true value for any table to reflect.

def remove(self, table)
def table_iterator(self, reverse=True, tables=None)
def __contains__(self, key)
back to section top

class PassiveDefault(DefaultGenerator)

A default that takes effect on the database side.

def __init__(self, arg, **kwargs)

Construct a new PassiveDefault.

back to section top

class PrimaryKeyConstraint(Constraint)

def __init__(self, *columns, **kwargs)

Construct a new PrimaryKeyConstraint.

def add(self, col)
def append_column(self, col)
def copy(self)
def remove(self, col)
def __eq__(self, other)
back to section top

class SchemaItem(object)

Base class for items that define a database schema.

bind = property()
def get_children(self, **kwargs)

used to allow SchemaVisitor access

metadata = property()
back to section top

class SchemaVisitor(ClauseVisitor)

Define the visiting for SchemaItem objects.

back to section top

class Sequence(DefaultGenerator)

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

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

Construct a new Sequence.

def create(self, bind=None, checkfirst=True)
def drop(self, bind=None, checkfirst=True)
back to section top

class Table(SchemaItem,TableClause)

Represent a relational database table.

This subclasses sql.TableClause to provide a table that is associated with an instance of MetaData, which in turn may be associated with an instance of Engine.

Whereas TableClause represents a table as its used in an SQL expression, Table represents a table as it exists in a database schema.

If this Table is ultimately associated with an engine, the Table gains the ability to access the database directly without the need for dealing with an explicit Connection object; this is known as "implicit execution".

Implicit operation allows the Table to access the database to reflect its own properties (via the autoload=True flag), it allows the create() and drop() methods to be called without passing a connectable, and it also propigates the underlying engine to constructed SQL objects so that they too can be executed via their execute() method without the need for a Connection.

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

Construct a Table.

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
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. Defaults to None.
autoload
Defaults to 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.
autoload_with
if autoload==True, this is an optional Engine or Connection instance to be used for the table reflection. If None, the underlying MetaData's bound connectable will be used.
include_columns
A list of strings indicating a subset of columns to be loaded via the autoload operation; table columns who aren't present in this list will not be represented on the resulting Table object. Defaults to None which indicates all columns should be reflected.
mustexist
Defaults to False: indicates that this Table must already have been defined elsewhere in the application, else an exception is raised.
useexisting
Defaults to False: indicates that if this Table was already defined elsewhere in the application, disregard the rest of the constructor arguments.
owner
Defaults to None: optional owning user of this table. useful for databases such as Oracle to aid in table reflection.
quote
Defaults to False: indicates that the Table identifier must be properly escaped and quoted before being sent to the database. This flag overrides all other quoting behavior.
quote_schema
Defaults to False: indicates that the Namespace identifier must be properly escaped and quoted before being sent to the database. This flag overrides all other quoting behavior.
def append_column(self, column)

Append a Column to this Table.

def append_constraint(self, constraint)

Append a Constraint to this Table.

def create(self, bind=None, checkfirst=False)

Issue a CREATE statement for this table.

See also metadata.create_all().

def drop(self, bind=None, checkfirst=False)

Issue a DROP statement for this table.

See also metadata.drop_all().

def exists(self, bind=None)

Return True if this table exists.

def get_children(self, column_collections=True, schema_visitor=False, **kwargs)
key = property()
primary_key = property()
def tometadata(self, metadata, schema=None)

Return a copy of this Table associated with a different MetaData.

back to section top

class ThreadLocalMetaData(MetaData)

A MetaData variant that presents a different bind in every thread.

Makes the bind property of the MetaData a thread-local value, allowing this collection of tables to be bound to different Engine implementations or connections in each thread.

The ThreadLocalMetaData starts off bound to None in each thread. Binds must be made explicitly by assigning to the bind property or using connect(). You can also re-bind dynamically multiple times per thread, just like a regular MetaData.

Use this type of MetaData when your tables are present in more than one database and you need to address them simultanesouly.

def __init__(self)

Construct a ThreadLocalMetaData.

Takes no arguments.

bind = property()

The bound Engine or Connection for this thread.

This property may be assigned an Engine or Connection, or assigned a string or URL to automatically create a basic Engine for this bind with create_engine().

def connect(*args, **kwargs)

Deprecated. Bind to an Engine in the caller's thread.

Use metadata.bind=<engine> or metadata.bind=<url>.

bind
A string, URL, Engine or Connection instance. If a string or URL, will be passed to create_engine() along with \**kwargs to produce the engine which to connect to. Otherwise connects directly to the given Engine.
def dispose(self)

Dispose any and all Engines to which this ThreadLocalMetaData has been connected.

def is_bound(self)

True if there is a bind for this thread.

back to section top

class UniqueConstraint(Constraint)

def __init__(self, *columns, **kwargs)

Construct a new UniqueConstraint.

def append_column(self, col)
def copy(self)
back to section top
Up: API Documentation | Previous: module sqlalchemy.sql | Next: module sqlalchemy.pool