Skip to content

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
def __init__(
    self,
    schema: str | None = None,
    schema_factory: Callable[[], str | None] | None = None,
    info: dict[Any, Any] | None = None,
) -> None:
    """Initializes the `MetaData` object.

    Args:
        schema: The default schema name to use for the metadata.
        schema_factory: 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.
        info: A dictionary of arbitrary data to be associated with the
            metadata.

    Note:
        See SQLAlchemy's documentation for more information on the
        parameters and their usage.
    """
    super().__init__(
        schema=schema,
        quote_schema=True,
        naming_convention=NAMING_CONVENTION,
        info=info,
    )

    # Initialize factory for schema name
    self.schema_factory = schema_factory

tables instance-attribute

tables: FacadeDict[str, Table]

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

sorted_tables: List[Table]

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`

schema property writable

schema: str | None

Property getter override for the schema attribute.

clear

clear() -> None

Clear all Table objects from this MetaData.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
def clear(self) -> None:
    """Clear all Table objects from this MetaData."""

    dict.clear(self.tables)  # type: ignore
    self._schemas.clear()
    self._fk_memos.clear()

remove

remove(table: Table) -> None

Remove the given Table object from this MetaData.

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py
def remove(self, table: Table) -> None:
    """Remove the given Table object from this MetaData."""

    self._remove_table(table.name, table.schema)

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
@util.preload_module("sqlalchemy.engine.reflection")
def reflect(
    self,
    bind: Union[Engine, Connection],
    schema: Optional[str] = None,
    views: bool = False,
    only: Union[
        _typing_Sequence[str], Callable[[str, MetaData], bool], None
    ] = None,
    extend_existing: bool = False,
    autoload_replace: bool = True,
    resolve_fks: bool = True,
    **dialect_kwargs: Any,
) -> None:
    r"""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.

    """

    with inspection.inspect(bind)._inspection_context() as insp:
        reflect_opts: Any = {
            "autoload_with": insp,
            "extend_existing": extend_existing,
            "autoload_replace": autoload_replace,
            "resolve_fks": resolve_fks,
            "_extend_on": set(),
        }

        reflect_opts.update(dialect_kwargs)

        if schema is None:
            schema = self.schema

        if schema is not None:
            reflect_opts["schema"] = schema

        kind = util.preloaded.engine_reflection.ObjectKind.TABLE
        available: util.OrderedSet[str] = util.OrderedSet(
            insp.get_table_names(schema)
        )
        if views:
            kind = util.preloaded.engine_reflection.ObjectKind.ANY
            available.update(insp.get_view_names(schema))
            try:
                available.update(insp.get_materialized_view_names(schema))
            except NotImplementedError:
                pass

        if schema is not None:
            available_w_schema: util.OrderedSet[str] = util.OrderedSet(
                [f"{schema}.{name}" for name in available]
            )
        else:
            available_w_schema = available

        current = set(self.tables)

        if only is None:
            load = [
                name
                for name, schname in zip(available, available_w_schema)
                if extend_existing or schname not in current
            ]
        elif callable(only):
            load = [
                name
                for name, schname in zip(available, available_w_schema)
                if (extend_existing or schname not in current)
                and only(name, self)
            ]
        else:
            missing = [name for name in only if name not in available]
            if missing:
                s = schema and (" schema '%s'" % schema) or ""
                missing_str = ", ".join(missing)
                raise exc.InvalidRequestError(
                    f"Could not reflect: requested table(s) not available "
                    f"in {bind.engine!r}{s}: ({missing_str})"
                )
            load = [
                name
                for name in only
                if extend_existing or name not in current
            ]
        # pass the available tables so the inspector can
        # choose to ignore the filter_names
        _reflect_info = insp._get_reflection_info(
            schema=schema,
            filter_names=load,
            available=available,
            kind=kind,
            scope=util.preloaded.engine_reflection.ObjectScope.ANY,
            **dialect_kwargs,
        )
        reflect_opts["_reflect_info"] = _reflect_info

        for name in load:
            try:
                Table(name, self, **reflect_opts)
            except exc.UnreflectableTableError as uerr:
                util.warn(f"Skipping table {name}: {uerr}")

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
def create_all(
    self,
    bind: _CreateDropBind,
    tables: Optional[_typing_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.

    """
    bind._run_ddl_visitor(
        ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables
    )

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
def drop_all(
    self,
    bind: _CreateDropBind,
    tables: Optional[_typing_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.

    """
    bind._run_ddl_visitor(
        ddl.SchemaDropper, self, checkfirst=checkfirst, tables=tables
    )

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 PostgreSQL SERIAL, MySQL AUTO_INCREMENT, or IDENTITY 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() (see https://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 - the SELECT 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.
  • 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
def __init__(
    self,
    __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[SchemaConst.NULL_UNSPECIFIED]]
    ] = SchemaConst.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,
):
    r"""
    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 PostgreSQL
        ``SERIAL``, MySQL ``AUTO_INCREMENT``, or ``IDENTITY`` 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()``
          (see
          `https://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 -
          the ``SELECT 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.

      * 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`


    """  # noqa: E501, RST201, RST202

    l_args = [__name_pos, __type_pos] + list(args)
    del args

    if l_args:
        if isinstance(l_args[0], str):
            if name is not None:
                raise exc.ArgumentError(
                    "May not pass name positionally and as a keyword."
                )
            name = l_args.pop(0)  # type: ignore
        elif l_args[0] is None:
            l_args.pop(0)
    if l_args:
        coltype = l_args[0]

        if hasattr(coltype, "_sqla_type"):
            if type_ is not None:
                raise exc.ArgumentError(
                    "May not pass type_ positionally and as a keyword."
                )
            type_ = l_args.pop(0)  # type: ignore
        elif l_args[0] is None:
            l_args.pop(0)

    if name is not None:
        name = quoted_name(name, quote)
    elif quote is not None:
        raise exc.ArgumentError(
            "Explicit 'name' is required when sending 'quote' argument"
        )

    # name = None is expected to be an interim state
    # note this use case is legacy now that ORM declarative has a
    # dedicated "column" construct local to the ORM
    super().__init__(name, type_)  # type: ignore

    self.key = key if key is not None else name  # type: ignore
    self.primary_key = primary_key
    self._insert_sentinel = insert_sentinel
    self._omit_from_statements = _omit_from_statements
    self._user_defined_nullable = udn = nullable
    if udn is not NULL_UNSPECIFIED:
        self.nullable = udn
    else:
        self.nullable = not primary_key

    # these default to None because .index and .unique is *not*
    # an informational flag about Column - there can still be an
    # Index or UniqueConstraint referring to this Column.
    self.index = index
    self.unique = unique

    self.system = system
    self.doc = doc
    self.autoincrement: _AutoIncrementType = autoincrement
    self.constraints = set()
    self.foreign_keys = set()
    self.comment = comment
    self.computed = None
    self.identity = None

    # check if this Column is proxying another column

    if _proxies is not None:
        self._proxies = _proxies
    else:
        # otherwise, add DDL-related events
        self._set_type(self.type)

    if default is not None:
        if not isinstance(default, (ColumnDefault, Sequence)):
            default = ColumnDefault(default)

        self.default = default
        l_args.append(default)
    else:
        self.default = None

    if onupdate is not None:
        if not isinstance(onupdate, (ColumnDefault, Sequence)):
            onupdate = ColumnDefault(onupdate, for_update=True)

        self.onupdate = onupdate
        l_args.append(onupdate)
    else:
        self.onupdate = None

    if server_default is not None:
        if isinstance(server_default, FetchedValue):
            server_default = server_default._as_for_update(False)
            l_args.append(server_default)
        else:
            server_default = DefaultClause(server_default)
            l_args.append(server_default)
    self.server_default = server_default

    if server_onupdate is not None:
        if isinstance(server_onupdate, FetchedValue):
            server_onupdate = server_onupdate._as_for_update(True)
            l_args.append(server_onupdate)
        else:
            server_onupdate = DefaultClause(
                server_onupdate, for_update=True
            )
            l_args.append(server_onupdate)
    self.server_onupdate = server_onupdate

    self._init_items(*cast(_typing_Sequence[SchemaItem], l_args))

    util.set_creation_order(self)

    if info is not None:
        self.info = info

    self._extra_kwargs(**dialect_kwargs)

timetuple class-attribute instance-attribute

timetuple: Literal[None] = None

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.

kwargs property

kwargs

A synonym for :attr:.DialectKWArgs.dialect_kwargs.

index instance-attribute

index: Optional[bool]

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

unique: Optional[bool]

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

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

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
@util.memoized_property
def proxy_set(self) -> 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.

    """
    return frozenset([self._deannotate()]).union(
        itertools.chain(*[c.proxy_set for c in self._proxies])
    )

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
def compare(self, other: ClauseElement, **kw: Any) -> bool:
    r"""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`).

    """
    return traversals.compare(self, other, **kw)

label

label(name: Optional[str]) -> Label[_T]

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
def label(self, name: Optional[str]) -> Label[_T]:
    """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.

    """
    return Label(name, self, self.type)

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
def shares_lineage(self, othercolumn: ColumnElement[Any]) -> bool:
    """Return True if the given :class:`_expression.ColumnElement`
    has a common ancestor to this :class:`_expression.ColumnElement`."""

    return bool(self.proxy_set.intersection(othercolumn.proxy_set))

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
def cast(self, 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`

    """
    return Cast(self, type_)

