1
0
mirror of https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git synced 2025-08-14 00:25:46 +02:00

Проверка 09.02.2025

This commit is contained in:
MoonTestUse1
2025-02-09 01:11:49 +06:00
parent ce52f8a23a
commit 0aa3ef8fc2
5827 changed files with 14316 additions and 1906434 deletions

View File

@@ -1,5 +1,5 @@
# sql/schema.py
# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
# Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
@@ -60,6 +60,7 @@ from . import roles
from . import type_api
from . import visitors
from .base import _DefaultDescriptionTuple
from .base import _NoArg
from .base import _NoneName
from .base import _SentinelColumnCharacterization
from .base import _SentinelDefaultCharacterization
@@ -76,7 +77,6 @@ from .elements import TextClause
from .selectable import TableClause
from .type_api import to_instance
from .visitors import ExternallyTraversible
from .visitors import InternalTraversal
from .. import event
from .. import exc
from .. import inspection
@@ -95,12 +95,13 @@ if typing.TYPE_CHECKING:
from ._typing import _InfoType
from ._typing import _TextCoercedExpressionArgument
from ._typing import _TypeEngineArgument
from .base import ColumnSet
from .base import ReadOnlyColumnCollection
from .compiler import DDLCompiler
from .elements import BindParameter
from .elements import KeyedColumnElement
from .functions import Function
from .type_api import TypeEngine
from .visitors import _TraverseInternalsType
from .visitors import anon_map
from ..engine import Connection
from ..engine import Engine
@@ -124,6 +125,8 @@ _ServerDefaultArgument = Union[
"FetchedValue", str, TextClause, ColumnElement[Any]
]
_ServerOnUpdateArgument = _ServerDefaultArgument
class SchemaConst(Enum):
RETAIN_SCHEMA = 1
@@ -319,9 +322,10 @@ class Table(
e.g.::
mytable = Table(
"mytable", metadata,
Column('mytable_id', Integer, primary_key=True),
Column('value', String(50))
"mytable",
metadata,
Column("mytable_id", Integer, primary_key=True),
Column("value", String(50)),
)
The :class:`_schema.Table`
@@ -391,11 +395,6 @@ class Table(
"""
_traverse_internals: _TraverseInternalsType = (
TableClause._traverse_internals
+ [("schema", InternalTraversal.dp_string)]
)
if TYPE_CHECKING:
@util.ro_non_memoized_property
@@ -636,11 +635,13 @@ class Table(
:class:`_schema.Column`
named "y"::
Table("mytable", metadata,
Column('y', Integer),
extend_existing=True,
autoload_with=engine
)
Table(
"mytable",
metadata,
Column("y", Integer),
extend_existing=True,
autoload_with=engine,
)
.. seealso::
@@ -737,12 +738,12 @@ class Table(
"handle the column reflection event"
# ...
t = Table(
'sometable',
"sometable",
autoload_with=engine,
listeners=[
('column_reflect', listen_for_reflect)
])
listeners=[("column_reflect", listen_for_reflect)],
)
.. seealso::
@@ -1349,7 +1350,7 @@ class Table(
m1 = MetaData()
user = Table('user', m1, Column('id', Integer, primary_key=True))
user = Table("user", m1, Column("id", Integer, primary_key=True))
m2 = MetaData()
user_copy = user.to_metadata(m2)
@@ -1373,7 +1374,7 @@ class Table(
unless
set explicitly::
m2 = MetaData(schema='newschema')
m2 = MetaData(schema="newschema")
# user_copy_one will have "newschema" as the schema name
user_copy_one = user.to_metadata(m2, schema=None)
@@ -1400,15 +1401,16 @@ class Table(
E.g.::
def referred_schema_fn(table, to_schema,
constraint, referred_schema):
if referred_schema == 'base_tables':
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)
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
@@ -1416,7 +1418,7 @@ class Table(
:class:`_schema.MetaData` target
with a new name.
"""
""" # noqa: E501
if name is None:
name = self.name
@@ -1438,7 +1440,7 @@ class Table(
args = []
for col in self.columns:
args.append(col._copy(schema=actual_schema))
args.append(col._copy(schema=actual_schema, _to_metadata=metadata))
table = Table(
name,
metadata,
@@ -1514,7 +1516,8 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
name: Optional[str] = None,
type_: Optional[_TypeEngineArgument[_T]] = None,
autoincrement: _AutoIncrementType = "auto",
default: Optional[Any] = None,
default: Optional[Any] = _NoArg.NO_ARG,
insert_default: Optional[Any] = _NoArg.NO_ARG,
doc: Optional[str] = None,
key: Optional[str] = None,
index: Optional[bool] = None,
@@ -1526,7 +1529,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
onupdate: Optional[Any] = None,
primary_key: bool = False,
server_default: Optional[_ServerDefaultArgument] = None,
server_onupdate: Optional[FetchedValue] = None,
server_onupdate: Optional[_ServerOnUpdateArgument] = None,
quote: Optional[bool] = None,
system: bool = False,
comment: Optional[str] = None,
@@ -1547,7 +1550,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
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.
case names as case insensitive such as Oracle Database.
The name field may be omitted at construction time and applied
later, at any time before the Column is associated with a
@@ -1560,10 +1563,10 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
as well, e.g.::
# use a type with arguments
Column('data', String(50))
Column("data", String(50))
# use no arguments
Column('level', Integer)
Column("level", Integer)
The ``type`` argument may be the second positional argument
or specified by keyword.
@@ -1619,8 +1622,8 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
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
"implied" default generator available; for example the Oracle Database
backends alway 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.
@@ -1665,8 +1668,12 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
# turn on autoincrement for this column despite
# the ForeignKey()
Column('id', ForeignKey('other.id'),
primary_key=True, autoincrement='ignore_fk')
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
@@ -1694,7 +1701,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
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"
* Oracle Database - The Oracle Database dialects have 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).
@@ -1711,10 +1718,10 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
(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
* PostgreSQL, SQL Server, Oracle Database - 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
* PostgreSQL, Oracle Database 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
@@ -1751,6 +1758,11 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
:ref:`metadata_defaults_toplevel`
:param insert_default: An alias of :paramref:`.Column.default`
for compatibility with :func:`_orm.mapped_column`.
.. versionadded: 2.0.31
: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
@@ -1778,7 +1790,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
"some_table",
metadata,
Column("x", Integer),
Index("ix_some_table_x", "x")
Index("ix_some_table_x", "x"),
)
To add the :paramref:`_schema.Index.unique` flag to the
@@ -1860,14 +1872,22 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
String types will be emitted as-is, surrounded by single quotes::
Column('x', Text, server_default="val")
Column("x", Text, server_default="val")
will render:
.. sourcecode:: sql
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()'))
Column("y", DateTime, server_default=text("NOW()"))
will render:
.. sourcecode:: sql
y DATETIME DEFAULT NOW()
@@ -1882,20 +1902,21 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
from sqlalchemy.dialects.postgresql import array
engine = create_engine(
'postgresql+psycopg2://scott:tiger@localhost/mydatabase'
"postgresql+psycopg2://scott:tiger@localhost/mydatabase"
)
metadata_obj = MetaData()
tbl = Table(
"foo",
metadata_obj,
Column("bar",
ARRAY(Text),
server_default=array(["biz", "bang", "bash"])
)
"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::
The above results in a table created with the following SQL:
.. sourcecode:: sql
CREATE TABLE foo (
bar TEXT[] DEFAULT ARRAY['biz', 'bang', 'bash']
@@ -1960,12 +1981,7 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
:class:`_schema.UniqueConstraint` construct explicitly at the
level of the :class:`_schema.Table` construct itself::
Table(
"some_table",
metadata,
Column("x", Integer),
UniqueConstraint("x")
)
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
@@ -2104,12 +2120,19 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
# otherwise, add DDL-related events
self._set_type(self.type)
if default is not None:
if not isinstance(default, (ColumnDefault, Sequence)):
default = ColumnDefault(default)
if insert_default is not _NoArg.NO_ARG:
resolved_default = insert_default
elif default is not _NoArg.NO_ARG:
resolved_default = default
else:
resolved_default = None
self.default = default
l_args.append(default)
if resolved_default is not None:
if not isinstance(resolved_default, (ColumnDefault, Sequence)):
resolved_default = ColumnDefault(resolved_default)
self.default = resolved_default
l_args.append(resolved_default)
else:
self.default = None
@@ -2466,6 +2489,8 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
server_onupdate = self.server_onupdate
if isinstance(server_default, (Computed, Identity)):
# TODO: likely should be copied in all cases
# TODO: if a Sequence, we would need to transfer the Sequence
# .metadata as well
args.append(server_default._copy(**kw))
server_default = server_onupdate = None
@@ -2569,8 +2594,11 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
new_onupdate = self.onupdate._copy()
new_onupdate._set_parent(other)
if self.index and not other.index:
other.index = True
if self.index in (True, False) and other.index is None:
other.index = self.index
if self.unique in (True, False) and other.unique is None:
other.unique = self.unique
if self.doc and other.doc is None:
other.doc = self.doc
@@ -2578,9 +2606,6 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
if self.comment and other.comment is None:
other.comment = self.comment
if self.unique and not other.unique:
other.unique = True
for const in self.constraints:
if not const._type_bound:
new_const = const._copy()
@@ -2594,6 +2619,8 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
def _make_proxy(
self,
selectable: FromClause,
primary_key: ColumnSet,
foreign_keys: Set[KeyedColumnElement[Any]],
name: Optional[str] = None,
key: Optional[str] = None,
name_is_truncatable: bool = False,
@@ -2663,10 +2690,13 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
c._propagate_attrs = selectable._propagate_attrs
if selectable._is_clone_of is not None:
c._is_clone_of = selectable._is_clone_of.columns.get(c.key)
if self.primary_key:
selectable.primary_key.add(c) # type: ignore
primary_key.add(c)
if fk:
selectable.foreign_keys.update(fk) # type: ignore
foreign_keys.update(fk) # type: ignore
return c.key, c
@@ -2727,8 +2757,10 @@ class ForeignKey(DialectKWArgs, SchemaItem):
object,
e.g.::
t = Table("remote_table", metadata,
Column("remote_id", ForeignKey("main_table.id"))
t = Table(
"remote_table",
metadata,
Column("remote_id", ForeignKey("main_table.id")),
)
Note that ``ForeignKey`` is only a marker object that defines
@@ -3377,12 +3409,11 @@ class ColumnDefault(DefaultGenerator, ABC):
For example, the following::
Column('foo', Integer, default=50)
Column("foo", Integer, default=50)
Is equivalent to::
Column('foo', Integer, ColumnDefault(50))
Column("foo", Integer, ColumnDefault(50))
"""
@@ -3669,9 +3700,14 @@ class Sequence(HasSchemaAttr, IdentityOptions, DefaultGenerator):
The :class:`.Sequence` is typically associated with a primary key column::
some_table = Table(
'some_table', metadata,
Column('id', Integer, Sequence('some_table_seq', start=1),
primary_key=True)
"some_table",
metadata,
Column(
"id",
Integer,
Sequence("some_table_seq", start=1),
primary_key=True,
),
)
When CREATE TABLE is emitted for the above :class:`_schema.Table`, if the
@@ -3782,11 +3818,11 @@ class Sequence(HasSchemaAttr, IdentityOptions, DefaultGenerator):
:param cache: optional integer value; number of future values in the
sequence which are calculated in advance. Renders the CACHE keyword
understood by Oracle and PostgreSQL.
understood by Oracle Database and PostgreSQL.
:param order: optional boolean value; if ``True``, renders the
ORDER keyword, understood by Oracle, indicating the sequence is
definitively ordered. May be necessary to provide deterministic
ORDER keyword, understood by Oracle Database, indicating the sequence
is definitively ordered. May be necessary to provide deterministic
ordering using Oracle RAC.
:param data_type: The type to be returned by the sequence, for
@@ -3947,7 +3983,7 @@ class FetchedValue(SchemaEventTarget):
E.g.::
Column('foo', Integer, FetchedValue())
Column("foo", Integer, FetchedValue())
Would indicate that some trigger or default generator
will create a new value for the ``foo`` column during an
@@ -4013,11 +4049,11 @@ class DefaultClause(FetchedValue):
For example, the following::
Column('foo', Integer, server_default="50")
Column("foo", Integer, server_default="50")
Is equivalent to::
Column('foo', Integer, DefaultClause("50"))
Column("foo", Integer, DefaultClause("50"))
"""
@@ -4196,6 +4232,10 @@ class ColumnCollectionMixin:
] = _gather_expressions
if processed_expressions is not None:
# this is expected to be an empty list
assert not processed_expressions
self._pending_colargs = []
for (
expr,
@@ -4846,11 +4886,13 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint):
:class:`_schema.Column` objects corresponding to those marked with
the :paramref:`_schema.Column.primary_key` flag::
>>> my_table = Table('mytable', metadata,
... Column('id', Integer, primary_key=True),
... Column('version_id', Integer, primary_key=True),
... Column('data', String(50))
... )
>>> my_table = Table(
... "mytable",
... metadata,
... Column("id", Integer, primary_key=True),
... Column("version_id", Integer, primary_key=True),
... Column("data", String(50)),
... )
>>> my_table.primary_key
PrimaryKeyConstraint(
Column('id', Integer(), table=<mytable>,
@@ -4864,13 +4906,14 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint):
the "name" of the constraint can also be specified, as well as other
options which may be recognized by dialects::
my_table = Table('mytable', metadata,
Column('id', Integer),
Column('version_id', Integer),
Column('data', String(50)),
PrimaryKeyConstraint('id', 'version_id',
name='mytable_pk')
)
my_table = Table(
"mytable",
metadata,
Column("id", Integer),
Column("version_id", Integer),
Column("data", String(50)),
PrimaryKeyConstraint("id", "version_id", name="mytable_pk"),
)
The two styles of column-specification should generally not be mixed.
An warning is emitted if the columns present in the
@@ -4888,13 +4931,14 @@ class PrimaryKeyConstraint(ColumnCollectionConstraint):
primary key column collection from the :class:`_schema.Table` based on the
flags::
my_table = Table('mytable', metadata,
Column('id', Integer, primary_key=True),
Column('version_id', Integer, primary_key=True),
Column('data', String(50)),
PrimaryKeyConstraint(name='mytable_pk',
mssql_clustered=True)
)
my_table = Table(
"mytable",
metadata,
Column("id", Integer, primary_key=True),
Column("version_id", Integer, primary_key=True),
Column("data", String(50)),
PrimaryKeyConstraint(name="mytable_pk", mssql_clustered=True),
)
"""
@@ -5091,19 +5135,21 @@ class Index(
E.g.::
sometable = Table("sometable", metadata,
Column("name", String(50)),
Column("address", String(100))
)
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)
)
sometable = Table(
"sometable", metadata, Column("name", String(50), index=True)
)
For a composite index, multiple columns can be specified::
@@ -5122,22 +5168,26 @@ class Index(
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")
)
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)"))
)
Table(
"sometable",
metadata,
Column("name", String(50)),
Column("address", String(100)),
Index("some_index", text("lower(name)")),
)
.. seealso::
@@ -5616,6 +5666,38 @@ class MetaData(HasSchemaAttr):
sorted(self.tables.values(), key=lambda t: t.key) # type: ignore
)
# overload needed to work around mypy this mypy
# https://github.com/python/mypy/issues/17093
@overload
def reflect(
self,
bind: Engine,
schema: Optional[str] = ...,
views: bool = ...,
only: Union[
_typing_Sequence[str], Callable[[str, MetaData], bool], None
] = ...,
extend_existing: bool = ...,
autoload_replace: bool = ...,
resolve_fks: bool = ...,
**dialect_kwargs: Any,
) -> None: ...
@overload
def reflect(
self,
bind: Connection,
schema: Optional[str] = ...,
views: bool = ...,
only: Union[
_typing_Sequence[str], Callable[[str, MetaData], bool], None
] = ...,
extend_existing: bool = ...,
autoload_replace: bool = ...,
resolve_fks: bool = ...,
**dialect_kwargs: Any,
) -> None: ...
@util.preload_module("sqlalchemy.engine.reflection")
def reflect(
self,
@@ -5863,9 +5945,11 @@ class Computed(FetchedValue, SchemaItem):
from sqlalchemy import Computed
Table('square', metadata_obj,
Column('side', Float, nullable=False),
Column('area', Float, Computed('side * side'))
Table(
"square",
metadata_obj,
Column("side", Float, nullable=False),
Column("area", Float, Computed("side * side")),
)
See the linked documentation below for complete details.
@@ -5970,9 +6054,11 @@ class Identity(IdentityOptions, FetchedValue, SchemaItem):
from sqlalchemy import Identity
Table('foo', metadata_obj,
Column('id', Integer, Identity())
Column('description', Text),
Table(
"foo",
metadata_obj,
Column("id", Integer, Identity()),
Column("description", Text),
)
See the linked documentation below for complete details.
@@ -6032,7 +6118,7 @@ class Identity(IdentityOptions, FetchedValue, SchemaItem):
:param on_null:
Set to ``True`` to specify ON NULL in conjunction with a
``always=False`` identity column. This option is only supported on
some backends, like Oracle.
some backends, like Oracle Database.
:param start: the starting index of the sequence.
:param increment: the increment value of the sequence.