Metadata
plateforme.core.database.schema
This module provides utilities for managing database schema definitions within the Plateforme framework using SQLAlchemy features.
NAMING_CONVENTION
module-attribute
NAMING_CONVENTION = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
The default naming convention for the database schema.
MetaData
MetaData(
schema: str | None = None,
schema_factory: Callable[[], str | None] | None = None,
info: dict[Any, Any] | None = None,
)
Bases: MetaData
A collection of Table
.
A collection of Table
objects and their associated schema constructs. It
overrides the schema attribute to provide a custom implementation factory
for the schema name.
Holds a collection of Table
objects as well as 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 MetaData
class is a thread-safe object for read operations.
Construction of new tables within a single MetaData
object, either
explicitly or via reflection, may not be completely thread-safe.
Initializes the MetaData
object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
schema
|
str | None
|
The default schema name to use for the metadata. |
None
|
schema_factory
|
Callable[[], str | None] | None
|
A callable that returns the schema name to use for the metadata. If provided, it will be called to get the schema name when needed. |
None
|
info
|
dict[Any, Any] | None
|
A dictionary of arbitrary data to be associated with the metadata. |
None
|
Note
See SQLAlchemy's documentation for more information on the parameters and their usage.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/schema.py
tables
instance-attribute
A dictionary of :class:_schema.Table
objects keyed to their name or "table key".
The exact key is that determined by the :attr:_schema.Table.key
attribute;
for a table with no :attr:_schema.Table.schema
attribute,
this is the same
as :attr:_schema.Table.name
. For a table with a schema,
it is typically of the
form schemaname.tablename
.
.. seealso::
:attr:`_schema.MetaData.sorted_tables`
sorted_tables
property
Returns a list of :class:_schema.Table
objects sorted in order of
foreign key dependency.
The sorting will place :class:_schema.Table
objects that have dependencies
first, before the dependencies themselves, representing the
order in which they can be created. To get the order in which
the tables would be dropped, use the reversed()
Python built-in.
.. warning::
The :attr:`.MetaData.sorted_tables` attribute cannot by itself
accommodate automatic resolution of dependency cycles between
tables, which are usually caused by mutually dependent foreign key
constraints. When these cycles are detected, the foreign keys
of these tables are omitted from consideration in the sort.
A warning is emitted when this condition occurs, which will be an
exception raise in a future release. Tables which are not part
of the cycle will still be returned in dependency order.
To resolve these cycles, the
:paramref:`_schema.ForeignKeyConstraint.use_alter` parameter may be
applied to those constraints which create a cycle. Alternatively,
the :func:`_schema.sort_tables_and_constraints` function will
automatically return foreign key constraints in a separate
collection when cycles are detected so that they may be applied
to a schema separately.
.. versionchanged:: 1.3.17 - a warning is emitted when
:attr:`.MetaData.sorted_tables` cannot perform a proper sort
due to cyclical dependencies. This will be an exception in a
future release. Additionally, the sort will continue to return
other tables not involved in the cycle in dependency order which
was not the case previously.
.. seealso::
:func:`_schema.sort_tables`
:func:`_schema.sort_tables_and_constraints`
:attr:`_schema.MetaData.tables`
:meth:`_reflection.Inspector.get_table_names`
:meth:`_reflection.Inspector.get_sorted_table_and_fkc_names`
clear
Clear all Table objects from this MetaData.
remove
remove(table: Table) -> None
reflect
reflect(
bind: Union[Engine, Connection],
schema: Optional[str] = None,
views: bool = False,
only: Union[
Sequence[str], Callable[[str, MetaData], bool], None
] = None,
extend_existing: bool = False,
autoload_replace: bool = True,
resolve_fks: bool = True,
**dialect_kwargs: Any,
) -> 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.
:param bind:
A :class:.Connection
or :class:.Engine
used to access the
database.
:param schema:
Optional, query and reflect tables from an alternate schema.
If None, the schema associated with this :class:_schema.MetaData
is used, if any.
:param views: If True, also reflect views (materialized and plain).
:param 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.
:param extend_existing: Passed along to each :class:_schema.Table
as
:paramref:_schema.Table.extend_existing
.
:param autoload_replace: Passed along to each :class:_schema.Table
as
:paramref:_schema.Table.autoload_replace
.
:param resolve_fks: if True, reflect :class:_schema.Table
objects linked
to :class:_schema.ForeignKey
objects located in each
:class:_schema.Table
.
For :meth:_schema.MetaData.reflect
,
this has the effect of reflecting
related tables that might otherwise not be in the list of tables
being reflected, for example if the referenced table is in a
different schema or is omitted via the
:paramref:.MetaData.reflect.only
parameter. When False,
:class:_schema.ForeignKey
objects are not followed to the
:class:_schema.Table
in which they link, however if the related table is also part of the
list of tables that would be reflected in any case, the
:class:_schema.ForeignKey
object will still resolve to its related
:class:_schema.Table
after the :meth:_schema.MetaData.reflect
operation is
complete. Defaults to True.
.. versionadded:: 1.3.0
.. seealso::
:paramref:`_schema.Table.resolve_fks`
:param **dialect_kwargs: Additional keyword arguments not mentioned
above are dialect specific, and passed in the form
<dialectname>_<argname>
. See the documentation regarding an
individual dialect at :ref:dialect_toplevel
for detail on
documented arguments.
.. seealso::
:ref:`metadata_reflection_toplevel`
:meth:`_events.DDLEvents.column_reflect` - Event used to customize
the reflected columns. Usually used to generalize the types using
:meth:`_types.TypeEngine.as_generic`
:ref:`metadata_reflection_dbagnostic_types` - describes how to
reflect tables using general types.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 |
|
create_all
create_all(
bind: _CreateDropBind,
tables: Optional[Sequence[Table]] = None,
checkfirst: bool = True,
) -> None
Create all tables stored in this metadata.
Conditional by default, will not attempt to recreate tables already present in the target database.
:param bind:
A :class:.Connection
or :class:.Engine
used to access the
database.
:param tables:
Optional list of Table
objects, which is a subset of the total
tables in the MetaData
(others are ignored).
:param checkfirst: Defaults to True, don't issue CREATEs for tables already present in the target database.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
drop_all
drop_all(
bind: _CreateDropBind,
tables: Optional[Sequence[Table]] = None,
checkfirst: bool = True,
) -> None
Drop all tables stored in this metadata.
Conditional by default, will not attempt to drop tables not present in the target database.
:param bind:
A :class:.Connection
or :class:.Engine
used to access the
database.
:param tables:
Optional list of Table
objects, which is a subset of the
total tables in the MetaData
(others are ignored).
:param checkfirst: Defaults to True, only issue DROPs for tables confirmed to be present in the target database.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
This module provides utilities for managing database schema definitions within the Plateforme framework using SQLAlchemy features.
Column
Column(
__name_pos: Optional[
Union[
str, _TypeEngineArgument[_T], SchemaEventTarget
]
] = None,
__type_pos: Optional[
Union[_TypeEngineArgument[_T], SchemaEventTarget]
] = None,
*args: SchemaEventTarget,
name: Optional[str] = None,
type_: Optional[_TypeEngineArgument[_T]] = None,
autoincrement: _AutoIncrementType = "auto",
default: Optional[Any] = None,
doc: Optional[str] = None,
key: Optional[str] = None,
index: Optional[bool] = None,
unique: Optional[bool] = None,
info: Optional[_InfoType] = None,
nullable: Optional[
Union[bool, Literal[NULL_UNSPECIFIED]]
] = NULL_UNSPECIFIED,
onupdate: Optional[Any] = None,
primary_key: bool = False,
server_default: Optional[_ServerDefaultArgument] = None,
server_onupdate: Optional[FetchedValue] = None,
quote: Optional[bool] = None,
system: bool = False,
comment: Optional[str] = None,
insert_sentinel: bool = False,
_omit_from_statements: bool = False,
_proxies: Optional[Any] = None,
**dialect_kwargs: Any,
)
Bases: DialectKWArgs
, SchemaItem
, ColumnClause[_T]
Represents a column in a database table.
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:_schema.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.TypeEngine
. 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.
If the type
is None
or is omitted, it will first default to
the special type :class:.NullType
. If and when this
:class:_schema.Column
is made to refer to another column using
:class:_schema.ForeignKey
and/or
:class:_schema.ForeignKeyConstraint
, the type
of the remote-referenced column will be copied to this column as
well, at the moment that the foreign key is resolved against that
remote :class:_schema.Column
object.
: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:_schema.ForeignKey
,
:class:.ColumnDefault
, :class:.Sequence
, :class:.Computed
:class:.Identity
. In some cases an
equivalent keyword argument is available such as server_default
,
default
and unique
.
:param autoincrement: Set up "auto increment" semantics for an
integer primary key column with no foreign key dependencies
(see later in this docstring for a more specific definition).
This may influence the :term:DDL
that will be emitted for
this column during a table create, as well as how the column
will be considered when INSERT statements are compiled and
executed.
The default value is the string "auto"
,
which indicates that a single-column (i.e. non-composite) primary key
that is of an INTEGER type with no other client-side or server-side
default constructs indicated should receive auto increment semantics
automatically. Other values include True
(force this column to
have auto-increment semantics for a :term:composite primary key
as
well), False
(this column should never have auto-increment
semantics), and the string "ignore_fk"
(special-case for foreign
key columns, see below).
The term "auto increment semantics" refers both to the kind of DDL
that will be emitted for the column within a CREATE TABLE statement,
when methods such as :meth:.MetaData.create_all
and
:meth:.Table.create
are invoked, as well as how the column will be
considered when an INSERT statement is compiled and emitted to the
database:
-
DDL rendering (i.e. :meth:
.MetaData.create_all
, :meth:.Table.create
): When used on a :class:.Column
that has no other default-generating construct associated with it (such as a :class:.Sequence
or :class:.Identity
construct), the parameter will imply that database-specific keywords such as PostgreSQLSERIAL
, MySQLAUTO_INCREMENT
, orIDENTITY
on SQL Server should also be rendered. Not every database backend has an "implied" default generator available; for example the Oracle backend always needs an explicit construct such as :class:.Identity
to be included with a :class:.Column
in order for the DDL rendered to include auto-generating constructs to also be produced in the database. -
INSERT semantics (i.e. when a :func:
_sql.insert
construct is compiled into a SQL string and is then executed on a database using :meth:_engine.Connection.execute
or equivalent): A single-row INSERT statement will be known to produce a new integer primary key value automatically for this column, which will be accessible after the statement is invoked via the :attr:.CursorResult.inserted_primary_key
attribute upon the :class:_result.Result
object. This also applies towards use of the ORM when ORM-mapped objects are persisted to the database, indicating that a new integer primary key will be available to become part of the :term:identity key
for that object. This behavior takes place regardless of what DDL constructs are associated with the :class:_schema.Column
and is independent of the "DDL Rendering" behavior discussed in the previous note above.
The parameter may be set to True
to indicate that a column which
is part of a composite (i.e. multi-column) primary key should
have autoincrement semantics, though note that only one column
within a primary key may have this setting. It can also
be set to True
to indicate autoincrement semantics on a
column that has a client-side or server-side default configured,
however note that not all dialects can accommodate all styles
of default as an "autoincrement". It can also be
set to False
on a single-column primary key that has a
datatype of INTEGER in order to disable auto increment semantics
for that column.
The setting only has an effect for columns which are:
-
Integer derived (i.e. INT, SMALLINT, BIGINT).
-
Part of the primary key
-
Not referring to another column via :class:
_schema.ForeignKey
, unless the value is specified as'ignore_fk'
::# turn on autoincrement for this column despite # the ForeignKey() Column('id', ForeignKey('other.id'), primary_key=True, autoincrement='ignore_fk')
It is typically not desirable to have "autoincrement" enabled on a column that refers to another via foreign key, as such a column is required to refer to a value that originates from elsewhere.
The setting has these effects on columns that meet the above criteria:
-
DDL issued for the column, if the column does not already include a default generating construct supported by the backend such as :class:
.Identity
, will include database-specific keywords intended to signify this column as an "autoincrement" column for specific backends. Behavior for primary SQLAlchemy dialects includes:- AUTO INCREMENT on MySQL and MariaDB
- SERIAL on PostgreSQL
- IDENTITY on MS-SQL - this occurs even without the
:class:
.Identity
construct as the :paramref:.Column.autoincrement
parameter pre-dates this construct. - SQLite - SQLite integer primary key columns are implicitly
"auto incrementing" and no additional keywords are rendered;
to render the special SQLite keyword
AUTOINCREMENT
is not included as this is unnecessary and not recommended by the database vendor. See the section :ref:sqlite_autoincrement
for more background. - Oracle - The Oracle dialect has no default "autoincrement"
feature available at this time, instead the :class:
.Identity
construct is recommended to achieve this (the :class:.Sequence
construct may also be used). - Third-party dialects - consult those dialects' documentation for details on their specific behaviors.
-
When a single-row :func:
_sql.insert
construct is compiled and executed, which does not set the :meth:_sql.Insert.inline
modifier, newly generated primary key values for this column will be automatically retrieved upon statement execution using a method specific to the database driver in use:- MySQL, SQLite - calling upon
cursor.lastrowid()
(seehttps://www.python.org/dev/peps/pep-0249/#lastrowid <https://www.python.org/dev/peps/pep-0249/#lastrowid>
_) - PostgreSQL, SQL Server, Oracle - use RETURNING or an equivalent construct when rendering an INSERT statement, and then retrieving the newly generated primary key values after execution
- PostgreSQL, Oracle for :class:
_schema.Table
objects that set :paramref:_schema.Table.implicit_returning
to False - for a :class:.Sequence
only, the :class:.Sequence
is invoked explicitly before the INSERT statement takes place so that the newly generated primary key value is available to the client - SQL Server for :class:
_schema.Table
objects that set :paramref:_schema.Table.implicit_returning
to False - theSELECT scope_identity()
construct is used after the INSERT statement is invoked to retrieve the newly generated primary key value. - Third-party dialects - consult those dialects' documentation for details on their specific behaviors.
- MySQL, SQLite - calling upon
-
For multiple-row :func:
_sql.insert
constructs invoked with a list of parameters (i.e. "executemany" semantics), primary-key retrieving behaviors are generally disabled, however there may be special APIs that may be used to retrieve lists of new primary key values for an "executemany", such as the psycopg2 "fast insertmany" feature. Such features are very new and may not yet be well covered in documentation.
:param default: A scalar, Python callable, or
:class:_expression.ColumnElement
expression representing the
default value for this column, which will be invoked upon insert
if this column is otherwise not specified in the VALUES clause of
the insert. This is a shortcut to using :class:.ColumnDefault
as
a positional argument; see that class for full detail on the
structure of the argument.
Contrast this argument to
:paramref:`_schema.Column.server_default`
which creates a default generator on the database side.
.. seealso::
:ref:`metadata_defaults_toplevel`
:param doc: optional String that can be used by the ORM or similar
to document attributes on the Python side. This attribute does
not render SQL comments; use the
:paramref:_schema.Column.comment
parameter for this purpose.
:param key: An optional string identifier which will identify this
Column
object on the :class:_schema.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 a :class:_schema.Index
construct will be automatically generated for this
:class:_schema.Column
, which will result in a "CREATE INDEX"
statement being emitted for the :class:_schema.Table
when the DDL
create operation is invoked.
Using this flag is equivalent to making use of the
:class:`_schema.Index` construct explicitly at the level of the
:class:`_schema.Table` construct itself::
Table(
"some_table",
metadata,
Column("x", Integer),
Index("ix_some_table_x", "x")
)
To add the :paramref:`_schema.Index.unique` flag to the
:class:`_schema.Index`, set both the
:paramref:`_schema.Column.unique` and
:paramref:`_schema.Column.index` flags to True simultaneously,
which will have the effect of rendering the "CREATE UNIQUE INDEX"
DDL instruction instead of "CREATE INDEX".
The name of the index is generated using the
:ref:`default naming convention <constraint_default_naming_convention>`
which for the :class:`_schema.Index` construct is of the form
``ix_<tablename>_<columnname>``.
As this flag is intended only as a convenience for the common case
of adding a single-column, default configured index to a table
definition, explicit use of the :class:`_schema.Index` construct
should be preferred for most use cases, including composite indexes
that encompass more than one column, indexes with SQL expressions
or ordering, backend-specific index configuration options, and
indexes that use a specific name.
.. note:: the :attr:`_schema.Column.index` attribute on
:class:`_schema.Column`
**does not indicate** if this column is indexed or not, only
if this flag was explicitly set here. To view indexes on
a column, view the :attr:`_schema.Table.indexes` collection
or use :meth:`_reflection.Inspector.get_indexes`.
.. seealso::
:ref:`schema_indexes`
:ref:`constraint_naming_conventions`
:paramref:`_schema.Column.unique`
:param info: Optional data dictionary which will be populated into the
:attr:.SchemaItem.info
attribute of this object.
:param nullable: When set to False
, will cause the "NOT NULL"
phrase to be added when generating DDL for the column. When
True
, will normally generate nothing (in SQL this defaults to
"NULL"), except in some very specific backend-specific edge cases
where "NULL" may render explicitly.
Defaults to True
unless :paramref:_schema.Column.primary_key
is also True
or the column specifies a :class:_sql.Identity
,
in which case it defaults to False
.
This parameter is only used when issuing CREATE TABLE statements.
.. note::
When the column specifies a :class:`_sql.Identity` this
parameter is in general ignored by the DDL compiler. The
PostgreSQL database allows nullable identity column by
setting this parameter to ``True`` explicitly.
:param onupdate: A scalar, Python callable, or
:class:~sqlalchemy.sql.expression.ClauseElement
representing a
default value to be applied to the column within UPDATE
statements, which will be invoked upon update if this column is not
present in the SET clause of the update. This is a shortcut to
using :class:.ColumnDefault
as a positional argument with
for_update=True
.
.. seealso::
:ref:`metadata_defaults` - complete discussion of onupdate
: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:_schema.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 :func:`~sqlalchemy.sql.expression.text` expression will be
rendered as-is, without quotes::
Column('y', DateTime, server_default=text('NOW()'))
y DATETIME DEFAULT NOW()
Strings and text() will be converted into a
:class:`.DefaultClause` object upon initialization.
This parameter can also accept complex combinations of contextually
valid SQLAlchemy expressions or constructs::
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, MetaData, ARRAY, Text
from sqlalchemy.dialects.postgresql import array
engine = create_engine(
'postgresql+psycopg2://scott:tiger@localhost/mydatabase'
)
metadata_obj = MetaData()
tbl = Table(
"foo",
metadata_obj,
Column("bar",
ARRAY(Text),
server_default=array(["biz", "bang", "bash"])
)
)
metadata_obj.create_all(engine)
The above results in a table created with the following SQL::
CREATE TABLE foo (
bar TEXT[] DEFAULT ARRAY['biz', 'bang', 'bash']
)
Use :class:`.FetchedValue` to indicate that an already-existing
column will generate a default value on the database side which
will be available to SQLAlchemy for post-fetch after inserts. This
construct does not specify any DDL and the implementation is left
to the database, such as via a trigger.
.. seealso::
:ref:`server_defaults` - complete discussion of server side
defaults
:param server_onupdate: A :class:.FetchedValue
instance
representing a database-side default generation function,
such as a trigger. This
indicates to SQLAlchemy that a newly generated value will be
available after updates. This construct does not actually
implement any kind of generation function within the database,
which instead must be specified separately.
.. warning:: This directive **does not** currently produce MySQL's
"ON UPDATE CURRENT_TIMESTAMP()" clause. See
:ref:`mysql_timestamp_onupdate` for background on how to
produce this clause.
.. seealso::
:ref:`triggered_columns`
: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.
:param unique: When True
, and the :paramref:_schema.Column.index
parameter is left at its default value of False
,
indicates that a :class:_schema.UniqueConstraint
construct will be automatically generated for this
:class:_schema.Column
,
which will result in a "UNIQUE CONSTRAINT" clause referring
to this column being included
in the CREATE TABLE
statement emitted, when the DDL create
operation for the :class:_schema.Table
object is invoked.
When this flag is ``True`` while the
:paramref:`_schema.Column.index` parameter is simultaneously
set to ``True``, the effect instead is that a
:class:`_schema.Index` construct which includes the
:paramref:`_schema.Index.unique` parameter set to ``True``
is generated. See the documentation for
:paramref:`_schema.Column.index` for additional detail.
Using this flag is equivalent to making use of the
:class:`_schema.UniqueConstraint` construct explicitly at the
level of the :class:`_schema.Table` construct itself::
Table(
"some_table",
metadata,
Column("x", Integer),
UniqueConstraint("x")
)
The :paramref:`_schema.UniqueConstraint.name` parameter
of the unique constraint object is left at its default value
of ``None``; in the absence of a :ref:`naming convention <constraint_naming_conventions>`
for the enclosing :class:`_schema.MetaData`, the UNIQUE CONSTRAINT
construct will be emitted as unnamed, which typically invokes
a database-specific naming convention to take place.
As this flag is intended only as a convenience for the common case
of adding a single-column, default configured unique constraint to a table
definition, explicit use of the :class:`_schema.UniqueConstraint` construct
should be preferred for most use cases, including composite constraints
that encompass more than one column, backend-specific index configuration options, and
constraints that use a specific name.
.. note:: the :attr:`_schema.Column.unique` attribute on
:class:`_schema.Column`
**does not indicate** if this column has a unique constraint or
not, only if this flag was explicitly set here. To view
indexes and unique constraints that may involve this column,
view the
:attr:`_schema.Table.indexes` and/or
:attr:`_schema.Table.constraints` collections or use
:meth:`_reflection.Inspector.get_indexes` and/or
:meth:`_reflection.Inspector.get_unique_constraints`
.. seealso::
:ref:`schema_unique_constraint`
:ref:`constraint_naming_conventions`
:paramref:`_schema.Column.index`
:param system: When True
, indicates this is a "system" column,
that is a column which is automatically made available by the
database, and should not be included in the columns list for a
CREATE TABLE
statement.
For more elaborate scenarios where columns should be
conditionally rendered differently on different backends,
consider custom compilation rules for :class:`.CreateColumn`.
:param comment: Optional string that will render an SQL comment on table creation.
.. versionadded:: 1.2 Added the
:paramref:`_schema.Column.comment`
parameter to :class:`_schema.Column`.
:param insert_sentinel: Marks this :class:_schema.Column
as an
:term:insert sentinel
used for optimizing the performance of the
:term:insertmanyvalues
feature for tables that don't
otherwise have qualifying primary key configurations.
.. versionadded:: 2.0.10
.. seealso::
:func:`_schema.insert_sentinel` - all in one helper for declaring
sentinel columns
:ref:`engine_insertmanyvalues`
:ref:`engine_insertmanyvalues_sentinel_columns`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 |
|
timetuple
class-attribute
instance-attribute
Hack, allows datetime objects to be compared on the LHS.
expression
property
expression: ColumnElement[Any]
Return a column expression.
Part of the inspection interface; returns self.
index
instance-attribute
The value of the :paramref:_schema.Column.index
parameter.
Does not indicate if this :class:_schema.Column
is actually indexed
or not; use :attr:_schema.Table.indexes
.
.. seealso::
:attr:`_schema.Table.indexes`
unique
instance-attribute
The value of the :paramref:_schema.Column.unique
parameter.
Does not indicate if this :class:_schema.Column
is actually subject to
a unique constraint or not; use :attr:_schema.Table.indexes
and
:attr:_schema.Table.constraints
.
.. seealso::
:attr:`_schema.Table.indexes`
:attr:`_schema.Table.constraints`.
foreign_keys
instance-attribute
foreign_keys: Set[ForeignKey]
A collection of all :class:_schema.ForeignKey
marker objects
associated with this :class:_schema.Column
.
Each object is a member of a :class:_schema.Table
-wide
:class:_schema.ForeignKeyConstraint
.
.. seealso::
:attr:`_schema.Table.foreign_keys`
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
proxy_set
proxy_set() -> FrozenSet[ColumnElement[Any]]
set of all columns we are proxying
as of 2.0 this is explicitly deannotated columns. previously it was effectively deannotated columns but wasn't enforced. annotated columns should basically not go into sets if at all possible because their hashing behavior is very non-performant.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
compare
compare(other: ClauseElement, **kw: Any) -> bool
Compare this :class:_expression.ClauseElement
to
the given :class:_expression.ClauseElement
.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare()
methods and
may be used to modify the criteria for comparison
(see :class:_expression.ColumnElement
).
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
label
Produce a column label, i.e. <columnname> AS <name>
.
This is a shortcut to the :func:_expression.label
function.
If 'name' is None
, an anonymous label name will be generated.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
shares_lineage
shares_lineage(othercolumn: ColumnElement[Any]) -> bool
Return True if the given :class:_expression.ColumnElement
has a common ancestor to this :class:_expression.ColumnElement
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
cast
cast(type_: _TypeEngineArgument[_OPT]) -> Cast[_OPT]
Produce a type cast, i.e. CAST(<expression> AS <type>)
.
This is a shortcut to the :func:_expression.cast
function.
.. seealso::
:ref:`tutorial_casts`
:func:`_expression.cast`
:func:`_expression.type_coerce`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
argument_for
classmethod
Add a new kind of dialect-specific keyword argument for this class.
E.g.::
Index.argument_for("mydialect", "length", None)
some_index = Index('a', 'b', mydialect_length=5)
The :meth:.DialectKWArgs.argument_for
method is a per-argument
way adding extra arguments to the
:attr:.DefaultDialect.construct_arguments
dictionary. This
dictionary provides a list of argument names accepted by various
schema-level constructs on behalf of a dialect.
New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.
:param dialect_name: name of a dialect. The dialect must be
locatable, else a :class:.NoSuchModuleError
is raised. The
dialect must also include an existing
:attr:.DefaultDialect.construct_arguments
collection, indicating
that it participates in the keyword-argument validation and default
system, else :class:.ArgumentError
is raised. If the dialect does
not include this collection, then any keyword argument can be
specified on behalf of this dialect already. All dialects packaged
within SQLAlchemy include this collection, however for third party
dialects, support may vary.
:param argument_name: name of the parameter.
:param default: default value of the parameter.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
dialect_kwargs
A collection of keyword arguments specified as dialect-specific options to this construct.
The arguments are present here in their original <dialect>_<kwarg>
format. Only arguments that were actually passed are included;
unlike the :attr:.DialectKWArgs.dialect_options
collection, which
contains all options known by this dialect including defaults.
The collection is also writable; keys are accepted of the
form <dialect>_<kwarg>
where the value will be assembled
into the list of options.
.. seealso::
:attr:`.DialectKWArgs.dialect_options` - nested dictionary form
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
dialect_options
A collection of keyword arguments specified as dialect-specific options to this construct.
This is a two-level nested registry, keyed to <dialect_name>
and <argument_name>
. For example, the postgresql_where
argument would be locatable as::
arg = my_object.dialect_options['postgresql']['where']
.. versionadded:: 0.9.2
.. seealso::
:attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
references
Return True if this Column references the given column via foreign key.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
ForeignKey
ForeignKey(
column: _DDLColumnArgument,
_constraint: Optional[ForeignKeyConstraint] = None,
use_alter: bool = False,
name: _ConstraintNameArgument = None,
onupdate: Optional[str] = None,
ondelete: Optional[str] = None,
deferrable: Optional[bool] = None,
initially: Optional[str] = None,
link_to_name: bool = False,
match: Optional[str] = None,
info: Optional[_InfoType] = None,
comment: Optional[str] = None,
_unresolvable: bool = False,
**dialect_kw: Any,
)
Bases: DialectKWArgs
, SchemaItem
Defines a dependency between two columns.
ForeignKey
is specified as an argument to a :class:_schema.Column
object,
e.g.::
t = Table("remote_table", metadata,
Column("remote_id", ForeignKey("main_table.id"))
)
Note that ForeignKey
is only a marker object that defines
a dependency between two columns. The actual constraint
is in all cases represented by the :class:_schema.ForeignKeyConstraint
object. This object will be generated automatically when
a ForeignKey
is associated with a :class:_schema.Column
which
in turn is associated with a :class:_schema.Table
. Conversely,
when :class:_schema.ForeignKeyConstraint
is applied to a
:class:_schema.Table
,
ForeignKey
markers are automatically generated to be
present on each associated :class:_schema.Column
, which are also
associated with the constraint object.
Note that you cannot define a "composite" foreign key constraint,
that is a constraint between a grouping of multiple parent/child
columns, using ForeignKey
objects. To define this grouping,
the :class:_schema.ForeignKeyConstraint
object must be used, and applied
to the :class:_schema.Table
. The associated ForeignKey
objects
are created automatically.
The ForeignKey
objects associated with an individual
:class:_schema.Column
object are available in the foreign_keys
collection
of that column.
Further examples of foreign key configuration are in
:ref:metadata_foreignkeys
.
Construct a column-level FOREIGN KEY.
The :class:_schema.ForeignKey
object when constructed generates a
:class:_schema.ForeignKeyConstraint
which is associated with the parent
:class:_schema.Table
object's collection of constraints.
:param column: A single target column for the key relationship. A
:class:_schema.Column
object or a column name as a string:
tablename.columnkey
or schema.tablename.columnkey
.
columnkey
is the key
which has been assigned to the column
(defaults to the column name itself), unless link_to_name
is
True
in which case the rendered name of the column is used.
:param name: Optional string. An in-database name for the key if
constraint
is not provided.
:param onupdate: Optional string. If set, emit ON UPDATE
:param ondelete: Optional string. If set, emit ON DELETE
:param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
:param initially: Optional string. If set, emit INITIALLY
:param link_to_name: if True, the string name given in column
is
the rendered name of the referenced column, not its locally
assigned key
.
:param use_alter: passed to the underlying
:class:_schema.ForeignKeyConstraint
to indicate the constraint should
be generated/dropped externally from the CREATE TABLE/ DROP TABLE
statement. See :paramref:_schema.ForeignKeyConstraint.use_alter
for further description.
.. seealso::
:paramref:`_schema.ForeignKeyConstraint.use_alter`
:ref:`use_alter`
:param match: Optional string. If set, emit MATCH
:param info: Optional data dictionary which will be populated into the
:attr:.SchemaItem.info
attribute of this object.
:param comment: Optional string that will render an SQL comment on foreign key constraint creation.
.. versionadded:: 2.0
:param **dialect_kw: Additional keyword arguments are dialect
specific, and passed in the form <dialectname>_<argname>
. The
arguments are ultimately handled by a corresponding
:class:_schema.ForeignKeyConstraint
.
See the documentation regarding
an individual dialect at :ref:dialect_toplevel
for detail on
documented arguments.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 |
|
argument_for
classmethod
Add a new kind of dialect-specific keyword argument for this class.
E.g.::
Index.argument_for("mydialect", "length", None)
some_index = Index('a', 'b', mydialect_length=5)
The :meth:.DialectKWArgs.argument_for
method is a per-argument
way adding extra arguments to the
:attr:.DefaultDialect.construct_arguments
dictionary. This
dictionary provides a list of argument names accepted by various
schema-level constructs on behalf of a dialect.
New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.
:param dialect_name: name of a dialect. The dialect must be
locatable, else a :class:.NoSuchModuleError
is raised. The
dialect must also include an existing
:attr:.DefaultDialect.construct_arguments
collection, indicating
that it participates in the keyword-argument validation and default
system, else :class:.ArgumentError
is raised. If the dialect does
not include this collection, then any keyword argument can be
specified on behalf of this dialect already. All dialects packaged
within SQLAlchemy include this collection, however for third party
dialects, support may vary.
:param argument_name: name of the parameter.
:param default: default value of the parameter.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
dialect_kwargs
A collection of keyword arguments specified as dialect-specific options to this construct.
The arguments are present here in their original <dialect>_<kwarg>
format. Only arguments that were actually passed are included;
unlike the :attr:.DialectKWArgs.dialect_options
collection, which
contains all options known by this dialect including defaults.
The collection is also writable; keys are accepted of the
form <dialect>_<kwarg>
where the value will be assembled
into the list of options.
.. seealso::
:attr:`.DialectKWArgs.dialect_options` - nested dictionary form
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
dialect_options
A collection of keyword arguments specified as dialect-specific options to this construct.
This is a two-level nested registry, keyed to <dialect_name>
and <argument_name>
. For example, the postgresql_where
argument would be locatable as::
arg = my_object.dialect_options['postgresql']['where']
.. versionadded:: 0.9.2
.. seealso::
:attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
references
Return True if the given :class:_schema.Table
is referenced by this
:class:_schema.ForeignKey
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
get_referent
get_referent(table: FromClause) -> Optional[Column[Any]]
Return the :class:_schema.Column
in the given
:class:_schema.Table
(or any :class:.FromClause
)
referenced by this :class:_schema.ForeignKey
.
Returns None if this :class:_schema.ForeignKey
does not reference the given
:class:_schema.Table
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
column
Return the target :class:_schema.Column
referenced by this
:class:_schema.ForeignKey
.
If no target column has been established, an exception is raised.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
Index
Index(
name: Optional[str],
*expressions: _DDLColumnArgument,
unique: bool = False,
quote: Optional[bool] = None,
info: Optional[_InfoType] = None,
_table: Optional[Table] = None,
_column_flag: bool = False,
**dialect_kw: Any,
)
Bases: DialectKWArgs
, ColumnCollectionMixin
, HasConditionalDDL
, SchemaItem
A table-level INDEX.
Defines a composite (one or more column) INDEX.
E.g.::
sometable = Table("sometable", metadata,
Column("name", String(50)),
Column("address", String(100))
)
Index("some_index", sometable.c.name)
For a no-frills, single column index, adding
:class:_schema.Column
also supports index=True
::
sometable = Table("sometable", metadata,
Column("name", String(50), index=True)
)
For a composite index, multiple columns can be specified::
Index("some_index", sometable.c.name, sometable.c.address)
Functional indexes are supported as well, typically by using the
:data:.func
construct in conjunction with table-bound
:class:_schema.Column
objects::
Index("some_index", func.lower(sometable.c.name))
An :class:.Index
can also be manually associated with a
:class:_schema.Table
,
either through inline declaration or using
:meth:_schema.Table.append_constraint
. When this approach is used,
the names
of the indexed columns can be specified as strings::
Table("sometable", metadata,
Column("name", String(50)),
Column("address", String(100)),
Index("some_index", "name", "address")
)
To support functional or expression-based indexes in this form, the
:func:_expression.text
construct may be used::
from sqlalchemy import text
Table("sometable", metadata,
Column("name", String(50)),
Column("address", String(100)),
Index("some_index", text("lower(name)"))
)
.. seealso::
:ref:`schema_indexes` - General information on :class:`.Index`.
:ref:`postgresql_indexes` - PostgreSQL-specific options available for
the :class:`.Index` construct.
:ref:`mysql_indexes` - MySQL-specific options available for the
:class:`.Index` construct.
:ref:`mssql_indexes` - MSSQL-specific options available for the
:class:`.Index` construct.
Construct an index object.
:param name: The name of the index
:param *expressions:
Column expressions to include in the index. The expressions
are normally instances of :class:_schema.Column
, but may also
be arbitrary SQL expressions which ultimately refer to a
:class:_schema.Column
.
:param unique=False: Keyword only argument; if True, create a unique index.
:param quote=None:
Keyword only argument; whether to apply quoting to the name of
the index. Works in the same manner as that of
:paramref:_schema.Column.quote
.
:param info=None: Optional data dictionary which will be populated
into the :attr:.SchemaItem.info
attribute of this object.
:param **dialect_kw: Additional keyword arguments not mentioned above
are dialect specific, and passed in the form
<dialectname>_<argname>
. See the documentation regarding an
individual dialect at :ref:dialect_toplevel
for detail on
documented arguments.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 |
|
ddl_if
ddl_if(
dialect: Optional[str] = None,
callable_: Optional[DDLIfCallable] = None,
state: Optional[Any] = None,
) -> Self
apply a conditional DDL rule to this schema item.
These rules work in a similar manner to the
:meth:.ExecutableDDLElement.execute_if
callable, with the added
feature that the criteria may be checked within the DDL compilation
phase for a construct such as :class:.CreateTable
.
:meth:.HasConditionalDDL.ddl_if
currently applies towards the
:class:.Index
construct as well as all :class:.Constraint
constructs.
:param dialect: string name of a dialect, or a tuple of string names to indicate multiple dialect types.
:param callable_: a callable that is constructed using the same form
as that described in
:paramref:.ExecutableDDLElement.execute_if.callable_
.
:param state: any arbitrary object that will be passed to the callable, if present.
.. versionadded:: 2.0
.. seealso::
:ref:`schema_ddl_ddl_if` - background and usage examples
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
argument_for
classmethod
Add a new kind of dialect-specific keyword argument for this class.
E.g.::
Index.argument_for("mydialect", "length", None)
some_index = Index('a', 'b', mydialect_length=5)
The :meth:.DialectKWArgs.argument_for
method is a per-argument
way adding extra arguments to the
:attr:.DefaultDialect.construct_arguments
dictionary. This
dictionary provides a list of argument names accepted by various
schema-level constructs on behalf of a dialect.
New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.
:param dialect_name: name of a dialect. The dialect must be
locatable, else a :class:.NoSuchModuleError
is raised. The
dialect must also include an existing
:attr:.DefaultDialect.construct_arguments
collection, indicating
that it participates in the keyword-argument validation and default
system, else :class:.ArgumentError
is raised. If the dialect does
not include this collection, then any keyword argument can be
specified on behalf of this dialect already. All dialects packaged
within SQLAlchemy include this collection, however for third party
dialects, support may vary.
:param argument_name: name of the parameter.
:param default: default value of the parameter.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
dialect_kwargs
A collection of keyword arguments specified as dialect-specific options to this construct.
The arguments are present here in their original <dialect>_<kwarg>
format. Only arguments that were actually passed are included;
unlike the :attr:.DialectKWArgs.dialect_options
collection, which
contains all options known by this dialect including defaults.
The collection is also writable; keys are accepted of the
form <dialect>_<kwarg>
where the value will be assembled
into the list of options.
.. seealso::
:attr:`.DialectKWArgs.dialect_options` - nested dictionary form
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
dialect_options
A collection of keyword arguments specified as dialect-specific options to this construct.
This is a two-level nested registry, keyed to <dialect_name>
and <argument_name>
. For example, the postgresql_where
argument would be locatable as::
arg = my_object.dialect_options['postgresql']['where']
.. versionadded:: 0.9.2
.. seealso::
:attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
create
create(
bind: _CreateDropBind, checkfirst: bool = False
) -> None
Issue a CREATE
statement for this
:class:.Index
, using the given
:class:.Connection
or :class:`.Engine`` for connectivity.
.. seealso::
:meth:`_schema.MetaData.create_all`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
drop
drop(
bind: _CreateDropBind, checkfirst: bool = False
) -> None
Issue a DROP
statement for this
:class:.Index
, using the given
:class:.Connection
or :class:.Engine
for connectivity.
.. seealso::
:meth:`_schema.MetaData.drop_all`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
Table
Table(
name: str,
metadata: MetaData,
*args: SchemaItem,
schema: Optional[
Union[str, Literal[BLANK_SCHEMA]]
] = None,
quote: Optional[bool] = None,
quote_schema: Optional[bool] = None,
autoload_with: Optional[
Union[Engine, Connection]
] = None,
autoload_replace: bool = True,
keep_existing: bool = False,
extend_existing: bool = False,
resolve_fks: bool = True,
include_columns: Optional[Collection[str]] = None,
implicit_returning: bool = True,
comment: Optional[str] = None,
info: Optional[Dict[Any, Any]] = None,
listeners: Optional[
Sequence[Tuple[str, Callable[..., Any]]]
] = None,
prefixes: Optional[Sequence[str]] = None,
_extend_on: Optional[Set[Table]] = None,
_no_init: bool = True,
**kw: Any,
)
Bases: DialectKWArgs
, HasSchemaAttr
, TableClause
, Inspectable['Table']
Represent a table in a database.
e.g.::
mytable = Table(
"mytable", metadata,
Column('mytable_id', Integer, primary_key=True),
Column('value', String(50))
)
The :class:_schema.Table
object constructs a unique instance of itself based
on its name and optional schema name within the given
:class:_schema.MetaData
object. Calling the :class:_schema.Table
constructor with the same name and same :class:_schema.MetaData
argument
a second time will return the same :class:_schema.Table
object - in this way
the :class:_schema.Table
constructor acts as a registry function.
.. seealso::
:ref:`metadata_describing` - Introduction to database metadata
Constructor for :class:_schema.Table
.
:param name: The name of this table as represented in the database.
The table name, along with the value of the ``schema`` parameter,
forms a key which uniquely identifies this :class:`_schema.Table`
within
the owning :class:`_schema.MetaData` collection.
Additional calls to :class:`_schema.Table` with the same name,
metadata,
and schema name will return the same :class:`_schema.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 or contain special characters.
A name with any number of upper case characters is considered
to be case sensitive, and will be sent as quoted.
To enable unconditional quoting for the table name, specify the flag
``quote=True`` to the constructor, or use the :class:`.quoted_name`
construct to specify the name.
:param metadata: a :class:_schema.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:.Connection
or :class:.Engine
.
:param *args: Additional positional arguments are used primarily
to add the list of :class:_schema.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:_schema.ForeignKeyConstraint
.
:param autoload_replace: Defaults to True
; when using
:paramref:_schema.Table.autoload_with
in conjunction with :paramref:_schema.Table.extend_existing
,
indicates
that :class:_schema.Column
objects present in the already-existing
:class:_schema.Table
object should be replaced with columns of the same
name retrieved from the autoload process. When False
, columns
already present under existing names will be omitted from the
reflection process.
Note that this setting does not impact :class:`_schema.Column` objects
specified programmatically within the call to :class:`_schema.Table`
that
also is autoloading; those :class:`_schema.Column` objects will always
replace existing columns of the same name when
:paramref:`_schema.Table.extend_existing` is ``True``.
.. seealso::
:paramref:`_schema.Table.autoload_with`
:paramref:`_schema.Table.extend_existing`
:param autoload_with: An :class:_engine.Engine
or
:class:_engine.Connection
object,
or a :class:_reflection.Inspector
object as returned by
:func:_sa.inspect
against one, with which this :class:_schema.Table
object will be reflected.
When set to a non-None value, the autoload process will take place
for this table against the given engine or connection.
.. seealso::
:ref:`metadata_reflection_toplevel`
:meth:`_events.DDLEvents.column_reflect`
:ref:`metadata_reflection_dbagnostic_types`
:param extend_existing: When True
, indicates that if this
:class:_schema.Table
is already present in the given
:class:_schema.MetaData
,
apply further arguments within the constructor to the existing
:class:_schema.Table
.
If :paramref:`_schema.Table.extend_existing` or
:paramref:`_schema.Table.keep_existing` are not set,
and the given name
of the new :class:`_schema.Table` refers to a :class:`_schema.Table`
that is
already present in the target :class:`_schema.MetaData` collection,
and
this :class:`_schema.Table`
specifies additional columns or other constructs
or flags that modify the table's state, an
error is raised. The purpose of these two mutually-exclusive flags
is to specify what action should be taken when a
:class:`_schema.Table`
is specified that matches an existing :class:`_schema.Table`,
yet specifies
additional constructs.
:paramref:`_schema.Table.extend_existing`
will also work in conjunction
with :paramref:`_schema.Table.autoload_with` to run a new reflection
operation against the database, even if a :class:`_schema.Table`
of the same name is already present in the target
:class:`_schema.MetaData`; newly reflected :class:`_schema.Column`
objects
and other options will be added into the state of the
:class:`_schema.Table`, potentially overwriting existing columns
and options of the same name.
As is always the case with :paramref:`_schema.Table.autoload_with`,
:class:`_schema.Column` objects can be specified in the same
:class:`_schema.Table`
constructor, which will take precedence. Below, the existing
table ``mytable`` will be augmented with :class:`_schema.Column`
objects
both reflected from the database, as well as the given
:class:`_schema.Column`
named "y"::
Table("mytable", metadata,
Column('y', Integer),
extend_existing=True,
autoload_with=engine
)
.. seealso::
:paramref:`_schema.Table.autoload_with`
:paramref:`_schema.Table.autoload_replace`
:paramref:`_schema.Table.keep_existing`
:param implicit_returning: True by default - indicates that RETURNING can be used, typically by the ORM, in order to fetch server-generated values such as primary key values and server side defaults, on those backends which support RETURNING.
In modern SQLAlchemy there is generally no reason to alter this
setting, except for some backend specific cases
(see :ref:`mssql_triggers` in the SQL Server dialect documentation
for one such example).
: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.
:param resolve_fks: Whether or not to reflect :class:_schema.Table
objects
related to this one via :class:_schema.ForeignKey
objects, when
:paramref:_schema.Table.autoload_with
is
specified. Defaults to True. Set to False to disable reflection of
related tables as :class:_schema.ForeignKey
objects are encountered; may be
used either to save on SQL calls or to avoid issues with related tables
that can't be accessed. Note that if a related table is already present
in the :class:_schema.MetaData
collection, or becomes present later,
a
:class:_schema.ForeignKey
object associated with this
:class:_schema.Table
will
resolve to that table normally.
.. versionadded:: 1.3
.. seealso::
:paramref:`.MetaData.reflect.resolve_fks`
:param info: Optional data dictionary which will be populated into the
:attr:.SchemaItem.info
attribute of this object.
:param keep_existing: When True
, indicates that if this Table
is already present in the given :class:_schema.MetaData
, ignore
further arguments within the constructor to the existing
:class:_schema.Table
, and return the :class:_schema.Table
object as
originally created. This is to allow a function that wishes
to define a new :class:_schema.Table
on first call, but on
subsequent calls will return the same :class:_schema.Table
,
without any of the declarations (particularly constraints)
being applied a second time.
If :paramref:`_schema.Table.extend_existing` or
:paramref:`_schema.Table.keep_existing` are not set,
and the given name
of the new :class:`_schema.Table` refers to a :class:`_schema.Table`
that is
already present in the target :class:`_schema.MetaData` collection,
and
this :class:`_schema.Table`
specifies additional columns or other constructs
or flags that modify the table's state, an
error is raised. The purpose of these two mutually-exclusive flags
is to specify what action should be taken when a
:class:`_schema.Table`
is specified that matches an existing :class:`_schema.Table`,
yet specifies
additional constructs.
.. seealso::
:paramref:`_schema.Table.extend_existing`
:param listeners: A list of tuples of the form (<eventname>, <fn>)
which will be passed to :func:.event.listen
upon construction.
This alternate hook to :func:.event.listen
allows the establishment
of a listener function specific to this :class:_schema.Table
before
the "autoload" process begins. Historically this has been intended
for use with the :meth:.DDLEvents.column_reflect
event, however
note that this event hook may now be associated with the
:class:_schema.MetaData
object directly::
def listen_for_reflect(table, column_info):
"handle the column reflection event"
# ...
t = Table(
'sometable',
autoload_with=engine,
listeners=[
('column_reflect', listen_for_reflect)
])
.. seealso::
:meth:`_events.DDLEvents.column_reflect`
:param must_exist: When True
, indicates that this Table must already
be present in the given :class:_schema.MetaData
collection, else
an exception is raised.
:param prefixes: A list of strings to insert after CREATE in the CREATE TABLE statement. They will be separated by spaces.
: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.
.. note:: setting this flag to ``False`` will not provide
case-insensitive behavior for table reflection; table reflection
will always search for a mixed-case name in a case sensitive
fashion. Case insensitive names are specified in SQLAlchemy only
by stating the name with all lower case characters.
:param quote_schema: same as 'quote' but applies to the schema identifier.
: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
.
If the owning :class:`_schema.MetaData` of this :class:`_schema.Table`
specifies its
own :paramref:`_schema.MetaData.schema` parameter,
then that schema name will
be applied to this :class:`_schema.Table`
if the schema parameter here is set
to ``None``. To set a blank schema name on a :class:`_schema.Table`
that
would otherwise use the schema set on the owning
:class:`_schema.MetaData`,
specify the special symbol :attr:`.BLANK_SCHEMA`.
The quoting rules for the schema name are the same as those for the
``name`` parameter, in that quoting is applied for reserved words or
case-sensitive names; to enable unconditional quoting for the schema
name, specify the flag ``quote_schema=True`` to the constructor, or use
the :class:`.quoted_name` construct to specify the name.
:param comment: Optional string that will render an SQL comment on table creation.
.. versionadded:: 1.2 Added the :paramref:`_schema.Table.comment`
parameter
to :class:`_schema.Table`.
:param **kw: Additional keyword arguments not mentioned above are
dialect specific, and passed in the form <dialectname>_<argname>
.
See the documentation regarding an individual dialect at
:ref:dialect_toplevel
for detail on documented arguments.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 |
|
inherit_cache
class-attribute
instance-attribute
Indicate if this :class:.HasCacheKey
instance should make use of the
cache key generation scheme used by its immediate superclass.
The attribute defaults to None
, which indicates that a construct has
not yet taken into account whether or not its appropriate for it to
participate in caching; this is functionally equivalent to setting the
value to False
, except that a warning is also emitted.
This flag can be set to True
on a particular class, if the SQL that
corresponds to the object does not change based on attributes which
are local to this class, and not its superclass.
.. seealso::
:ref:`compilerext_caching` - General guideslines for setting the
:attr:`.HasCacheKey.inherit_cache` attribute for third-party or user
defined SQL constructs.
constraints
instance-attribute
constraints: Set[Constraint] = set()
A collection of all :class:_schema.Constraint
objects associated with
this :class:_schema.Table
.
Includes :class:_schema.PrimaryKeyConstraint
,
:class:_schema.ForeignKeyConstraint
, :class:_schema.UniqueConstraint
,
:class:_schema.CheckConstraint
. A separate collection
:attr:_schema.Table.foreign_key_constraints
refers to the collection
of all :class:_schema.ForeignKeyConstraint
objects, and the
:attr:_schema.Table.primary_key
attribute refers to the single
:class:_schema.PrimaryKeyConstraint
associated with the
:class:_schema.Table
.
.. seealso::
:attr:`_schema.Table.constraints`
:attr:`_schema.Table.primary_key`
:attr:`_schema.Table.foreign_key_constraints`
:attr:`_schema.Table.indexes`
:class:`_reflection.Inspector`
indexes
instance-attribute
A collection of all :class:_schema.Index
objects associated with this
:class:_schema.Table
.
.. seealso::
:meth:`_reflection.Inspector.get_indexes`
foreign_key_constraints
property
foreign_key_constraints: Set[ForeignKeyConstraint]
:class:_schema.ForeignKeyConstraint
objects referred to by this
:class:_schema.Table
.
This list is produced from the collection of
:class:_schema.ForeignKey
objects currently associated.
.. seealso::
:attr:`_schema.Table.constraints`
:attr:`_schema.Table.foreign_keys`
:attr:`_schema.Table.indexes`
autoincrement_column
property
Returns the :class:.Column
object which currently represents
the "auto increment" column, if any, else returns None.
This is based on the rules for :class:.Column
as defined by the
:paramref:.Column.autoincrement
parameter, which generally means the
column within a single integer column primary key constraint that is
not constrained by a foreign key. If the table does not have such
a primary key constraint, then there's no "autoincrement" column.
A :class:.Table
may have only one column defined as the
"autoincrement" column.
.. versionadded:: 2.0.4
.. seealso::
:paramref:`.Column.autoincrement`
key
property
key: str
Return the 'key' for this :class:_schema.Table
.
This value is used as the dictionary key within the
:attr:_schema.MetaData.tables
collection. It is typically the same
as that of :attr:_schema.Table.name
for a table with no
:attr:_schema.Table.schema
set; otherwise it is typically of the form
schemaname.tablename
.
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
entity_namespace
Return a namespace used for name-based access in SQL expressions.
This is the namespace that is used to resolve "filter_by()" type expressions, such as::
stmt.filter_by(address='some address')
It defaults to the .c
collection, however internally it can
be overridden using the "entity_namespace" annotation to deliver
alternative results.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
compare
compare(other: ClauseElement, **kw: Any) -> bool
Compare this :class:_expression.ClauseElement
to
the given :class:_expression.ClauseElement
.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare()
methods and
may be used to modify the criteria for comparison
(see :class:_expression.ColumnElement
).
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
is_derived_from
is_derived_from(fromclause: Optional[FromClause]) -> bool
Return True
if this :class:_expression.FromClause
is
'derived' from the given FromClause
.
An example would be an Alias of a Table is derived from that Table.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
lateral
Return a LATERAL alias of this :class:_expression.Selectable
.
The return value is the :class:_expression.Lateral
construct also
provided by the top-level :func:_expression.lateral
function.
.. seealso::
:ref:`tutorial_lateral_correlation` - overview of usage.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
replace_selectable
replace_selectable(old: FromClause, alias: Alias) -> Self
Replace all occurrences of :class:_expression.FromClause
'old' with the given :class:_expression.Alias
object, returning a copy of this :class:_expression.FromClause
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
corresponding_column
corresponding_column(
column: KeyedColumnElement[Any],
require_embedded: bool = False,
) -> Optional[KeyedColumnElement[Any]]
Given a :class:_expression.ColumnElement
, return the exported
:class:_expression.ColumnElement
object from the
:attr:_expression.Selectable.exported_columns
collection of this :class:_expression.Selectable
which corresponds to that
original :class:_expression.ColumnElement
via a common ancestor
column.
:param column: the target :class:_expression.ColumnElement
to be matched.
:param require_embedded: only return corresponding columns for
the given :class:_expression.ColumnElement
, if the given
:class:_expression.ColumnElement
is actually present within a sub-element
of this :class:_expression.Selectable
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this :class:_expression.Selectable
.
.. seealso::
:attr:`_expression.Selectable.exported_columns` - the
:class:`_expression.ColumnCollection`
that is used for the operation.
:meth:`_expression.ColumnCollection.corresponding_column`
- implementation
method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
select
Return a SELECT of this :class:_expression.FromClause
.
e.g.::
stmt = some_table.select().where(some_table.c.id == 5)
.. seealso::
:func:`_expression.select` - general purpose
method which allows for arbitrary column lists.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
join
join(
right: _FromClauseArgument,
onclause: Optional[
_ColumnExpressionArgument[bool]
] = None,
isouter: bool = False,
full: bool = False,
) -> Join
Return a :class:_expression.Join
from this
:class:_expression.FromClause
to another :class:FromClause
.
E.g.::
from sqlalchemy import join
j = user_table.join(address_table,
user_table.c.id == address_table.c.user_id)
stmt = select(user_table).select_from(j)
would emit SQL along the lines of::
SELECT user.id, user.name FROM user
JOIN address ON user.id = address.user_id
:param right: the right side of the join; this is any
:class:_expression.FromClause
object such as a
:class:_schema.Table
object, and
may also be a selectable-compatible object such as an ORM-mapped
class.
:param onclause: a SQL expression representing the ON clause of the
join. If left at None
, :meth:_expression.FromClause.join
will attempt to
join the two tables based on a foreign key relationship.
:param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN.
:param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER
JOIN. Implies :paramref:.FromClause.join.isouter
.
.. seealso::
:func:`_expression.join` - standalone function
:class:`_expression.Join` - the type of object produced
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
outerjoin
outerjoin(
right: _FromClauseArgument,
onclause: Optional[
_ColumnExpressionArgument[bool]
] = None,
full: bool = False,
) -> Join
Return a :class:_expression.Join
from this
:class:_expression.FromClause
to another :class:FromClause
, with the "isouter" flag set to
True.
E.g.::
from sqlalchemy import outerjoin
j = user_table.outerjoin(address_table,
user_table.c.id == address_table.c.user_id)
The above is equivalent to::
j = user_table.join(
address_table,
user_table.c.id == address_table.c.user_id,
isouter=True)
:param right: the right side of the join; this is any
:class:_expression.FromClause
object such as a
:class:_schema.Table
object, and
may also be a selectable-compatible object such as an ORM-mapped
class.
:param onclause: a SQL expression representing the ON clause of the
join. If left at None
, :meth:_expression.FromClause.join
will attempt to
join the two tables based on a foreign key relationship.
:param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
.. seealso::
:meth:`_expression.FromClause.join`
:class:`_expression.Join`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
alias
Return an alias of this :class:_expression.FromClause
.
E.g.::
a2 = some_table.alias('a2')
The above code creates an :class:_expression.Alias
object which can be used
as a FROM clause in any SELECT statement.
.. seealso::
:ref:`tutorial_using_aliases`
:func:`_expression.alias`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
tablesample
tablesample(
sampling: Union[float, Function[Any]],
name: Optional[str] = None,
seed: Optional[ExpressionElementRole[Any]] = None,
) -> TableSample
Return a TABLESAMPLE alias of this :class:_expression.FromClause
.
The return value is the :class:_expression.TableSample
construct also
provided by the top-level :func:_expression.tablesample
function.
.. seealso::
:func:`_expression.tablesample` - usage guidelines and parameters
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
table_valued
table_valued() -> TableValuedColumn[Any]
Return a :class:_sql.TableValuedColumn
object for this
:class:_expression.FromClause
.
A :class:_sql.TableValuedColumn
is a :class:_sql.ColumnElement
that
represents a complete row in a table. Support for this construct is
backend dependent, and is supported in various forms by backends
such as PostgreSQL, Oracle and SQL Server.
E.g.:
.. sourcecode:: pycon+sql
>>> from sqlalchemy import select, column, func, table
>>> a = table("a", column("id"), column("x"), column("y"))
>>> stmt = select(func.row_to_json(a.table_valued()))
>>> print(stmt)
{printsql}SELECT row_to_json(a) AS row_to_json_1
FROM a
.. versionadded:: 1.4.0b2
.. seealso::
:ref:`tutorial_functions` - in the :ref:`unified_tutorial`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
insert
Generate an :class:_sql.Insert
construct against this
:class:_expression.TableClause
.
E.g.::
table.insert().values(name='foo')
See :func:_expression.insert
for argument and usage information.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
update
update() -> Update
Generate an :func:_expression.update
construct against this
:class:_expression.TableClause
.
E.g.::
table.update().where(table.c.id==7).values(name='foo')
See :func:_expression.update
for argument and usage information.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
delete
delete() -> Delete
Generate a :func:_expression.delete
construct against this
:class:_expression.TableClause
.
E.g.::
table.delete().where(table.c.id==7)
See :func:_expression.delete
for argument and usage information.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
argument_for
classmethod
Add a new kind of dialect-specific keyword argument for this class.
E.g.::
Index.argument_for("mydialect", "length", None)
some_index = Index('a', 'b', mydialect_length=5)
The :meth:.DialectKWArgs.argument_for
method is a per-argument
way adding extra arguments to the
:attr:.DefaultDialect.construct_arguments
dictionary. This
dictionary provides a list of argument names accepted by various
schema-level constructs on behalf of a dialect.
New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.
:param dialect_name: name of a dialect. The dialect must be
locatable, else a :class:.NoSuchModuleError
is raised. The
dialect must also include an existing
:attr:.DefaultDialect.construct_arguments
collection, indicating
that it participates in the keyword-argument validation and default
system, else :class:.ArgumentError
is raised. If the dialect does
not include this collection, then any keyword argument can be
specified on behalf of this dialect already. All dialects packaged
within SQLAlchemy include this collection, however for third party
dialects, support may vary.
:param argument_name: name of the parameter.
:param default: default value of the parameter.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
dialect_kwargs
A collection of keyword arguments specified as dialect-specific options to this construct.
The arguments are present here in their original <dialect>_<kwarg>
format. Only arguments that were actually passed are included;
unlike the :attr:.DialectKWArgs.dialect_options
collection, which
contains all options known by this dialect including defaults.
The collection is also writable; keys are accepted of the
form <dialect>_<kwarg>
where the value will be assembled
into the list of options.
.. seealso::
:attr:`.DialectKWArgs.dialect_options` - nested dictionary form
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
dialect_options
A collection of keyword arguments specified as dialect-specific options to this construct.
This is a two-level nested registry, keyed to <dialect_name>
and <argument_name>
. For example, the postgresql_where
argument would be locatable as::
arg = my_object.dialect_options['postgresql']['where']
.. versionadded:: 0.9.2
.. seealso::
:attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
add_is_dependent_on
add_is_dependent_on(table: Table) -> None
Add a 'dependency' for this Table.
This is another Table object which must be created first before this one can, or dropped after this one.
Usually, dependencies between tables are determined via ForeignKey objects. However, for other situations that create dependencies outside of foreign keys (rules, inheriting), this method can manually establish such a link.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
append_column
append_column(
column: ColumnClause[Any],
replace_existing: bool = False,
) -> None
Append a :class:_schema.Column
to this :class:_schema.Table
.
The "key" of the newly added :class:_schema.Column
, i.e. the
value of its .key
attribute, will then be available
in the .c
collection of this :class:_schema.Table
, and the
column definition will be included in any CREATE TABLE, SELECT,
UPDATE, etc. statements generated from this :class:_schema.Table
construct.
Note that this does not change the definition of the table as it exists within any underlying database, assuming that table has already been created in the database. Relational databases support the addition of columns to existing tables using the SQL ALTER command, which would need to be emitted for an already-existing table that doesn't contain the newly added column.
:param replace_existing: When True
, allows replacing existing
columns. When False
, the default, an warning will be raised
if a column with the same .key
already exists. A future
version of sqlalchemy will instead rise a warning.
.. versionadded:: 1.4.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
append_constraint
append_constraint(
constraint: Union[Index, Constraint],
) -> None
Append a :class:_schema.Constraint
to this
:class:_schema.Table
.
This has the effect of the constraint being included in any
future CREATE TABLE statement, assuming specific DDL creation
events have not been associated with the given
:class:_schema.Constraint
object.
Note that this does not produce the constraint within the
relational database automatically, for a table that already exists
in the database. To add a constraint to an
existing relational database table, the SQL ALTER command must
be used. SQLAlchemy also provides the
:class:.AddConstraint
construct which can produce this SQL when
invoked as an executable clause.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
create
create(
bind: _CreateDropBind, checkfirst: bool = False
) -> None
Issue a CREATE
statement for this
:class:_schema.Table
, using the given
:class:.Connection
or :class:.Engine
for connectivity.
.. seealso::
:meth:`_schema.MetaData.create_all`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
drop
drop(
bind: _CreateDropBind, checkfirst: bool = False
) -> None
Issue a DROP
statement for this
:class:_schema.Table
, using the given
:class:.Connection
or :class:.Engine
for connectivity.
.. seealso::
:meth:`_schema.MetaData.drop_all`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
tometadata
tometadata(
metadata: MetaData,
schema: Union[
str, Literal[RETAIN_SCHEMA]
] = RETAIN_SCHEMA,
referred_schema_fn: Optional[
Callable[
[
Table,
Optional[str],
ForeignKeyConstraint,
Optional[str],
],
Optional[str],
]
] = None,
name: Optional[str] = None,
) -> Table
Return a copy of this :class:_schema.Table
associated with a different
:class:_schema.MetaData
.
See :meth:_schema.Table.to_metadata
for a full description.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
to_metadata
to_metadata(
metadata: MetaData,
schema: Union[
str, Literal[RETAIN_SCHEMA]
] = RETAIN_SCHEMA,
referred_schema_fn: Optional[
Callable[
[
Table,
Optional[str],
ForeignKeyConstraint,
Optional[str],
],
Optional[str],
]
] = None,
name: Optional[str] = None,
) -> Table
Return a copy of this :class:_schema.Table
associated with a
different :class:_schema.MetaData
.
E.g.::
m1 = MetaData()
user = Table('user', m1, Column('id', Integer, primary_key=True))
m2 = MetaData()
user_copy = user.to_metadata(m2)
.. versionchanged:: 1.4 The :meth:_schema.Table.to_metadata
function
was renamed from :meth:_schema.Table.tometadata
.
:param metadata: Target :class:_schema.MetaData
object,
into which the
new :class:_schema.Table
object will be created.
:param schema: optional string name indicating the target schema.
Defaults to the special symbol :attr:.RETAIN_SCHEMA
which indicates
that no change to the schema name should be made in the new
:class:_schema.Table
. If set to a string name, the new
:class:_schema.Table
will have this new name as the .schema
. If set to None
, the
schema will be set to that of the schema set on the target
:class:_schema.MetaData
, which is typically None
as well,
unless
set explicitly::
m2 = MetaData(schema='newschema')
# user_copy_one will have "newschema" as the schema name
user_copy_one = user.to_metadata(m2, schema=None)
m3 = MetaData() # schema defaults to None
# user_copy_two will have None as the schema name
user_copy_two = user.to_metadata(m3, schema=None)
:param referred_schema_fn: optional callable which can be supplied
in order to provide for the schema name that should be assigned
to the referenced table of a :class:_schema.ForeignKeyConstraint
.
The callable accepts this parent :class:_schema.Table
, the
target schema that we are changing to, the
:class:_schema.ForeignKeyConstraint
object, and the existing
"target schema" of that constraint. The function should return the
string schema name that should be applied. To reset the schema
to "none", return the symbol :data:.BLANK_SCHEMA
. To effect no
change, return None
or :data:.RETAIN_SCHEMA
.
.. versionchanged:: 1.4.33 The referred_schema_fn
function
may return the :data:.BLANK_SCHEMA
or :data:.RETAIN_SCHEMA
symbols.
E.g.::
def referred_schema_fn(table, to_schema,
constraint, referred_schema):
if referred_schema == 'base_tables':
return referred_schema
else:
return to_schema
new_table = table.to_metadata(m2, schema="alt_schema",
referred_schema_fn=referred_schema_fn)
:param name: optional string name indicating the target table name.
If not specified or None, the table name is retained. This allows
a :class:_schema.Table
to be copied to the same
:class:_schema.MetaData
target
with a new name.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 |
|