argument_for classmethod

argument_for(dialect_name, argument_name, default)

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
@classmethod
def argument_for(cls, dialect_name, argument_name, default):
    """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.

    """

    construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
    if construct_arg_dictionary is None:
        raise exc.ArgumentError(
            "Dialect '%s' does have keyword-argument "
            "validation and defaults enabled configured" % dialect_name
        )
    if cls not in construct_arg_dictionary:
        construct_arg_dictionary[cls] = {}
    construct_arg_dictionary[cls][argument_name] = default

dialect_kwargs

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
@util.memoized_property
def dialect_kwargs(self):
    """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

    """
    return _DialectArgView(self)

dialect_options

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
@util.memoized_property
def dialect_options(self):
    """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

    """

    return util.PopulateDict(
        util.portable_instancemethod(self._kw_reg_for_dialect_cls)
    )

references

references(column: Column[Any]) -> bool

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
def references(self, column: Column[Any]) -> bool:
    """Return True if this Column references the given column via foreign
    key."""

    for fk in self.foreign_keys:
        if fk.column.proxy_set.intersection(column.proxy_set):
            return True
    else:
        return False

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 when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.

:param ondelete: Optional string. If set, emit ON DELETE when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.

: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 when issuing DDL for this constraint.

: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 when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL.

