SQLAlchemy 0.4 Documentation
- 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.schema
The schema module provides the building blocks for database metadata.
Each element within this module describes a database entity which can be created and dropped, or is otherwise part of such an entity. Examples include tables, columns, sequences, and indexes.
All entities are subclasses of SchemaItem, and as defined in this module they are intended to be agnostic of any vendor-specific constructs.
A collection of entities are grouped into a unit called MetaData. MetaData serves as a logical grouping of schema elements, and can also be associated with an actual database connection such that operations involving the contained elements can contact the database as needed.
Two of the elements here also build upon their "syntactic" counterparts, which are defined in module sqlalchemy.sql.expression, specifically Table and Column. Since these objects are part of the SQL expression language, they are usable as components in SQL expressions.
class CheckConstraint(Constraint)
A table- or column-level CHECK constraint.
Can be included in the definition of a Table or Column.
Construct a CHECK constraint.
- sqltext
- A string containing the constraint definition. Will be used verbatim.
- name
- Optional, the in-database name of the constraint.
- deferrable
- Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
- initially
- Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
class Column(SchemaItem,_ColumnClause)
Represent a column in a database table.
This is a subclass of expression.ColumnClause and represents an actual existing table in the database, in a similar fashion as TableClause/Table.
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. Name may be omitted at construction time but must be assigned before adding a Column instance to a Table.
- 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 the column name: a Python-only 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.
- info
- Defaults to {}: A space to store application specific data; this must be a dictionary.
- 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
- When True, indicates that the Column identifier must be quoted. This flag does not disable quoting; for case-insensitive names, use an all lower case identifier.
class ColumnDefault(DefaultGenerator)
A plain default value on a column.
This could correspond to a constant, a callable function, or a SQL clause.
class Constraint(SchemaItem)
A table-level SQL constraint, such as a KEY.
Implements a hybrid of dict/setlike behavior with regards to the list of underying columns.
Create a SQL constraint.
- name
- Optional, the in-database name of this Constraint.
- deferrable
- Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
- initially
- Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
class DDL(object)
A literal DDL statement.
Specifies literal SQL DDL to be executed by the database. DDL objects can be attached to Tables or MetaData instances, conditionally executing SQL as part of the DDL lifecycle of those schema items. Basic templating support allows a single DDL instance to handle repetitive tasks for multiple tables.
Examples:
tbl = Table('users', metadata, Column('uid', Integer)) # ...
DDL('DROP TRIGGER users_trigger').execute_at('before-create', tbl)
spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE', on='somedb')
spow.execute_at('after-create', tbl)
drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE')
connection.execute(drop_spow)
Create a DDL statement.
- statement
A string or unicode string to be executed. Statements will be processed with Python's string formatting operator. See the context argument and the execute_at method.
A literal '%' in a statement must be escaped as '%%'.
SQL bind parameters are not available in DDL statements.
- on
Optional filtering criteria. May be a string or a callable predicate. If a string, it will be compared to the name of the executing database dialect:
DDL('something', on='postgres')If a callable, it will be invoked with three positional arguments:
- event
- The name of the event that has triggered this DDL, such as 'after-create' Will be None if the DDL is executed explicitly.
- schema_item
- A SchemaItem instance, such as Table or MetaData. May be None if the DDL is executed explicitly.
- connection
- The Connection being used for DDL execution
If the callable returns a true value, the DDL statement will be executed.
- context
- Optional dictionary, defaults to None. These values will be available for use in string substitutions on the DDL statement.
- bind
- Optional. A Connectable, used by default when execute() is invoked without a bind argument.
Execute this DDL immediately.
Executes the DDL statement in isolation using the supplied Connectable or Connectable assigned to the .bind property, if not supplied. If the DDL has a conditional on criteria, it will be invoked with None as the event.
- bind
- Optional, an Engine or Connection. If not supplied, a valid Connectable must be present in the .bind property.
- schema_item
- Optional, defaults to None. Will be passed to the on callable criteria, if any, and may provide string expansion data for the statement. See execute_at for more information.
Link execution of this DDL to the DDL lifecycle of a SchemaItem.
Links this DDL to a Table or MetaData instance, executing it when that schema item is created or dropped. The DDL statement will be executed using the same Connection and transactional context as the Table create/drop itself. The .bind property of this statement is ignored.
- event
- One of the events defined in the schema item's .ddl_events; e.g. 'before-create', 'after-create', 'before-drop' or 'after-drop'
- schema_item
- A Table or MetaData instance
When operating on Table events, the following additional statement string substitions are available:
%(table)s - the Table name, with any required quoting applied %(schema)s - the schema name, with any required quoting applied %(fullname)s - the Table name including schema, quoted if needed
The DDL's context, if any, will be combined with the standard substutions noted above. Keys present in the context will override the standard substitutions.
A DDL instance can be linked to any number of schema items. The statement subsitution support allows for DDL instances to be used in a template fashion.
execute_at builds on the append_ddl_listener interface of MetaDta and Table objects.
Caveat: Creating or dropping a Table in isolation will also trigger any DDL set to execute_at that Table's MetaData. This may change in a future release.
class ForeignKey(SchemaItem)
Defines a column-level FOREIGN KEY constraint between two columns.
ForeignKey is specified as an argument to a Column object.
For a composite (multiple column) FOREIGN KEY, use a ForeignKeyConstraint within the Table definition.
Construct a column-level FOREIGN KEY.
- column
- A single target column for the key relationship. A Column object or a column name as a string: tablename.columnname or schema.tablename.columnname.
- constraint
- Optional. A parent ForeignKeyConstraint object. If not supplied, a ForeignKeyConstraint will be automatically created and added to the parent table.
- name
- Optional string. An in-database name for the key if constraint is not provided.
- onupdate
- Optional string. If set, emit ON UPDATE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.
- ondelete
- Optional string. If set, emit ON DELETE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.
- deferrable
- Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
- initially
- Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
- use_alter
- If True, do not emit this key as part of the CREATE TABLE definition. Instead, use ALTER TABLE after table creation to add the key. Useful for circular dependencies.
Return the column in the given table referenced by this ForeignKey.
Returns None if this ForeignKey does not reference the given table.
class ForeignKeyConstraint(Constraint)
A table-level FOREIGN KEY constraint.
Defines a single column or composite FOREIGN KEY ... REFERENCES constraint. For a no-frills, single column foreign key, adding a ForeignKey to the definition of a Column is a shorthand equivalent for an unnamed, single column ForeignKeyConstraint.
Construct a composite-capable FOREIGN KEY.
- columns
- A sequence of local column names. The named columns must be defined and present in the parent Table.
- refcolumns
- A sequence of foreign column names or Column objects. The columns must all be located within the same Table.
- name
- Optional, the in-database name of the key.
- onupdate
- Optional string. If set, emit ON UPDATE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.
- ondelete
- Optional string. If set, emit ON DELETE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.
- deferrable
- Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
- initially
- Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
- use_alter
- If True, do not emit this key as part of the CREATE TABLE definition. Instead, use ALTER TABLE after table creation to add the key. Useful for circular dependencies.
class Index(SchemaItem)
A table-level INDEX.
Defines a composite (one or more column) INDEX. For a no-frills, single column index, adding index=True to the Column definition is a shorthand equivalent for an unnamed, single column Index.
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.
- postgres_where
- Defaults to None: create a partial index when using PostgreSQL
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.
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.
Append a DDL event listener to this MetaData.
The listener callable will be triggered when this MetaData is involved in DDL creates or drops, and will be invoked either before all Table-related actions or after.
Arguments are:
- event
- One of MetaData.ddl_events; 'before-create', 'after-create', 'before-drop' or 'after-drop'.
- listener
A callable, invoked with three positional arguments:
- event
- The event currently being handled
- schema_item
- The MetaData object being operated upon
- bind
- The Connection bueing used for DDL execution.
Listeners are added to the MetaData's ddl_listeners attribute.
Note: MetaData listeners are invoked even when Tables are created in isolation. This may change in a future release. I.e.:
# triggers all MetaData and Table listeners: metadata.create_all() # triggers MetaData listeners too: some.table.create()
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.
Create all tables stored in this metadata.
Conditional by default, will not attempt to recreate tables already present in the target 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).
- checkfirst
- Defaults to True, don't issue CREATEs for tables already present in the target database.
Drop all tables stored in this metadata.
Conditional by default, will not attempt to drop tables not present in the target 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).
- checkfirst
- Defaults to True, don't issue CREATEs for tables already present in the target database.
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.
class PassiveDefault(DefaultGenerator)
A default that takes effect on the database side.
class PrimaryKeyConstraint(Constraint)
A table-level PRIMARY KEY constraint.
Defines a single column or composite PRIMARY KEY constraint. For a no-frills primary key, adding primary_key=True to one or more Column definitions is a shorthand equivalent for an unnamed single- or multiple-column PrimaryKeyConstraint.
Construct a composite-capable PRIMARY KEY.
- *columns
- A sequence of column names. All columns named must be defined and present within the parent Table.
- name
- Optional, the in-database name of the key.
- deferrable
- Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
- initially
- Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
class Sequence(DefaultGenerator)
Represents a named database sequence.
Construct a new Sequence.
class Table(SchemaItem,TableClause)
Represent a relational database table.
Construct a Table.
Table objects can be constructed directly. 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
kwargs 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.
- info
- Defaults to {}: A space to store application specific data; this must be a dictionary.
- 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
- Deprecated; this is an oracle-only argument - "schema" should be used in its place.
- quote
- When True, indicates that the Table identifier must be quoted. This flag does not disable quoting; for case-insensitive names, use an all lower case identifier.
- quote_schema
- When True, indicates that the schema identifier must be quoted. This flag does not disable quoting; for case-insensitive names, use an all lower case identifier.
Append a DDL event listener to this Table.
The listener callable will be triggered when this Table is created or dropped, either directly before or after the DDL is issued to the database. The listener may modify the Table, but may not abort the event itself.
Arguments are:
- event
- One of Table.ddl_events; e.g. 'before-create', 'after-create', 'before-drop' or 'after-drop'.
- listener
A callable, invoked with three positional arguments:
- event
- The event currently being handled
- schema_item
- The Table object being created or dropped
- bind
- The Connection bueing used for DDL execution.
Listeners are added to the Table's ddl_listeners attribute.
Issue a CREATE statement for this table.
See also metadata.create_all().
Issue a DROP statement for this table.
See also metadata.drop_all().
Return a copy of this Table associated with a different MetaData.
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.
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.
class UniqueConstraint(Constraint)
A table-level UNIQUE constraint.
Defines a single column or composite UNIQUE constraint. For a no-frills, single column constraint, adding unique=True to the Column definition is a shorthand equivalent for an unnamed, single column UniqueConstraint.
Construct a UNIQUE constraint.
- *columns
- A sequence of column names. All columns named must be defined and present within the parent Table.
- name
- Optional, the in-database name of the key.
- deferrable
- Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
- initially
- Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
