'ForeignKeyConstraint', 'PrimaryKeyConstraint', 'CheckConstraint',
'UniqueConstraint', 'DefaultGenerator', 'Constraint', 'MetaData',
'ThreadLocalMetaData', 'SchemaVisitor', 'PassiveDefault',
- 'DefaulClause', 'FetchedValue', 'ColumnDefault', 'DDL']
+ 'DefaultClause', 'FetchedValue', 'ColumnDefault', 'DDL']
__all__.sort()
class SchemaItem(visitors.Visitable):
class Table(SchemaItem, expression.TableClause):
- """Represent a relational database table."""
+ """Represent a table in a database."""
__metaclass__ = _TableSingleton
ddl_events = ('before-create', 'after-create', 'before-drop', 'after-drop')
def __init__(self, name, metadata, *args, **kwargs):
- """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
+ """
+ Construct a Table.
+
+ :param name: The name of this table as represented in the database.
+
+ This property, along with the *schema*, indicates the *singleton
+ identity* of this table in relation to its parent :class:`MetaData`.
+ Additional calls to :class:`Table` with the same name, metadata,
+ and schema name will return the same :class:`Table` object.
+
+ Names which contain no upper case characters
+ will be treated as case insensitive names, and will not be quoted
+ unless they are a reserved word. Names with any number of upper
+ case characters will be quoted and sent exactly. Note that this
+ behavior applies even for databases which standardize upper
+ case names as case insensitive such as Oracle.
+
+ :param metadata: a :class:`MetaData` object which will contain this
+ table. The metadata is used as a point of association of this table
+ with other tables which are referenced via foreign key. It also
+ may be used to associate this table with a particular
+ :class:`~sqlalchemy.engine.base.Connectable`.
+
+ :param \*args: Additional positional arguments are used primarily
+ to add the list of :class:`Column` objects contained within this table.
+ Similar to the style of a CREATE TABLE statement, other :class:`SchemaItem`
+ constructs may be added here, including :class:`PrimaryKeyConstraint`,
+ and :class:`ForeignKeyConstraint`.
+
+ :param 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
+ :param 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
+ :param 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.
+ :param info: A dictionary which 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.
+ :param mustexist: When ``True``, indicates that this Table must already
+ be present in the given :class:`MetaData`` collection.
- prefixes
+ :param prefixes:
A list of strings to insert after CREATE in the CREATE TABLE
statement. They will be separated by spaces.
- useexisting
- Defaults to False: indicates that if this Table was already
- defined elsewhere in the application, disregard the rest of the
- constructor arguments.
+ :param quote: Force quoting of this table's name on or off, corresponding
+ to ``True`` or ``False``. When left at its default of ``None``,
+ the column identifier will be quoted according to whether the name is
+ case sensitive (identifiers with at least one upper case character are
+ treated as case sensitive), or if it's a reserved word. This flag
+ is only needed to force quoting of a reserved word which is not known
+ by the SQLAlchemy dialect.
- owner
- Deprecated; this is an oracle-only argument - "schema" should
- be used in its place.
+ :param quote_schema: same as 'quote' but applies to the schema identifier.
- quote
- Force quoting of the identifier on or off, based on `True` or
- `False`. Defaults to `None`. This flag is rarely needed,
- as quoting is normally applied
- automatically for known reserved words, as well as for
- "case sensitive" identifiers. An identifier is "case sensitive"
- if it contains non-lowercase letters, otherwise it's
- considered to be "case insensitive".
+ :param 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``.
- quote_schema
- same as 'quote' but applies to the schema identifier.
+ :param useexisting: When ``True``, indicates that if this Table is already
+ present in the given :class:`MetaData`, apply further arguments within
+ the constructor to the existing :class:`Table`. If this flag is not
+ set, an error is raised when the parameters of an existing :class:`Table`
+ are overwritten.
"""
super(Table, self).__init__(name)
return Table(self.name, metadata, schema=schema, *args)
class Column(SchemaItem, expression.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``.
- """
+ """Represents a column in a database table."""
def __init__(self, *args, **kwargs):
- """Construct a new ``Column`` object.
-
- Arguments are:
+ """
+ Construct a new ``Column`` object.
+
+ :param name: The name of this column as represented in the database.
+ This argument may be the first positional argument, or specified
+ via keyword.
+
+ Names which contain no upper case characters
+ will be treated as case insensitive names, and will not be quoted
+ unless they are a reserved word. Names with any number of upper
+ case characters will be quoted and sent exactly. Note that this
+ behavior applies even for databases which standardize upper
+ case names as case insensitive such as Oracle.
+
+ The name field may be omitted at construction time and applied
+ later, at any time before the Column is associated with a
+ :class:`Table`. This is to support convenient
+ usage within the :mod:`~sqlalchemy.ext.declarative` extension.
+
+ :param type\_: The column's type, indicated using an instance which
+ subclasses :class:`~sqlalchemy.types.AbstractType`. If no arguments
+ are required for the type, the class of the type can be sent
+ as well, e.g.::
+
+ # use a type with arguments
+ Column('data', String(50))
+
+ # use no arguments
+ Column('level', Integer)
+
+ The ``type`` argument may be the second positional argument
+ or specified by keyword.
- 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
+ If this column also contains a :class:`ForeignKey`,
+ the type argument may be left as ``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.
-
- server_default
- Defaults to None: A FetchedValue instance, str, Unicode or
- sqlalchemy.text() string representing the DDL DEFAULT value for
- the column.
-
- String types will be emitted as-is, surrounded by single quotes::
+ :param \*args: Additional positional arguments include various
+ :class:`SchemaItem` derived constructs which will be applied
+ as options to the column. These include instances of
+ :class:`Constraint`, :class:`ForeignKey`, :class:`ColumnDefault`,
+ and :class:`Sequence`. In some cases an equivalent keyword
+ argument is available such as ``server_default``, ``default``
+ and ``unique``.
+
+ :param autoincrement: This flag may be set to ``False`` to disable
+ SQLAlchemy indicating at the DDL level that an integer primary
+ key column should have autoincrementing behavior. This
+ is an oft misunderstood flag and has no effect whatsoever unless
+ all of the following conditions are met:
+
+ * The column is of the :class:`~sqlalchemy.types.Integer` datatype.
+ * The column has the ``primary_key`` flag set, or is otherwise
+ a member of a :class:`PrimaryKeyConstraint` on this table.
+ * a CREATE TABLE statement is being issued via :meth:`create()`
+ or :meth:`create_all()`. The flag has no relevance at any
+ other time.
+ * The database supports autoincrementing behavior, such as
+ Postgres or MySQL, and this behavior can be disabled (which does
+ not include SQLite).
+
+ :param default: A scalar, Python callable, or :class:`~sqlalchemy.sql.expression.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. Contrast this argument
+ to ``server_default`` which creates a default generator on the
+ database side.
+
+ :param key: An optional string identifier which will identify this ``Column``
+ object on the :class:`Table`. When a key is provided, this is the
+ only identifier referencing the ``Column`` within the application,
+ including ORM attribute mapping; the ``name`` field is used only
+ when rendering SQL.
+
+ :param index: When ``True``, indicates that the column is indexed.
+ This is a shortcut for using a :class:`Index` construct on the table.
+ To specify indexes with explicit names or indexes that contain multiple
+ columns, use the :class:`Index` construct instead.
+
+ :param info: A dictionary which defaults to ``{}``. A space to store application
+ specific data. This must be a dictionary.
+
+ :param nullable: If set to the default of ``True``, indicates the column
+ will be rendered as allowing NULL, else it's rendered as NOT NULL.
+ This parameter is only used when issuing CREATE TABLE statements.
+
+ :param primary_key: If ``True``, marks this column as a primary key
+ column. Multiple columns can have this flag set to specify composite
+ primary keys. As an alternative, the primary key of a :class:`Table` can
+ be specified via an explicit :class:`PrimaryKeyConstraint` object.
+
+ :param server_default: A :class:`FetchedValue` instance, str, Unicode or
+ :func:`~sqlalchemy.sql.expression.text` construct representing
+ the DDL DEFAULT value for the column.
+
+ String types will be emitted as-is, surrounded by single quotes::
Column('x', Text, server_default="val")
x TEXT DEFAULT 'val'
- A sqlalchemy.text() expression will be rendered as-is, without
- quotes::
+ A :func:`~sqlalchemy.sql.expression.text` expression will be
+ rendered as-is, without quotes::
Column('y', DateTime, server_default=text('NOW()'))0
y DATETIME DEFAULT NOW()
- Strings and text() will be converted into a ``DefaultClause``
- object upon initialization.
-
- 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.
+ Strings and text() will be converted into a :class:`DefaultClause`
+ object upon initialization.
- info
- Defaults to {}: A space to store application specific data; this
- must be a dictionary.
+ :param quote: Force quoting of this column's name on or off, corresponding
+ to ``True`` or ``False``. When left at its default of ``None``,
+ the column identifier will be quoted according to whether the name is
+ case sensitive (identifiers with at least one upper case character are
+ treated as case sensitive), or if it's a reserved word. This flag
+ is only needed to force quoting of a reserved word which is not known
+ by the SQLAlchemy dialect.
- 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
+ :param unique: When ``True``, indicates that this column contains a unique
+ constraint, or if ``index`` is ``True`` as well, indicates that the
+ :class:`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 ``DefaultClause``), 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
- Force quoting of the identifier on or off, based on `True` or
- `False`. Defaults to `None`. This flag is rarely needed,
- as quoting is normally applied
- automatically for known reserved words, as well as for
- "case sensitive" identifiers. An identifier is "case sensitive"
- if it contains non-lowercase letters, otherwise it's
- considered to be "case insensitive".
+ use the :class:`UniqueConstraint` or :class:`Index` constructs explicitly.
+
"""
name = kwargs.pop('name', None)
in this ``MetaData`` no longer exists in the database.
bind
- A ``Connectable`` used to access the database; if None, uses the
+ A :class:`~sqlalchemy.engine.base.Connectable` used to access the database; if None, uses the
existing bind on this ``MetaData``, if any.
schema
present in the target database.
bind
- A ``Connectable`` used to access the database; if None, uses the
+ A :class:`~sqlalchemy.engine.base.Connectable` used to access the database; if None, uses the
existing bind on this ``MetaData``, if any.
tables
the target database.
bind
- A ``Connectable`` used to access the database; if None, uses
+ A :class:`~sqlalchemy.engine.base.Connectable` used to access the database; if None, uses
the existing bind on this ``MetaData``, if any.
tables
available for use in string substitutions on the DDL statement.
bind
- Optional. A ``Connectable``, used by default when ``execute()``
+ Optional. A :class:`~sqlalchemy.engine.base.Connectable`, used by default when ``execute()``
is invoked without a bind argument.
+
"""
if not isinstance(statement, basestring):
"""Execute this DDL immediately.
Executes the DDL statement in isolation using the supplied
- ``Connectable`` or ``Connectable`` assigned to the ``.bind`` property,
+ :class:`~sqlalchemy.engine.base.Connectable` or :class:`~sqlalchemy.engine.base.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.
+ valid :class:`~sqlalchemy.engine.base.Connectable` must be present in the ``.bind`` property.
schema_item
Optional, defaults to None. Will be passed to the ``on`` callable