: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
def __init__(
    self,
    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,
):
    r"""
    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 <value> when
        issuing DDL for this constraint. Typical values include CASCADE,
        DELETE and RESTRICT.

    :param ondelete: Optional string. If set, emit ON DELETE <value> when
        issuing DDL for this constraint. Typical values include CASCADE,
        DELETE and RESTRICT.

    :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 <value> when
        issuing DDL for this constraint.

    :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 <value> when issuing
        DDL for this constraint. Typical values include SIMPLE, PARTIAL
        and FULL.

    :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.

    """

    self._colspec = coercions.expect(roles.DDLReferredColumnRole, column)
    self._unresolvable = _unresolvable

    if isinstance(self._colspec, str):
        self._table_column = None
    else:
        self._table_column = self._colspec

        if not isinstance(
            self._table_column.table, (type(None), TableClause)
        ):
            raise exc.ArgumentError(
                "ForeignKey received Column not bound "
                "to a Table, got: %r" % self._table_column.table
            )

    # the linked ForeignKeyConstraint.
    # ForeignKey will create this when parent Column
    # is attached to a Table, *or* ForeignKeyConstraint
    # object passes itself in when creating ForeignKey
    # markers.
    self.constraint = _constraint

    # .parent is not Optional under normal use
    self.parent = None  # type: ignore

    self.use_alter = use_alter
    self.name = name
    self.onupdate = onupdate
    self.ondelete = ondelete
    self.deferrable = deferrable
    self.initially = initially
    self.link_to_name = link_to_name
    self.match = match
    self.comment = comment
    if info:
        self.info = info
    self._unvalidated_dialect_kw = dialect_kw

kwargs property

kwargs

A synonym for :attr:.DialectKWArgs.dialect_kwargs.

argument_for classmethod

argument_for(dialect_name, argument_name, default)

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
@classmethod
def argument_for(cls, dialect_name, argument_name, default):
    """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.

    """

    construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
    if construct_arg_dictionary is None:
        raise exc.ArgumentError(
            "Dialect '%s' does have keyword-argument "
            "validation and defaults enabled configured" % dialect_name
        )
    if cls not in construct_arg_dictionary:
        construct_arg_dictionary[cls] = {}
    construct_arg_dictionary[cls][argument_name] = default

dialect_kwargs

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
@util.memoized_property
def dialect_kwargs(self):
    """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

    """
    return _DialectArgView(self)

dialect_options

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
@util.memoized_property
def dialect_options(self):
    """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

    """

    return util.PopulateDict(
        util.portable_instancemethod(self._kw_reg_for_dialect_cls)
    )

references

references(table: Table) -> bool

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
def references(self, table: Table) -> bool:
    """Return True if the given :class:`_schema.Table`
    is referenced by this
    :class:`_schema.ForeignKey`."""

    return table.corresponding_column(self.column) is not None

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
def get_referent(self, 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`.

    """
    # our column is a Column, and any subquery etc. proxying us
    # would be doing so via another Column, so that's what would
    # be returned here
    return table.columns.corresponding_column(self.column)  # type: ignore

column

column() -> Column[Any]

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
@util.ro_memoized_property
def column(self) -> Column[Any]:
    """Return the target :class:`_schema.Column` referenced by this
    :class:`_schema.ForeignKey`.

    If no target column has been established, an exception
    is raised.

    """

    return self._resolve_column()

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
def __init__(
    self,
    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,
) -> None:
    r"""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.

    """
    self.table = table = None

    self.name = quoted_name.construct(name, quote)
    self.unique = unique
    if info is not None:
        self.info = info

    # TODO: consider "table" argument being public, but for
    # the purpose of the fix here, it starts as private.
    if _table is not None:
        table = _table

    self._validate_dialect_kwargs(dialect_kw)

    self.expressions = []
    # will call _set_parent() if table-bound column
    # objects are present
    ColumnCollectionMixin.__init__(
        self,
        *expressions,
        _column_flag=_column_flag,
        _gather_expressions=self.expressions,
    )
    if table is not None:
        self._set_parent(table)

kwargs property

kwargs

A synonym for :attr:.DialectKWArgs.dialect_kwargs.

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
def ddl_if(
    self,
    dialect: Optional[str] = None,
    callable_: Optional[ddl.DDLIfCallable] = None,
    state: Optional[Any] = None,
) -> Self:
    r"""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


    """
    self._ddl_if = ddl.DDLIf(dialect, callable_, state)
    return self

argument_for classmethod

argument_for(dialect_name, argument_name, default)

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
@classmethod
def argument_for(cls, dialect_name, argument_name, default):
    """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.

    """

    construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
    if construct_arg_dictionary is None:
        raise exc.ArgumentError(
            "Dialect '%s' does have keyword-argument "
            "validation and defaults enabled configured" % dialect_name
        )
    if cls not in construct_arg_dictionary:
        construct_arg_dictionary[cls] = {}
    construct_arg_dictionary[cls][argument_name] = default

dialect_kwargs

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
@util.memoized_property
def dialect_kwargs(self):
    """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

    """
    return _DialectArgView(self)

dialect_options

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
@util.memoized_property
def dialect_options(self):
    """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

    """

    return util.PopulateDict(
        util.portable_instancemethod(self._kw_reg_for_dialect_cls)
    )

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
def create(self, 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`.

    """
    bind._run_ddl_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)

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
def drop(self, 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`.

    """
    bind._run_ddl_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)

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
def __init__(
    self,
    name: str,
    metadata: MetaData,
    *args: SchemaItem,
    schema: Optional[Union[str, Literal[SchemaConst.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[
        _typing_Sequence[Tuple[str, Callable[..., Any]]]
    ] = None,
    prefixes: Optional[_typing_Sequence[str]] = None,
    # used internally in the metadata.reflect() process
    _extend_on: Optional[Set[Table]] = None,
    # used by __new__ to bypass __init__
    _no_init: bool = True,
    # dialect-specific keyword args
    **kw: Any,
) -> None:
    r"""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.

    """  # noqa: E501
    if _no_init:
        # don't run __init__ from __new__ by default;
        # __new__ has a specific place that __init__ is called
        return

    super().__init__(quoted_name(name, quote))
    self.metadata = metadata

    if schema is None:
        self.schema = metadata.schema
    elif schema is BLANK_SCHEMA:
        self.schema = None
    else:
        quote_schema = quote_schema
        assert isinstance(schema, str)
        self.schema = quoted_name(schema, quote_schema)

    self._sentinel_column = None

    self.indexes = set()
    self.constraints = set()
    PrimaryKeyConstraint(
        _implicit_generated=True
    )._set_parent_with_dispatch(self)
    self.foreign_keys = set()  # type: ignore
    self._extra_dependencies: Set[Table] = set()
    if self.schema is not None:
        self.fullname = "%s.%s" % (self.schema, self.name)
    else:
        self.fullname = self.name

    self.implicit_returning = implicit_returning
    _reflect_info = kw.pop("_reflect_info", None)

    self.comment = comment

    if info is not None:
        self.info = info

    if listeners is not None:
        for evt, fn in listeners:
            event.listen(self, evt, fn)

    self._prefixes = prefixes if prefixes else []

    self._extra_kwargs(**kw)

    # load column definitions from the database if 'autoload' is defined
    # we do it after the table is in the singleton dictionary to support
    # circular foreign keys
    if autoload_with is not None:
        self._autoload(
            metadata,
            autoload_with,
            include_columns,
            _extend_on=_extend_on,
            _reflect_info=_reflect_info,
            resolve_fks=resolve_fks,
        )

    # initialize all the column, etc. objects.  done after reflection to
    # allow user-overrides

    self._init_items(
        *args,
        allow_replacements=extend_existing
        or keep_existing
        or autoload_with,
        all_names={},
    )

inherit_cache class-attribute instance-attribute

inherit_cache: Optional[bool] = None

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.

kwargs property

kwargs

A synonym for :attr:.DialectKWArgs.dialect_kwargs.

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

indexes: Set[Index] = set()

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

autoincrement_column: Optional[Column[int]]

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

memoized_attribute(
    fget: Callable[..., _T], doc: Optional[str] = None
)

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
def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
    self.fget = fget
    self.__doc__ = doc or fget.__doc__
    self.__name__ = fget.__name__

memoized_instancemethod classmethod

memoized_instancemethod(fn: _F) -> _F

Decorate a method memoize its return value.

:meta private:

Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
@classmethod
def memoized_instancemethod(cls, fn: _F) -> _F:
    """Decorate a method memoize its return value.

    :meta private:

    """

    def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
        result = fn(self, *args, **kw)

        def memo(*a, **kw):
            return result

        memo.__name__ = fn.__name__
        memo.__doc__ = fn.__doc__
        self.__dict__[fn.__name__] = memo
        self._memoized_keys |= {fn.__name__}
        return result

    return update_wrapper(oneshot, fn)  # type: ignore

entity_namespace

entity_namespace() -> _EntityNamespace

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
@util.ro_non_memoized_property
def entity_namespace(self) -> _EntityNamespace:
    """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.

    """
    return self.c

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
def compare(self, other: ClauseElement, **kw: Any) -> bool:
    r"""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`).

    """
    return traversals.compare(self, other, **kw)

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
def is_derived_from(self, 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.

    """
    # this is essentially an "identity" check in the base class.
    # Other constructs override this to traverse through
    # contained elements.
    return fromclause in self._cloned_set

lateral

lateral(name: Optional[str] = None) -> LateralFromClause

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
def lateral(self, name: Optional[str] = None) -> LateralFromClause:
    """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.

    """
    return Lateral._construct(self, name=name)

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
@util.deprecated(
    "1.4",
    message="The :meth:`.Selectable.replace_selectable` method is "
    "deprecated, and will be removed in a future release.  Similar "
    "functionality is available via the sqlalchemy.sql.visitors module.",
)
@util.preload_module("sqlalchemy.sql.util")
def replace_selectable(self, 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`.

    """
    return util.preloaded.sql_util.ClauseAdapter(alias).traverse(self)

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
def corresponding_column(
    self, 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.

    """

    return self.exported_columns.corresponding_column(
        column, require_embedded
    )

select

select() -> Select[Any]

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
def select(self) -> Select[Any]:
    r"""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.

    """
    return Select(self)

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
def join(
    self,
    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

    """

    return Join(self, right, onclause, isouter, full)

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
def outerjoin(
    self,
    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`

    """

    return Join(self, right, onclause, True, full)

alias

alias(
    name: Optional[str] = None, flat: bool = False
) -> NamedFromClause

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
def alias(
    self, name: Optional[str] = None, flat: bool = False
) -> NamedFromClause:
    """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`

    """

    return Alias._construct(self, name=name)

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
def tablesample(
    self,
    sampling: Union[float, Function[Any]],
    name: Optional[str] = None,
    seed: Optional[roles.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

    """
    return TableSample._construct(
        self, sampling=sampling, name=name, seed=seed
    )

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
@util.preload_module("sqlalchemy.sql.sqltypes")
def table_valued(self) -> 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`

    """
    return TableValuedColumn(self, type_api.TABLEVALUE)

insert

insert() -> 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
@util.preload_module("sqlalchemy.sql.dml")
def insert(self) -> util.preloaded.sql_dml.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.

    """

    return util.preloaded.sql_dml.Insert(self)

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
@util.preload_module("sqlalchemy.sql.dml")
def update(self) -> 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.

    """
    return util.preloaded.sql_dml.Update(
        self,
    )

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
@util.preload_module("sqlalchemy.sql.dml")
def delete(self) -> 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.

    """
    return util.preloaded.sql_dml.Delete(self)

argument_for classmethod

argument_for(dialect_name, argument_name, default)

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
@classmethod
def argument_for(cls, dialect_name, argument_name, default):
    """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.

    """

    construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
    if construct_arg_dictionary is None:
        raise exc.ArgumentError(
            "Dialect '%s' does have keyword-argument "
            "validation and defaults enabled configured" % dialect_name
        )
    if cls not in construct_arg_dictionary:
        construct_arg_dictionary[cls] = {}
    construct_arg_dictionary[cls][argument_name] = default

dialect_kwargs

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
@util.memoized_property
def dialect_kwargs(self):
    """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

    """
    return _DialectArgView(self)

dialect_options

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
@util.memoized_property
def dialect_options(self):
    """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

    """

    return util.PopulateDict(
        util.portable_instancemethod(self._kw_reg_for_dialect_cls)
    )

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
def add_is_dependent_on(self, 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.

    """
    self._extra_dependencies.add(table)

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
def append_column(
    self, 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
    """

    try:
        column._set_parent_with_dispatch(
            self,
            allow_replacements=replace_existing,
            all_names={c.name: c for c in self.c},
        )
    except exc.DuplicateColumnError as de:
        raise exc.DuplicateColumnError(
            f"{de.args[0]} Specify replace_existing=True to "
            "Table.append_column() to replace an "
            "existing column."
        ) from de

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
def append_constraint(self, 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.

    """

    constraint._set_parent_with_dispatch(self)

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
def create(self, 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`.

    """

    bind._run_ddl_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)

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
def drop(self, 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`.

    """
    bind._run_ddl_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)

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
@util.deprecated(
    "1.4",
    ":meth:`_schema.Table.tometadata` is renamed to "
    ":meth:`_schema.Table.to_metadata`",
)
def tometadata(
    self,
    metadata: MetaData,
    schema: Union[str, Literal[SchemaConst.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.

    """
    return self.to_metadata(
        metadata,
        schema=schema,
        referred_schema_fn=referred_schema_fn,
        name=name,
    )

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
def to_metadata(
    self,
    metadata: MetaData,
    schema: Union[str, Literal[SchemaConst.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.

    """
    if name is None:
        name = self.name

    actual_schema: Optional[str]

    if schema is RETAIN_SCHEMA:
        actual_schema = self.schema
    elif schema is None:
        actual_schema = metadata.schema
    else:
        actual_schema = schema
    key = _get_table_key(name, actual_schema)
    if key in metadata.tables:
        util.warn(
            f"Table '{self.description}' already exists within the given "
            "MetaData - not copying."
        )
        return metadata.tables[key]

    args = []
    for col in self.columns:
        args.append(col._copy(schema=actual_schema))
    table = Table(
        name,
        metadata,
        schema=actual_schema,
        comment=self.comment,
        *args,
        **self.kwargs,
    )
    for const in self.constraints:
        if isinstance(const, ForeignKeyConstraint):
            referred_schema = const._referred_schema
            if referred_schema_fn:
                fk_constraint_schema = referred_schema_fn(
                    self, actual_schema, const, referred_schema
                )
            else:
                fk_constraint_schema = (
                    actual_schema
                    if referred_schema == self.schema
                    else None
                )
            table.append_constraint(
                const._copy(
                    schema=fk_constraint_schema, target_table=table
                )
            )
        elif not const._type_bound:
            # skip unique constraints that would be generated
            # by the 'unique' flag on Column
            if const._column_flag:
                continue

            table.append_constraint(
                const._copy(schema=actual_schema, target_table=table)
            )
    for index in self.indexes:
        # skip indexes that would be generated
        # by the 'index' flag on Column
        if index._column_flag:
            continue
        Index(
            index.name,
            unique=index.unique,
            *[
                _copy_expression(expr, self, table)
                for expr in index._table_bound_expressions
            ],
            _table=table,
            **index.kwargs,
        )
    return self._schema_item_copy(table)